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
<repo_name>alexaugustobr/aggregates-by-example<file_sep>/examples/java/cart/src/main/java/io/pillopl/seconddesign/CartId.java package io.pillopl.seconddesign; import java.util.Objects; import java.util.UUID; class CartId { private final UUID uuid; CartId(UUID uuid) { this.uuid = uuid; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CartId cartId = (CartId) o; return Objects.equals(uuid, cartId.uuid); } } <file_sep>/examples/php/src/Loan/AttachmentId.php <?php namespace AggregatesByExample\Loan; use Webmozart\Assert\Assert; final class AttachmentId { /** * @var string */ private $id; /** * AttachmentId constructor. * @param string $id */ private function __construct(string $id) { Assert::uuid($id); $this->id = $id; } /** * @param string $id * @return AttachmentId */ public static function fromString(string $id): AttachmentId { return new self($id); } /** * @return string */ public function toString(): string { return $this->id; } } <file_sep>/examples/php/src/Availability/Policy/Rejection.php <?php namespace AggregatesByExample\Availability\Policy; final class Rejection { /** * @var string */ private $reason; /** * Rejection constructor. * @param string $reason */ public function __construct(string $reason) { $this->reason = $reason; } /** * @return string */ public function getReason(): string { return $this->reason; } } <file_sep>/examples/java/cart/src/main/java/io/pillopl/seconddesign/CartDatabase.java package io.pillopl.seconddesign; import java.util.HashMap; import java.util.Map; class CartDatabase { private final Map<CartId, Cart> views = new HashMap<>(); Cart findViewBy(CartId cartId) { return views.get(cartId); } void save(CartId cardId, Cart view) { views.put(cardId, view); } } <file_sep>/examples/php/src/Loan/Policy/DecisionRegistration/OverwritingDecisions.php <?php namespace AggregatesByExample\Loan\Policy\DecisionRegistration; use AggregatesByExample\Loan\AttachmentDecision; use AggregatesByExample\Loan\AttachmentDecisions; use AggregatesByExample\Loan\DecisionRegistrationPolicy; use AggregatesByExample\Loan\LoanApplication; class OverwritingDecisions implements DecisionRegistrationPolicy { /** * @param AttachmentDecision $newDecision * @param LoanApplication $loanApplication * @return AttachmentDecisions */ public function register(AttachmentDecision $newDecision, LoanApplication $loanApplication): AttachmentDecisions { return $loanApplication->getAttachmentDecisions()->overwrite($newDecision); } } <file_sep>/examples/php/src/Loan/Policy/DecisionRegistration/Deadline.php <?php namespace AggregatesByExample\Loan\Policy\DecisionRegistration; use AggregatesByExample\Loan\AttachmentDecision; use AggregatesByExample\Loan\AttachmentDecisions; use AggregatesByExample\Loan\DecisionRegistrationPolicy; use AggregatesByExample\Loan\LoanApplication; class Deadline implements DecisionRegistrationPolicy { /** * @var DecisionRegistrationPolicy */ private $policy; /** * @var \DateInterval */ private $interval; /** * Deadline constructor. * @param DecisionRegistrationPolicy $policy * @param \DateInterval $interval */ public function __construct(DecisionRegistrationPolicy $policy, \DateInterval $interval) { $this->policy = $policy; $this->interval = $interval; } /** * @param AttachmentDecision $newDecision * @param LoanApplication $loanApplication * @return AttachmentDecisions * @throws \Exception */ public function register(AttachmentDecision $newDecision, LoanApplication $loanApplication): AttachmentDecisions { if ($loanApplication->getCreated()->add($this->interval) > new \DateTimeImmutable()) { throw new \DomainException('Registering new decision after deadline is not allowed'); } return $this->policy->register($newDecision, $loanApplication); } } <file_sep>/README.md ![Logo](assets/logo.png) Aggregate definition -------------------- What is an aggregate? > Cluster the entities and value objects into aggregates and define boundaries around each. Choose one entity to be the root of each aggregate, and allow external objects to hold references to the root only (references to internal members passed out for use within a single operation only). Define properties and invariants for the aggregate as a whole and give enforcement responsibility to the root or some designated framework mechanism. > - Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries List of examples ---------------- This repository contains following examples: | Example name | Description | Language | Persistence method | | ------------ | ----------- | :--------:|:------------------:| | [Availability / Resource](examples/example-availability-resource.md) | Reserving resource based on its availability and other policies | PHP | *not available* | | [Loan / Loan Application](examples/example-loan-application.md) | Accepting loan application based on attachment verifications | PHP | *not available* | | [Cart / Shopping Basket](examples/example-cart-shopping-basket.md) | Shopping cart with free items | Java | *in memory hashmap* | ### Info Presented implementations are just examples to show some concepts. There is almost always more than one valid solution for given requirements. Aggregates designing rules -------------------------- 4 rules about designing aggregates by Eric Evans: - Model true invariants in consistency boundaries - Design small aggregates - Reference other aggregates by identity - Use Eventual Consistency outside the boundary Aggregate Design Canvas ----------------------- Coming soon... Authors ------- - [<NAME>](https://twitter.com/mariuszgil) - [<NAME>](https://twitter.com/JakubPilimon) <file_sep>/examples/java/cart/src/main/java/io/pillopl/seconddesign/CartCommandsHandler.java package io.pillopl.seconddesign; import java.util.Set; //in real-life project is better to have command handler as a separate class class CartCommandsHandler { private final CartDatabase cartDatabase; private final ExtraItemsPolicy extraItemsPolicy; CartCommandsHandler(CartDatabase cartRepository, ExtraItemsPolicy extraItems) { this.cartDatabase = cartRepository; this.extraItemsPolicy = extraItems; } void handle(AddItemCommand cmd) { Cart cartView = cartDatabase.findViewBy(cmd.cartId); cartView.add(cmd.addedItem); Set<Item> freeItems = extraItemsPolicy.findAllFor(cmd.addedItem); freeItems.forEach(cartView::addFree); cartDatabase.save(cmd.cartId, cartView); } void handle(RemoveItemCommand cmd) { Cart cartView = cartDatabase.findViewBy(cmd.cartId); cartView.remove(cmd.removedItem); Set<Item> freeItems = extraItemsPolicy.findAllFor(cmd.removedItem); freeItems.forEach(cartView::removeFreeItem); cartDatabase.save(cmd.cartId, cartView); } void handle(IntentionallyRemoveFreeItemCommand cmd) { Cart cartView = cartDatabase.findViewBy(cmd.cartId); cartView.removeFreeItemIntentionally(cmd.removedItem); cartDatabase.save(cmd.cartId, cartView); } void handle(AddFreeItemBackCommand cmd) { Cart cartView = cartDatabase.findViewBy(cmd.cartId); cartView.addFreeItemBack(cmd.addedItem); cartDatabase.save(cmd.cartId, cartView); } } class AddItemCommand { final CartId cartId; final Item addedItem; AddItemCommand(CartId cartId, Item addedItem) { this.cartId = cartId; this.addedItem = addedItem; } } class RemoveItemCommand { final CartId cartId; final Item removedItem; RemoveItemCommand(CartId cartId, Item removedItem) { this.cartId = cartId; this.removedItem = removedItem; } } class IntentionallyRemoveFreeItemCommand { final CartId cartId; final Item removedItem; IntentionallyRemoveFreeItemCommand(CartId cartId, Item removedItem) { this.cartId = cartId; this.removedItem = removedItem; } } class AddFreeItemBackCommand { final CartId cartId; final Item addedItem; AddFreeItemBackCommand(CartId cartId, Item addedItem) { this.cartId = cartId; this.addedItem = addedItem; } } //changes of quantity: //ChangeQuantity from 3 -> 5 == AddFreeItemBackCommand, AddFreeItemBackCommand //ChangeQuantity from 5 -> 4 == IntentionallyRemoveFreeItemCommand <file_sep>/examples/php/tests/Loan/LoanApplicationTest.php <?php namespace Tests\AggregatesByExample\Loan; use AggregatesByExample\Loan\AttachmentDecisions; use AggregatesByExample\Loan\AttachmentId; use AggregatesByExample\Loan\Decision; use AggregatesByExample\Loan\DecisionRegistrationPolicy; use AggregatesByExample\Loan\LoanApplication; use AggregatesByExample\Loan\LoanApplicationId; use AggregatesByExample\Loan\Policy\DecisionProcessing\AllDecidedTo; use AggregatesByExample\Loan\Policy\DecisionRegistration\OverwritingDecisions; use AggregatesByExample\Loan\Policy\DecisionRegistration\SingleDecisions; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid; class LoanApplicationTest extends TestCase { /** * @test * @throws \Exception */ public function applicationDecisionIsMadeAfterAllAttachmentDecisions() { // Arrange list($attachmentId1, $attachmentId2) = $this->prepareAttachmentIds(2); $loanApplication = $this->prepareLoanApplication([$attachmentId1, $attachmentId2], new SingleDecisions()); // Act $loanApplication->registerDecision($attachmentId1, Decision::ACCEPTED()); $loanApplication->registerDecision($attachmentId2, Decision::ACCEPTED()); // Assert $this->assertEquals(Decision::ACCEPTED(), $loanApplication->getDecision()); } /** * @test * @throws \Exception */ public function applicationDecisionIsNotAvailableBeforeAllAttachmentDecisions() { // Arrange list($attachmentId1, $attachmentId2) = $this->prepareAttachmentIds(2); $loanApplication = $this->prepareLoanApplication([$attachmentId1, $attachmentId2], new SingleDecisions()); // Act $loanApplication->registerDecision($attachmentId1, Decision::ACCEPTED()); // Assert $this->assertEquals(Decision::NONE(), $loanApplication->getDecision()); } /** * @test * @throws \Exception */ public function changingAttachmentDecisionsAfterApplicationDecisionIsForbidden() { // Assert $this->expectException(\DomainException::class); // Arrange list($attachmentId1, $attachmentId2) = $this->prepareAttachmentIds(2); $loanApplication = $this->prepareLoanApplication([$attachmentId1, $attachmentId2], new OverwritingDecisions()); $loanApplication->registerDecision($attachmentId1, Decision::ACCEPTED()); $loanApplication->registerDecision($attachmentId2, Decision::ACCEPTED()); // Act $loanApplication->registerDecision($attachmentId2, Decision::REJECTED()); } /** * @param int $howMany * @return array */ private function prepareAttachmentIds(int $howMany): array { $ids = []; for ($i = 1; $i <= $howMany; $i++) { $ids[] = AttachmentId::fromString(Uuid::uuid4()->toString()); } return $ids; } /** * @param array $attachmentIds * @param DecisionRegistrationPolicy $registrationPolicy * @return LoanApplication * @throws \Exception */ private function prepareLoanApplication(array $attachmentIds, DecisionRegistrationPolicy $registrationPolicy): LoanApplication { return new LoanApplication( LoanApplicationId::fromString(Uuid::uuid4()->toString()), AttachmentDecisions::createFor($attachmentIds), $registrationPolicy, new AllDecidedTo(Decision::ACCEPTED(), Decision::ACCEPTED()) ); } } <file_sep>/examples/example-loan-application.md # Example: Loan / Loan Application Description ------------ Let's assume we have a loan application process, where customer need to deliver some documents about income, credit cards and so on. Evaluation of the application depends on evaluation of these documents, e.g. in some cases all of them need to be verified positively to accept the application. Moreover, maybe there is a specific deadline for all documents checks. Use-case scenario ----------------- ### Submitting and reviewing application attachments ![](../assets/examples/loan/board-loan-application-process.png)<file_sep>/examples/php/src/Loan/DecisionProcessingPolicy.php <?php namespace AggregatesByExample\Loan; interface DecisionProcessingPolicy { /** * @param AttachmentDecisions $decisions * @return Decision */ public function process(AttachmentDecisions $decisions): Decision; } <file_sep>/examples/php/src/Loan/AttachmentContent.php <?php namespace AggregatesByExample\Loan; /** * Content is not important for application decision processing, * we can extract all these information to separate class. * * Class AttachmentContent * @package AggregatesByExample\Loan */ class AttachmentContent { /** * @var AttachmentId */ private $id; /** * AttachmentContent constructor. * @param AttachmentId $id */ public function __construct(AttachmentId $id) { $this->id = $id; } // ... } <file_sep>/examples/php/src/Loan/AttachmentDecision.php <?php namespace AggregatesByExample\Loan; class AttachmentDecision { /** * @var AttachmentId */ private $attachmentId; /** * @var Decision */ private $decision; /** * @var \DateTimeImmutable */ private $created; /** * AttachmentDecision constructor. * @param AttachmentId $attachmentId * @param Decision $decision * @param \DateTimeImmutable $created * @throws \Exception */ public function __construct(AttachmentId $attachmentId, Decision $decision, \DateTimeImmutable $created = null) { $this->attachmentId = $attachmentId; $this->decision = $decision; $this->created = $created ?: new \DateTimeImmutable(); } /** * @param AttachmentId $attachmentId * @return bool */ public function isFor(AttachmentId $attachmentId): bool { return $this->attachmentId->toString() == $attachmentId->toString(); } /** * @return AttachmentId */ public function getAttachmentId(): AttachmentId { return $this->attachmentId; } /** * @return Decision */ public function getDecision(): Decision { return $this->decision; } /** * @return \DateTimeImmutable */ public function getCreated(): \DateTimeImmutable { return $this->created; } } <file_sep>/examples/php/src/Availability/Resource.php <?php namespace AggregatesByExample\Availability; use League\Period\Period; use Munus\Collection\GenericList; use Munus\Control\Either; use Munus\Control\Either\Left; use Munus\Control\Either\Right; class Resource { /** * @var ResourceId */ private $resourceId; /** * @var GenericList<Reservation> */ private $reservations; /** * Resource constructor. * @param ResourceId $resourceId */ public function __construct(ResourceId $resourceId) { $this->reservations = GenericList::empty(); $this->resourceId = $resourceId; } /** * @param Period $period * @param GenericList<Policy> $policies * @return Either */ public function reserve(Period $period, GenericList $policies): Either { $rejections = $policies ->map(function (Policy $policy) use ($period): Either { return $policy->isSatisfied($period, $this->getReservedPeriods()); }) ->find(function (Either $either): bool { return $either->isLeft(); }) ->map(function (Either $either) { return $either->getLeft(); }); if ($rejections->isEmpty()) { $reservation = new Reservation($period); $this->reservations = $this->reservations->append($reservation); return new Right($reservation); } else { return new Left($rejections->get()); } } public function getReservedPeriods(): GenericList { return $this->reservations->map(function (Reservation $reservation) { return $reservation->getPeriod(); }); } /** * @return ResourceId */ public function getResourceId(): ResourceId { return $this->resourceId; } } <file_sep>/examples/php/src/Loan/Decision.php <?php namespace AggregatesByExample\Loan; use MyCLabs\Enum\Enum; class Decision extends Enum { public const NONE = 'none'; public const ACCEPTED = 'accepted'; public const REJECTED = 'rejected'; } <file_sep>/examples/php/src/Loan/LoanApplicationId.php <?php namespace AggregatesByExample\Loan; use Webmozart\Assert\Assert; final class LoanApplicationId { /** * @var string */ private $id; /** * LoanApplicationId constructor. * @param string $id */ private function __construct(string $id) { Assert::uuid($id); $this->id = $id; } /** * @param string $id * @return LoanApplicationId */ public static function fromString(string $id): LoanApplicationId { return new self($id); } /** * @return string */ public function toString(): string { return $this->id; } } <file_sep>/examples/php/src/Availability/Policy/LimitedDuration.php <?php namespace AggregatesByExample\Availability\Policy; use AggregatesByExample\Availability\Policy; use League\Period\Duration; use League\Period\Period; use Munus\Collection\GenericList; use Munus\Control\Either; use Munus\Control\Either\Left; use Munus\Control\Either\Right; class LimitedDuration implements Policy { /** * @var Duration */ private $maxDuration; /** * LimitedReservationDuration constructor. * @param Duration $maxDuration */ public function __construct(Duration $maxDuration) { $this->maxDuration = $maxDuration; } /** * @param Period $period * @param GenericList<Period> $reservedPeriods * @return Either */ public function isSatisfied(Period $period, GenericList $reservedPeriods): Either { return $period->durationLessThan($period->withDurationAfterStart($this->maxDuration)) ? new Right(new Allowance()) : new Left(new Rejection('Duration limited exceeded')); } } <file_sep>/examples/php/src/Availability/Policy/NoGapsBetween.php <?php namespace AggregatesByExample\Availability\Policy; use AggregatesByExample\Availability\Policy; use League\Period\Period; use Munus\Collection\GenericList; use Munus\Control\Either; use Munus\Control\Either\Left; use Munus\Control\Either\Right; class NoGapsBetween implements Policy { /** * @param Period $period * @param GenericList<Period> $reservedPeriods * @return Either */ public function isSatisfied(Period $period, GenericList $reservedPeriods): Either { $touched = $reservedPeriods->filter(function (Period $reservedPeriod) use ($period) { return $reservedPeriod->abuts($period); }); return $reservedPeriods->isEmpty() || $touched->length() >= 1 ? new Right(new Allowance()) : new Left(new Rejection('Reservation must abust with previous ones')); } } <file_sep>/examples/php/src/Loan/Policy/DecisionProcessing/AllDecidedTo.php <?php namespace AggregatesByExample\Loan\Policy\DecisionProcessing; use AggregatesByExample\Loan\AttachmentDecision; use AggregatesByExample\Loan\AttachmentDecisions; use AggregatesByExample\Loan\Decision; use AggregatesByExample\Loan\DecisionProcessingPolicy; class AllDecidedTo implements DecisionProcessingPolicy { /** * @var Decision */ private $requiredDecision; /** * @var Decision */ private $finalDecision; /** * AllDecidedTo constructor. * @param Decision $requiredDecision * @param Decision $finalDecision */ public function __construct(Decision $requiredDecision, Decision $finalDecision) { $this->requiredDecision = $requiredDecision; $this->finalDecision = $finalDecision; } /** * @param AttachmentDecisions $attachmentDecisions * @return Decision */ public function process(AttachmentDecisions $attachmentDecisions): Decision { /** * @var $attachmentDecision AttachmentDecision */ foreach ($attachmentDecisions as $attachmentDecision) { if (!$attachmentDecision->getDecision()->equals($this->requiredDecision)) { return Decision::NONE(); } } return $this->finalDecision; } } <file_sep>/examples/java/cart/src/main/java/io/pillopl/firstdesign/CartCommandsHandler.java package io.pillopl.firstdesign; import java.util.Set; //in real-life project is better to have command handler as a separate class class CartCommandsHandler { private final CartDatabase cartDatabase; private final ExtraItemsPolicy extraItemsPolicy; CartCommandsHandler(CartDatabase cartRepository, ExtraItemsPolicy extraItems) { this.cartDatabase = cartRepository; this.extraItemsPolicy = extraItems; } void addItem(CartId cartId, Item addedItem) { Cart cartView = cartDatabase.findViewBy(cartId); cartView.add(addedItem); Set<Item> freeItems = extraItemsPolicy.findAllFor(addedItem); freeItems.forEach(cartView::addFree); cartDatabase.save(cartId, cartView); } void removeItem(CartId cartId, Item removedItem) { Cart cartView = cartDatabase.findViewBy(cartId); cartView.remove(removedItem); Set<Item> freeItems = extraItemsPolicy.findAllFor(removedItem); freeItems.forEach(cartView::removeFree); cartDatabase.save(cartId, cartView); } } <file_sep>/examples/example-cart-shopping-basket.md # Example: Cart / Shopping Basket Description ------------ TBD...<file_sep>/examples/java/cart/src/test/java/io.pillopl/firstdesign/CartTest.java package io.pillopl.firstdesign; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static java.util.UUID.randomUUID; import static org.junit.jupiter.api.Assertions.assertEquals; class CartTest { CartId cartId = new CartId(randomUUID()); CartDatabase cartRepository = new CartDatabase(); ExtraItemsPolicy extraItemsPolicy = new ExtraItemsPolicy(); CartCommandsHandler commandHandler = new CartCommandsHandler(cartRepository, extraItemsPolicy); final Item DELL_XPS = new Item("DELL XPS"); final Item BAG = new Item("BAG"); @Test @DisplayName("Can add an item") void canAdd() throws Exception { //given Cart cart = aCartView(); //when commandHandler.addItem(cartId, DELL_XPS); //then assertEquals("DELL XPS", cart.print()); } @Test @DisplayName("Can add two same items") void canAddTwoSameItems() throws Exception { //given Cart cart = aCartView(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); //then assertEquals("DELL XPS, DELL XPS", cart.print()); } @Test @DisplayName("Can remove an item") void canRemove() throws Exception { //given Cart cart = aCartView(); //and commandHandler.addItem(cartId, DELL_XPS); //when commandHandler.removeItem(cartId, DELL_XPS); //then assertEquals("", cart.print()); } @Test @DisplayName("Can remove two same items") void canRemoveTwoSameItems() throws Exception { //given Cart cart = aCartView(); //and commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); //when commandHandler.removeItem(cartId, DELL_XPS); commandHandler.removeItem(cartId, DELL_XPS); //then assertEquals("", cart.print()); } @Test @DisplayName("When adding a laptop, bag is added for free") void laptopBagIsFreeItem() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); //then assertEquals("DELL XPS, [FREE] BAG", cart.print()); } @Test @DisplayName("Two laptops means 2 bags") void twoLaptopsMeansTwoBags() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); //then assertEquals("DELL XPS, DELL XPS, [FREE] BAG, [FREE] BAG", cart.print()); } @Test @DisplayName("Can remove free bag") void canRemoveFreeBag() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.removeItem(cartId, BAG); //then assertEquals("DELL XPS", cart.print()); } @Test @DisplayName("Can remove just one free bag") void canRemoveJustOneOfTwoFreeBags() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); commandHandler.removeItem(cartId, BAG); //then assertEquals("DELL XPS, DELL XPS, [FREE] BAG", cart.print()); } @Test @DisplayName("I want my free bag back") void wantsMyFreeBagBack() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); commandHandler.removeItem(cartId, BAG); commandHandler.addItem(cartId, BAG); //then assertEquals("DELL XPS, DELL XPS, [FREE] BAG, [FREE] BAG", cart.print()); } @Test @DisplayName("Already has 2 free bags (and 2 laptops), wants just one new bag!") void twoBagsAreFreeAndWantsAnotherOne() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, BAG); //then assertEquals( "BAG, " + "DELL XPS, " + "DELL XPS, " + "[FREE] BAG, " + "[FREE] BAG", cart.print()); } @Test @DisplayName("Has 2 free bags, removes one, adds it back, adds additional bag, removes it and adds back") void eveyrthingComplex() throws Exception { //given Cart cart = aCartView(); //and freeBagDiscountIsEnabled(); //when commandHandler.addItem(cartId, DELL_XPS); commandHandler.addItem(cartId, DELL_XPS); commandHandler.removeItem(cartId, BAG); commandHandler.addItem(cartId, BAG); commandHandler.addItem(cartId, BAG); commandHandler.removeItem(cartId, BAG); commandHandler.addItem(cartId, BAG); //then assertEquals( "BAG, " + "DELL XPS, " + "DELL XPS, " + "[FREE] BAG, " + "[FREE] BAG", cart.print()); } void freeBagDiscountIsEnabled() { extraItemsPolicy.add(new ExtraItem(DELL_XPS, BAG)); } Cart aCartView() { Cart view = new Cart(cartId); cartRepository.save(cartId, view); return view; } }<file_sep>/examples/php/tests/Availability/ReservationTest.php <?php namespace Tests\AggregatesByExample\Availability; use AggregatesByExample\Availability\Policy; use AggregatesByExample\Availability\Policy\LimitedDuration; use AggregatesByExample\Availability\Policy\NoGapsBetween; use AggregatesByExample\Availability\Policy\NoOverlapping; use AggregatesByExample\Availability\Policy\Rejection; use AggregatesByExample\Availability\Resource; use AggregatesByExample\Availability\ResourceId; use League\Period\Duration; use League\Period\Period; use Munus\Collection\GenericList; use PHPUnit\Framework\TestCase; class ReservationTest extends TestCase { /** * @var Resource */ private $resource; /** * @var GenericList<Policy> */ private $policies; /** * @test */ public function reservationMayBeRequestedRightAfterPreviousOne() { // Act $this->resource->reserve(new Period('2020-03-01 10:00:00', '2020-03-01 12:00:00'), $this->policies); $this->resource->reserve(new Period('2020-03-01 12:00:00', '2020-03-01 14:00:00'), $this->policies); // Assert $this->assertEquals(2, $this->resource->getReservedPeriods()->length()); } /** * @test */ public function reservationCantOverlapWithPreviousOnes() { // Arrange $this->resource->reserve(new Period('2020-03-01 10:00:00', '2020-03-01 12:00:00'), $this->policies); // Act & Assert $this->assertInstanceOf( Rejection::class, $this->resource->reserve(new Period('2020-03-01 11:00:00', '2020-03-01 14:00:00'), $this->policies)->getLeft() ); } /** * @test */ public function reservationCantBeLongerThenGivenLimit() { // Act & Assert $this->assertInstanceOf( Rejection::class, $this->resource->reserve(new Period('2020-03-01 10:00:00', '2020-03-01 18:00:00'), $this->policies)->getLeft() ); } /** * */ protected function setUp(): void { // Arrange parent::setUp(); $this->resource = new Resource(ResourceId::fromString('39acb44d-e4cc-4bb1-869e-f4aaa458751f')); $this->policies = GenericList::of( new NoOverlapping(), new NoGapsBetween(), new LimitedDuration(Duration::create('3 HOURS')) ); } }<file_sep>/examples/php/src/Loan/LoanApplication.php <?php namespace AggregatesByExample\Loan; class LoanApplication { /** * @var LoanApplicationId */ private $id; /** * @var \DateTimeImmutable */ private $created; /** * @var Decision */ private $decision; /** * @var AttachmentDecisions */ private $attachmentDecisions; /** * @var DecisionRegistrationPolicy */ private $registrationPolicy; /** * @var DecisionRegistrationPolicy */ private $processingPolicy; /** * LoanApplication constructor. * @param LoanApplicationId $id * @param AttachmentDecisions $attachmentDecisions * @param DecisionRegistrationPolicy $registrationPolicy * @param DecisionProcessingPolicy $processingPolicy * @param \DateTimeImmutable $created * @throws \Exception */ public function __construct( LoanApplicationId $id, AttachmentDecisions $attachmentDecisions, DecisionRegistrationPolicy $registrationPolicy, DecisionProcessingPolicy $processingPolicy, \DateTimeImmutable $created = null ) { if (count($attachmentDecisions) == 0) { throw new \DomainException('Loan application must have at least 1 attachment to check'); } $this->id = $id; $this->attachmentDecisions = $attachmentDecisions; $this->registrationPolicy = $registrationPolicy; $this->processingPolicy = $processingPolicy; $this->decision = Decision::NONE(); $this->created = $created ?: new \DateTimeImmutable(); } /** * @param AttachmentId $id * @param Decision $decision * @throws \Exception */ public function registerDecision(AttachmentId $id, Decision $decision): void { // When application decision is made, no changes are allowed if (!$this->decision->equals(Decision::NONE())) { throw new \DomainException('Registering new decisions is forbidden'); } $this->attachmentDecisions = $this->registrationPolicy->register( new AttachmentDecision($id, $decision, new \DateTimeImmutable()), $this ); $this->decision = $this->processingPolicy->process( $this->attachmentDecisions ); } /** * @return LoanApplicationId */ public function getId(): LoanApplicationId { return $this->id; } /** * @return \DateTimeImmutable */ public function getCreated(): \DateTimeImmutable { return $this->created; } /** * @return Decision */ public function getDecision(): Decision { return $this->decision; } /** * @return AttachmentDecisions */ public function getAttachmentDecisions(): AttachmentDecisions { return $this->attachmentDecisions; } } <file_sep>/examples/php/src/Availability/Policy/NoOverlapping.php <?php namespace AggregatesByExample\Availability\Policy; use AggregatesByExample\Availability\Policy; use AggregatesByExample\Availability\Reservation; use League\Period\Period; use Munus\Collection\GenericList; use Munus\Control\Either; use Munus\Control\Either\Left; use Munus\Control\Either\Right; class NoOverlapping implements Policy { /** * @param Period $period * @param GenericList<Period> $periods * @return Either */ public function isSatisfied(Period $period, GenericList $reservedPeriods): Either { $overlapped = $reservedPeriods->filter(function (Period $reservedPeriod) use ($period) { return $reservedPeriod->overlaps($period); }); return $overlapped->isEmpty() ? new Right(new Allowance()) : new Left(new Rejection('Reservation cant overlap with previous ones')); } } <file_sep>/examples/php/src/Availability/ResourceId.php <?php namespace AggregatesByExample\Availability; use Webmozart\Assert\Assert; final class ResourceId { /** * @var string */ private $id; private function __construct(string $id) { Assert::uuid($id); $this->id = $id; } public static function fromString(string $id): ResourceId { return new self($id); } public function toString(): string { return $this->id; } } <file_sep>/examples/php/src/Availability/Policy.php <?php namespace AggregatesByExample\Availability; use League\Period\Period; use Munus\Collection\GenericList; use Munus\Control\Either; interface Policy { /** * @param Period $period * @param GenericList<Period> $reservedPeriods * @return Either */ public function isSatisfied(Period $period, GenericList $reservedPeriods): Either; } <file_sep>/examples/php/src/Loan/Policy/DecisionRegistration/SingleDecisions.php <?php namespace AggregatesByExample\Loan\Policy\DecisionRegistration; use AggregatesByExample\Loan\AttachmentDecision; use AggregatesByExample\Loan\AttachmentDecisions; use AggregatesByExample\Loan\Decision; use AggregatesByExample\Loan\DecisionRegistrationPolicy; use AggregatesByExample\Loan\LoanApplication; class SingleDecisions implements DecisionRegistrationPolicy { /** * @param AttachmentDecision $newDecision * @param LoanApplication $loanApplication * @return AttachmentDecisions */ public function register(AttachmentDecision $newDecision, LoanApplication $loanApplication): AttachmentDecisions { $existingDecisions = $loanApplication->getAttachmentDecisions(); // 2 cases must be supported here: // 1) Collection contains only ACCEPTED or REJECTED decisions, so size is expanding here if needed if (!$existingDecisions->containsDecisionFor($newDecision->getAttachmentId())) { return $existingDecisions->append($newDecision); } // 2) Collection contains all decisions, but some of them are in NONE status. We need to overwrite one of them if (!$existingDecisions->isDecisionFor($newDecision->getAttachmentId(), Decision::NONE())) { throw new \DomainException('Attachment decision was already provided'); } return $existingDecisions->overwrite($newDecision); } } <file_sep>/examples/php/src/Availability/Policy/Allowance.php <?php namespace AggregatesByExample\Availability\Policy; final class Allowance { } <file_sep>/examples/php/src/Loan/AttachmentDecisions.php <?php namespace AggregatesByExample\Loan; class AttachmentDecisions implements \IteratorAggregate, \Countable { /** * @var AttachmentDecision[] */ private $decisions; /** * AttachmentDecisions constructor. * @param AttachmentDecision[] $decisions */ public function __construct(array $decisions) { $this->decisions = $decisions; } /** * @param array $attachmentsIds * @return static */ public static function createFor(array $attachmentsIds): self { return new self(array_map(function (AttachmentId $attachmentId) { return new AttachmentDecision($attachmentId, Decision::NONE(), new \DateTimeImmutable()); }, $attachmentsIds)); } /** * @param AttachmentDecision $decision * @return $this */ public function append(AttachmentDecision $decision): self { $x = new self($this->decisions + [$decision]); } /** * @param AttachmentDecision $decision * @return $this */ public function overwrite(AttachmentDecision $decision): self { if (!$this->containsDecisionFor($decision->getAttachmentId())) { return $this->append($decision); } $target = []; foreach ($this->decisions as $existingDecision) { $target[] = $existingDecision->isFor($decision->getAttachmentId()) ? $decision : $existingDecision; } return new self($target); } /** * @param AttachmentId $attachmentId * @return bool */ public function containsDecisionFor(AttachmentId $attachmentId): bool { foreach ($this->decisions as $existingDecision) { if ($existingDecision->isFor($attachmentId)) { return true; } } return false; } /** * @param AttachmentId $attachmentId * @param Decision $decision * @return bool */ public function isDecisionFor(AttachmentId $attachmentId, Decision $decision): bool { $attachmentDecision = $this->getDecisionFor($attachmentId); return is_null($attachmentDecision) ? false : $attachmentDecision->getDecision()->equals($decision); } /** * Returns latest decision for given attachment. * * Latest - current implementation relies on position in collection, not on datetime. * @todo CHANGE IT * * @param AttachmentId $attachmentId * @return AttachmentDecision|null */ public function getDecisionFor(AttachmentId $attachmentId): ?AttachmentDecision { $result = null; foreach ($this->decisions as $existingDecision) { if ($existingDecision->isFor($attachmentId)) { $result = $existingDecision; } } return $result; } /** * @return \ArrayObject|\Traversable */ public function getIterator(): \Traversable { return new \ArrayObject($this->decisions); } /** * @return int */ public function count(): int { return count($this->decisions); } } <file_sep>/examples/java/cart/src/main/java/io/pillopl/firstdesign/Cart.java package io.pillopl.firstdesign; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; class Cart { private final CartId cartId; private List<Item> items = new ArrayList<>(); private List<Item> freeItems = new ArrayList<>(); private List<Item> returnedFreeItems = new ArrayList<>(); Cart(CartId cartId) { this.cartId = cartId; } void add(Item item) { if (returnedFreeItems.contains(item)) { returnedFreeItems.remove(item); freeItems.add(item); } else { items.add(item); } } void addFree(Item item) { freeItems.add(item); } void remove(Item item) { if (!items.contains(item)) { if (freeItems.contains(item)) { freeItems.remove(item); returnedFreeItems.add(item); } } else { items.remove(item); } } void removeFree(Item item) { freeItems.remove(item); } String print() { return Stream.concat( items.stream().map(item -> item.name).sorted(), freeItems.stream().map(item -> "[FREE] " + item.name).sorted()) .collect(Collectors.joining(", ")); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cart cart = (Cart) o; return Objects.equals(cartId, cart.cartId); } } class Item { final String name; Item(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; return Objects.equals(name, item.name); } } <file_sep>/examples/example-availability-resource.md # Example: Availability / Resource Description ------------ In many cases users need to rival for limited amount of resources. Good examples are: - hot desks in co-working office - copy of book in library - rooms in hotel - vehicles in car rental service Depending on the context, resource may have one or more instances to reserve. This example describes single identifiable resource concept, where some extra policies may be injected in runtime. Explanation ----------- Resource can't be reserved for many reasons, e.g. car was damaged and need to be repaired, hotel room is occupied by someone or hotel staff is cleaning conference room after the event. From the reservation process perspective the only important thing is: it's not available at given moment. Finally, availability of the resource may be derived from other resource reservations. Sometimes reservation will be connected with additional details, like costs, payer details or compensation for cancellation. But all these data are not needed to process reservation requests and should be stored outside resource aggregate. Possible use-case scenarios --------------------------- ### Booking conference room ![](../assets/examples/availability/board-booking-conference-room.png) <file_sep>/examples/php/src/Availability/Reservation.php <?php namespace AggregatesByExample\Availability; use League\Period\Period; class Reservation { /** * @var Period */ private $period; /** * Reservation constructor. * @param Period $period */ public function __construct(Period $period) { $this->period = $period; } /** * @return Period */ public function getPeriod(): Period { return $this->period; } } <file_sep>/examples/php/src/Loan/DecisionRegistrationPolicy.php <?php namespace AggregatesByExample\Loan; interface DecisionRegistrationPolicy { /** * @param AttachmentDecision $newDecision * @param LoanApplication $loanApplication * @return AttachmentDecisions */ public function register(AttachmentDecision $newDecision, LoanApplication $loanApplication): AttachmentDecisions; }
683e08fce6869144efe7410927a6e86a33f3d9bc
[ "Markdown", "Java", "PHP" ]
34
Java
alexaugustobr/aggregates-by-example
68f404fb5bf24d57641471b41b4b1eb997d3ad78
74d7e4926045cf453ebf632755976b76fea6d311
refs/heads/master
<repo_name>vini-barba/lotus-branco<file_sep>/front/src/components/signin.js import React from 'react'; import { Link } from 'react-router-dom'; import {signIn} from '../services/auth' class Signin extends React.Component { render() { return ( <div className="container"> <div className="row"> <div className="col-sm-9 col-md-7 col-lg-5 mx-auto my-5"> <div className="card card-signin my-5"> <div className="card-body"> <h5 className="card-title text-center">Login</h5> <form className="form-signin"> <div className="form-label-group"> <label for="inputEmail">Email</label> <input type="email" id="inputEmail" className="form-control" placeholder="<EMAIL>" required autoFocus /> </div> <div className="form-label-group my-3"> <label for="inputPassword">Senha</label> <input type="password" id="inputPassword" className="form-control" placeholder="<PASSWORD>" required /> </div> <div className="custom-control custom-checkbox my-3 "> <input type="checkbox" className="custom-control-input" id="customCheck1" /> <label className="custom-control-label" for="customCheck1"> Lembrar senha </label> </div> <button className="btn btn-lg btn-primary btn-block text-uppercase" type="submit" onClick={() => signIn({})}//aqui to-do implementar submeter form > Entrar </button> <Link to="/sign-up">Não tenho cadastro</Link> </form> </div> </div> </div> </div> </div> ); } } export default Signin; <file_sep>/front/src/components/game.js import React from 'react'; import _ from 'lodash'; import tla from '../assets/json/tla'; import Board from './board'; import SideBar from './sidebar'; import Navbar from './navbar'; const gameStart = () => { return _.sample(tla); }; class Game extends React.Component { c1 = gameStart(); render() { return ( <div> <Navbar></Navbar> <div className="row"> <Board lista={tla}></Board> <SideBar nome={this.c1.nome} foto={this.c1.foto}></SideBar> </div> </div> ); } } export default Game; <file_sep>/back/app/routes/game.route.js module.exports = (app) => { // app.post('/game/init', async(req, res) => { // }); // app.post('/game/room', async(req, res) => { // }); }<file_sep>/back/server.js const express = require('express') const app = express() const cors = require('cors') const bodyParser = require('body-parser') const authMiddleware = require('./app/middlewares/auth.middleware') const db = require('./config/db') app.use(authMiddleware) app.use(cors({ origin: '*' })) app.use(bodyParser.json()) db.then(res=>{ require('./app/routes')(app) }) app.listen(3210, () => { console.log('\x1b[0m', 'Backend escutando e enviando na porta 3210') })<file_sep>/front/src/components/signup.js import React from 'react'; import { Link } from 'react-router-dom'; import {signUp} from '../services/auth' class Signup extends React.Component { render() { return ( <div className="container"> <div className="row"> <div className="col-sm-9 col-md-7 col-lg-5 mx-auto my-5"> <div className="card card-signin my-5"> <div className="card-body"> <h5 className="card-title text-center">Registrar</h5> <form className="form-signin"> <div className="form-label-group"> <label for="inputNome">Username</label> <input type="text" id="inputNome" className="form-control" placeholder="Username" required autoFocus /> </div> <div className="form-label-group"> <label for="inputEmail">Email</label> <input type="email" id="inputEmail" className="form-control" placeholder="<EMAIL>" required /> </div> <div className="form-label-group my-3"> <label for="inputPassword">Senha</label> <input type="password" id="inputPassword1" className="form-control" placeholder="<PASSWORD>" required /> </div> <div className="form-label-group my-3"> <label for="inputPassword">Senha</label> <input type="password" id="inputPassword2" className="form-control" placeholder="<PASSWORD>" required /> </div> <button className="btn btn-lg btn-primary btn-block text-uppercase" type="submit" onClick={() => signUp({})}//aqui to-do implementar submeter form > Registrar </button> <Link to="/sign-in">Já sou cadastrado</Link> </form> </div> </div> </div> </div> </div> ); } } export default Signup; <file_sep>/front/src/components/board.js import React from 'react'; import Tile from './tile'; class Board extends React.Component { constructor(props) { super(props); this.state = { tiles: this.props.lista }; } handleClick(i) { const tiles = this.state.tiles.slice(); tiles[i].status = !tiles[i].status; this.setState({ tiles: tiles }); } renderTile(i) { return ( <Tile key={i} character={this.state.tiles[i]} onClick={() => this.handleClick(i)} ></Tile> ); } render() { return ( <div className="col-9 row"> {this.props.lista.map((character, i) => { return this.renderTile(i); })} </div> ); } } export default Board; <file_sep>/front/src/services/auth.js import {api} from "../config/api" export const signUp = (data) => { return api.post(`/sign-up`, data) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }); }; export const signIn = (data) => { return api.post(`/sign-in`, data) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }); }; <file_sep>/front/src/assets/json/tla.js import aang from '../images/aang.png'; import appa from '../images/appa.png'; import azula from '../images/azula.png'; import iroh from '../images/iroh.png'; import katara from '../images/katara.png'; import momo from '../images/momo.png'; import ozai from '../images/ozai.png'; import sokka from '../images/sokka.png'; import toph from '../images/toph.png'; import zuko from '../images/zuko.png'; import bumi from '../images/bumi.png'; import cara_dos_repolhos from '../images/cara_dos_repolhos.png'; import gyatso from '../images/gyatso.png'; import homem_combustao from '../images/homem_combustao.png'; import jato from '../images/jato.png'; import kyoshi from '../images/kyoshi.png'; import mai from '../images/mai.png'; import pakku from '../images/pakku.png'; import piandao from '../images/piandao.png'; import roku from '../images/roku.png'; import ty_lee from '../images/ty_lee.png'; import sozin from '../images/sozin.png'; import suki from '../images/suki.png'; import yue from '../images/yue.png'; const tla = [ { nome: 'aang', foto: aang, status: true }, { nome: 'appa', foto: appa, status: true }, { nome: 'azula', foto: azula, status: true }, { nome: 'iroh', foto: iroh, status: true }, { nome: 'katara', foto: katara, status: true }, { nome: 'momo', foto: momo, status: true }, { nome: 'ozai', foto: ozai, status: true }, { nome: 'sokka', foto: sokka, status: true }, { nome: 'toph', foto: toph, status: true }, { nome: 'zuko', foto: zuko, status: true }, { nome: 'bumi', foto: bumi, status: true }, { nome: '<NAME>', foto: cara_dos_repolhos, status: true }, { nome: 'gyatso', foto: gyatso, status: true }, { nome: '<NAME>', foto: homem_combustao, status: true }, { nome: 'jato', foto: jato, status: true }, { nome: 'kyoshi', foto: kyoshi, status: true }, { nome: 'mai', foto: mai, status: true }, { nome: 'pakku', foto: pakku, status: true }, { nome: 'piandao', foto: piandao, status: true }, { nome: 'roku', foto: roku, status: true }, { nome: 'ty_lee', foto: ty_lee, status: true }, { nome: 'sozin', foto: sozin, status: true }, { nome: 'suki', foto: suki, status: true }, { nome: 'yue', foto: yue, status: true } ]; export default tla; <file_sep>/back/app/controllers/user.controller.js const { User, validate } = require('../models/user.model'); const bcrypt = require('bcrypt') const signUp = (userData) => { console.log("signUp", userData); return new Promise(async (resolve, reject) => { const { error } = validate(userData); if (error) { return reject(error.details[0].message); } let user = await User.findOne({ email: userData.email }); if (user) { return reject('User already registered.'); } user = new User({ nome: userData.nome, senha: userData.senha, email: userData.email }); user.senha = await bcrypt.hash(user.senha, 10); await user.save(); const response = { user: { _id: user._id, nome: user.nome, email: user.email } }; return resolve(response); }); }; const signIn = (userData) => { return new Promise(async (resolve, reject) => { if(!userData.email){ return reject("Email is required!") } if(!userData.senha){ return reject("Password is required!") } let user = await User.findOne({ email: userData.email }); if (!user) { return reject('No user found.'); } const matchPassword = await bcrypt.compare(senha, user.senha); if (!matchPassword) { return reject('Entered Password and Hash do not match!'); } const token = user.generateAuthToken(); const response = { token, user: { _id: user._id, nome: user.nome, email: user.email } }; return resolve(response); }); }; module.exports = { signIn, signUp }; <file_sep>/back/app/routes/index.js module.exports = (app) => { require('./auth.route')(app), require('./game.route')(app) }<file_sep>/front/src/components/tile.js import React from 'react'; const Tile = (props) => { return ( <div className="col-2 border border-secondary p-0" style={{ opacity: props.character.status ? 1 : 0.2 }} onClick={() => props.onClick()} > <img className="w-100" src={props.character.foto} alt={props.character.nome} ></img> <h5 className="text-center">{props.character.nome}</h5> </div> ); }; export default Tile;
aaa720d0c363dd4dfb974bd8340df2bdb68af51e
[ "JavaScript" ]
11
JavaScript
vini-barba/lotus-branco
819aa3675b4f0b77ae323f49e67164d0733f07d2
bc1cc135f0e8cadd51fdfc4ac45e76ef4c4b63e9
refs/heads/master
<file_sep>package login1; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JPasswordField; import javax.swing.JButton; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Login { private JFrame frmLogin; private JTextField txtUsername; private JPasswordField txtPassword; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Login window = new Login(); window.frmLogin.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Login() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmLogin = new JFrame(); frmLogin.setTitle("Login"); frmLogin.getContentPane().setBackground(Color.GRAY); frmLogin.setBounds(100, 100, 323, 229); frmLogin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmLogin.getContentPane().setLayout(null); JLabel lblUsername = new JLabel("Username"); lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 13)); lblUsername.setBounds(10, 25, 84, 22); frmLogin.getContentPane().add(lblUsername); txtUsername = new JTextField(); txtUsername.setBounds(90, 27, 147, 20); frmLogin.getContentPane().add(txtUsername); txtUsername.setColumns(10); JLabel lblPassword = new JLabel("<PASSWORD>"); lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 13)); lblPassword.setBounds(10, 70, 66, 22); frmLogin.getContentPane().add(lblPassword); txtPassword = new JPasswordField(); txtPassword.setBounds(90, 72, 147, 20); frmLogin.getContentPane().add(txtPassword); JButton btnLogin = new JButton("Login"); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if((txtUsername.getText().equals("user")) && (txtPassword.getText().equals("<PASSWORD>"))) { JOptionPane.showMessageDialog(null, "Correct username and password."); frmLogin.dispose(); //access the other frame Frame2 obj = new Frame2(); obj.setVisible(true); } } }); btnLogin.setBounds(90, 124, 89, 23); frmLogin.getContentPane().add(btnLogin); } }
6970755d685c487c827272c332129b3e13bf7be5
[ "Java" ]
1
Java
chalinor/Assignment1_PM
2bebc641a6fd56f5ee787b32b1aa3cb1afbb401a
f4d131ad7f1c3b1d33f38e3bdff3c82744bf4915
refs/heads/master
<file_sep>//Dichiarazione delle variabili var nameUser, lastName, age, color, password, immage; //Assegnamo le variabili con la funzione globale di JavaScript prompt() e recuperiamo l'elemento html dal DOM nameUser = prompt('Inserisci il tuo nome'); var eleName = document.getElementById('name'); eleName.innerHTML = nameUser; lastName = prompt('Inserisci il tuo cognome'); var eleLastName = document.getElementById('lastname'); eleLastName.innerHTML = lastName; //Possiamo anche scriverlo in questa maniera senza dichiarare la variabile age = prompt('Inserisci i tuoi anni'); document.getElementById('age').innerHTML = parseInt(age); color = prompt('Inserisci il tuo colore preferito'); document.getElementById('color').innerHTML = color; immage = prompt('Inserisci il link di una tua immagine'); immage = immage ? immage : 'img/avatar.png'; document.getElementById('immage').src = immage; password = <PASSWORD> + lastName + age + color + 21; password = password.toLowerCase(); document.getElementById('password').innerHTML = password.replace(/ /g, '');
c0c8ca29cf2e07010bd9b1cab023737d13ec94a3
[ "JavaScript" ]
1
JavaScript
filippo1996/js-pwdgen-wannabe
d650683232adfa55999e1e95d95bbf3f00ff85bb
6d022e05f5cd8a2f4346bad785b882c7acfac814
refs/heads/master
<repo_name>HichamDz38/python-code-challenges<file_sep>/Simulate_Dice.py """ this script is for solving the chalenge: Simulate dice from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import random import timeit # this module to compare between the solutions from collections import Counter from random import randint def simulation(*args): '''my solution without seeing the instructor solution''' # initialize the results holder DS results = {i: 0 for i in range(len(args), sum(args)+1)} for sample in range(10**6): some = 0 for arg in args: # for each dice some += random.randint(1, arg) # sum of random faces results[some] += 1/10**6 # increase this propability return results def simulation2(*dice, num_trials=1_000_000): '''the instructor solution''' counts = Counter() for roll in range(num_trials): counts[sum((randint(1,sides) for sides in dice))] += 1 """ for outcome in range(len(dice), sum(dice)+1): print('{}\t {:0.2f}%'.format(outcome, counts[outcome]*100/num_trials)) """ return counts def simulation3(*args): '''my solution after seeing the instructor solution''' # initialize the results holder DS results = {i: 0 for i in range(len(args), sum(args)+1)} for sample in range(10**6): results[sum((random.randint(1, arg) for arg in args))] += 1/10**6 return results # test the solutions print(simulation.__doc__) results = simulation(4, 6, 6) for result in results: print("{:2} {:.2%}".format(result, results[result])) print(simulation2.__doc__) counts = simulation2(4, 6, 6) for outcome in range(len((4, 6, 6)), sum((4, 6, 6))+1): print('{}\t{:0.2f}%'.format(outcome, counts[outcome]*100/1_000_000)) print(simulation3.__doc__) results = simulation3(4, 6, 6) for result in results: print("{:2} {:.2%}".format(result, results[result])) # compare the performance print("My_solution : ", timeit.timeit("simulation(4, 6, 6)", setup="from __main__ import simulation", number=10)) print("instructor_solution : ", timeit.timeit("simulation2(4, 6, 6)", setup="from __main__ import simulation2", number=10)) print("My_solution2 : ", timeit.timeit("simulation3(4, 6, 6)", setup="from __main__ import simulation3", number=10))<file_sep>/Set_an_alarm.py """ this script is for solving the chalenge: Play_the_waiting_game from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ from playsound import playsound import time def play(timing, file, message): """my solution without seeing the instructor solution""" time.sleep(timing) playsound(file) print(message) input("enter any key to exit") return True # test print(play.__doc__) play(1, 'simple.wav', "work_time") <file_sep>/Find_all_list_items.py """ this script is for solving the chalenge: Find_all_list_items from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import timeit # this module to compare between the solutions import random def index_all(List, number): """my solution without seeing the instructor solution""" LL = [] for i in range(len(List)): if type(List[i]) != list: if List[i] == number: LL += [i] else: pos = index_all(List[i], number) for p in pos: if type(p) != list: LL += [[i]+[p]] else: LL += [[i]+p] return LL def index_all2(search_list, item): """the instructor solution""" indices = list() for i in range(len(search_list)): if search_list[i] == item: indices.append([i]) elif isinstance(search_list[i], list): for index in index_all2(search_list[i], item): indices.append([i]+index) return indices # test the solutions # my solution print(index_all.__doc__) print(index_all([[[1, 2, 3], 2, [1, 3]], [1, 2, 3]], 2)) assert index_all([1,2,2,4], 2) == [1, 2] assert index_all([1, [1,2,2], 2, 2, 3], 2) == [[1,1], [1,2], 2, 3] assert index_all([[[1, 2, 3], 2, [1, 3]], [1, 2, 3]], 2) == [[0, 0, 1], [0, 1], [1,1]] assert index_all([[[1, 2, 2, 3], 2, [1, 3]], [1, 2, 3]], 2) == [[0, 0, 1], [0, 0, 2], [0, 1], [1,1]] # instructor solution print(index_all2.__doc__) print(index_all2([[[1, 2, 3], 2, [1, 3]], [1, 2, 3]], 2)) print(index_all2([1,2,2,4], 2)) # assert index_all2([1,2,2,4], 2) == [1, 2] assert index_all2([1, [1,2,2], 2, 2, 3], 2) == [[1,1], [1,2], 2, 3] assert index_all2([[[1, 2, 3], 2, [1, 3]], [1, 2, 3]], 2) == [[0, 0, 1], [0, 1], [1,1]] assert index_all2([[[1, 2, 2, 3], 2, [1, 3]], [1, 2, 3]], 2) == [[0, 0, 1], [0, 0, 2], [0, 1], [1,1]] # prepared simple List = [[random.randint(1, 100) for i in range(random.randint(1, 100))] for j in range(random.randint(1, 100))] Item = random.randint(1, 100) # compare the performance print("My_solution : ", timeit.timeit("index_all(List,Item)", setup="from __main__ import index_all, List, Item", number=100)) print("instructor_solution : ", timeit.timeit("index_all2(List,Item)", setup="from __main__ import index_all2, List, Item", number=100)) <file_sep>/Count_unique_words.py """ this script is for solving the chalenge: Count unique words from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges i diden't used the comparing here, because my first aproach was wrong => usindg split ( . , ! ?) so i just used the Re as the instructor solution """ import re from collections import Counter import timeit # this module to compare between the solutions def count_words(path): '''my solution before seening the instructor solution''' with open(path, "r", encoding='utf8') as File: # open the giving file data = File.read().lower() # read the file as a lower-string data = data.replace(',',' ').replace('.',' ') # rep , . with spaces data = data.replace('!',' ').replace('?',' ') # rep ? ! with spaces data = data.split() # devide the string unto list where space or \n container = {} # DS to store the frequency for i in data: container[i] = container.get(i, 0) + 1 unique_words = list(container.keys()) # get the keys(unique words) unique_words.sort(key=lambda x:container[x], reverse=True) # sorte values top_20_words = {i: container[i] for i in unique_words[:20]} # top 20 words return top_20_words, len(unique_words) def count_words2(path): '''the instructor solution''' with open(path, encoding='utf-8') as file: all_words = re.findall(r"[0-9a-zA-Z-']+", file.read()) all_words = [word.upper() for word in all_words] word_counts = Counter() for word in all_words: word_counts[word] += 1 return word_counts, len(all_words) def count_words3(path): '''my solution after seening the instructor solution''' with open(path, "r", encoding='utf8') as File: # open the giving file data = File.read().lower() # read the file as a lower-string data = re.findall(r'[a-zA-Z][a-zA-Z-]+', data ) # get all words/numbers # data = data.split() # devide the string unto list where space or \n container = {} # DS to store the frequency #print(data) for i in data: container[i] = container.get(i, 0) + 1 unique_words = list(container.keys()) # get the keys(unique words) unique_words.sort(key=lambda x:container[x], reverse=True) # sorte values top_20_words = {i: container[i] for i in unique_words[:20]} # top 20 words return top_20_words, len(data) # tests print(count_words.__doc__) words, total = count_words('shakespeare.txt') print('Total Words: {}'.format(total)) print('\nTop 20 Words:') for word in words.items(): print('{}\t{}'.format(word[0], word[1])) print('-'*50) print(count_words2.__doc__) word_counts, total = count_words2('shakespeare.txt') print('Total Words: {}'.format(total)) print('\nTop 20 Words:') for word in word_counts.most_common(20): print(word[0], '\t', word[1]) print('-'*50) print(count_words3.__doc__) words, total = count_words3('shakespeare.txt') print('Total Words: {}'.format(total)) print('\nTop 20 Words:') for word in words.items(): print('{}\t{}'.format(word[0], word[1]))<file_sep>/solve_a_sodoku.py """ this script is for solving the chalenge: Solve_a_sodoku from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import timeit # this module to compare between the solutions import random import logging logging.basicConfig(level=logging.DEBUG) def check(grid): """this function will check if the provided puzzel is correct""" for row in grid: R = row for r in R: if r!=0 and R.count(r)>1: logging.debug('row conflict {}'.format(r)) logging.debug(R) return False gridp = list(zip(*grid)) for row in gridp: R = row for r in R: if r!=0 and R.count(r)>1: logging.debug('column conflict {}'.format(r)) logging.debug(R) return False groups = [] for i in range(3): for j in range(3): groups.append([G[j*3:j*3+3] for G in grid[i*3:i*3+3]]) groups = list(map(lambda x:x[0]+x[1]+x[2],groups)) for g in groups: R = g for r in R: if r!=0 and R.count(r)>1: logging.debug('inner grid coflict {}'.format(r)) logging.debug(R) return False return True def is_full(puzzel): """this function will check if the board is full""" for r in range(9): for c in range(9): if puzzel[r][c]==0: return False return True def solve(puzzel): """my solution before seen the instructor's solution""" print(puzzel) if is_full(puzzel): if check(puzzel): return puzzel return False for r in range(9): for c in range(9): if puzzel[r][c] == 0: for n in range(1,10): new_puzzel = [i for i in puzzel] new_puzzel[r][c] = n if check(new_puzzel): result = solve(new_puzzel) if result : return result return False return False # tests print(solve.__doc__) puzzel = [[0,0,1,0,0,0,0,0,0], [2,0,0,0,0,0,0,7,0], [0,7,0,0,0,0,0,0,0], [1,0,0,4,0,6,0,0,7], [0,0,0,0,0,0,0,0,0], [0,0,0,0,1,2,5,4,6], [3,0,2,7,6,0,9,8,0], [0,6,4,9,0,3,0,0,1], [9,8,0,5,2,1,0,6,0]] puzzel = [[1,0,3,4,5,6,7,8,9], [4,5,0,7,8,9,1,2,3], [7,8,9,1,2,3,4,5,6], [2,3,4,5,6,0,8,9,1], [5,6,7,8,9,1,2,3,4], [8,9,1,2,3,4,5,6,7], [3,4,5,0,7,8,9,1,2], [6,7,8,9,1,2,3,0,0], [9,1,2,3,4,5,6,7,0]] puzzel = [[2,3,0,4,1,5,0,6,8], [0,8,0,2,3,6,5,1,9], [1,6,0,9,8,7,2,3,4], [3,1,7,0,9,4,0,2,5], [4,5,8,1,2,0,6,9,7], [9,2,6,0,5,8,3,0,1], [0,0,0,5,0,0,1,0,2], [0,0,0,8,4,2,9,0,3], [5,9,2,3,7,1,4,8,6]] puzzel = [ [0, 0, 0, 0, 0, 0, 0, 0, 8], [0, 2, 0, 0, 5, 0, 7, 6, 0], [0, 6, 0, 0, 0, 0, 0, 0, 3], [5, 0, 0, 0, 0, 0, 2, 0, 7], [0, 3, 0, 0, 1, 0, 0, 0, 0], [2, 0, 0, 4, 0, 0, 0, 3, 0], [0, 0, 0, 6, 0, 0, 0, 0, 0], [8, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 2, 7, 0, 0, 4, 0]] puzzel = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7]] grid = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] print(solve(grid)) <file_sep>/Sending_an_email.py import smtplib smtp = smtplib.SMTP_SSL("172.16.31.10", 465)<file_sep>/Save_a_dictionary.py """ this script is for solving the chalenge: Find_all_list_items from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import timeit # this module to compare between the solutions import pickle def save_dict(dict_object, path): """Mysolution saving without seening the instructor solution""" try: f = open(path, "w") f.write(str(dict_object)) f.close() return True except Exception as e: print(e) return False def get_dict(path): """Mysolution reading without seening the instructor solution""" try: f = open(path, 'r') m = f.read() f.close() return eval(m) except Exception as e: print(e) return False def save_dict2(dict_object, path): """instructor solution saving""" with open(path, 'wb') as file: pickle.dump(dict_object, file) def get_dict2(path): """instructor solution reading""" with open(path, 'rb') as file: return pickle.load(file) # test the solution D = {1: 1, 2: 4} # my solution print(save_dict.__doc__) save_dict(d, 'test') print(get_dict.__doc__) D2 = get_dict('test') print(D == D2) # instructor solution print(save_dict2.__doc__) save_dict2(D, 'test') print(get_dict2.__doc__) D2 = get_dict2('test') print(D == D2) # preparing simple D = {i: i**2 for i in range(1500)} MY_FILE = "Test1.txt" INS_FILE = "Test2.txt" # compare the performance writing print("My_solution : ", timeit.timeit("save_dict(d, my_file)", setup="from __main__ import save_dict, D, MY_FILE", number=100)) print("instructor_solution : ", timeit.timeit("save_dict2(d, ins_file)", setup="from __main__ import save_dict2, D, INS_FILE", number=100)) # compare the performance reading print("My_solution : ", timeit.timeit("print(get_dict(my_file) == d)", setup="from __main__ import get_dict, d, my_file", number=100)) print("instructor_solution : ", timeit.timeit("print(get_dict2(ins_file) == d)", setup="from __main__ import get_dict2, d, ins_file", number=100)) <file_sep>/Find_prime_factor.py """ this script is for solving the chalenge: Find prime factors from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import timeit # this module to compare between the solutions def factor(n): """my solution before seeing the instructor solution""" for i in range(2, round(n**0.5)+1): if not(n % i) and factor(i) == [i]: return [i] + factor(n // i) return [n] def factor2(n): """my solution after seeing the instructor solution""" for i in range(2, round(n**0.5)+1): if not(n % i): # we dont need to check if the divider is prime return [i] + factor(n//i) return [n] def factor3(N): """this is the instructor solution""" factors = list() divisor = 2 while(divisor <= N): if (N % divisor) == 0: factors.append(divisor) N = N / divisor else: divisor += 1 return factors # to make sure that the the solution output the same result # my solution print(factor.__doc__) print(factor(2)) print(factor(3)) print(factor(4)) print(factor(5)) print(factor(6)) print(factor(100)) print(factor(630)) # my solution2 print(factor2.__doc__) print(factor2(2)) print(factor2(3)) print(factor2(4)) print(factor2(5)) print(factor2(6)) print(factor2(100)) print(factor2(630)) # instructor solution print(factor3.__doc__) print(factor3(2)) print(factor3(3)) print(factor3(4)) print(factor3(5)) print(factor3(6)) print(factor3(100)) print(factor3(630)) # compare the performance print("My_solution : ", timeit.timeit("factor(1234567891250)", setup="from __main__ import factor", number=100)) print("My_solution2 : ", timeit.timeit("factor2(1234567891250)", setup="from __main__ import factor2", number=100)) print("instructor_solution : ", timeit.timeit("factor3(1234567891230)", setup="from __main__ import factor3", number=100)) <file_sep>/Identify_a_palindrom.py """ this script is for solving the chalenge: identify a palidrome from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import re # the instuctor solution used the re module import timeit # this module to compare between the solutions def palindrom(S): """this is my solution without seeing the instructor solution""" SP = '' for i in S: j = ord(i) if j > 90: j = j - 32 if j >= 65 and j <= 90: SP += chr(j) return SP == SP[::-1] def palindrom2(phrase): """instuctor solution""" forwards = "".join(re.findall(r"[a-z]+", phrase.lower())) backwards = forwards[::-1] return forwards == backwards # my solution print(palindrom.__doc__) print(palindrom("Go hang a salami - I'm a lasagna hog")) # the instructor solution print(palindrom2.__doc__) print(palindrom2("Go hang a salami - I'm a lasagna hog")) print("My_solution : ", timeit.timeit('palindrom("Go hang a salami - \ I\'m a lasagna hog"*10000)', setup="from __main__ import palindrom", number=100)) print("instructor_solution : ", timeit.timeit('palindrom2("Go hang a salami - \ I\'m a lasagna hog"*10000)', setup="from __main__ import palindrom2", number=100)) <file_sep>/Sort_a_string.py """ this script is for solving the chalenge: Sort a string from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import timeit # this module to compare between the solutions def sort(phrase): """my solution without seeing the instructor solution""" words=phrase.split(" ") lower_words = phrase.lower().split(" ") words_dict=dict(zip(lower_words,words)) lower_words.sort() sorted_phrase = [] for word in lower_words: sorted_phrase += [words_dict[word]] return " ".join(sorted_phrase) def sort2(phrase): """the instructor solution""" words = phrase.split() words = [w.lower() + w for w in words] words.sort() words = [w[len(w)//2:] for w in words] return " ".join(words) # to make sure that the the solution output the same result # my solution print(sort('banana ORANGE apple')) # instructor solution print(sort2('banana ORANGE apple')) # compare the performance print("My_solution : ", timeit.timeit("sort('banana ORANGE apple'*100000)", setup="from __main__ import sort", number=100)) print("instructor_solution : ", timeit.timeit("sort2('banana ORANGE apple'*100000)", setup="from __main__ import sort2", number=100))<file_sep>/Play_the_waiting_game.py """ this script is for solving the chalenge: Play_the_waiting_game from: Python Code Challenges link: https://www.linkedin.com/learning/python-code-challenges """ import timeit # this module to compare between the solutions import time import random def wait(): """My solution before seening the instuctor solution""" x_time = random.randint(2,4) print("your target time is {}\nseconds.".format(x_time)) print(" ---Press Enter to Begin---") input() t1 = time.time() print("...Press Enter again after\n{} seconds...".format(x_time)) input() t2 = time.time() result = t2-t1 print("Elapsed time: {:.3f} seconds".format(result)) if result < x_time: print('({:.3f} seconds too fast)'.format(x_time-result)) elif result >x_time: print('({:.3f} seconds too slow)'.format(result-x_time)) else: print("amazing") # test the solution, we dont need to compare it with the instruction # solution, there is no calculation here. # my solution print(wait.__doc__) wait()
3b61a8cb8f6df8bd9abb41720a662178b980d430
[ "Python" ]
11
Python
HichamDz38/python-code-challenges
79f0d28fc5557caa4cc583261cfbf00c75908955
748f0e921a4b95e14604243e80925cd5ac6edc23
refs/heads/master
<file_sep>class Favorite < ApplicationRecord belongs_to :user belongs_to :taste end <file_sep>class TastesController < ApplicationController before_action :authorized, except: [:index, :create, :show, :update, :fetch] def fetch @query = request.headers['query'] @genre = request.headers['genre'] @likes = request.headers['likes'] @result = RestClient.get("https://tastedive.com/api/similar?k=332551-SchoolPr-C1J9RIC5&info=1&q=#{@query}&type=#{@genre}") @api_data = JSON.parse(@result.body) render json: @api_data end def index @tastes = Taste.all render json: @tastes, status: :ok end def create @taste = Taste.find_or_create_by!(name: tastes_params[:name], genre: tastes_params[:genre], teaser: tastes_params[:teaser], wUrl: tastes_params[:wUrl], yUrl: tastes_params[:yUrl], yID: tastes_params[:yID]) if @taste.save currentUser = User.find(tastes_params[:userID]) if currentUser.tastes.any?{|taste| taste['name'] === @taste['name']} render json: @taste, status: :ok else @taste.users << currentUser render json: @taste, status: :created end else render json: @taste.errors.full_messages, status: :unprocessable_entity end end def show @taste = Taste.find(params[:id]) render json: @taste, status: :ok end def update @taste = Taste.find(params[:id]) @taste.update(likes: tastes_params[:likes]) render json: @taste, status: :ok end private def tastes_params params.permit(:name, :genre, :teaser, :wUrl, :yUrl, :yID, :userID, :likes) end end <file_sep>class FavoritesController < ApplicationController before_action :authorized, except: [:index, :create, :destroy] def index @favorites = Favorite.all render json: @favorites, status: :ok end def create @favorite = Favorite.new(user_id: favorite_params['user_id'], taste_id: favorite_params['taste_id']) if @favorite.save render json: @favorite, status: :created else render json: @favorite.errors.full_messages, status: :unprocessable_entity end end def destroy currentUser = User.find(favorites_params[:user_id]) @favorite = currentUser.favorites.find_by(taste_id: favorites_params[:taste_id]) if @favorite.destroy render json: @favorite, status: :created else render json: @favorite.errors.full_messages, status: :unprocessable_entity end end private def favorites_params params.permit(:user_id, :taste_id) end end<file_sep>class RemoveTypeFromTastes < ActiveRecord::Migration[5.1] def change remove_column :tastes, :type, :string end end <file_sep>class AddLikesToTastes < ActiveRecord::Migration[5.1] def change add_column :tastes, :likes, :integer end end <file_sep>Rails.application.routes.draw do resources :tastes resources :favorites resources :users post '/login', to: 'auth#create' get '/searched-wavelength', to: 'tastes#fetch' delete '/remove-wavelength', to: 'favorites#destroy' end <file_sep>[Visit Get On My Wavelength!]() ## Get On My Wavelength Search for your favorite artists, movies, shows, podcasts, books, and games that you love and discover recommendations on the same 'wavelength' as them! Filter those recommendations based on type and explore more information on each result through an embedded YouTube video and a Wikipedia summary. View trending searches to find inspiration on what other users have been searching and liking. Add things that you are interested in exploring to your ~ Wavelength ~. ## `Live Application` This is the backend that powers Get On My Wavelength. <file_sep>class User < ApplicationRecord has_many :favorites has_many :tastes, through: :favorites has_secure_password validates :name, presence: true, uniqueness: true validates :password, presence: true end <file_sep>class AddGenreToTastes < ActiveRecord::Migration[5.1] def change add_column :tastes, :genre, :string end end <file_sep>class CreateTastes < ActiveRecord::Migration[5.1] def change create_table :tastes do |t| t.string :name t.string :type t.string :teaser t.string :wUrl t.string :yUrl t.string :yID t.timestamps end end end
2083ec37daa27f78fa5fb8b5c2617593aaa85f98
[ "Markdown", "Ruby" ]
10
Ruby
syun07/backend-taste-maker-app
ed9b136762b0e95c3b2395f54fd38884b386d9b2
84d260a81d49db317d5c6bc19decca6db1aa5052
refs/heads/master
<file_sep><?php require("../../assets/php/include/loginhandler.php"); require("../../assets/php/modules/omxplayer.php"); require("../../assets/php/modules/io.php"); $nsfw = isset($_GET["nsfw"]) or isset($_POST["nsfw"]); $libs = getLibs($nsfw); $url = ""; if (isset($_GET["play"])) { $url = $_GET["play"]; } if (isset($_POST["p"])) { require("../../assets/php/modules/phpquery.php"); $url = $_POST["p"]; foreach ($libs as $l) { if ($l->isFromHere($url)) { $url = $l->extract($url); break; } } $a = isset($_POST["local"]) ? "local" : "hdmi"; shell_exec("export DISPLAY=0.0 && sudo -u pi screen -S omxplayer -d -m omxplayer -o $a -b \"$url\""); header("Location: index.php"); } if (isset($_GET["stop"])) { shell_exec("sudo -u pi screen -S omxplayer -X quit"); header("Location:index.php"); } else if(isset($_GET["pause"])) { shell_exec("sudo -u pi screen -S omxplayer -X stuff \"p\""); header("Location:index.php"); } else if(isset($_GET["prev"])) { shell_exec("sudo -u pi screen -S omxplayer -X stuff \"^[[D\""); header("Location:index.php"); } else if(isset($_GET["next"])) { shell_exec("sudo -u pi screen -S omxplayer -X stuff \"^[[C\""); header("Location:index.php"); } ?><!doctype html> <html> <head> <title>Player - Raspberry Pi</title> <link rel="stylesheet" href="../../assets/css/style.css"> <link rel="icon" href="../../assets/images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <?php $page = 1; include("../../assets/php/include/menu.php"); ?> <div class="container content"> <?php $d = "0"; if (count(getScreens()) == 1) { $i = trim(shell_exec("sudo -u pi ../../assets/bash/omxcontrol.sh status")); if ($i != "") { $i = explode("\n", $i); $d = array_pop(explode(" ", $i[0])); $p = array_pop(explode(" ", $i[1])); $p = $p / (float)$d * 100; $s = array_pop(explode(" ", $i[2])); } else { $d = 999999999999; $p = 0; $s = "false"; } if ($s == "false") { $s = "Pause"; } else { $s = "Resume"; } echo ' <div class="block"> <h2>Video Controls</h2> <div class="slider"> <div class="progressbar"> <div class="progress" style="width: ' . $p . '%;" id="progress"></div> </div> <div class="dragger" id="drag" style="left: ' . $p . '%;"> </div> </div> <br> <br> <div class="row"> <div class="col-25"> <a href="?stop" class="btn fullwidth">Stop</a> <br> <br> </div> <div class="col-25"> <a href="?pause" class="btn btn-accent fullwidth">' . $s . '</a> <br> <br> </div> <div class="col-25"> <a href="?prev" class="btn fullwidth">-30 Seconds</a> <br> <br> </div> <div class="col-25"> <a href="?next" class="btn fullwidth">+30 Seconds</a> <br> <br> </div> </div> </div>'; } else { $lib = 0; $q = ''; if (isset($_POST["q"])) { $lib = $_POST["lib"]; $q = $_POST["q"]; require("../../assets/php/modules/phpquery.php"); $search_results = $libs[$lib]->search($q); } if ($nsfw) { $nsfw = ' <input type="hidden" name="nsfw" value="enabled">'; } else { $nsfw = ''; } echo ' <div class="row"> <div class="col-50"> <div class="block"> <h2>Play URL</h2> <form method="post" class="row">' . $nsfw . ' <div class="col-50"> <input type="text" name="p" value="' . $url . '" class="fullwidth" placeholder="URL..." required> <br> <br> </div> <div class="col-25"> <label> <input type="checkbox" name="local" value="val"> Local Audio </label> <br> <br> </div> <div class="col-25"> <input type="submit" class="btn btn-accent fullwidth" value="Play"> <br> <br> </div> </form> </div> </div> <div class="col-50"> <div class="block"> <h2>Search</h2> <form method="post" class="row">' . $nsfw . ' <div class="col-50"> <input type="text" name="q" value="' . $q . '" class="fullwidth" placeholder="Query..."> <br> <br> </div> <div class="col-25"> <select name="lib" class="fullwidth">'; foreach ($libs as $k=>$l) { $s = ''; if ($k == $lib) { $s = ' selected'; } echo ' <option value="' . $k . '"' . $s . '>' . $l->getDisplayName() . '</option>'; } echo ' </select> <br> <br> </div> <div class="col-25"> <input type="submit" class="btn btn-accent fullwidth" value="Search"> <br> <br> </div> </form> </div> </div> </div>'; } if (isset($search_results)) { echo ' <div class="block fullwidth"> <h2>Results</h2>'; $i = 0; foreach ($search_results as $url=>$information) { $u = urlencode($url); if ($nsfw) { $u .= "&nsfw"; } if ($i == 0) { echo ' <div class="row">'; } echo ' <div class="col-50"> <a href="?play=' . $u . '" class="row"> <div class="col-50"> ' . utf8_decode($information[2]) . ' </div> <div class="col-50"> ' . utf8_decode($information[0]) . ' <br> <span class="muted">' . utf8_decode($information[1]) . '</span> </div> </a> <br> <br> </div>'; $i++; if ($i == 2) { $i = 0; echo ' </div>'; } } echo ' </div>'; } ?> </div> <script type="text/javascript">var videolength = <?php echo $d; ?>;</script> <script type="text/javascript" src="../../assets/js/slider.min.js"></script> </body> </html><file_sep><?php function isJukebox() { $s = trim(shell_exec("sudo -u pi screen -ls | grep jukebox")); return $s !== ""; } function startJukebox() { @unlink("/tmp/jukebox.log"); file_put_contents("/tmp/jukebox.log", "This is jukebox. Let's listen to some music\n"); chmod("/tmp/jukebox.log", 0766); exec("sudo -u pi DISPLAY=:0 screen -d -S jukebox -m python jukebox.py /tmp/jukebox.log"); header("Location: index.php"); } function pauseJukebox() { exec("sudo -u pi screen -S jukebox -X stuff \" \""); } function killJukebox() { exec("sudo -u pi screen -S jukebox -X stuff \"q\""); header("Location: index.php"); } function nextJukebox() { exec("sudo -u pi screen -S jukebox -X stuff \"n\""); header("Location: index.php"); } function prevJukebox() { exec("sudo -u pi screen -S jukebox -X stuff \"p\""); header("Location: index.php"); } function shuffleJukebox() { exec("sudo -u pi screen -S jukebox -X stuff \"r\""); header("Location: index.php"); } function appendJukebox($a) { $p = explode("\n", trim(file_get_contents("playlist.txt"))); file_put_contents("playlist.txt", str_replace("//", "/", base64_decode($_GET["a"])) . "\n", FILE_APPEND); if (strlen($p) == 0) { nextJukebox(); } } function delJukebox($a) { $p = explode("\n", trim(file_get_contents("playlist.txt"))); $n = false; $o = ""; $a = base64_decode($a); foreach ($p as $k) { if (strpos($k, $a) !== false) { $t = explode(" ", $k); if ($t[0] == "active") { $n = true; } } else { $o .= $k . "\n"; } } file_put_contents("playlist.txt", $o); if ($n) { nextJukebox(); } else { header("Location: index.php"); } } function getInformation() { exec("sudo -u pi screen -S jukebox -X stuff \"i\""); $c = trim(@file_get_contents("/tmp/jukebox.log")); $c = explode("\n", $c); $c = array_pop($c); $t = (array)json_decode(base64_decode($c)); if ($t == array()) { return array("title"=>"Fetching data...", "album"=>"", "artist"=>"", "time"=>"0:00", "paused"=>false); } else { $s = $t["time"] % 60; $m = ($t["time"] - $s) / 60; if ($s < 10) { $s = "0" . $s; } $t["time"] = "$m:$s"; return $t; } } ?><file_sep><?php function listdir($dir) { if (substr($dir, -1) != "/") { $dir .= "/"; } $d = opendir($dir); $o = array("dirs"=>array(), "files"=>array()); while (($j = readdir($d)) !== false) { if ($j != ".") { if (is_dir($dir . $j)) { $o["dirs"][] = $j; } else { $o["files"][] = $j; } } } closedir($d); sort($o["dirs"]); sort($o["files"]); return $o; } function walkdir($d) { if (substr($d, -1) != "/") { $d .= "/"; } $o = array(); foreach (listdir($d) as $k) { $j = $d . $k; if (is_dir($j)) { $o = array_merge($o, walkdir($j)); } else { $o[] = $j; } } return $o; } ?><file_sep><?php require("../../assets/php/include/loginhandler.php"); function getScreens() { $s = explode("\n", trim(shell_exec("screen -ls | grep download"))); $t = array(); foreach ($s as $k) { $k = trim($k); if ($k === "") { continue; } else { $t[] = array_shift(explode("\t", array_pop(explode("download.", $k)))); } } return $t; } function startDownload($u) { global $DOWNLOAD_DIR; $l = "/tmp/downloads"; if (!file_exists($l)) { mkdir($l); } $id = uniqid(); file_put_contents("$l/$id", basename($u) . ": " . "0"); exec("screen -d -S download.$id -m python pget.py \"$u\" \"$DOWNLOAD_DIR\" \"$l/$id\""); } function killDownload($id) { exec("screen -S \"download.$id\" -X quit"); } function togglePause($id) { exec("screen -S \"download.$id\" -X stuff ' '"); } function getInformation($s) { $f = explode("\n", trim(file_get_contents("/tmp/downloads/$s"))); $n = array_shift(explode(":", $f[0])); $e = implode("\n", array_slice($f, -2, 2, true)); $s = strpos($e, "[Paused]") !== false; $p = array_pop(explode(":", array_pop($f))) . "%"; return array("file"=>$n, "progress"=>$p, "paused"=>$s); } if (isset($_POST["u"])) { startDownload($_POST["u"]); header("Location: index.php"); } else if (isset($_GET["k"])) { killDownload($_GET["k"]); header("Location: index.php"); } else if (isset($_GET["p"])) { togglePause($_GET["p"]); header("Location: index.php"); } $screens = getScreens(); $info = array(); foreach ($screens as $screen) { $info[$screen] = getInformation($screen); } ?><!doctype html> <html> <head> <title>Downloader - Raspberry Pi</title> <link rel="stylesheet" href="../../assets/css/style.css"> <link rel="icon" href="../../assets/images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <?php $page = 3; include("../../assets/php/include/menu.php"); ?> <div class="container content"> <div class="block fullwidth"> <h2>Add new download</h2> <form method="post" class="row"> <div class="col-75"> <input type="text" placeholder="http://example.com/file.zip" name="u" class="fullwidth" required> <br> </div> <div class="col-25"> <input type="submit" class="btn btn-accent fullwidth" value="Start"> <br> <br> </div> </form> </div> <?php if ($info !== array()) { echo ' <div class="block fullwidth"> <h2>Active downloads</h2>'; foreach ($info as $id=>$i) { echo ' <div class="row"> <div class="col-75"> <i class="cut-text"> <a href="?k=' . $id . '"> <i class="cross"></i> </a> <a href="?p=' . $id . '"> <i class="' . ($i["paused"] ? "play" : "pause") . '"></i> </a> ' . $i["file"] . ' </i> </div> <div class="col-25"> <div class="progressbar"> <div class="progress" style="width: ' . $i["progress"] . '"></div> </div> </div> </div>'; } echo ' <br> </div>'; } ?> </div> </body> </html><file_sep><?php require("../../assets/php/include/loginhandler.php"); require("../../assets/php/modules/io.php"); require("../../assets/php/modules/jukebox.php"); if (isset($_GET["start"])) { startJukebox(); } else if (isset($_GET["pause"])) { pauseJukebox(); } else if (isset($_GET["stop"])) { killJukebox(); } else if (isset($_GET["next"])) { nextJukebox(); } else if (isset($_GET["prev"])) { prevJukebox(); } else if (isset($_GET["shuffle"])) { shuffleJukebox(); } else if (isset($_GET["a"])) { appendJukebox($_GET["a"]); } else if (isset($_GET["del"])) { delJukebox($_GET["del"]); } $dir = $JUKEBOX_DIR; if (isset($_GET["d"])) { $dir = base64_decode($_GET["d"]); } if (substr($dir, -1) != "/") { $dir .= "/"; } $ACTIVE = isJukebox(); ?> <!doctype html> <html> <head> <title>Jukebox - Raspberry Pi</title> <link rel="stylesheet" href="../../assets/css/style.css"> <link rel="stylesheet" href="../../assets/css/jukebox.css"> <link rel="icon" href="../../assets/images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <?php $page = 2; include("../../assets/php/include/menu.php"); ?> <div class="container content"> <div class="row"> <div class="col-50"> <div class="block"> <h2>Now Playing</h2> <div class="row"> <div class="col-50"> <div class="circle"> <div class="content"> <?php if (!$ACTIVE) { echo ' <a href="?start"> <i class="play-icon"></i> </a>'; } else { $information = getInformation(); echo ' <a href="?pause"> <i class="' . ($information["paused"] ? "play" : "pause") . '-icon"></i> </a> <span class="muted"> ' . $information["time"] . ' </span>'; } ?> </div> </div> <br> </div> <div class="col-5">&nbsp;</div> <div class="col-40"> <?php if ($ACTIVE) { echo ' <h2 class="accent">' . $information["title"] . '</h2> ' . $information["artist"] . ' <br> <span class="muted">' . $information["album"] . '</span> <br> <br> <br> <div class="centered fullwidth"> <a href="?prev"> <i class="prev-icon"></i> </a> <a href="?stop"> <i class="stop-icon"></i> </a> <a href="?next"> <i class="next-icon"></i> </a> </div>'; } else { echo ' <h2 class="accent">Nothing</h2> No Artist <br> <span class="muted">No Album</span>'; } ?> </div> </div> </div> </div> <div class="col-50"> <div class="block"> <h2 style="display: inline-block; line-height: 200%;">Playlist</h2> <a href="?shuffle" class="btn btn-accent pull-right">Shuffle</a> <ul class="playlist"> <?php $p = trim(@file_get_contents("playlist.txt")) or ""; $k = explode("\n", $p); foreach ($k as $t) { if ($t == "") { continue; } $j = explode(" ", $t); if (count($j) > 1 and $j[0] == "active") { $class = ' active'; array_shift($j); $t = implode(" ", $j); } else { $class = ''; } $j = basename($t); $t = base64_encode($t); echo ' <li class="cut-text' . $class . '"> <a href="?del=' . $t . '"><i class="cross"></i></a> <a href="?play=' . $t . '"> ' . $j . ' </a> </li>'; } ?> </ul> </div> </div> </div> <div class="block"> <h2>Add to playlist</h2> <?php $d = listdir($dir); foreach ($d["dirs"] as $_) { $l = $dir . $_; if ($_ == "..") { $k = explode("/", $dir); array_pop($k); array_pop($k); $l = implode("/", $k); } if (strlen($l) < strlen($JUKEBOX_DIR)) { continue; } $url = base64_encode($l); echo ' <a class="fullwidth" href="?d=' . $url . '"> <img src="../../assets/images/folder-icon.png" height="20px"> <b>' . utf8_decode($_) . '</b> </a> <br> <br>'; } foreach ($d["files"] as $_) { $l = $dir . "/$_"; $url = base64_encode($l); echo ' <a class="fullwidth" href="?a=' . $url . '"> <img src="../../assets/images/music-icon.png" height="20px"> ' . utf8_decode($_) . ' </a> <br> <br>'; } ?> </div> </div> </body> </html><file_sep><?php $USE_PASSWORD = false; #use a password for PiDash $PASSWORD = "<PASSWORD>"; #use the md5.php to create your own. default: raspberry $MAX_TRIES = 3; #maximum number of false login passwords $WAIT_FOR_IT = 30; #seconds to reset the $MAX_TRIES $VPN = false; #show vpn enable/disable button $VPN_CONFIG = "/home/pi/vpn/raspberry.conf"; #openvpn config file $JUKEBOX_DIR = "/home/pi/music"; #directory where the music is played from, make sure the permission is at least 0756 $DOWNLOAD_DIR = "/home/pi/download"; #output-dir of the downloads. make sure the dir is accessible for the webserver-user (e.g. www-data) ?><file_sep><?php interface ILibrary { function getDisplayName(); function isNSFW(); function isFromHere($url); function search($query); function extract($url); } ?> <file_sep>#!/usr/bin/python2 import sys import urllib2 import thread import time import os import os.path import tty import termios class pget(object): def __init__(self, url, path=".", logfile=None): self.paused = False self.progress = 0 self.path = path self.url = url self.logfile = logfile def log(self, msg, nn=False): if self.logfile != None: with open(self.logfile, "a") as f: f.write(msg.strip() + "\n") else: if nn: print msg, else: print msg def get(self): n = self.url.split("/")[-1] N = os.path.join(self.path, n) self.tempname = N + ".pydownload" if os.path.exists(self.tempname): mode = "ab" self.r = urllib2.Request(self.url, headers={"Range": "bytes=%s-"%os.path.getsize(self.tempname)}) else: mode = "wb" self.r = urllib2.Request(self.url) self.u = urllib2.urlopen(self.r) with open(self.tempname, mode) as f: m = self.u.info() fs = int(m.getheaders("Content-Length")[0]) bs = 8192 d = 0 waitForConnection = False while True: if self.paused: time.sleep(0.5) waitForConnection = True else: if waitForConnection: time.sleep(1) waitForConnection = False if self.u == None: time.sleep(0.5) continue b = self.u.read(bs) if not b: break d += len(b) f.write(b) self.progress = d*100.0 / fs o = n + ": %0.2f"%self.progress self.log(o + " "*len(o) + "\r", True) self.u.close() os.rename(self.tempname, N) os._exit(1) def togglePause(self): if self.paused: self.u = urllib2.urlopen(self.r) else: self.u.close() self.u = None self.r = urllib2.Request(self.url, headers={"Range": "bytes=%s-"%os.path.getsize(self.tempname)}) self.paused = not self.paused def read(self): fd = sys.stdin.fileno() s = termios.tcgetattr(fd) c = None try: tty.setraw(sys.stdin.fileno()) c = ord(sys.stdin.read(1)) finally: termios.tcsetattr(fd, termios.TCSADRAIN, s) return c if __name__ == "__main__": l = len(sys.argv) if l == 2: p = pget(sys.argv[1]) elif l == 3: p = pget(sys.argv[1], sys.argv[2]) elif l == 4: p = pget(sys.argv[1], sys.argv[2], sys.argv[3]) else: print "Usage: pget.py URL [OUTPUT_DIR] [LOGFILE]" sys.exit(1) thread.start_new_thread(p.get, ()) while p.progress != 100: i = p.read() if i == 32: p.togglePause() if p.paused: p.log("[Paused]: %0.2f"%p.progress)<file_sep><?php $l = ''; if (isset($_SESSION["login"])) { $l = ' data-logout="logout"'; } echo ' <div class="navbar" id="menu"' . $l . '> <div class="container">'; if (!isset($ROOT)) { $ROOT = "../.."; } echo ' <a class="brand" href="' . $ROOT . '">Raspberry Pi</a> <ul>'; $dirs = array( "Dashboard"=>array("", "in-mobile"), "Player"=>array("player", ""), "Jukebox"=>array("jukebox", ""), "Downloader"=>array("download", ""), "Filebrowser"=>array("explorer", "") ); $i = 0; foreach ($dirs as $n=>$d) { if ($i == $page) { $d[1] .= " active"; } echo ' <li class="' . $d[1] . '"> <a href="' . $ROOT . '/' . $d[0] . '">' . $n . '</a> </li>'; $i += 1; if ($i == 1) { $ROOT .= "/pages"; } } if ($l != '') { echo ' <li class="logout"> <a href="?logout">Logout</a> </li>'; } ?> </ul> <a href="#menu" class="menu-toggle in-mobile"> <i class="chevron"></i> </a> <a href="#close" class="menu-toggle menu-toggle-active in-mobile"> <i class="chevron"></i> </a> </div> </div> <file_sep><?php $accent = "#3ebc84"; $p = 0.75; if (isset($_GET["p"])) { $p = $_GET["p"]; } if ($p > 1) { $p = 1; } function hex2rgb($h) { $h = str_replace("#", "", $h); if (strlen($h) == 3) { $h = $h[0] . $h[0] . $h[1] . $h[1] . $h[2] . $h[2]; } $r = substr($h, 0, 2); $g = substr($h, 2, 2); $b = substr($h, 4, 2); return array(hexdec($r), hexdec($g), hexdec($b)); } $w = 700; $h = $w / 2; $i = imagecreatetruecolor($w, $h); #1000, 500); $accent = hex2rgb($accent); $accent = imagecolorallocate($i, $accent[0], $accent[1], $accent[2]); $white = imagecolorallocate($i, 255, 255, 255); $gray = imagecolorallocate($i, 242, 242, 242); imagefill($i, 0, 0, $white); imagefilledellipse($i, $w /2 , $h / 2, $w / 2, $w / 2, $gray); #500, 250, 500, 500, $gray); if ($p > 0) { imagefilledarc($i, $w / 2, $h / 2 - 1, $h, $h, 270, (int)270 - 360*(1 - $p), $accent, IMG_ARC_PIE); } imagefilledellipse($i, $w / 2, $h / 2, $h * 0.8, $h * 0.8, $white); header("Content-type: image/jpeg"); imagejpeg($i); imagedestroy($i); ?><file_sep><?php require("../../assets/php/include/loginhandler.php"); require("../../assets/php/modules/io.php"); $dir = "/"; if (isset($_GET["d"])) { $dir = base64_decode($_GET["d"]); if (substr($dir, -1) != "/") { $dir .= "/"; } } ?><!doctype html> <html> <head> <title>Filebrowser - Raspberry Pi</title> <link rel="stylesheet" href="../../assets/css/style.css"> <link rel="icon" href="../../assets/images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <?php $page = 4; include("../../assets/php/include/menu.php"); ?> <div class="container content"> <div class="block fullwidth"> <h2 class="cut-text">Index of <b class="accent"><?php echo $dir; ?></b></h2> <?php $d = listdir($dir); foreach ($d["dirs"] as $_) { $l = $dir . $_; if ($l == "/..") { continue; } else if ($_ == "..") { $k = explode("/", $dir); array_pop($k); array_pop($k); $l = implode("/", $k); } $url = base64_encode($l); echo ' <a class="row" href="?d=' . $url . '"> <div class="col-50"> <img src="../../assets/images/folder-icon.png" height="20px"> <b>' . $_ . '</b> </div> </a>'; } $k = array('B','kB','MB','GB'); foreach ($d["files"] as $_) { $l = $dir . $_; $url = base64_encode($l); $b = sprintf("%u", filesize($l)); $s = (int)(strlen($b) / 3); $s = round($b / pow(1024, $s), 2) . $k[$s]; $d = date("F d Y, H:i:s", filemtime($l)); echo ' <a class="row" href="getfile.php?f=' . $url . '"> <div class="col-50"> <img src="../../assets/images/file-icon.png" height="20px"> ' . $_ . ' </div> <div class="col-25"> ' . $s . ' </div> <div class="col-25"> ' . $d . ' </div> </a>'; } ?> </div> </div> </body> </html><file_sep><?php function strip($s) { while (strpos($s, " ") !== false) { $s = str_replace(" ", " ", $s); } return $s; } class Stats { function CPU() { $o = array("model"=>"", "load"=>array("1"=>0, "5"=>0, "15"=>0)); $load = file_get_contents("/proc/loadavg"); $cpu = file_get_contents("/proc/cpuinfo"); $loadavg = explode(" ", $load); $o["load"]["1"] = ($loadavg[0] + 0)*100; $o["load"]["5"] = ($loadavg[1] + 0)*100; $o["load"]["15"] = ($loadavg[2] + 0)*100; $model = explode("model name", $cpu); $model = substr(trim($model[1]), 2); $model = explode("stepping", $model); $model = trim($model[0]); $o["model"] = $model; return $o; } function Temperature() { $t = shell_exec("sudo vcgencmd measure_temp"); return array_shift(explode("'", array_pop(explode("=", $t)))); } function DiskSpace() { $result= Array(); foreach (Stats::get_disks() as $disk) { $total = disk_total_space($disk); $free = disk_free_space($disk); $f = round($free / (float)($total), 2) * 100; $u = 100 - $f; $result[]=array("label"=>$disk,"total"=>round($total/1024/1024/1024, 2), "free"=>$f, "used"=>$u); } return $result; } function RAM() { $freem = explode(" ", strip(shell_exec("free -m"))); $t = $freem[7]; $u = $freem[14]; $f = $t - $u; $u = round($u / (double)$t * 100, 0); return array("total"=>$t, "free"=>$f, "used"=>$u); } function Version() { $r = file_get_contents("/etc/os-release"); $o = explode("PRETTY_NAME=\"", $r); $o = explode("\"", $o[1]); return $o[0]; } function Uptime() { $time = explode(" ", file_get_contents("/proc/uptime")); $t = time() - $time[0]; $start = date("d.m.Y - H:i:s", $t); return $start; } function Wifi() { $i = explode("\n", trim(shell_exec("iwconfig"))); $o = array("essid"=>"", "ap"=>"", "quality"=>"", "signal"=>"", "noise"=>""); $t = explode("\"", strip($i[0])); $t = explode("\"", $t[1]); $o["essid"] = $t[0]; $t = explode(": ", strip($i[1])); $o["ap"] = trim($t[1]); $k = explode(" ", strip($i[5])); $t = explode("=", $k[2]); $t = explode("/", $t[1]); $o["quality"] = $t[0]; $t = explode("=", $k[4]); $t = explode("/", $t[1]); $o["signal"] = $t[0]; $t = explode("=", $k[6]); $t = explode("/", $t[1]); $o["noise"] = $t[0]; return $o; } function Network() { $o = array(); $i = explode("\n\n", trim(shell_exec("sudo ifconfig"))); foreach ($i as $k) { $n = array_shift(explode(" ", $k)); if ($n == "lo") { continue; } $l = explode("\n", $k); $mac = array_pop(explode(" ", trim($l[0]))); $mac = str_replace("-", ":", strtolower(substr($mac, 0, 17))); $ips = explode(":", trim($l[1])); $ip = explode(" ", $ips[1]); $extra = array_shift(explode(" ", $ips[2])); $mask = array_shift(explode(" ", $ips[3])); $o[$n] = array("MAC"=>$mac, "IPv4"=>$ip[0], "Mask"=>$mask, $ip[2]=>$extra); } return $o; } function get_disks(){ $data=`mount | grep -E "sd|/ "`; $disks_line=preg_split("/\\r\\n|\\r|\\n/",$data); $disks=Array(); foreach($disks_line as $line) { $val=explode(' ',$line); if (sizeof($val) > 1) $disks[]=$val[2]; } return $disks; } } ?> <file_sep><?php require_once("ILibrary.php"); class ARD implements ILibrary { function getDisplayName() { return "Example library"; } function isNSFW() { return false; } function isFromHere($url) { return false; } function search($query) { return array(); } function extract($url) { return $url; } } ?> <file_sep><?php session_start(); require("config.php"); if (isset($_SESSION["login"]) or !$USE_PASSWORD) { header("Location: index.php"); } if (!isset($_SESSION["nice_try"])) { $_SESSION["nice_try"] = array(); } $wait = false; $wait_diff = time() - key(array_slice($_SESSION["nice_try"], -1, 1, TRUE)); if ($wait_diff > $WAIT_FOR_IT) { $_SESSION["nice_try"] = array(); } if (isset($_POST["p"])) { if (md5($_POST["p"]) == $PASSWORD) { $_SESSION["login"] = true; header("Location: index.php"); } else { $_SESSION["nice_try"][time()] = $_POST["p"]; } } if (count($_SESSION["nice_try"]) == $MAX_TRIES) { $wait = true; } ?> <html> <head> <link rel="stylesheet" href="assets/css/style.css"> <link rel="stylesheet" href="assets/css/login.css"> <link rel="icon" href="assets/images/favicon.ico"> <title>Login - Raspberry Pi</title> </head> <body> <div class="vcenter container"> <div class="circle"> <div class="logo vcenter"> &pi; </div> </div> <?php if ($wait) { echo ' Wrong password. Please wait ' . ($WAIT_FOR_IT - $wait_diff) . ' seconds'; } else { echo ' <form method="post" action="" class="row"> <input type="password" name="p" placeholder="<PASSWORD>" autofocus required> </form>'; } ?> </div> </body> </html><file_sep># pidash --- A dashboard for the Raspberry Pi ## Installation: - Install a webserver like `nginx` from their official repositories - Install `php5-fpm` and configure it to work with your webserver - Download this repository to your webservers base directory - Run the `setup.sh` in the root-directory of the repository as your webserver-user (e.g. *www-data*) - Open up your webbrowser and navigate to the Pi's webserver you've just set up - Half optional: Allow www-data to `sudo shutdown` - Optional: modify the `config.php` in the root-directory ## Features - Dashboard with system relevant information - An OMXPlayer remote control - A Jukebox for listening to your private music library on the Pi - A HTTP-downloadserver - A basic filebrowser - A customizable login with a wait function for wrong passwords - If it's installed: OpenVPN shortcut - Responsive UI ## Screenshots **Login screen** ![Login screen](http://i.imgur.com/zUBxo6l.png) **Dashboard** On Desktop ![Dashboard desktop](http://i.imgur.com/D5oT87T.png) On Mobile ![Dashboard mobile](http://i.imgur.com/RRZACu4.png) **Player** Searching a movie ![Player mediathek](http://i.imgur.com/Gi7waHd.png) When the movie is playing ![Player playing](http://i.imgur.com/wozvYHc.png) **Jukebox** ![Jukebox](http://i.imgur.com/kIGhBxu.png) **Downloader** ![Downloader](http://i.imgur.com/aHTIIRK.png) **Filebrowser** ![Filebrowser](http://i.imgur.com/DzE8xsK.png) <file_sep>#!/usr/bin/python import sys import os import os.path import pygame import time import tty import termios import thread import random import subprocess import json class Jukebox(object): def __init__(self): os.system("sudo amixer set PCM 100% > /dev/null") pygame.mixer.init() pygame.display.set_mode((0, 0)) pygame.mixer.music.set_endevent(pygame.USEREVENT) pygame.display.set_caption("Jukebox") pygame.display.iconify() random.seed() self.info = {} self.active = 0 self.paused = False self.time = 0 self._gettime = True self._resettime = False self.load_playlist() def load_playlist(self, set_active=True): self.playlist = [] cached = self.info.keys() if os.path.exists("playlist.txt"): with open("playlist.txt", "r") as f: z = 0 for i in f.read().strip().split("\n"): k = i.split(" ") if len(k) > 1 and len(k[0]) == 6: if set_active: self.active = z i = " ".join(k[1:]) self.playlist.append(i) else: self.playlist.append(i) if i not in cached: self.info[i] = {"title": "", "artist": "", "album": "", "empty": "true"} thread.start_new_thread(self.cacheAudioInfo, tuple([i])) z += 1 def dump_playlist(self): k = "" for t in range(0, len(self.playlist)): if t == self.active: k += "active " + self.playlist[t] else: k += self.playlist[t] k += "\n" with open("playlist.txt", "w") as f: f.write(k) def play(self, file): if len(self.playlist) == 1 or self.playlist[0].strip() == "": self.active = 0 return if not self.playlist.__contains__(file): self.playlist.append(file) try: pygame.mixer.music.load(file) pygame.mixer.music.set_volume(1.0) pygame.mixer.music.play() self.paused = False self._resettime = True except: self.next(False) def pause(self): if self.paused: pygame.mixer.music.unpause() else: pygame.mixer.music.pause() self.paused = not self.paused def next(self, set_active=True): self.load_playlist(set_active) self.active += 1 if self.active > len(self.playlist) - 1: self.active = 0 self.play(self.playlist[self.active]) self.dump_playlist() def prev(self): self.load_playlist() self.active -= 1 if self.active < 0: self.active = len(self.playlist) - 1 self.play(self.playlist[self.active]) self.dump_playlist() def read(self): fd = sys.stdin.fileno() s = termios.tcgetattr(fd) c = None try: tty.setraw(sys.stdin.fileno()) c = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, s) return c def _time(self): interval = 0.5 while self._gettime: if self._resettime: self._resettime = False self.time = 0 else: self.time += interval for event in pygame.event.get(): if event.type == pygame.USEREVENT: self.next() time.sleep(interval) def randomize(self): p = [self.playlist[self.active]] t = len(self.playlist) - 1 d = [0] for i in range(0, t): z = random.randint(1, t) while d.__contains__(z): random.seed() z = random.randint(1, t) p.append(self.playlist[z]) d.append(z) self.active = 0 self.playlist = p self.dump_playlist() def cacheAudioInfo(self, filename): t = subprocess.Popen(["ffmpeg", "-i", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, err = t.communicate() i = err.strip().split("\n")[7:-3] o = {"title": "", "artist": "", "album": "", "empty": "false"} j = o.keys() for k in i: k = k.strip() n = k.split(":")[0].strip() if n in j: o[n] = k[k.find(":") + 1:].strip() self.info[filename] = o def log(t): if len(sys.argv) == 2: with open(sys.argv[1], "a") as f: f.write(t + "\n") if __name__ == "__main__": j = Jukebox() thread.start_new_thread(j._time, ()) while True: i = j.read() if i == " ": j.pause() elif i == "n": j.next() elif i == "p": j.prev() elif i == "r": j.randomize() elif i == "i": o = j.info[j.playlist[j.active]] o["time"] = int(j.time) o["paused"] = j.paused o = json.dumps(o).encode("base64").replace("\n", "") print o log(o) elif i == "q": j._gettime = False break sys.exit(0)<file_sep><?php require("../../assets/php/include/loginhandler.php"); if (isset($_GET["p"])) { $p = $_GET["p"]; if (is_numeric($p)) { $p = (int)$p; echo $p; echo shell_exec("sudo -u pi ../../assets/bash/omxcontrol.sh setposition $p"); } } ?><file_sep>#!/bin/bash #sudo echo -n echo " ____ _ ____ _ " echo " | _ \(_) _ \ __ _ ___| |__ " echo " | |_) | | | | |/ _ / __| '_ \ " echo " | __/| | |_| | (_| \__ \ | | |" echo " |_| |_|____/ \__,_|___/_| |_|" echo echo "------------------------------------------------------------------------------" echo echo -n "Would you like me to setup some software needed for PiDash? [y/n] " read -n 1 q case $q in y) echo;; *) echo echo "Alright, call me up when you want to use PiDash" exit;; esac echo CWD=`pwd` echo "First of all, I'm going to install stuff like unzip, screen, omxplayer, wget, raspi2png and youtube-dl..." #sudo apt-get -y install unzip screen omxplayer wget youtube-dl git libpng12-dev make python-pexpect ffmpeg openvpn > /dev/null echo "Install done, updating youtube-dl..." #sudo youtube-dl -U > /dev/null echo "Installing raspi2png..." cd /tmp git clone "https://github.com/AndrewFromMelbourne/raspi2png.git" > /dev/null cd raspi2png make > /dev/null cp raspi2png $CWD/assets/c rm /tmp/raspi2png -rf cd $CWD echo "Downloading phpQuery..." cd assets/php/modules wget -O phpquery.zip https://phpquery.googlecode.com/files/phpQuery-0.9.5.386-onefile.zip > /dev/null unzip phpquery.zip rm phpquery.zip mv phpQuery-onefile.php phpquery.php cd $CWD echo "Downloading omxplayer dbus-script..." cd assets/php/bash wget -O omxcontrol.sh https://raw.githubusercontent.com/popcornmix/omxplayer/master/dbuscontrol.sh > /dev/null chmod +x omxcontrol.sh cd $CWD <file_sep><?php require_once("ILibrary.php"); class ARD implements ILibrary { function getDisplayName() { return "ARD-Mediathek"; } function isNSFW() { return false; } function isFromHere($url) { $url = str_replace("https", "http", $url); $url = str_replace("http", "", $url); $url = str_replace("://", "", $url); $url = str_replace("www.", "", $url); $probe = "m.ardmediathek.de"; return strpos($url, $probe) === 0; } function getVideos($query, $page="") { $o = array(); $c = file_get_contents("http://m.ardmediathek.de/Suche?sort=r&pageId=13932884&s=" . urlencode($query) . $page); $pq = phpQuery::newDocumentHTML($c); $elements = $pq[".pagingList ul li a"]; foreach ($elements as $e) { $k = pq($e); $url = "http://m.ardmediathek.de" . $k->attr("href"); $info = array(); foreach ($k->find("p") as $i) { $info[] = $i->textContent; } $image = $k->find("img")->attr("src"); if (strpos($image, "scaled") === false) { $n = array_shift(explode("/", array_pop(explode("contentblob/", $image)))); $z = $n - 8; $image = str_replace($n, $z, $image); } else { $image = str_replace("bild-xs", "bild-l", $image); } $o[$url] = array($k->find("h2")->text(), implode(" | ", $info), '<img class="fullwidth" src="http://m.ardmediathek.de' . $image . '" />'); } return $o; } function search($query) { $pages = 2; $o = array(); for ($i = 0; $i < $pages; $i++) { $o = array_merge($o, $this->getVideos($query, "&goto=" . ($i + 1))); } return $o; } function extract($url) { $s = file_get_contents($url); $pq = phpQUery::newDocumentHTML($s); $v = $pq['video source[data-quality="L"]']; foreach ($v as $s) { $k = $s; } $k = pq($k)->attr("src"); return trim($k); } } ?> <file_sep><?php require("../include/loginhandler.php"); set_time_limit(0); $n = uniqid(); $t = "/tmp/$n.jpg"; shell_exec("sudo -u pi DISPLAY=:0 ../../c/raspi2png -p \"$t\""); header("Content-Type: image/png"); header("Content-Length: " . filesize($t)); readfile($t); shell_exec("sudo rm \"$t\""); ?><file_sep><?php require("assets/php/include/loginhandler.php"); if (isset($_GET["reboot"])) { shell_exec("sudo shutdown -r now"); } else if (isset($_GET["halt"])) { shell_exec("sudo halt"); } else if (isset($_GET["vpn-enable"])) { shell_exec("sudo screen -S vpn -d -m sudo openvpn \"$VPN_CONFIG\""); header("Location: index.php?vpn-enabled"); } else if (isset($_GET["vpn-disable"])) { shell_exec("sudo screen -S vpn -X stuff \"^C\""); header("Location: index.php"); } else if (isset($_GET["vpn-enabled"])) { $VPN = false; } require("assets/php/modules/pistats.php"); $s = new Stats(); $n = $s->Network(); ?> <!doctype html> <html> <head> <title>Dashboard - Raspberry Pi</title> <link rel="stylesheet" href="assets/css/style.css"> <link rel="icon" href="assets/images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <?php $ROOT = "."; $page = 0; include("assets/php/include/menu.php"); ?> <div class="container content"> <div class="row"> <div class="col-50"> <div class="block"> <h2>Device Status</h2> <br> <?php $d = $s->CPU(); $l = $d["load"]["1"]; $r = $s->RAM(); $rl = 100 - round($r["free"] * 100 / $r["total"]); echo ' <div class="row"> <div class="col-50"> <div class="diagram"> <b class="accent">CPU</b> <img src="assets/php/modules/diagram.php?p=' . ($l / 100.) . '"> <div class="data"> ' . $l . '% </div> </div> </div> <div class="col-50"> <div class="diagram"> <b class="accent">RAM</b> <img src="assets/php/modules/diagram.php?p=' . ($rl / 100.) . '"> <div class="data"> ' . $rl . '% </div> </div> </div> </div>'; ?> </div> </div> <div class="col-50"> <div class="block"> <h2>Device Management</h2> <br> <?php $disks = $s->DiskSpace(); echo ' <div class="row"> <div class="col-50">'; foreach ($disks as $disk) { ?> <div class="diagram"> <b class="accent">Filesystem <?php echo $disk["label"];?></b> <img src="assets/php/modules/diagram.php?p=<?php echo $disk["used"]/100;?>"> <div class="data"> <?php echo $disk["used"];?>% </div> </div> <?php } echo ' </div> <div class="col-50"> <b class="accent">Temperature: </b>' . $s->Temperature() . '&deg;C <br> <br> <a class="btn btn-accent fullwidth" href="?halt">Shutdown</a> <br> <br> <a class="btn fullwidth" href="?reboot">Reboot</a> </div> </div> </div> </div> </div>'; ?> <div class="row"> <div class="col-50"> <div class="block"> <h2 style="display: inline; line-height: 200%;">Networking</h2><?php $n = $s->Network(); if ($VPN) { if (!array_key_exists("tun0", $n)) { echo ' <a href="?vpn-enable" class="btn btn-accent pull-right">Enable VPN</a>'; } else { echo ' <a href="?vpn-disable" class="btn btn-accent pull-right">Disable VPN</a>'; } } echo ' <br> <br> <b class="accent">Hostname </b>' . gethostname() . ' <br> <br> <h3>Interfaces</h3>'; foreach ($n as $i=>$d) { echo ' <div class="row"> <div class="col-25"> <b class="accent">' . $i . '</b> </div> <div class="col-50">'; foreach ($d as $k=>$v) { echo ' <b>' . $k . ': </b>' . $v . '<br>'; } echo ' </div> </div> <br>'; } if (array_key_exists("wlan0", $n)) { $w = $s->WiFi(); echo ' <h3>WiFi</h3> <div class="row"> <div class="col-25"> <b class="accent">ESSID</b> </div> <div class="col-50"> ' . $w["essid"] . ' <span class="muted">(' . strtolower($w["ap"]) . ')</span> </div> </div> <br> <div class="row"> <div class="col-50"> <div class="diagram"> <b class="accent">Signal</b> <img src="assets/php/modules/diagram.php?p=' . ($w["signal"] / 100.) . '"> <div class="data"> ' . $w["signal"] . '% </div> </div> </div> <div class="col-50"> <div class="diagram"> <b class="accent">Quality</b> <img src="assets/php/modules/diagram.php?p=' . ($w["quality"] / 100.) . '"> <div class="data"> ' . $w["quality"] . '% </div> </div> </div> </div> <br>'; } ?> </div> </div> <div class="col-50"> <div class="block"> <h2 style="display: inline">Now Displaying</h2> <span class="muted">(may take a while)</span> <br> <br> <img width="100%" src="assets/php/modules/screenshot.php"> </div> </div> </div> </div> <br> </body> </html> <file_sep><?php require_once("ILibrary.php"); class ZDF implements ILibrary { function getDisplayName() { return "ZDF-Mediathek"; } function isNSFW() { return false; } function isFromHere($url) { $url = str_replace("https", "http", $url); $url = str_replace("http", "", $url); $url = str_replace("://", "", $url); $url = str_replace("www.", "", $url); $probe = "zdf.de"; return strpos($url, $probe) === 0; } function _search($query) { $o = array(); $search = file_get_contents("http://www.zdf.de/ZDFmediathek/suche?flash=off&sucheText=" . urlencode($query)); $search = str_replace("flash=off\"/>", "flash=off\">", $search); $pq = phpQuery::newDocumentHTML($search); $elements = $pq[".row ul li p a"]; $i = 0; $k = 0; $z = ""; foreach ($elements as $e) { if ($i == 0) { $z = "http://www.zdf.de" . pq($e)->attr("href") . "&ipad=on"; $o[$z] = array(); } $j = trim($e->textContent); if ($j != "") { $o[$z][] = $j; $i++; if ($i == 3) { $i = 0; $k++; } } } return $o; } function search($query) { $o = array(); $search = file_get_contents("http://www.zdf.de/ZDFmediathek/suche?flash=off&sucheText=" . urlencode($query)); $search = str_replace("flash=off\"/>", "flash=off\">", $search); $pq = phpQuery::newDocumentHTML($search); $elements = $pq[".row ul li"]; foreach ($elements as $e) { $k = pq($e); $i = array(); foreach ($k->find(".text p") as $p) { $i[] = trim($p->textContent); } if (count($i) == 3 and strpos($i[2], "VIDEO") === 0) { #continue; $t = $k->find(".image a"); $image = $t->find("img")->attr("src"); $image = str_replace("timg94x65blob", "timg476x268blob", $image); $url = $k->find("a")->attr("href"); $o["http://www.zdf.de" . $url] = array($i[1], $i[0] . " | " . $i[2], '<img class="fullwidth" src="' . $image . '" />'); } } return $o; } function extract($url) { $s = file_get_contents($url); $pq = phpQuery::newDocumentHTML($s); $dsl = $pq[".dslChoice li a.play"]; foreach ($dsl as $d) { $best = $d; } $best = pq($best); return $best->attr("href"); } } ?> <file_sep><?php require_once(dirname(dirname(__FILE__)) . "../../../config.php"); if ($USE_PASSWORD) { session_start(); if (isset($_GET["logout"])) { unset($_SESSION["login"]); } if (!isset($_SESSION["login"])) { $pidash_root = "."; $c = getcwd(); if (basename(dirname(dirname($c))) == "php") { $pidash_root = "../../.."; } else if (basename(dirname($c)) == "pages") { $pidash_root = "../.."; } header("Location: $pidash_root/login.php"); } } ?><file_sep><?php function getScreens() { $_s = trim(shell_exec("sudo -u pi screen -ls")); $s = array(); $t = array(); if (substr($_s, 0, 2) !== "No") { $t = explode("\n", $_s); array_shift($t); array_pop($t); foreach ($t as $_) { if (strpos($_, "omxplayer") !== false) { $_ = explode(".", $_); $_ = explode("\t", $_[1]); array_push($s, $_[0]); } } } return $s; } function get_php_classes($file) { $classes = array(); $tokens = token_get_all(file_get_contents($file)); $count = count($tokens); for ($i = 2; $i < $count; $i++) { if ( $tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) { $class_name = $tokens[$i][1]; $classes[] = $class_name; } } return $classes; } function getLibs($nsfw) { $o = array(); foreach (preg_grep('/ILibrary\.php$/', glob('libs/*.php'), PREG_GREP_INVERT) as $l) { $c = get_php_classes($l); include($l); $c = $c[0]; $c = new $c(); if ((!$c->isNSFW() and !$nsfw) or $nsfw) { $o[] = $c; } } return $o; } ?><file_sep><!doctype html> <html> <head> <title>md5 - Raspberry Pi</title> <link rel="stylesheet" href="assets/css/style.css"> <link rel="icon" href="assets/images/favicon.ico"> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <div class="container"> <?php if (isset($_POST["p"])) { echo ' <div class="row"> <div class="col-50"> <div class="block"> <h2>Result</h2> ' . md5($_POST["p"]) . ' </div> </div> <div class="col-50"> <div class="block"> <h2>Create Hash</h2> <form method="post" action=""> <input type="password" class="fullwidth" name="p" placeholder="Text to hash"> </form> </div> </div> </div>'; } else { echo ' <div class="block"> <h2>Create Hash</h2> <form method="post" action=""> <input type="password" class="fullwidth" name="p" placeholder="Text to hash"> </form> </div>'; } ?> </div> </body> </html><file_sep><?php require("../../assets/php/include/loginhandler.php"); if (isset($_GET["f"])) { $f = base64_decode($_GET["f"]); if (file_exists($f)) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $ct = finfo_file($finfo, $f); finfo_close($finfo); header("Content-type: $ct"); readfile($f); } } ?>
5ad50fd2c72783dac60560d45e0b3d4a6df9fafd
[ "Markdown", "Python", "PHP", "Shell" ]
26
PHP
minedev/pidash
8b78b31fed6984669b19e2be93a4892f708c1b33
a14803b95fa650a9c6bac8e2527275bd84962f98
refs/heads/master
<file_sep>from django.urls import path from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('tasks/', views.tasks, name='tasks'), path('<int:task_id>/', views.task, name='task'), path('users-tasks/', views.users_tasks, name='users_tasks'), path('user-tasks/<int:user_id>/', views.user_tasks, name='user_tasks'), ] <file_sep>Babel==2.7.0 Django==2.2.28 django-debug-toolbar==2.1 django-extensions==2.2.5 django-model-utils==4.0.0 django-phonenumber-field==4.0.0 Faker==3.0.0 phonenumberslite==8.11.1 python-dateutil==2.8.1 python-stdnum==1.12 pytz==2019.3 six==1.13.0 sqlparse==0.3.0 text-unidecode==1.3 Werkzeug==0.16.0 <file_sep>from django.http import Http404 from django.shortcuts import render from django.views.generic import TemplateView from .models import Task, UserTask class HomePageView(TemplateView): template_name = 'pages/home.html' def tasks(request): all_tasks = Task.objects.order_by('-task') return render(request, 'tasks/tasks.html', {'all_tasks': all_tasks}) def task(request, task_id): try: task = Task.objects.get(pk=task_id) except Task.DoesNotExist: raise Http404("Task does not exist") return render(request, 'tasks/task.html', {'task': task}) def users_tasks(request): users_tasks = UserTask.objects.order_by('-user') return render(request, 'tasks/users_tasks.html', {'users_tasks': users_tasks}) def user_tasks(request, user_id): user_tasks = UserTask.objects.filter(user=user_id) return render(request, 'tasks/user_tasks.html', {'user_tasks': user_tasks}) <file_sep>from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField from .managers import CustomUserManager class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) phone_number = PhoneNumberField(default="+19020000000") USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return f"{self.first_name} {self.last_name}" class Task(models.Model): task = models.CharField(max_length=50) notes = models.TextField() created_at = models.DateTimeField( verbose_name=u"Created at", auto_now_add=True ) edited_by = models.ForeignKey( "CustomUser", on_delete=models.SET_NULL, null=True ) def __str__(self): return self.task def get_absolute_url(self): return reverse("task_detail", args=[str(self.id)]) class UserTask(models.Model): user = models.ForeignKey( "CustomUser", related_name="user_tasks", on_delete=models.SET_NULL, null=True ) task = models.ForeignKey( "Task", related_name="user_tasks", on_delete=models.SET_NULL, null=True ) created = models.DateTimeField(auto_now_add=True) completed = models.DateTimeField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'task'], name='unique_user_task') ] <file_sep>import re from random import choice, randint from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.utils import timezone from faker import Faker fake = Faker(["en_CA"]) def get_phone_number(): """ Faker is not consistent when generating phone numbers """ phone = fake.phone_number() phone_number = re.findall(r"[0-9]+", phone) if len(phone_number) == 3: phone = "".join(phone_number) return f"+1{phone}" elif len(phone_number) == 4 and int(phone_number[0]) == 1: phone = "".join(phone_number) return f"+{phone}" else: # with extension phone = "".join(phone_number)[:-3] return f"+1{phone}" def check_email(*args): # Needs to check if email exists first_name, last_name = args provider_choice = randint(0, 1) if provider_choice: provider = fake.domain_name() else: provider = fake.free_email_domain() return f"{first_name.lower()}.{last_name.lower()}@{provider}" def generate_user(): User = get_user_model() password = <PASSWORD>() male_female = randint(0, 1) if male_female: first_name = fake.first_name_female() last_name = fake.last_name_female() else: first_name = fake.first_name_male() last_name = fake.last_name_male() user_email = check_email(first_name, last_name) first_name = first_name last_name = last_name email = user_email joined = choice([24, 48, 72, 96, 120]) phone_number = get_phone_number() user = User.objects.create_user( email=email, password=<PASSWORD>, first_name=first_name, last_name=last_name, date_joined=timezone.now() + timezone.timedelta(hours=-joined, seconds=-1), last_login=timezone.now(), phone_number=phone_number, ) return user class Command(BaseCommand): help = "Indicates the number of users to be created" def add_arguments(self, parser): parser.add_argument( "total", type=int, help=help ) def handle(self, *args, **kwargs): total = kwargs["total"] for i in range(total): generate_user() <file_sep>## Tasks Project Simple Learning project ## Tools Used 1. Python 3.7 2. Django 2.2.12 3. SQLite3 3.30.1 4. DBeaver 6.3.1 ## Git Clone the project and cd into project Move to a working directory on your computer, and open terminal. `$: git clone <EMAIL>:diek/tasks-project.git` `$: cd tasks_project` ## Create a venv and activate it `$: python3 -m venv _env` `$: source _env/bin/activate` `$: pip install --upgrade pip` `$: pip install -r requirements.txt` ## Run migrations `$: python manage.py migrate tasks` `$: python manage.py migrate` ## Load Initial Data `$: python manage.py loaddata user_data.json` `$: python manage.py loaddata task_data.json` `$: python manage.py loaddata user_task_data.json` ## Generate Users via Management Command `$: python manage.py populate_users <int:number>` ## Generate User Tasks via Management Command `$: python manage.py populate_user_tasks <int:number>` ## ERD of Key Tables ![ERD of Key Tables](./docs/tasks_primary_tables_ERD.png) ## Acknowledments The project includes code and concepts from: - WS Vincent's [DjangoX project](https://github.com/wsvincent/djangox) - <NAME>, et. al, [Cookiecutter Django](https://github.com/pydanny/cookiecutter-django) - <NAME>'s Testdriven Blog - [Creating a Custom User Model in Django](https://testdriven.io/blog/django-custom-user-model/) <file_sep>import random from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.db.utils import IntegrityError from django.utils import timezone from tasks.models import Task, UserTask def generate_user_task(): User = get_user_model() users = User.objects.values_list('pk', flat=True).order_by('pk') tasks = Task.objects.values_list('pk', flat=True).order_by('pk') user_id = random.choice(users) user = User.objects.get(id=user_id) task_id = random.choice(tasks) task = Task.objects.get(id=task_id) date_time = timezone.now() user_task = UserTask(user=user, task=task, created=date_time) user_task.save() class Command(BaseCommand): help = 'Generates x number of usertasks' def add_arguments(self, parser): parser.add_argument('total', type=int, help='Indicates the number of user_tasks to be created') def handle(self, *args, **kwargs): total = kwargs['total'] count = 0 for i in range(total): try: generate_user_task() except IntegrityError: count += 1 if count: print(f"{total - count } of {total} were created, the user task already existed.") else: print(f"All {total} tasks were created.")
df31d0afe6c5fe09085c4447b6365bf26ef3b7ae
[ "Markdown", "Python", "Text" ]
7
Python
diek/tasks-project
e9855b4ef4e8f3a266ab605b4654a8aafd395b1b
3891615b6badb51e1d08c86b7bab4a6f406b9e3c
refs/heads/main
<file_sep>import numpy as np import pandas as pd data = pd.read_csv('uscecchini28.csv') data.head()<file_sep># FraudDetection Trying to complete Finish before April ! You Can Do It ! More Working... More Working... More Working...
99a8ef1aad7a962bfac3237ee997126c34348fdf
[ "Markdown", "Python" ]
2
Python
RuaConIT/FraudDetection
270c20c665c5ea4d54b31085c32ddcc025a57484
5907cdd215a6e3589123068a58e006180fe927ff
refs/heads/master
<file_sep>hello = 5 summary(hello) median(hello) print("Great Job!")
2f21abe9a46a356b02baffd374360f6990efc33c
[ "R" ]
1
R
nishagoldsworthy/Test
fe9db350f99b3ef8d0ff6bb8b94e078e6649a586
0eab76ad35e28ee97bdd543dcc5bdff512e3bd07
refs/heads/main
<repo_name>ZbestbadZ/learning_management<file_sep>/app/User.php <?php namespace App; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use App\Models\Notify; use App\Models\Progress; class User extends Authenticatable { use Notifiable; protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','<PASSWORD>', 'achievement', 'role' ]; public function notify() { return $this->hasMany(Notify::class, 'user_id', 'id'); } public function progress() { return $this->hasMany(Progress::class, 'user_id', 'id'); } // public function generateToken() // { // $this->api_token = str_random(60); // $this->save(); // return $this->api_token; // } /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; }<file_sep>/app/Http/Requests/AddStudentRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class AddStudentRequest 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 [ 'ma_sv' => 'required|numeric', ]; } public function messages() { return [ 'ma_sv.required' => 'Bạn chưa nhập MSSV', 'ma_sv.numeric' => 'MSSV không hợp lệ' ]; } }<file_sep>/database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $classes = [ UserSeeder::class, NotifySeeder::class, SubjectSeeder::class, ProgressSeeder::class, ]; $this->call($classes); } }<file_sep>/database/seeds/NotifySeeder.php <?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Carbon\Carbon; class NotifySeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 20 ; $i++) { DB::table('notifies')->insert([ 'user_id'=> 1, 'name' => 'Thông báo'.($i), 'notify' => 'Đây là Nội dung thông báo '.($i), 'created_at' => Carbon::now() ]); } } }<file_sep>/app/Models/Notify.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\User; class Notify extends Model { protected $table = 'notifies'; protected $fillable = [ 'user_id', 'name', 'notify' ]; public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } }<file_sep>/app/Http/Controllers/SubjectController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Subject; use App\Models\Notify; use Carbon\Carbon; use App\User; use App\Models\Progress; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class SubjectController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); $subject = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh', 'ki_hoc', 'giang_vien', 'email_gv') ->paginate(5); return view('user.subject.list_subject', compact('total_score', 'i', 'data', 'scores', 'subject')); } // search header public function getSearch(Request $request) { $search = $request->search; // dd($search); if (empty($search)) { return redirect('user/list_subject')->with('thongbao', "Không tìm thấy kết quả tìm kiếm"); } else { $subject = Subject::where('name', 'like', '%' . $request->search . '%') ->orWhere('ma_mh', $request->search) ->get(); } $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh', 'user_id') ->get(); return view('user.subject.search_subject', compact('subject', 'search', 'total_score', 'i', 'data', 'scores')); } public function getDetailSubject(Request $request, $id) { $index = $request->index; $subject = Subject::find($id); $user_id = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->where('subjects.ma_mh', $index) ->select('user_id', 'ma_mh')->first(); $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh', 'user_id') ->get(); return view('user.subject.detail_subject', compact('subject', 'total_score', 'i', 'data', 'scores', 'user_id')); } public function store(Request $request, $id) { $subject = Subject::find($id); $user_subject = Progress::create([ 'user_id' => Auth::user()->id, 'subject_id' => $subject->id ]); return redirect('user/list_subject')->with('thongbao', "Đăng kí môn học thành công!"); } public function getListNotify() { $notify = Notify::orderBy('created_at', 'desc') ->paginate(5); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); $user = User::with('notify')->first(); $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); return view('user.notify.list_notify', compact('notify', 'user', 'scores', 'total_score', 'i', 'data')); } public function getScore(Request $request) { $index = $request->index; $id = Auth::user()->id; $index2 = Subject::where('ma_mh', $index)->select('id')->first(); $index3 = $index2->id; $score = Progress::where('user_id', $id) ->where('subject_id', $index3) ->select('score') ->first(); $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); $data = $total_score->pluck('name')->toArray(); return view('user.score.myscore', compact('index', 'scores', 'score', 'total_score', 'i', 'data')); } public function getRate(Request $request) { $index = $request->index; $id = Auth::user()->id; $index2 = Subject::where('ma_mh', $index)->select('id')->first(); $index3 = $index2->id; $rate = Progress::where('user_id', $id) ->where('subject_id', $index3) ->select('rate') ->first(); $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); $data = $total_score->pluck('name')->toArray(); return view('user.rate.myrate', compact('index', 'rate', 'total_score', 'i', 'data', 'scores')); } public function getAllScore(Request $request) { $id = Auth::user()->id; $scores = Progress::where('user_id', $id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh', 'score') ->get(); $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); return view('user.score.allscore', compact('scores', 'total_score', 'i', 'data')); } }<file_sep>/app/Http/Controllers/GuzzleController.php <?php namespace App\Http\Controllers; // use Illuminate\Support\Facades\Http; use Illuminate\Http\Request; use GuzzleHttp\Client; class GuzzleController extends Controller { // public function getRemoteData() // { // $client = new Client([ // 'headers' => ['content-type' =>'application/json', 'Accept' => 'application/json' ], // ]); // $response = $client->request('GET', 'http://apig8.toedu.me/api/Integrations/Transcript?contestID=04845905-5072-6564-8204-096404114208&fbclid=IwAR0wwySDGmfvcWNBpn_NE5tcNIRbc5nBkUwqWHPyiv3e0w8iv81u8EhM1kU', [ // 'code' => '714b320c-1046-4e37-a3c3-20bc6fcac014', // ]); // $data = $response->getBody(); // $data = json_decode($data); // dd($data); // return $data // } public function getRemoteData() { return view('admin.subject.update_score_online'); } } <file_sep>/app/Models/Subject.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\Progress; class Subject extends Model { protected $table = 'subjects'; protected $fillable = [ 'name', 'ma_mh', 'description', 'giang_vien', 'email_gv', 'ki_hoc' ]; public function progress() { return $this->hasMany(Progress::class, 'subject_id', 'id'); } }<file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\Models\Subject; use App\Models\Progress; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class UserController extends Controller { // list students in class public function index(Request $request) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->join('users', 'users.id', '=', 'progresses.user_id') ->select('users.*') // ->paginate(10); ->get(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); $i = 1; $k = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); return view('user.student.list_student', compact('user', 'scores', 'index', 'total_score', 'i', 'k', 'data')); } //search students in class public function getSearchStudent(Request $request) { $search_student = $request->search_student; if (empty($search_student)) { return redirect('user/list_student')->with('thongbao', "Không tìm thấy kết quả tìm kiếm"); } else { $students = User::where('name', 'like', '%' . $request->search_student . '%') ->orWhere('ma_sv', $request->search_student) ->orWhere('email', $request->search_student) ->get(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); } $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); return view('user.student.search_student', compact('students', 'search_student', 'scores', 'total_score', 'i', 'data')); } }<file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Subject; use App\Models\Progress; use App\User; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $subject = Subject::all(); $i = 1; $total_score = Progress::join('users', 'users.id', '=', 'progresses.user_id') ->select('name', DB::raw('AVG(score) as Score')) ->groupBy('name') ->havingRaw('AVG(score) > ?', [5]) ->orderBy('Score', 'desc') ->get(); $data = $total_score->pluck('name')->toArray(); $scores = Progress::where('user_id', Auth::user()->id) ->join('subjects', 'progresses.subject_id', '=', 'subjects.id') ->select('name', 'ma_mh') ->get(); return view('home', compact('subject', 'total_score', 'i', 'data', 'scores')); } }<file_sep>/app/Models/Progress.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\User; use App\Models\Subject; class Progress extends Model { protected $table = 'progresses'; protected $fillable = [ 'user_id', 'subject_id', 'score', 'rate', ]; public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } public function subject() { return $this->belongsTo(Subject::class, 'subject_id', 'id'); } }<file_sep>/app/Http/Requests/CreateSubjectRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class CreateSubjectRequest 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 [ 'name' => 'required|min:5|string', 'ma_mh' => 'required|min:5|string', 'description' => "required|min:10|string", ]; } public function messages() { return [ 'name.required' => 'Bạn chưa nhập tên môn học', 'name.min'=>'Tên môn học có ít nhất 5 kí tự', 'ma_mh.required' => 'Bạn chưa nhập mã môn học', 'ma_mh.min'=>'Mã môn học có ít nhất 5 kí tự', 'description.required' => 'Bạn chưa nhập phần mô tả', 'description.min' => 'Mô tả phải có ít nhất 10 kí tự' ]; } }<file_sep>/database/seeds/ProgressSeeder.php <?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class ProgressSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 20; $i++) { for ($j = 1; $j <= 20; $j++) { DB::table('progresses')->insert([ 'user_id' => $j+1, 'subject_id' => $i, 'score' => rand(5, 10), 'rate' => 'Có ý thức chăm chỉ trong học tập' ]); } } } }<file_sep>/app/Http/Requests/NotifyRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class NotifyRequest 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 [ 'name' => 'required|min:3', 'notify' => 'required|min:5' ]; } public function messages() { return [ 'name.required' => 'Bạn chưa nhập tên thông báo', 'name.min'=>'Tên thông báo có ít nhất 3 kí tự', 'notify.required' => 'Bạn chưa nhập nội dung', 'notify.min'=>'Thông báo có ít nhất 3 kí tự', ]; } }<file_sep>/app/Http/Controllers/AdminController.php <?php namespace App\Http\Controllers; use App\Http\Requests\NotifyRequest; use App\Http\Requests\AddStudentRequest; use App\User; use App\Models\Notify; use Illuminate\Support\Facades\Auth; use App\Models\Subject; use App\Http\Requests\CreateSubjectRequest; use Illuminate\Http\Request; use App\Models\Progress; class AdminController extends Controller { public function __construct() { $this->middleware('isadmin'); } // show list users public function getListUser() { $user = User::paginate(10); return view('admin.user.list_user', compact('user')); } // create notify public function createNotify(NotifyRequest $request) { $notify = Notify::create([ 'user_id' => Auth::user()->id, 'name' => $request->name, 'notify' => $request->notify ]); return redirect('admin/list_user')->with('thongbao', 'Tạo thông báo thành công!'); } public function create() { return view('admin.subject.create_subject'); } //create subject public function store(CreateSubjectRequest $request) { $subject = Subject::create([ 'name' => $request->name, 'ma_mh' => $request->ma_mh, 'description' => $request->description, 'giang_vien' => 'TS.<NAME>', 'email_gv' => '<EMAIL>', 'ki_hoc' => 'Học kì I năm 2020 - 2021', ]); return redirect('admin/list_subject')->with('thongbao', 'Thêm môn học thành công!'); } public function list_subject() { $subject = Subject::paginate(5); return view('admin.subject.list_subject', compact('subject')); } public function getListStudentClass(Request $request) { $subject = Subject::all(); $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->join('users', 'users.id', '=', 'progresses.user_id') ->select('users.*', 'progresses.*') ->get(); $k = 1; return view('admin.subject.list_student_in_subject', compact('subject', 'index', 'user', 'k')); } //delete students public function destroy(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); $user->delete(); return redirect()->back()->with('thongbao', 'Xóa sinh viên thành công!'); } //add student in class subject public function add_student(AddStudentRequest $request) { $msv = $request->input('ma_sv'); $index = $request->index; $user = User::where('ma_sv', $msv)->select('id')->first(); if (empty($user)) { return redirect()->back()->with('thongbao', 'Mã sinh viên không tồn tại!'); } $students = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->join('users', 'users.id', '=', 'progresses.user_id') ->select('users.*', 'progresses.*') ->get(); foreach ($students as $student) { if ($student->ma_sv == $msv) { return redirect()->back()->with('thongbao', 'Sinh viên đã đăng kí lớp học rồi!'); } } $subject = Subject::where('ma_mh', $index)->select('id')->first(); $user_subject = Progress::create([ 'user_id' => $user->id, 'subject_id' => $subject->id ]); return redirect()->back()->with('thongbao', 'Thêm sinh viên thành công!'); } //edit score public function getEdit_score(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); return view('admin.subject.edit_score', compact('user')); } //edit score public function edit_score(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); $request->validate([ 'score' => 'required|max:10|min:0|numeric', ]); $user->update([ 'score' => $request->score, ]); return redirect('admin/list_subject')->with('thongbao', 'Sửa điểm thành công!'); } //add score public function getAdd_score() { return view('admin.subject.add_score'); } //add score public function add_score(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); $request->validate([ 'score' => 'required|max:10|min:0|numeric', ]); $user->update([ 'score' => $request->score, ]); return redirect('admin/list_subject')->with('thongbao', 'Thêm điểm thành công!'); } //edit rate public function getEdit_rate(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); return view('admin.subject.edit_rate', compact('user')); } //edit rate public function edit_rate(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); $request->validate([ 'rate' => 'required|max:100|min:10|string', ]); $user->update([ 'rate' => $request->rate, ]); return redirect('admin/list_subject')->with('thongbao', 'Sửa đánh giá thành công!'); } //add rate public function getAdd_rate() { return view('admin.subject.add_rate'); } //add rate public function add_rate(Request $request, $user_id) { $index = $request->index; $user = Progress::join('subjects', 'subjects.id', '=', 'progresses.subject_id') ->where('ma_mh', $index) ->where('user_id', $user_id) ->select('progresses.*') ->first(); $request->validate([ 'rate' => 'required|max:100|min:10|string', ]); $user->update([ 'rate' => $request->rate, ]); return redirect('admin/list_subject')->with('thongbao', 'Thêm đánh giá thành công!'); } }<file_sep>/database/seeds/UserSeeder.php <?php use App\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Faker\Generator as Faker; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'name' => 'admin', 'ma_sv' => '17020775', 'email' => '<EMAIL>', 'role' => '1', 'password' => bcrypt('123'), ]); DB::table('users')->insert([ 'name' => 'user', 'ma_sv' => '17020777', 'email' => '<EMAIL>', 'role' => '0', 'password' => bcrypt('123'), ]); DB::table('users')->insert([ 'name' => 'user1', 'ma_sv' => '17020755', 'email' => '<EMAIL>', 'role' => '0', 'password' => bcrypt('123'), ]); factory(App\User::class, 30)->create(); } }<file_sep>/database/seeds/SubjectSeeder.php <?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class SubjectSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 20; $i++) { DB::table('subjects')->insert([ 'name' => '<NAME>' . ($i), 'ma_mh' => 'INT3307_' . ($i), 'giang_vien' => '<NAME>', 'email_gv' => '<EMAIL>', 'ki_hoc' => 'Học kì I năm 2020 - 2021', 'description' => 'Đây là môn học yêu thích của bạn' ]); } } }<file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Http; /* |-------------------------------------------------------------------------- | 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('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::group(['prefix' => 'user', 'middleware' => 'auth'], function () { Route::get('list_subject', 'SubjectController@index')->name('user.list_subject_'); Route::get('search_subject', 'SubjectController@getSearch')->name('search'); Route::get('list_notify', 'SubjectController@getListNotify')->name('list_notify'); Route::get('list_student', 'UserController@index')->name('list_student'); Route::get('search_student', 'UserController@getSearchStudent')->name('search_student'); Route::get('score', 'SubjectController@getScore')->name('score'); Route::get('rate', 'SubjectController@getRate')->name('rate'); Route::get('all_score', 'SubjectController@getAllScore')->name('all_score'); Route::get('subject/{id}', 'SubjectController@getDetailSubject'); Route::post('register_subject/{id}', 'SubjectController@store'); }); Route::group(['prefix' => 'admin', 'middleware' => 'isadmin'], function () { Route::get('list_user', 'AdminController@getListUser')->name('admin.user.list'); Route::post('notify', 'AdminController@createNotify')->name('notify'); Route::get('create_subject', 'AdminController@create')->name('add_subject'); Route::post('create', 'AdminController@store')->name('create_subject'); Route::get('list_subject', 'AdminController@list_subject'); Route::get('list_student_in_subject', 'AdminController@getListStudentClass'); Route::delete('/{user_id}', 'AdminController@destroy')->name('destroy'); Route::post('add_student', 'AdminController@add_student')->name('add_student'); Route::get('edit_score/{user_id}', 'AdminController@getEdit_score'); Route::post('edit_score/{user_id}', 'AdminController@edit_score')->name('edit_score'); Route::get('edit_rate/{user_id}', 'AdminController@getEdit_rate'); Route::post('edit_rate/{user_id}', 'AdminController@edit_rate')->name('edit_rate'); Route::get('add_score/{user_id}', 'AdminController@getAdd_score'); Route::post('add_score/{user_id}', 'AdminController@add_score')->name('add_score'); Route::get('add_rate/{user_id}', 'AdminController@getAdd_rate'); Route::post('add_rate/{user_id}', 'AdminController@add_rate')->name('add_rate'); Route::get('update_score', 'GuzzleController@getRemoteData'); });
55d63248304e3cabee9e66652e49b1fb7a08aaf6
[ "PHP" ]
18
PHP
ZbestbadZ/learning_management
aad529d6daa37b67eab36af0966e022a06ca6001
cb59de5b2ae3180d1d55a82e041608f1d6bc45cf
refs/heads/master
<file_sep># The simplest of all!
4099f53c323028a42fcb43fcecba68fa91264ce4
[ "Python" ]
1
Python
ushki/Pythonika
50e01b339de7a809921f11ced6ed6e6d172b03cb
a0b7c5864387f9e119675ff0c965ed0a9b3dd19b
refs/heads/master
<file_sep>using System.Configuration; using System.IO; namespace PKHeX.WinForms { public static class ConfigUtil { public static bool checkConfig() { try { ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); return true; } catch (ConfigurationErrorsException e) { string path = (e.InnerException as ConfigurationErrorsException)?.Filename; if (path != null) File.Delete(path); return false; } } } } <file_sep>using System; using System.Linq; using System.Windows.Forms; using PKHeX.Core; namespace PKHeX.WinForms { public partial class SAV_BoxLayout : Form { public SAV_BoxLayout(int box) { InitializeComponent(); WinFormsUtil.TranslateInterface(this, Main.curlanguage); editing = true; // Repopulate Wallpaper names CB_BG.Items.Clear(); switch (SAV.Generation) { case 3: if (SAV.GameCube) goto default; CB_BG.Items.AddRange(GameInfo.Strings.wallpapernames.Take(16).ToArray()); break; case 4: case 5: case 6: CB_BG.Items.AddRange(GameInfo.Strings.wallpapernames); break; case 7: CB_BG.Items.AddRange(GameInfo.Strings.wallpapernames.Take(16).ToArray()); break; default: WinFormsUtil.Error("Box layout is not supported for this game.", "Please close the window."); break; } // Go LB_BoxSelect.Items.Clear(); for (int i = 0; i < SAV.BoxCount; i++) LB_BoxSelect.Items.Add(SAV.getBoxName(i)); // Flags byte[] flags = SAV.BoxFlags; if (flags != null) { flagArr = new NumericUpDown[flags.Length]; for (int i = 0; i < flags.Length; i++) { flagArr[i] = new NumericUpDown { Minimum = 0, Maximum = 255, Width = CB_Unlocked.Width - 5, Hexadecimal = true, Value = flags[i] }; FLP_Flags.Controls.Add(flagArr[i]); } } else { FLP_Flags.Visible = false; } // Unlocked if (SAV.BoxesUnlocked > 0) { CB_Unlocked.Items.Clear(); for (int i = 0; i <= SAV.BoxCount; i++) CB_Unlocked.Items.Add(i); CB_Unlocked.SelectedIndex = Math.Min(SAV.BoxCount, SAV.BoxesUnlocked); } else { FLP_Unlocked.Visible = L_Unlocked.Visible = CB_Unlocked.Visible = false; } LB_BoxSelect.SelectedIndex = box; } private readonly NumericUpDown[] flagArr = new NumericUpDown[0]; private readonly SaveFile SAV = Main.SAV.Clone(); private bool editing; private bool renameBox; private void changeBox(object sender, EventArgs e) { if (renameBox) return; editing = true; CB_BG.SelectedIndex = SAV.getBoxWallpaper(LB_BoxSelect.SelectedIndex); TB_BoxName.Text = SAV.getBoxName(LB_BoxSelect.SelectedIndex); editing = false; } private void changeBoxDetails(object sender, EventArgs e) { if (editing) return; renameBox = true; SAV.setBoxName(LB_BoxSelect.SelectedIndex, TB_BoxName.Text); LB_BoxSelect.Items[LB_BoxSelect.SelectedIndex] = TB_BoxName.Text; renameBox = false; } private void B_Cancel_Click(object sender, EventArgs e) { Close(); } private void B_Save_Click(object sender, EventArgs e) { if (flagArr.Length > 0) SAV.BoxFlags = flagArr.Select(i => (byte) i.Value).ToArray(); if (CB_Unlocked.Visible) SAV.BoxesUnlocked = CB_Unlocked.SelectedIndex; Main.SAV = SAV; Main.SAV.Edited = true; Close(); } private void changeBoxBG(object sender, EventArgs e) { if (!editing) SAV.setBoxWallpaper(LB_BoxSelect.SelectedIndex, CB_BG.SelectedIndex); PAN_BG.BackgroundImage = SAV.WallpaperImage(CB_BG.SelectedIndex); } private bool MoveItem(int direction) { // Checking selected item if (LB_BoxSelect.SelectedItem == null || LB_BoxSelect.SelectedIndex < 0) return false; // No selected item - nothing to do // Calculate new index using move direction int newIndex = LB_BoxSelect.SelectedIndex + direction; // Checking bounds of the range if (newIndex < 0 || newIndex >= LB_BoxSelect.Items.Count) return false; // Index out of range - nothing to do object selected = LB_BoxSelect.SelectedItem; // Removing removable element LB_BoxSelect.Items.Remove(selected); // Insert it in new position LB_BoxSelect.Items.Insert(newIndex, selected); // Restore selection LB_BoxSelect.SetSelected(newIndex, true); editing = renameBox = false; return true; } private void moveBox(object sender, EventArgs e) { int index = LB_BoxSelect.SelectedIndex; int dir = sender == B_Up ? -1 : +1; editing = renameBox = true; if (!MoveItem(dir)) { System.Media.SystemSounds.Asterisk.Play(); } else if (!SAV.SwapBox(index, index + dir)) // valid but locked { MoveItem(-dir); // undo WinFormsUtil.Alert("Locked slots prevent movement of box(es)."); } else changeBox(null, null); editing = renameBox = false; } } }<file_sep>using System.Drawing; using PKHeX.Core; using PKHeX.Core.Properties; namespace PKHeX.WinForms { public static class PKMUtil { public static Image getBallSprite(int ball) { string str = PKX.getBallString(ball); return (Image)Resources.ResourceManager.GetObject(str) ?? Resources._ball4; // Poké Ball (default) } public static Image getSprite(int species, int form, int gender, int item, bool isegg, bool shiny, int generation = -1) { if (species == 0) return Resources._0; string file = PKX.getSpriteString(species, form, gender, generation); // Redrawing logic Image baseImage = (Image)Resources.ResourceManager.GetObject(file); if (baseImage == null) { baseImage = (Image) Resources.ResourceManager.GetObject("_" + species); baseImage = baseImage != null ? ImageUtil.LayerImage(baseImage, Resources.unknown, 0, 0, .5) : Resources.unknown; } if (isegg) { // Start with a partially transparent species by layering the species with partial opacity onto a blank image. baseImage = ImageUtil.LayerImage(Resources._0, baseImage, 0, 0, 0.33); // Add the egg layer over-top with full opacity. baseImage = ImageUtil.LayerImage(baseImage, Resources.egg, 0, 0, 1); } if (shiny) { // Add shiny star to top left of image. baseImage = ImageUtil.LayerImage(baseImage, Resources.rare_icon, 0, 0, 0.7); } if (item > 0) { Image itemimg = (Image)Resources.ResourceManager.GetObject("item_" + item) ?? Resources.helditem; if (generation >= 2 && generation <= 4 && 328 <= item && item <= 419) // gen2/3/4 TM itemimg = Resources.item_tm; // Redraw baseImage = ImageUtil.LayerImage(baseImage, itemimg, 22 + (15 - itemimg.Width) / 2, 15 + (15 - itemimg.Height), 1); } return baseImage; } public static Image getRibbonSprite(string name) { return Resources.ResourceManager.GetObject(name.Replace("CountG3", "G3").ToLower()) as Image; } public static Image getTypeSprite(int type) { return Resources.ResourceManager.GetObject("type_icon_" + type.ToString("00")) as Image; } private static Image getSprite(MysteryGift gift) { if (gift.Empty) return null; Image img; if (gift.IsPokémon) img = getSprite(gift.convertToPKM(Main.SAV)); else if (gift.IsItem) img = (Image)(Resources.ResourceManager.GetObject("item_" + gift.Item) ?? Resources.unknown); else img = Resources.unknown; if (gift.GiftUsed) img = ImageUtil.LayerImage(new Bitmap(img.Width, img.Height), img, 0, 0, 0.3); return img; } private static Image getSprite(PKM pkm) { return getSprite(pkm.Species, pkm.AltForm, pkm.Gender, pkm.SpriteItem, pkm.IsEgg, pkm.IsShiny, pkm.Format); } private static Image getSprite(SaveFile SAV) { string file = "tr_00"; if (SAV.Generation == 6 && (SAV.ORAS || SAV.ORASDEMO)) file = "tr_" + SAV.MultiplayerSpriteID.ToString("00"); return Resources.ResourceManager.GetObject(file) as Image; } private static Image getWallpaper(SaveFile SAV, int box) { string s = BoxWallpaper.getWallpaper(SAV, box); return (Bitmap)(Resources.ResourceManager.GetObject(s) ?? Resources.box_wp16xy); } // Extension Methods public static Image Sprite(this MysteryGift gift) => getSprite(gift); public static Image Sprite(this PKM pkm) => getSprite(pkm); public static Image Sprite(this SaveFile SAV) => getSprite(SAV); public static Image WallpaperImage(this SaveFile SAV, int box) => getWallpaper(SAV, box); } } <file_sep>using System; using System.Threading; using System.Windows.Forms; namespace PKHeX.WinForms { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main() { // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += UIThreadException; // Set the unhandled exception mode to force all Windows Forms errors to go through our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Run the application Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } // Handle the UI exceptions by showing a dialog box, and asking the user whether or not they wish to abort execution. private static void UIThreadException(object sender, ThreadExceptionEventArgs t) { DialogResult result = DialogResult.Cancel; try { // Todo: make this translatable ErrorWindow.ShowErrorDialog("An unhandled exception has occurred.\nYou can continue running PKHeX, but please report this error.", t.Exception, true); } catch { try { // Todo: make this translatable MessageBox.Show("A fatal error has occurred in PKHeX, and the details could not be displayed. Please report this to the author.", "PKHeX Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { Application.Exit(); } } // Exits the program when the user clicks Abort. if (result == DialogResult.Abort) Application.Exit(); } // Handle the UI exceptions by showing a dialog box, and asking the user whether // or not they wish to abort execution. // NOTE: This exception cannot be kept from terminating the application - it can only // log the event, and inform the user about it. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { var ex = (Exception)e.ExceptionObject; // Todo: make this translatable ErrorWindow.ShowErrorDialog("An unhandled exception has occurred.\nPKHeX must now close.", ex, false); } catch { try { // Todo: make this translatable MessageBox.Show("A fatal non-UI error has occurred in PKHeX, and the details could not be displayed. Please report this to the author.", "PKHeX Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { Application.Exit(); } } } } }
0d662b10a1928dab3747c85a09e318dcf3da9276
[ "C#" ]
4
C#
neonoafs/ImportableToPKHeX
f8f31af1ebecf070a2de6e527a84905d758f53f7
dc62eb9a35bc2f46740b4e44491a06c516880f79
refs/heads/master
<repo_name>mitibatta/GAME-share-api<file_sep>/config/initializers/carrierwave.rb unless Rails.env.development? || Rails.env.test? CarrierWave.configure do |config| config.asset_host = 'https://s3.amazonaws.com/gsimage' config.fog_credentials = { provider: 'AWS', aws_access_key_id: 'AKIATLKQBI5SFVKEAGMI', aws_secret_access_key: '<KEY>', region: 'ap-northeast-1' } config.fog_public = false config.fog_directory = 'gsimage' config.cache_storage = :fog end # CarrierWave.configure do |config| # config.asset_host = 'http://localhost:3000' # end # config.asset_host = 'https://game-share-api.herokuapp.com' end<file_sep>/config/routes.rb Rails.application.routes.draw do match '*path' => 'options_request#preflight', via: :options namespace :api, {format: 'json'} do resources :users, only: [:create, :show] resources :sessions, only: [:create, :destroy] resources :posts get '/posts/tags/:id', to: 'posts#tags' # get '/posts/tag_post', to: 'posts#tag_post' resources :favorites, only: [:index, :create, :destroy] get '/favorites/userIndex/:id', to: 'favorites#indexUsers' get '/favorites/count', to: 'favorites#count' resources :comments, only: [:create, :show] end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end <file_sep>/app/controllers/api/favorites_controller.rb class Api::FavoritesController < ApplicationController def index @login_user = User.find_by(id: params[:id]) page = @login_user.favorite_posts.all.length.fdiv(5).ceil @favorites = @login_user.favorite_posts.page(params[:page] ||= 1).per(5).order(created_at: :desc) @favs = Favorite.all @pictures = [] @users = [] @favorites.each do |favorite| pic = Picture.find_by(post_id: favorite.id) @pictures.push(pic) @users.push(favorite.user) end render json: {posts: @favorites, pictures: @pictures, users: @users, favorites: @favs, pages: page} end def indexUsers @user = User.find_by(id: params[:id]) @post = @user.favorite_posts.all render json: @post end def count @post = Post.find_by(id: params[:id]) @favorite = @post.favorites.all render json: @favorite.length end def create @favorite = Favorite.new(favorite_params) # @favorite.user_id = current_user.id if @favorite.user_id.blank? || @favorite.post_id.blank? response_bad_request elsif @favorite.save response_success('いいね') else response_internal_server_error end end def destroy @favorite = Favorite.find_by(favorite_params) if @favorite.destroy response_success('いいねの削除') else response_internal_server_error end end private def favorite_params params.require(:favorite).permit(:post_id, :user_id) end def post_params params.require(:favorite).permit(:user_id) end end <file_sep>/app/models/post.rb class Post < ApplicationRecord validates :user_id, presence:true validates :text, presence:true belongs_to :user has_many :pictures has_many :favorites has_many :comments has_many :tagmaps, dependent: :destroy has_many :tags, through: :tagmaps, source:'tag' has_many :favorite_users, through: :favorites, source:'user' accepts_nested_attributes_for :pictures def save_posts(savepost_tags) current_tags = self.tags.pluck(:name) unless self.tags.nil? old_tags = current_tags - savepost_tags new_tags = savepost_tags - current_tags # Destroy old taggings: old_tags.each do |old_name| self.tags.delete Tag.find_by(name:old_name) end # Create new taggings: new_tags.each do |new_name| post_tag = Tag.find_or_create_by(name:new_name) self.tags << post_tag # post_tag = Tag.new(name:new_name) # post_tag.save end end end <file_sep>/app/controllers/api/comments_controller.rb class Api::CommentsController < ApplicationController def create @comment = Comment.new(comment_params) if @comment.text.blank? || @comment.post_id.blank? ||@comment.user_id.blank? response_bad_request elsif @comment.save response_success('コメントの投稿') else response_internal_server_error end end def show @post = Post.find_by(id: params[:id]) @comments = @post.comments.all @user = [] @comments.each do |comment| user = User.find_by(id: comment.user_id) @user.push(user) end render json: {comments: @comments, users: @user} end private def comment_params params.require(:comment).permit(:text, :post_id, :user_id) end end <file_sep>/app/controllers/api/sessions_controller.rb class Api::SessionsController < ApplicationController before_action :set_user, only: :create def create @user.password = <PASSWORD> if @user.email.blank? || @user.password.blank? response_bad_request elsif @user.authenticate(password_params[:password_digest]) log_in @user response_success_login else response_unauthorized end end def destroy log_out response_success("ログアウト") end private def set_user @user = User.find_by(email_params) response_not_found(:user) if @user.blank? end def email_params params.require(:session).permit(:email) end def password_params params.require(:session).permit(:password_<PASSWORD>) end def log_in(user) session[:user_id] = user.id end def log_out session.delete(:user_id) end end <file_sep>/app/controllers/api/posts_controller.rb class Api::PostsController < ApplicationController before_action :set_post, only: [:show, :update, :destroy] def index page = Post.all.length.fdiv(5).ceil @posts = Post.page(params[:page] ||= 1).per(5).order(created_at: :desc) @favorite = Favorite.all @tag = Tag.pluck(:name) @tag_post = {} @user = [] @picture = [] @posts.each do |post| key = post.id value = post.tags user = post.user pic = Picture.find_by(post_id: post.id) @tag_post[key] = value @user.push(user) @picture.push(pic) end # binding.pry render json: {posts: @posts, users: @user, pictures: @picture, favorites: @favorite, pages: page, tags: @tag, tag_post: @tag_post} end def create # binding.pry @post = Post.new(post_params) @post.pictures.build(image: params[:post][:image], video: params[:post][:video], user_id: params[:post][:user_id]) @post.pictures.each do |picture| picture.post_id = @post.id end if @post.text.blank? response_bad_request elsif @post.save tag_list = params[:post][:tag_name].split(",") @post.save_posts(tag_list) response_success("投稿") else response_internal_server_error end end def show @picture = Picture.find_by(post_id: params[:id]) @favorites = @post.favorites @user = @post.user.name @tag_post = @post.tags render json: {post: @post, picture: @picture, user: @user, favorites: @favorites, tag_post: @tag_post} end def update if @post.text.blank? response_bad_request elsif @post.update(post_params) @post.pictures.update(image: params[:post][:image], video: params[:post][:video]) response_success('投稿の更新') else response_internal_server_error end end def destroy if @post.destroy @pic = Picture.find_by(id: params[:id]) @pic.destroy response_success('投稿の削除') else response_internal_server_error end end def tags tag = Tag.find_by(name: params[:id]) page = tag.posts.all.length.fdiv(5).ceil @posts = tag.posts.page(params[:page] ||= 1).per(5).order(created_at: :desc) @favorite = Favorite.all @tag = Tag.pluck(:name) @tag_post = {} @user = [] @picture = [] @posts.each do |post| key = post.id value = post.tags user = post.user pic = Picture.find_by(post_id: post.id) @tag_post[key] = value @user.push(user) @picture.push(pic) end # binding.pry render json: {posts: @posts, users: @user, pictures: @picture, favorites: @favorite, pages: page, tags: @tag, tag_post: @tag_post} end private def set_post @post = Post.find_by(id: params[:id]) response_not_found(:post) if @post.blank? end def post_params params.require(:post).permit(:text, :user_id) end # def picture_params # params.require(:post).permit(:image, :video, :user_id) # end end <file_sep>/app/models/user.rb class User < ApplicationRecord validates :name, presence: true validates :name, length:{maximum:15} validates :email, presence: true validates :email, format:{ with: /\A[\w+-.]+@[a-z\d\-.]+\.[a-z]+\z/i} validates :email, uniqueness: true validates :password_digest, length:{minimum:8} validates :password_digest, length:{maximum:32} validates :password_digest, format:{ with: /\A[\w]+\z/} has_many :pictures has_many :posts has_many :favorites has_many :comments has_many :favorite_posts, through: :favorites, source:'post' has_secure_password end <file_sep>/app/controllers/api/users_controller.rb class Api::UsersController < ApplicationController before_action :set_user, only: :show def create @user = User.new(user_params) if @user.name.blank? || @user.email.blank? ||@user.password_digest.blank? response_bad_request elsif User.exists?(email: @user.email) response_conflict(:user) elsif @user.save response_success('アカウント作成') else response_internal_server_error end end def show page = @user.posts.all.length.fdiv(5).ceil @posts = @user.posts.page(params[:page] ||= 1).per(5).order(created_at: :desc) @pictures = [] @favorites = Favorite.all @posts.each do |post| pic = Picture.find_by(post_id: post.id) @pictures.push(pic) end render json: {user: @user, posts: @posts, pictures: @pictures, favorites: @favorites, pages: page} end private def set_user @user = User.find_by(id: params[:id]) response_not_found(:user) if @user.blank? end def user_params params.require(:user).permit(:name, :email, :password_digest) end end <file_sep>/app/models/picture.rb class Picture < ApplicationRecord validates :image, presence: true, if: -> { video.blank? } validates :video, presence: true, if: -> { image.blank? } belongs_to :post belongs_to :user mount_uploader :image, ImageUploader mount_uploader :video, VideoUploader end
5591c8a2f7511ba1f9dc3d684487ebee385f9af5
[ "Ruby" ]
10
Ruby
mitibatta/GAME-share-api
036ce68eb126e1c70ebf73da82ac217202ff64e4
91eb125d92cd4d9fbe31ecbc8f955cbd07909852
refs/heads/master
<file_sep>class LoggingTable < ActiveRecord::Migration def up create_table :model_accesses do |t| t.string :username, null: false, limit: 50 t.string :model, null: false, limit: 50 t.string :time, null: false end end def down drop_table :model_accesses end end <file_sep>class AddOrdersTable < ActiveRecord::Migration def up create_table :orders do |t| t.references :user, index: true t.references :product, index: true t.integer :total_price, null: false t.integer :quantity, null: false t.timestamps end create_table :user_addresses do |t| t.references :user, index: true t.string :address t.string :country t.string :code t.timestamps end end def down drop_table :orders drop_table :user_addresses end end <file_sep>class ChangePorductDescriptionColumn < ActiveRecord::Migration def up change_column :products, :product_description, :text, :null => false, :limit => 300 end def down change_column :products, :product_description, :text, :null => false, :limit => 50 end end <file_sep>class AddTableToHoldPermissions < ActiveRecord::Migration def up create_table :sensitive_models do |t| t.string :name, null: false, limit: 50 t.timestamps end create_table :user_permissions do |t| t.string :username, null: false, limit: 50 t.string :sensitive_model_name, null: false, limit: 50 t.boolean :allow_write, null: false, default: false t.boolean :allow_read, null: false, default: false end end def down drop_table :sensitive_models drop_table :user_permissions end end <file_sep>class UsersController < ApplicationController before_action :set_user_and_address, only: [:show] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show end private # Use callbacks to share common setup or constraints between actions. def set_user_and_address @user = User.find(params[:id]) @address = UserAddress.where(user: @user)[0] end end <file_sep>class SensitiveModel < ActiveRecord::Base end <file_sep>class ModelAccess < ActiveRecord::Base end <file_sep>json.extract! @order, :id, :user, :product, :quantity, :total_price, :created_at, :updated_at <file_sep>class AddReferenceToAddress < ActiveRecord::Migration def up remove_column :users, :address end def down remove_reference :users, :user_addresses add_column :users, :address, :text end end <file_sep>class ModelAccessesController < ApplicationController before_action :set_model_view, only: [:show] # GET /orders # GET /orders.json def index @accesses = ModelAccess.all end # GET /orders/1 # GET /orders/1.json def show end private # Use callbacks to share common setup or constraints between actions. def set_model_view @access = ModelAccess.find(params[:id]) end end <file_sep>class AddUsersModel < ActiveRecord::Migration[5.1] def up create_table :users do |t| t.string :name, null: false, limit: 50 t.string :surname, null: false, limit: 50 t.text :address t.string :phone_number, null: false, limit: 20 t.timestamps end end def down drop_table :users end end <file_sep>class AdminController < ApplicationController def index all_models all_users user_permissions sensitive_models end def create UserPermission.destroy_all persist_allow_read(params) persist_allow_write(params) redirect_to action: "index" end private def persist_allow_read(params) checkboxes = params.keys.select{ |x| x.start_with?("access_r_")} checkboxes.each do |checkbox| value = params[checkbox] values = value.split('_') model = values[0] user = values[1] perm = UserPermission.find_or_create_by(sensitive_model_name: Object.const_get(model).table_name, username: user) perm.update_attributes(allow_read: true) end end def persist_allow_write(params) checkboxes = params.keys.select{ |x| x.start_with?("access_w_")} checkboxes.each do |checkbox| value = params[checkbox] values = value.split('_') model = values[0] user = values[1] perm = UserPermission.find_or_create_by(sensitive_model_name: Object.const_get(model).table_name, username: user) perm.update_attributes(allow_write: true) end end def all_models Rails.application.eager_load! models = ActiveRecord::Base.descendants @models_str = [] models.each do |model| @models_str << model.to_s unless remove_model?(model) end end def remove_model?(model) model.to_s == "ActiveRecord::SchemaMigration" || model.to_s == "ModelAccess" || model.to_s == "SensitiveModel" || model.to_s == "UserPermission" end def all_users @users = Etc.getgrnam('ubuntu').mem end def user_permissions @user_permissions ||= UserPermission.all end def sensitive_models @sensitive_models ||= SensitiveModel.all.map { |x| x.name } end end <file_sep>json.array!(@accesses) do |access| json.extract! access, :id, :username, :model, :time json.url product_url(product, format: :json) end <file_sep>json.extract! @access, :id, :username, :model, :time <file_sep># ruby-getting-started A simple Rails app based on Heroku bootstrap app for demo purposes. This was built as part of my project in Computer Forensics and Digital investigations as a way to demonstrate the functionality of [rails-console-access-check gem](https://github.com/siwS/rails-console-access-check) ## Running Locally Make sure you have Ruby installed. Also, install the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) (formerly known as the Heroku Toolbelt). ```sh $ git clone <EMAIL>:siwS/ucd-demo-app.git $ cd ruby-getting-started $ bundle install $ bundle exec rake db:create db:migrate $ rails server ``` Your app should now be running on [localhost:3000](http://localhost:3000/).
68e5c78435e62e232f9b18ec8049f167a0c88b40
[ "Markdown", "Ruby" ]
15
Ruby
siwS/ucd-demo-app
53c209b89333f8fa984ef4cc663b24fc501df186
649760b3d775a1ecd07c18d678b76e87f3eea7f2
refs/heads/master
<file_sep>from __future__ import division import numpy as np import pdb from _layer import _layer class Input(_layer): def __init__(self, shape): """ Input layer for a model * shape: shape of the input will passed, height x width x channels """ super().__init__() self._f_output = np.zeros(shape).astype(np.float32) self._outp_shape = self._f_output.shape self._name = 'Input_' + self._name self._outp_layer = None def _forward(self, input_data): """Copy input data to memory""" self._f_output = np.copy(input_data).astype(np.float32) def _backprop(self): pass @property def detail(self): print(self._name) print('Input shape:' + str(self._outp_shape)) class Output(_layer): def __init__(self): super().__init__() self._name = 'Output_' + self._name def _forward(self): self._f_output = self._inp_layer._f_output def _backprop(self, grad): self._b_output = grad class Dropout(_layer): def __init__(self, rate): super(Dropout, self).__init__() self._dropout_rate = rate self._name = 'Dropout_' + self._name def _forward(self): # f_input = self._inp_layer._f_output; self._drop_mask = np.random.normal( 0, 1, self._outp_shape) > self._dropout_rate self._f_output = np.multiply(self._inp_layer._f_output, self._drop_mask) def _backprop(self): # b_input = self._outp_layer._b_output; self._b_output = np.multiply(self._outp_layer._b_output, self._drop_mask) class Flatten(_layer): def __init__(self): super(Flatten, self).__init__() self._name = 'Flatten_' + self._name def _forward(self): self._f_output = self.inp_layer._f_output.flatten() def _backprop(self): self._b_output = np.reshape(self._outp_layer._b_output, self._inp_layer._f_output.shape) def _set_outp_shape(self, input_shape): self.outp_shape = (np.prod(input_shape), ) class FC(_layer): def __init__(self, n_unit, l2=0): super(FC, self).__init__() self._name = 'FC_' + self._name self._n_unit = n_unit self._weight_update = True self._input_error = None self._l2 = l2 def _set_outp_shape(self, input_shape): self.outp_shape = (self._n_unit, ) # Set the output shape # Init the weight matrix and bias vector self._w = np.random.normal( 0, 0.1, (self.inp_layer._outp_shape[0], self._n_unit)).astype(np.float32) self._b = np.random.normal(0, 0.1, (self._n_unit, )).astype(np.float32) def _check_input(self, layer): if (len(layer.outp_shape) == 1): self._input_error = None return True else: self._input_error = "Expected input shape to be a matrix of (n,1)! The input's shape: {} ".format( str(layer.outp_shape)) def _forward(self): """ Feed forward """ # pdb.set_trace() mul = np.reshape(np.matmul(self._w.T, self.inp_layer._f_output), self._outp_shape) self._f_output = np.add(mul, self._b) def _backprop(self): """ Backpropagation """ # pdb.set_trace(); self._b_output = np.matmul(self._w, self.outp_layer._b_output) if (self._weight_update): x = np.reshape(self.inp_layer._f_output, (-1, 1)) y = np.reshape(self.outp_layer._b_output, (-1, 1)) self._grad_w = np.matmul(x, y.T) + self._l2 * (2 * self._w) self._grad_b = np.sum(self.outp_layer._b_output) class Conv2d(_layer): def __init__(self, filter_size, n_filter, stride, padding='same', l2=0): super(Conv2d, self).__init__() self._filter_size = filter_size self._n_filter = n_filter self._stride = stride self._name = 'Conv2d_' + self._name self._padding = padding self._grad = True self._weight_update = True self._l2 = l2 def _check_input(self, layer): shape = layer.outp_shape if (len(shape)) != 2: self._input_error = None # Check input layer 's output shape and filter_size. Input shape must be channel x h x w return True def _set_outp_shape(self, shape): if (len(shape) not in [2, 3]): raise ValueError('Expected input to be 2D or 3D') if (len(shape) == 2): inp_shape = (1, ) + tuple(shape) else: inp_shape = tuple(shape) # Compute the output shape of the layer with the padding mode outp_h = (inp_shape[1] - self._filter_size[0]) / self._stride[0] + 1 outp_w = (inp_shape[2] - self._filter_size[1]) / self._stride[1] + 1 if (self._padding == 'valid'): outp_h = np.floor(outp_h).astype(np.int) outp_w = np.floor(outp_w).astype(np.int) else: outp_h = np.ceil(outp_h).astype(np.int) outp_w = np.ceil(outp_w).astype(np.int) self.outp_shape = (self._n_filter, outp_h, outp_w) self.inp_shape = inp_shape # init the weight self._init_weight(inp_shape) def _init_weight(self, inp_shape): self._w = np.random.normal( 0, 0.1, (self._n_filter, inp_shape[0], self._filter_size[0], self._filter_size[1])) self._b = np.random.normal(0, 0.1, (self._n_filter, 1)) def _pad(self, inp): if (self._padding == 'valid'): padded = inp elif (self._padding == 'same'): h_pad_size_b = np.floor( ((self.outp_shape[1] - 1) * self._stride[0] + self._filter_size[0] - self.inp_shape[1]) / 2).astype(np.int) h_pad_size_a = np.ceil( ((self.outp_shape[1] - 1) * self._stride[0] + self._filter_size[0] - self.inp_shape[1]) / 2).astype(np.int) w_pad_size_b = np.floor( ((self.outp_shape[2] - 1) * self._stride[1] + self._filter_size[1] - self.inp_shape[2]) / 2).astype(np.int) w_pad_size_a = np.ceil( ((self.outp_shape[2] - 1) * self._stride[1] + self._filter_size[1] - self.inp_shape[2]) / 2).astype(np.int) self._pad_width = ((0, 0), (h_pad_size_b, h_pad_size_a), (w_pad_size_b, w_pad_size_a)) padded = np.pad(inp, self._pad_width, mode='constant', constant_values=0) self._padded_size = padded.shape return padded def _depad(self, inp, pad_width): h_b = pad_width[1][0] h_a = pad_width[1][1] w_b = pad_width[2][0] w_a = pad_width[2][1] depad = np.copy(inp[:, h_b:self._padded_size[1] - h_a, w_b:self._padded_size[2] - w_a]) return depad def _forward(self): # Feed forward convolution, using numpy only if (len(self._inp_layer.outp_shape) == 2): padded = np.expand_dims(self._inp_layer._f_output, axis=0) padded = self._pad(padded) else: padded = self._pad(self._inp_layer._f_output) self._f_output = self._conv2d(padded, self._w, self._b, self._stride, self.outp_shape) def _backprop(self): # Backpropagation self._b_output = np.zeros(self._padded_size).astype(np.float32) inp = self._padded_size w = self._w stride = self._stride inp_shape = self._padded_size o_h = 0 o_w = 0 if (len(self._inp_layer.outp_shape) == 2): padded = np.expand_dims(self._inp_layer._f_output, axis=0) padded = self._pad(padded) else: padded = self._pad(self._inp_layer._f_output) if (self._grad): self._grad_w = np.zeros(self._w.shape).astype(np.float32) self._grad_b = np.zeros(self._b.shape).astype(np.float32) for h_o in range(0, inp[1] - w.shape[2] + 1, stride[0]): o_w = 0 for w_o in range(0, inp[2] - w.shape[3] + 1, stride[1]): for n in range(0, w.shape[0]): self._b_output[:, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]] += ( self._outp_layer._b_output[n, o_h, o_w] * w[n, :, :, :]) if (self._grad): self._grad_w[n, :, :, :] += ( padded[:, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]] * self._outp_layer._b_output[n, o_h, o_w]) self._grad_b[n, 0] += ( self._outp_layer._b_output[n, o_h, o_w] * np.sum(padded[:, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]])) o_w += 1 o_h += 1 self._b_output = self._depad(self._b_output, self._pad_width) if (len(self.inp_layer.outp_shape) == 2): self._b_output = np.squeeze(self._b_output, axis=0) def _conv2d(self, inp, w, b, stride, outp_shape): """ perform 2D convolution over the input by the filters * inp: 3D or 2D numpy array. The order of dimension is channel x h x w * w: weight of filter (or kernels) used to convolved, a numpy array with the order: n_filter x channel x h x w * b: bias vector, a numpy array with shape [n_filter,1] * stride: stride of the convolution h x w * outp_shape: output shape of the convolution """ o_h = 0 o_w = 0 outp = np.zeros(outp_shape) for n in range(0, w.shape[0]): o_h = 0 for h_o in range(0, inp.shape[1] - w.shape[2] + 1, stride[0]): o_w = 0 for w_o in range(0, inp.shape[2] - w.shape[3] + 1, stride[1]): outp[n, o_h, o_w] = np.sum( np.multiply( w[n, :, :, :], inp[:, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]])) + b[n, 0] o_w = o_w + 1 o_h = o_h + 1 return outp class AvgPool(Conv2d): def __init__(self, pool_size, padding='same', stride=None): """ 2D convolution with average weight and no bias """ if stride == None: _stride = pool_size else: _stride = stride super(AvgPool, self).__init__(filter_size=pool_size, n_filter=1, stride=_stride, padding=padding) self._weight_update = False self._name = 'AvgPool_' + str(self._name.strip('_')[-1]) def _init_weight(self, inp_shape): self._w = np.ones((self._n_filter, inp_shape[0], self._filter_size[0], self._filter_size[1])) / np.prod(self._filter_size) self._b = np.zeros((self._n_filter, 1)) def _conv2d(self, inp, w, b, stride, outp_shape): o_h = 0 o_w = 0 outp = np.zeros(outp_shape) for h_o in range(0, inp.shape[1] - w.shape[2] + 1, stride[0]): o_w = 0 for w_o in range(0, inp.shape[2] - w.shape[3] + 1, stride[1]): outp[:, o_h, o_w] = np.sum(np.multiply( w[0, :, :, :], inp[:, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]]), axis=(1, 2)) + b[:, 0] o_w = o_w + 1 o_h = o_h + 1 return outp def _set_outp_shape(self, shape): if (len(shape) not in [2, 3]): raise ValueError('Expected input to be 2D or 3D') if (len(shape) == 2): inp_shape = (1, ) + tuple(shape) else: inp_shape = tuple(shape) # Compute the output shape of the layer with the padding mode outp_h = (inp_shape[1] - self._filter_size[0]) / self._stride[0] + 1 outp_w = (inp_shape[2] - self._filter_size[1]) / self._stride[1] + 1 if (self._padding == 'valid'): outp_h = np.floor(outp_h).astype(np.int) outp_w = np.floor(outp_w).astype(np.int) else: outp_h = np.ceil(outp_h).astype(np.int) outp_w = np.ceil(outp_w).astype(np.int) self.outp_shape = (inp_shape[0], outp_h, outp_w) self.inp_shape = inp_shape # init the weight self._init_weight(inp_shape) def _backprop(self): # Backpropagation self._b_output = np.zeros(self._padded_size).astype(np.float32) inp = self._padded_size w = self._w stride = self._stride inp_shape = self._padded_size o_h = 0 o_w = 0 if (len(self._inp_layer.outp_shape) == 2): padded = np.expand_dims(self._inp_layer._f_output, axis=0) padded = self._pad(padded) else: padded = self._pad(self._inp_layer._f_output) for h_o in range(0, inp[1] - w.shape[2] + 1, stride[0]): o_w = 0 for w_o in range(0, inp[2] - w.shape[3] + 1, stride[1]): for n in range(0, inp_shape[0]): self._b_output[n, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]] += ( self._outp_layer._b_output[n, o_h, o_w] * w[0, n, :, :]) o_w += 1 o_h += 1 # pdb.set_trace() self._b_output = self._depad(self._b_output, self._pad_width) if (len(self.inp_layer.outp_shape) == 2): self._b_output = np.squeeze(self._b_output, axis=0) class MaxPool(Conv2d): def __init__(self, pool_size, padding='same', stride=None): """ 2D convolution with average weight and no bias """ if stride == None: _stride = pool_size else: _stride = stride super(MaxPool, self).__init__(filter_size=pool_size, n_filter=1, stride=_stride, padding=padding) self._name = 'MaxPool_' + str(self._name.strip('_')[-1]) self._weight_update = False def _init_weight(self, inp_shape): self._w = np.ones((self._n_filter, inp_shape[0], self._filter_size[0], self._filter_size[1])) / np.prod(self._filter_size) self._b = np.zeros((self._n_filter, 1)) def _conv2d(self, inp, w, b, stride, outp_shape): self._arg_max = np.zeros(outp_shape).astype(np.int32) o_h = 0 o_w = 0 outp = np.zeros(outp_shape) for h_o in range(0, inp.shape[1] - w.shape[2] + 1, stride[0]): o_w = 0 for w_o in range(0, inp.shape[2] - w.shape[3] + 1, stride[1]): for n in range(inp.shape[0]): x = inp[n, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]] self._arg_max[n, o_h, o_w] = np.argmax(x) outp[n, o_h, o_w] = np.max(x) o_w = o_w + 1 o_h = o_h + 1 return outp def _set_outp_shape(self, shape): if (len(shape) not in [2, 3]): raise ValueError('Expected input to be 2D or 3D') if (len(shape) == 2): inp_shape = (1, ) + tuple(shape) else: inp_shape = tuple(shape) # Compute the output shape of the layer with the padding mode outp_h = (inp_shape[1] - self._filter_size[0]) / self._stride[0] + 1 outp_w = (inp_shape[2] - self._filter_size[1]) / self._stride[1] + 1 if (self._padding == 'valid'): outp_h = np.floor(outp_h).astype(np.int) outp_w = np.floor(outp_w).astype(np.int) else: outp_h = np.ceil(outp_h).astype(np.int) outp_w = np.ceil(outp_w).astype(np.int) self.outp_shape = (inp_shape[0], outp_h, outp_w) self.inp_shape = inp_shape # init the weight self._init_weight(inp_shape) def _forward(self): # Feed forward convolution, using numpy only if (len(self._inp_layer.outp_shape) == 2): padded = np.expand_dims(self._inp_layer._f_output, axis=0) padded = self._pad(padded) else: padded = self._pad(self._inp_layer._f_output) self._f_output = self._conv2d(padded, self._w, self._b, self._stride, self.outp_shape) def _backprop(self): # Backpropagation self._b_output = np.zeros(self._padded_size).astype(np.float32) inp = self._padded_size w = self._w stride = self._stride inp_shape = self._padded_size o_h = 0 o_w = 0 if (len(self._inp_layer.outp_shape) == 2): padded = np.expand_dims(self._inp_layer._f_output, axis=0) padded = self._pad(padded) else: padded = self._pad(self._inp_layer._f_output) for h_o in range(0, inp[1] - w.shape[2] + 1, stride[0]): o_w = 0 for w_o in range(0, inp[2] - w.shape[3] + 1, stride[1]): for n in range(0, inp_shape[0]): arg = np.unravel_index(self._arg_max[n, o_h, o_w], (w.shape[2], w.shape[3])) self._b_output[ n, h_o:h_o + w.shape[2], w_o:w_o + w.shape[3]][arg] += self._outp_layer._b_output[n, o_h, o_w] o_w += 1 o_h += 1 pdb.set_trace() self._b_output = self._depad(self._b_output, self._pad_width) if (len(self.inp_layer.outp_shape) == 2): self._b_output = np.squeeze(self._b_output, axis=0) <file_sep>This repo is naive CNN implementation following Keras style in the very early time of learning deep learning. <file_sep>from __future__ import division import numpy as np def CrossEntropy(y_true, y_pred): y_true = y_true.flatten() y_pred = y_pred.flatten() eps = 1e-16 loss = -np.sum(np.multiply(y_true, np.log(y_pred + eps))) grad = -np.divide(y_true, y_pred + eps) return loss, grad def Logistic(y_true, y_pred): eps = 1e-16 loss = -y_true * np.log(y_pred + eps) - (1 - y_true) * np.log(1 - y_pred + eps) grad = -y_true / (y_pred + eps) + (1 - y_true) / (1 - y_pred + eps) return loss, grad <file_sep>from __future__ import division import time import random import numpy as np import glob2 import matplotlib.pyplot as plt import glob2 from primitive.Model import * from primitive.Layers import * from primitive.Activations import * from primitive.Loss import * def loadImage(imgDir, num=150, flatten=True): files = glob2.glob(imgDir + '/*.jpg') if num != None: idx = np.random.randint(0, len(files) - num - 1) files = files[idx:idx + num] if (flatten): x = [plt.imread(img).flatten() for img in files] else: x = [plt.imread(img) for img in files] x = np.pad(x, ((0, 0), (2, 2), (2, 2)), mode='constant') img = np.array(x) return img # Logistic regression classifier num = 2000 labels = range(0, 10) X = [loadImage('./trainingSet/' + str(s), num, True) for s in labels] X = np.concatenate(X, axis=0) y = list([]) for s in labels: l = np.zeros((num, len(labels), 1)) l[:, s, 0] = 1 y.append(l) y = np.concatenate(y, axis=0) c = list(zip(X, y)) random.shuffle(c) X, y = zip(*c) X = np.array(X) y = np.array(y) X = X - np.mean(X) X = X / np.max(X) X = np.expand_dims(X, axis=1) X_train = X[:-5000] y_train = y[:-5000] X_test = X[-5000:] y_test = y[-5000:] model = Model() model.add(Input(shape=(784, 1))) model.add(Flatten()) model.add(FC(120)) model.add(ReLU()) model.add(FC(84)) model.add(ReLU()) model.add(FC(10)) model.add(Softmax()) model.get_name() model.compile(loss=CrossEntropy, lrate=1e-3) print('Number of trainable parameters: ' + str(model.get_num_params)) model.fit(X_train, y_train, epoch=10, batch_size=2) p = model.predict(X_test) acc = [evaluate(y_test[n], p[n]) for n in range(0, p.shape[0])] print(np.sum(acc) / p.shape[0]) model.save('FC_Lenet5.pkl') print('End') <file_sep>import numpy as np from Optimizers import SGD import pdb _layer_cnt = 0 class _layer(object): def __init__(self): """ Base class for layers """ global _layer_cnt # self._f_input = 0; self._f_ouput = 0 self._b_output = 0 # self._b_input = 0; self._outp_layer = None self._inp_layer = None self._outp_shape = None self._inp_shape = None self._name = str(_layer_cnt) _layer_cnt = _layer_cnt + 1 self._weight = 0 self._optimizer = None self._input_error = None self._weight_update = False self._l2 = 0 self._optimizer = None def __call__(self, layer): """ __call__ makes the object callable * Set layer to be input and set the output of that layer to be self. """ if self._check_input(layer): self.inp_layer = layer layer.outp_layer = self else: print(self._input_error) return self @property def outp_layer(self): return self._outp_layer @outp_layer.setter def outp_layer(self, layer): self._outp_layer = layer @property def inp_layer(self): return self._inp_layer @inp_layer.setter def inp_layer(self, layer): self._inp_layer = layer self._set_outp_shape(layer.outp_shape) @property def outp_shape(self): return self._outp_shape @outp_shape.setter def outp_shape(self, shape): self._outp_shape = shape @property def inp_shape(self): return self._inp_shape @inp_shape.setter def inp_shape(self, shape): self._inp_shape = shape def _forward(self): """ Forward propagation """ pass def _backprop(self): """ Backpropagation """ pass def _check_input(self, layer): """ check compatibility of the input layer """ return True def _set_outp_shape(self, shape): """ Set the output shape of the object, base on input shape and the object's own attributes """ self.outp_shape = shape def update(self, batch_size): """ Update the weight of object """ if (self._weight_update): step_w, step_b = self._optimizer._return_step(reset_step=True) self._w -= step_w / batch_size self._b -= step_b / batch_size else: pass @property def detail(self): print(self._name) def set_optimizer(self, optimizer): self._optimizer = optimizer if (self._weight_update): self._optimizer._set_shape(self._w.shape, self._b.shape) else: pass @property def num_params(self): num_params = 0 if (self._weight_update): num_params = np.prod(self._w.shape) + np.prod(self._b.shape) return num_params def update_step(self): if (self._weight_update): # pdb.set_trace() grad_w = self._grad_w + self._w * self._l2 grad_b = self._grad_b + self._b * self._l2 self._optimizer._update_step(grad_w=grad_w, grad_b=grad_b) else: pass <file_sep>import numpy as np Pool_cnt = 0 class Avg_Pool(object): def __init__(self, shape, stride=None): global Pool_cnt self._pool_shape = shape self._pool_stride = stride self._name = 'Avg_Pool_' + str(Pool_cnt) Pool_cnt = Pool_cnt + 1 <file_sep>from __future__ import division import numpy as np import sys, time import pickle from Layers import Input, Output from Optimizers import SGD from Loss import CrossEntropy class Model(object): def __init__(self): """Init layer stack to an empty list!""" self._layer_stack = [] self._loss = None self._grad = 0 def add(self, layer): """Add a layer to model's layer stack""" # pdb.set_trace(); if (len(self._layer_stack) == 0): if isinstance(layer, Input): self._layer_stack.append(layer) else: print("The first layer must be an instance of Input class") else: self._layer_stack.append(layer(self._layer_stack[-1])) def fit(self, train_data, label, validation_data=None, batch_size=1, epoch=1): """Fit the model with given data * train_data: train data, n_samples x channel x h x w * validation_data: validatation_data * batch_size: mini-batch size * epoch: number of epoch """ train_history = 0 for e in range(0, epoch): output = list([]) batch_n = 0 t_start = time.time() for k in range(train_data.shape[0]): if k in range(0, train_data.shape[0], batch_size): # print("Batch: " +str(batch_n)) batch_n += 1 if (batch_n > 1): self.update(batch_size) sys.stdout.write('Epoch {0} / {1}: {2} / {3}\r'.format( str(e), str(epoch), str(k), str(train_data.shape[0]))) sys.stdout.flush() self._forward(train_data[k]) # pdb.set_trace(); loss, self._grad = self._loss(label[k], self._layer_stack[-1]._f_output) # print(loss) output.append(evaluate(label[k], self.output)) self._backprop() output = np.array(output) # pdb.set_trace(); t_end = time.time() print('Epoch {0} / {1}: {2} / {3}. Train_acc: {4} {5}s'.format( str(e), str(epoch), str(k), str(train_data.shape[0]), str(np.sum(np.array(output)) / label.shape[0]), str(t_start - t_end))) def predict(self, data): output = list([]) # pdb.set_trace(); for n, single_data in enumerate(data): self._forward(single_data) output.append(self.output) return np.array(output) @property def output(self): return self._layer_stack[-1]._f_output def save(self, file_name): """ Save the object, use pickle """ def load_para(self, file_name): """ Load the paramters from saved file """ def _forward(self, single_data): """ Perform feed forward """ for layer in self._layer_stack: if (isinstance(layer, Input)): layer._forward(single_data) else: layer._forward() def _backprop(self): """ Backpropagation """ for layer in reversed(self._layer_stack): if (isinstance(layer, Output)): layer._backprop(self._grad) else: layer._backprop() layer.update_step() def metrics(y_pred, y_true): """ Compute accuracy and precision of prediction """ accuracy = 0 precision = 0 return accuracy, precision def load(file_path): """ Load a completed model from file """ model = 0 return model def get_name(self): for layer in self._layer_stack: print(layer._name, layer.outp_shape) @property def get_num_params(self): num_params = 0 for layer in self._layer_stack: num_params += layer.num_params return num_params def compile(self, optimizer=SGD, lrate=1e-3, momentum=0.9, loss=CrossEntropy, l2=0): Out = Output() self.add(Out) self._loss = loss for layer in self._layer_stack: opt = optimizer(lrate=lrate, momentum=momentum) layer.set_optimizer(opt) self._l2 = l2 def update(self, batch_size): for layer in self._layer_stack: layer.update(batch_size) def save(self, filename): f = open(filename, 'wb') pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) f.close() print('Model was saved to ' + filename) def load_model(filename): f = open(filename, 'wb') model = pickle.load(f) f.close() return model def evaluate(y_true, y_pred): if (np.size(y_true) == 1): return np.int(np.int(y_pred > 0.5) == y_true) else: return np.int( np.argmax(y_true.flatten()) == np.argmax(y_pred.flatten())) <file_sep>from __future__ import division from primitive.Model import * from primitive.Layers import * from primitive.Activations import * from primitive.Loss import * import time import pdb import glob2 import matplotlib.pyplot as plt def loadImage(imgDir, num=150, flatten=True): files = glob2.glob(imgDir + '/*.jpg') idx = np.random.randint(0, len(files) - num - 1) files = files[idx:idx + num] if (flatten): x = [plt.imread(img).flatten() for img in files] else: x = [plt.imread(img) for img in files] x = np.pad(x, ((0, 0), (2, 2), (2, 2)), mode='constant') img = np.array(x) return img # Logistic regression classifier num = 2000 labels = range(0, 10) X = [loadImage('../trainingSet/' + str(s), num, False) for s in labels] X = np.concatenate(X, axis=0) y = list([]) for s in labels: l = np.zeros((num, len(labels), 1)) l[:, s, 0] = 1 y.append(l) y = np.concatenate(y, axis=0) c = list(zip(X, y)) import random random.shuffle(c) X, y = zip(*c) X = np.array(X) y = np.array(y) X = X - np.mean(X) X = X / np.max(X) X = np.expand_dims(X, axis=1) X_train = X[:-5000] y_train = y[:-5000] X_test = X[-5000:] y_test = y[-5000:] model = load_model('Lenet5.pkl') p = model.predict(X_test) acc = [evaluate(y_test[n], p[n]) for n in range(0, p.shape[0])] print(np.sum(acc) / p.shape[0]) print('End') <file_sep>""" python primitives """ <file_sep>import numpy as np from _layer import _layer class ReLU(_layer): def __init__(self): """A RelU activation object """ super(ReLU, self).__init__() self._name = 'ReLU_' + str(self._name) def _forward(self): """ Input a numpy array then return the ReLU of the array""" self._f_mask = self._inp_layer._f_output > 0 self._f_output = np.multiply(self._inp_layer._f_output, self._f_mask) def _backprop(self): self._b_output = np.multiply(self._f_mask, self._outp_layer._b_output) @property def detail(self): print('Name: ' + self._name) class Sigmoid(_layer): def __init__(self): """Sigmoid activation object """ super(Sigmoid, self).__init__() self._name = 'Sigmoid_' + self._name def _forward(self): D = np.max(self._inp_layer._f_output) / 2 """ Input a numpy array then return the sigmoid of the array """ self._f_output = np.exp(D) / (np.exp(D) + np.exp(D - self._inp_layer._f_output)) def _backprop(self): local_grad = np.multiply((1 - self._f_output), self._f_output) self._b_output = np.multiply(local_grad, self._outp_layer._b_output) class tanh(_layer): def __init__(self): """ tanh activation object """ super(tanh, self).__init__() self._name = 'tanh_' + self._name def _forward(self): """ Input a numpy array then return the sigmoid of the array""" self._f_output = np.tanh(self._inp_layer._f_output) def _backprop(self): local_grad = (1 - np.multiply(self._f_output, self._f_output)) self._b_output = np.multiply(local_grad, self._outp_layer._b_output) class Softmax(_layer): def __init__(self): super(Softmax, self).__init__() self._name = 'Softmax_' + self._name def _forward(self): D = np.max(self._inp_layer._f_output) self._exp = np.exp(self._inp_layer._f_output - D) self._f_output = self._exp / np.sum(self._exp) def _backprop(self): _exp = np.reshape(self._f_output, (-1, 1)) exp_mat = np.diag(_exp.flatten()) _exp = -np.matmul(_exp, _exp.T) local_grad = exp_mat + _exp self._b_output = np.matmul(local_grad, self._outp_layer._b_output) <file_sep>from __future__ import division import numpy as np import pdb class SGD(object): def __init__(self, lrate=1e-3, momentum=0.9): """ Stochastic gradient descent with momentum optimizer * lrate: Learning rate, default 1e-3 * shape: shape of gradient * momentum: momentum to update the gradient from velocity matrix """ self._lrate = lrate self._momentum = momentum self._mini_batch = 1 def _set_shape(self, shape_w, shape_b): self._v_w = np.zeros(shape_w).astype(np.float32) # Velocity vector w self._step_w = np.zeros(shape_w).astype(np.float32) self._v_b = np.zeros(shape_b).astype(np.float32) # Velocity vector b self._step_b = np.zeros(shape_b).astype(np.float32) def _update_step(self, grad_w=0, grad_b=0): # pdb.set_trace(); self._v_w = self._momentum * self._v_w + grad_w self._v_b = self._momentum * self._v_b + grad_b self._step_w += (self._lrate * self._v_w) self._step_b += (self._lrate * self._v_b) def _return_step(self, reset_step=True): # pdb.set_trace() step_w = self._step_w / self._mini_batch step_b = self._step_b / self._mini_batch self._step_w -= self._step_w self._step_b -= self._step_b return step_w, step_b
70c20eb5ecbda05f5534495b8de02bd378346a03
[ "Markdown", "Python" ]
11
Python
cao-nv/DL-from-scratch
6fb7b496478221d9e1002301af91085c4d659122
2f0d33f555577aca53181935d74f1dd38c73ca28
refs/heads/master
<repo_name>emlanam2608/AutomationClass<file_sep>/JavaPractice/src/main/java/Pages/BasePage.java package Pages; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.WebDriverWait; public class BasePage { ChromeDriver driver; WebDriverWait wait; Actions action; Logger logger = LogManager.getLogger(); JavascriptExecutor js; BasePage(ChromeDriver driver) { this.driver = driver; this.wait = new WebDriverWait(driver, 30); this.action = new Actions(driver); this.js = (JavascriptExecutor) driver; } } <file_sep>/JavaPractice/src/test/java/Practice1/JavaBasicEx4.java package Practice1; public class JavaBasicEx4 { static void findGradeByScore(int score) { if(score >= 9) { System.out.println("Excellent"); } else if(score >= 7) { System.out.println("Good"); } else if(score >= 5) { System.out.println("Normal"); } else { System.out.println("Bad"); } } } <file_sep>/JavaPractice/src/main/java/Scripts/BaseScript.java package Scripts; import Libs.DriverManagement; import Pages.AmazonCartPage; import Pages.AmazonHomePage; import Pages.AmazonProductPage; import Pages.AmazonSearchResultPage; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; public class BaseScript { String url = "https://www.amazon.com/"; DriverManagement driverMgt = new DriverManagement(); ChromeDriver driver = driverMgt.createChromeDriver(); AmazonHomePage homePage = new AmazonHomePage(driver); AmazonSearchResultPage searchResultPage = new AmazonSearchResultPage(driver); AmazonProductPage productPage = new AmazonProductPage(driver); AmazonCartPage cartPage = new AmazonCartPage(driver); Logger logger = LogManager.getLogger(); WebDriverWait wait = new WebDriverWait(driver, 30); JavascriptExecutor js = (JavascriptExecutor) driver; @BeforeTest void beforeTest() { logger.info(String.format("Opening %s", url)); driver.get(url); } @AfterTest void afterTest() { logger.info("Closing all browsers"); // driver.quit(); } } <file_sep>/JavaPractice/src/test/java/Selenium/YahooLoginPage.java package Selenium; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class YahooLoginPage { By btnLoginCreateAccount = By.xpath("//a[@id='createacc']"); ChromeDriver driver; YahooLoginPage(ChromeDriver driver) { this.driver = driver; } void clickCreateAccount() { driver.findElement(btnLoginCreateAccount).click(); } } <file_sep>/JavaPractice/src/main/java/Libs/DriverManagement.java package Libs; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.concurrent.TimeUnit; public class DriverManagement { public ChromeDriver createChromeDriver() { WebDriverManager.chromedriver().setup(); ChromeOptions options = new ChromeOptions(); options.addArguments("--start-maximized"); ChromeDriver driver = new ChromeDriver(options); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return driver; } } <file_sep>/JavaPractice/src/test/java/Selenium/YahooSignUpPage.java package Selenium; import Utils.Utilities; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.chrome.ChromeDriver; import java.util.Locale; public class YahooSignUpPage { By inputSignUpFormFirstName = By.xpath("//input[@id='usernamereg-firstName']"); By inputSignUpFormLastName = By.xpath("//input[@id='usernamereg-lastName']"); By inputSignUpFormEmail = By.xpath("//input[@id='usernamereg-yid']"); By inputSignUpFormPassword = By.xpath("//input[@id='usernamereg-password']"); By selectSignUpFormCountryCode = By.xpath("//select[@name='shortCountryCode']"); By optionSignUpFormCountryCodeVN = By.xpath("//option[@value='VN']"); By inputSignUpFormPhoneNumber = By.xpath("//input[@id='usernamereg-phone']"); By selectSignUpFormDOBMonth = By.xpath("//select[@id='usernamereg-month']"); // By optionSignUpFormMonthAug = By.xpath("//option[contains(text(), 'August')]"); By inputSignUpFormDOBDay = By.xpath("//input[@id='usernamereg-day']"); By inputSignUpFormDOBYear = By.xpath("//input[@id='usernamereg-year']"); By inputSignUpFormGender = By.xpath("//input[@id='usernamereg-freeformGender']"); By btnSignUpFormSubmit = By.xpath("//button[@id='reg-submit-button']"); ChromeDriver driver; YahooSignUpPage(ChromeDriver driver) { this.driver = driver; } By selectMonthOption(int month) { String monthAsText; switch (month) { case 1: monthAsText = "Jan"; break; case 2: monthAsText = "Feb"; break; case 3: monthAsText = "Mar"; break; case 4: monthAsText = "Apr"; break; case 5: monthAsText = "May"; break; case 6: monthAsText = "Jun"; break; case 7: monthAsText = "Jul"; break; case 8: monthAsText = "Aug"; break; case 9: monthAsText = "Sep"; break; case 10: monthAsText = "Oct"; break; case 11: monthAsText = "Nov"; break; case 12: monthAsText = "Dec"; break; default: throw new IllegalStateException("Unexpected value: " + month); } return By.xpath(String.format("//option[contains(text(), '%s')]", monthAsText)); } By selectCountryCodeOption(String countryCode) { String[] listOfCountryCode = {"VN",}; for (int i = 0; i < listOfCountryCode.length; i++) { if (countryCode.toLowerCase().equals(listOfCountryCode[i].toLowerCase())) { return By.xpath(String.format("//option[@value='%s']", countryCode)); } } throw new IllegalStateException("Unexpected value: " + countryCode); } void signUp(String firstName, String lastName, String email, String password, String countryCode, String phoneNumber, int dayOfBirth, int monthOfBirth, int yearOfBirth, String gender) { driver.findElement(inputSignUpFormFirstName).sendKeys(firstName); driver.findElement(inputSignUpFormLastName).sendKeys(lastName); driver.findElement(inputSignUpFormEmail).sendKeys(email); //work around to pass the mail suggestion dropdown Utilities.sleep(1); driver.findElement(inputSignUpFormEmail).sendKeys(Keys.TAB); driver.findElement(inputSignUpFormPassword).sendKeys(<PASSWORD>); driver.findElement(selectSignUpFormCountryCode).click(); driver.findElement(selectCountryCodeOption(countryCode)).click(); driver.findElement(inputSignUpFormPhoneNumber).sendKeys(phoneNumber); driver.findElement(selectSignUpFormDOBMonth).click(); driver.findElement(selectMonthOption(monthOfBirth)).click(); driver.findElement(inputSignUpFormDOBDay).sendKeys(Integer.toString(dayOfBirth)); driver.findElement(inputSignUpFormDOBYear).sendKeys(Integer.toString(yearOfBirth)); driver.findElement(inputSignUpFormGender).sendKeys(gender); // driver.findElement(btnSignUpFormSubmit).click(); } } <file_sep>/JavaPractice/src/main/java/Utils/Utilities.java package Utils; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; public class Utilities { public static void sleep(long sec) { try { Thread.sleep(sec * 1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } static String emailValidator(String email) { //<EMAIL> if (email.contains("@")) { String[] splitEmail = email.split("@"); String username = splitEmail[0]; String domain = splitEmail[1]; if (!username.contains("@") && !domain.contains("@") && domain.contains(".")) { return email; } else { throw new IllegalStateException("Unexpected value: " + email); } } else { throw new IllegalStateException("Unexpected value: " + email); } } public static int[] dateOfBirthValidator(String dateOfBirth) { //dd-mm-yyyy String[] listOfSeparatesSymbol = {"/", "-",}; String[] splitDateOfBirth = {}; for (String s : listOfSeparatesSymbol) { if (dateOfBirth.contains(s)) { splitDateOfBirth = dateOfBirth.split(s); } } if (splitDateOfBirth.length == 3) { int day = Integer.parseInt(splitDateOfBirth[0]); int month = Integer.parseInt(splitDateOfBirth[1]); int year = Integer.parseInt(splitDateOfBirth[2]); if (year < 0 || month < 0 || day < 0 || month > 12 || day > 31) { throw new IllegalStateException("Unexpected value: " + dateOfBirth); } int maxDay; switch(month) { case 2: if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { maxDay = 29; } else { maxDay = 28; } break; case 4: case 6: case 9: case 11: maxDay = 30; break; default: maxDay = 31; break; } if (day > maxDay) { throw new IllegalStateException("Unexpected value: " + dateOfBirth); } return new int[]{day, month, year}; } else { throw new IllegalStateException("Unexpected value: " + dateOfBirth); } } public static void scrollToBottom(JavascriptExecutor js) { //This will scroll the web page till end. long scrollHeight = 0; while ((long) js.executeScript("return document.body.scrollHeight") > scrollHeight) { scrollHeight = (long) js.executeScript("return document.body.scrollHeight"); js.executeScript(String.format("window.scrollTo(0, %d)", scrollHeight)); } } public static void scrollInElement(JavascriptExecutor js, Actions action, WebElement element) { //Hover and scroll in element action.moveToElement(element).perform(); js.executeScript("scrollTo(0, 200)"); } } <file_sep>/JavaPractice/src/test/java/Practice1/JavaBasicEx5.java package Practice1; public class JavaBasicEx5 { static void findReplacementInt(int[] array, int[] replacedArray) { for(int i = 0; i < array.length; i++) { if(array[i] != replacedArray[i]) { System.out.println("The number '" + array[i] + "' is replaced by number '" + replacedArray[i] + "'"); } } } } <file_sep>/JavaPractice/src/test/java/Selenium/YahooLandingPage.java package Selenium; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class YahooLandingPage { By btnLandingSignUp = By.xpath("//span[contains(text(), 'Sign up')]/.."); ChromeDriver driver; public YahooLandingPage(ChromeDriver driver) { this.driver = driver; } void clickCreateAccount() { driver.findElement(btnLandingSignUp).click(); } } <file_sep>/JavaPractice/src/main/java/Pages/AmazonCartPage.java package Pages; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class AmazonCartPage extends BasePage{ By textProductSize = By.xpath("//span[contains(text(), 'Size:')]//following-sibling::span"); By textProductColor = By.xpath("//span[contains(text(), 'Color:')]//following-sibling::span"); By textProductQuantity = By.xpath("(//span[contains(text(), 'Qty:')]//following-sibling::span)[last()]"); public AmazonCartPage(ChromeDriver driver) { super(driver); } public int getProductQuantity() { logger.info("-----Getting product quantity"); int quantity = Integer.parseInt(driver.findElement(textProductQuantity).getText()); logger.info(quantity); return quantity; } public String getTextProductColor() { logger.info("-----Getting product color"); String color = driver.findElement(textProductColor).getText(); logger.info(color); return color; } public String getTextProductSize() { logger.info("-----Getting product size"); String size = driver.findElement(textProductSize).getText(); logger.info(size); return size; } } <file_sep>/JavaPractice/src/test/java/Practice1/JavaAdvanceEx1.java package Practice1; public class JavaAdvanceEx1 { static int[] swapInt(int a, int b) { a = a + b; b = a - b; a = a - b; return new int[]{a, b}; } } <file_sep>/JavaPractice/src/main/java/Scripts/Test.java package Scripts; public class Test { public static void main(String[] args) { BuyingShoe testcase = new BuyingShoe(); testcase.TC_AddToCartAndValidateSizeColor(); } }
a88ffe1ecf73160f52c8bc2f8d628c4ee64c0ff1
[ "Java" ]
12
Java
emlanam2608/AutomationClass
c6521a77d6192b3121af069c28f8302944d246c6
09db429352783a8db285943f9a88b8e45212be6c
refs/heads/master
<repo_name>AranGarcia/HumiditySensor<file_sep>/arduinoiface.py import serial import threading import numpy class DoubleVarContainer: def __init__(self, container): self.container = container def update(self, value): self.container.set(value) class Reader: def __init__(self, port, dvar, size): try: self.arduino = serial.Serial(port, 115200, timeout=.1) except serial.serialutil.SerialException: print("[ERROR] No se pudo conectar con el arduino.") exit(1) self.dvar = DoubleVarContainer(dvar) self.t = None self.measures = [0 for i in range(int(size))] def start(self): self.t = threading.Thread(target=self.__read) self.t.daemon = True self.t.start() def __read(self): resolution = 100 / 255 while True: data = self.arduino.read(1) if data: value = int.from_bytes(data, byteorder="little") m = value * resolution self.dvar.update(m) self.measures.pop(0) self.measures.append(m) <file_sep>/notes.md ### Credits water-drop.png made by <NAME> from [Flaticon](https://www.flaticon.com/free-icon/water-drop_179181) <file_sep>/monitor.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import tkinter as tk import matplotlib.animation as animation import serial from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from tkinter import font import util from arduinoiface import Reader PROPS = util.get_config() class CustomWidget: """ Abstract class for all widgets. The create_widghets method is to be overwritten so that the widget may be properly intialized. """ def create_widgets(self): raise NotImplementedError class InfoFrame(tk.Frame, CustomWidget): bgcolor = util.rgb(41, 43, 44) txcolor = util.rgb(255, 255, 255) def __init__(self, master): super(InfoFrame, self).__init__(master, background=InfoFrame.bgcolor) self.pack(side=tk.LEFT, fill=tk.BOTH) self.create_widgets() def create_widgets(self): lblfont = font.Font(family="Verdana") tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor, text="Instituto Politecnico Nacional\nEscuela Superior de Computo\n").grid(row=0, columnspan=2) tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor, text="Instrumentacion").grid(row=1, column=0) tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor, text=PROPS["grupo"]).grid(row=1, column=1) names = PROPS["integrantes"].split(";") lblteam = tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor, justify="left", text='\n'.join(names)) lblteam.grid(row=3, columnspan=2) self.measurement = tk.DoubleVar(self, value=0) tk.Entry(self, text="Valor de prueba", justify="center", state="readonly", textvariable=self.measurement, width=10).grid(row=5, column=0) tk.Label(self, font=lblfont, background=InfoFrame.bgcolor, foreground=InfoFrame.txcolor, text="% de humedad").grid(row=5, column=1) self.grid_rowconfigure(2, minsize=100) self.grid_rowconfigure(4, minsize=50) class MonitorCanvas(Figure, CustomWidget): def __init__(self, master): super(MonitorCanvas, self).__init__(figsize=(5, 4), dpi=100) self.master = master # Plot stuff self.liminf = int(PROPS["liminf"]) self.limsup = int(PROPS["limsup"]) # Serial reader self.r = Reader(PROPS["port"], i.measurement, int(PROPS["seconds"]) / 0.01) self.r.start() self.create_widgets() def create_widgets(self): ax = self.subplots() self.x = np.arange(0, int(PROPS["seconds"]), 0.01) self.y = np.zeros(len(self.x)) self.line, = ax.plot(self.x, self.y) ax.set_ylabel("Porcentaje de humedad") ax.set_ybound(0, 105) self.set_tight_layout(True) canvas = FigureCanvasTkAgg(self, master=self.master) canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.ani = animation.FuncAnimation( self, self.animate, init_func=self.init, interval=32, blit=True, save_count=50) canvas.draw() def init(self): self.line.set_ydata(np.zeros(len(self.x))) return self.line, def animate(self, i): self.line.set_ydata(self.r.measures) return self.line, if __name__ == '__main__': root = tk.Tk() root.title("Sensor de humedad") icon = tk.PhotoImage(file='water-drop.png') root.tk.call('wm', 'iconphoto', root._w, icon) i = InfoFrame(root) m = MonitorCanvas(root) root.mainloop() <file_sep>/util.py def get_config(fname="sensor.config"): with open(fname, encoding="utf8") as fobj: lines = fobj.readlines() props = {} try: for l in lines: key, value = l.split('=') props[key] = value.rstrip('\n') except ValueError: print("Error al cargar configuracion del sensor.") return props def rgb(r, g, b): return "#%02x%02x%02x" % (r, g, b) if __name__ == "__main__": print(get_config()) <file_sep>/requirements.txt cycler==0.10.0 kiwisolver==1.0.1 matplotlib==3.0.0 numpy==1.15.2 pkg-resources==0.0.0 pyparsing==2.2.2 pyserial==3.4 python-dateutil==2.7.3 six==1.11.0
a267109af06f1e5100b87be78b571052fa9e151c
[ "Markdown", "Python", "Text" ]
5
Python
AranGarcia/HumiditySensor
5426ef8d765857926bde686423ce5097249b9adb
c0be1713ab7db520706404bb249605d8404b0b7f
refs/heads/master
<repo_name>maxtrussell/gym-stock-bot<file_sep>/query-item.sh #!/bin/bash db="db.sqlite" sqlite3 ${db} <<EOF SELECT ProductName, ItemName, InStock, DATETIME(Timestamp, 'localtime') FROM stock WHERE ItemName = "$1"; .exit EOF <file_sep>/main.go package main import ( "bufio" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "regexp" "strings" "time" "github.com/PuerkitoBio/goquery" "github.com/maxtrussell/gym-stock-bot/analytics" "github.com/maxtrussell/gym-stock-bot/database" "github.com/maxtrussell/gym-stock-bot/models/item" "github.com/maxtrussell/gym-stock-bot/models/product" "github.com/maxtrussell/gym-stock-bot/telegram" "github.com/maxtrussell/gym-stock-bot/vendors/rep" "github.com/maxtrussell/gym-stock-bot/vendors/rogue" "github.com/maxtrussell/gym-stock-bot/web" ) func main() { telegram_api_ptr := flag.String("api", "", "api token for telegram bot") telegram_chat_id_ptr := flag.String("chat", "", "chat id for telegram bot") telegram_server := flag.Bool("server", false, "whether or not to be a telegram server") test_ptr := flag.Bool("test", false, "whether to run offline for test purposes") update_test_files_ptr := flag.Bool("update-test-files", false, "downloads all test files") update_db_ptr := flag.Bool("update-db", false, "whether to update the stock db") analytics_ptr := flag.String("analyze", "", "item id name to analyze") flag.Parse() start_time := time.Now() fmt.Printf("Current time: %s\n", start_time) if *telegram_server { go telegram.ListenAndServe(*telegram_api_ptr) web.ListenAndServe() return } if *analytics_ptr != "" { db := database.Setup() analytics.ItemReport(db, *analytics_ptr) return } all_products := product.Products if *update_test_files_ptr { get_test_files(all_products) } ch := make(chan []item.Item) var items []item.Item for _, product := range all_products { fmt.Printf("Getting %s...\n", product.Name) go make_items(ch, product, *test_ptr) } for _, _ = range all_products { items = append(items, <-ch...) } watched_terms := read_watched() fmt.Println("") fmt.Println("Available Products:") already_notified := get_notified_items() var notify_items []item.Item var available_items []item.Item var watched_available_items []item.Item curr_product := &product.Product{} for _, i := range items { if i.IsAvailable() { available_items = append(available_items, i) if i.Product.Name != curr_product.Name { if curr_product.Name != "" { fmt.Println() } curr_product = i.Product fmt.Printf("%s:\n", curr_product.Name) fmt.Printf("Link: %s\n", curr_product.URL) } fmt.Printf("- %s\n", i) if watched(i, watched_terms) { watched_available_items = append(watched_available_items, i) if !already_notified[i.ID()] { notify_items = append(notify_items, i) } } } } // Update last_in_stock.txt last_in_stock(available_items) // Send telegram notification if *telegram_api_ptr != "" && *telegram_chat_id_ptr != "" { msg := "Watched In Stock Items:\n" curr_product = &product.Product{} for _, i := range notify_items { if i.Product.Name != curr_product.Name { if curr_product.Name != "" { msg += "\n" } curr_product = i.Product msg += fmt.Sprintf("%s:\n", curr_product.Name) msg += fmt.Sprintf("Link: %s\n", curr_product.URL) } msg += fmt.Sprintf("> %s\n", i) } if len(notify_items) > 0 { fmt.Println() fmt.Println("Sending notification...") fmt.Println(msg) telegram.SendMessage( *telegram_api_ptr, *telegram_chat_id_ptr, msg, ) } // Store notified items, so as to not re-notify var item_names []string for _, i := range watched_available_items { item_names = append(item_names, i.ID()) } err := ioutil.WriteFile("notified_items.txt", []byte(strings.Join(item_names, "\n")), 0644) if err != nil { log.Fatal(err) } } // Update the stock db if *update_db_ptr { db := database.Setup() database.UpdateStock(db, items) } end_time := time.Now() fmt.Println() fmt.Printf("Completed in %.2f seconds\n", end_time.Sub(start_time).Seconds()) } func get_notified_items() map[string]bool { file, err := os.Open("notified_items.txt") if err != nil { // The file probably does not exist return map[string]bool{} } defer file.Close() notified_items := make(map[string]bool) scanner := bufio.NewScanner(file) for scanner.Scan() { notified_items[strings.Trim(scanner.Text(), "\n")] = true } return notified_items } func watched(i item.Item, watched_terms []string) bool { for _, term := range watched_terms { re := regexp.MustCompile(term) if re.FindStringIndex(i.ID()) != nil { return true } } return false } func make_items(ch chan []item.Item, product product.Product, test bool) { var doc *goquery.Document var err error if test { doc = get_test_doc(product) } else { doc, err = goquery.NewDocument(product.URL) if err != nil { log.Fatal(err) } } var items []item.Item switch product.Brand { case "Rogue": items = rogue.MakeRogue(doc, product) case "RepFitness": items = rep.MakeRep(doc, product) } ch <- items } func get_test_doc(p product.Product) *goquery.Document { f, err := os.Open(p.GetTestFile()) if err != nil { log.Fatal(err) } defer f.Close() doc, err := goquery.NewDocumentFromReader(f) if err != nil { log.Fatal(err) } return doc } func get_test_files(all_products []product.Product) { // Make test_pages dir if needed if _, err := os.Stat("test_pages"); os.IsNotExist(err) { os.Mkdir("test_pages", 0755) } ch := make(chan bool) for _, p := range all_products { fmt.Printf("Getting test file for %s...\n", p.Name) go get_test_file(p, ch) } for _, _ = range all_products { <-ch } fmt.Println("Done fetching test files!") fmt.Println() } func get_test_file(product product.Product, ch chan bool) { resp, err := http.Get(product.URL) if err != nil { log.Fatal(err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } defer resp.Body.Close() err = ioutil.WriteFile(product.GetTestFile(), body, 0644) if err != nil { log.Fatal(err) } ch <- true } func last_in_stock(in_stock_now []item.Item) { last_in_stock := read_last_in_stock() t := time.Now() for _, item := range in_stock_now { last_in_stock[item.ID()] = t.Format("Jan 02, 2006 15:04") } contents := "" for id, timestamp := range last_in_stock { contents += fmt.Sprintf("%s :: %s\n", id, timestamp) } err := ioutil.WriteFile("last_in_stock.txt", []byte(contents), 0644) if err != nil { log.Fatal(err) } } func read_last_in_stock() map[string]string { last_in_stock := map[string]string{} file, err := os.Open("last_in_stock.txt") if os.IsNotExist(err) { last_in_stock = map[string]string{} } else if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line_parts := strings.Split(scanner.Text(), " :: ") last_in_stock[line_parts[0]] = line_parts[1] } return last_in_stock } func read_watched() []string { watched := []string{} file, err := os.Open("watched.txt") if os.IsNotExist(err) { return watched } else if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { watched = append(watched, scanner.Text()) } return watched } <file_sep>/Makefile build: go build . clean: rm notified_items.txt mv db.sqlite db.sqlite.bak <file_sep>/web/web.go package web import ( "fmt" "html/template" "io/ioutil" "log" "net/http" "strings" ) func ListenAndServe() { fileServer := http.FileServer(http.Dir(".")) http.HandleFunc("/", renderIndex) http.Handle("/files/", http.StripPrefix("/files/", fileServer)) if err := http.ListenAndServe("0.0.0.0:6004", nil); err != nil { fmt.Println("HERE") log.Fatal(err) } } func renderIndex(w http.ResponseWriter, r *http.Request) { files := []string{} dirContents, err := ioutil.ReadDir(".") if err != nil { log.Fatal(err) } for _, file := range dirContents { if strings.HasSuffix(file.Name(), ".txt") { files = append(files, file.Name()) } } vars := struct{ Files []string }{Files: files} parsedTemplate, err := template.ParseFiles("index.html") if err != nil { log.Fatal(err) } if err = parsedTemplate.Execute(w, vars); err != nil { log.Fatal(err) } } <file_sep>/vendors/rogue/rogue.go package rogue import ( "encoding/json" "log" "strings" "github.com/PuerkitoBio/goquery" "github.com/maxtrussell/gym-stock-bot/models/item" "github.com/maxtrussell/gym-stock-bot/models/product" ) func MakeRogue(doc *goquery.Document, product product.Product) []item.Item { var items []item.Item switch product.Category { case "multi": items = makeRogueMulti(doc, product) case "single": items = makeRogueSingle(doc, product) case "script": items = makeFromScript(doc, product, "RogueColorSwatches") } return items } func makeRogueSingle(doc *goquery.Document, product product.Product) []item.Item { var items []item.Item i := item.Item{ Product: &product, Name: doc.Find(".product-title").Text(), Price: doc.Find(".price").Text(), Availability: strings.Trim(doc.Find(".product-options-bottom button").Text(), " \n"), } if strings.Contains(i.Availability, "Notify Me") { i.Availability = "Out of stock" } items = append(items, i) return items } func makeRogueMulti(doc *goquery.Document, product product.Product) []item.Item { var items []item.Item doc.Find(".grouped-item").Each(func(index int, selection *goquery.Selection) { i := item.Item{ Product: &product, Name: strings.TrimSpace(selection.Find(".item-name").Text()), Price: selection.Find(".price").Text(), Availability: strings.Trim(selection.Find(".bin-stock-availability").Text(), " \n"), } items = append(items, i) }) return items } func makeFromScript(doc *goquery.Document, product product.Product, script_name string) []item.Item { var items []item.Item // Find json blob to parse selection := doc.Find("script[type='text/javascript']") for _, node := range selection.Nodes { for c := node.FirstChild; c != nil; c = c.NextSibling { i := strings.Index(c.Data, script_name) if i == -1 { continue } for _, line := range strings.Split(c.Data, "\n") { stripped_line := strings.Trim(line, " ") if strings.HasPrefix(stripped_line, "{") { items = append( items, parseColorSwatchJson(stripped_line[:len(stripped_line)-1], product)..., ) } } } } return items } // helper function for makeFromScript func parseColorSwatchJson(color_swatch string, product product.Product) []item.Item { var top_level map[string]interface{} err := json.Unmarshal([]byte(color_swatch), &top_level) if err != nil { log.Fatal(err) } // 1. Get options var item_options []map[string]interface{} attributes := top_level["attributes"].(map[string]interface{}) for _, val := range attributes { options, _ := val.(map[string]interface{})["options"] for _, option := range options.([]interface{}) { if additional_option, ok := option.(map[string]interface{})["additional_options"]; ok { for _, item_info := range additional_option.(map[string]interface{}) { item_options = append(item_options, item_info.(map[string]interface{})) } } } } // 2. Convert options to items var items []item.Item for _, option := range item_options { var availability string if option["isInStock"].(bool) { availability = "In stock" } else { availability = "Out of stock" } i := item.Item{ Product: &product, Name: option["realLabel"].(string)[3:], Price: "$" + strings.TrimSuffix(option["bin_price"].(string), "00"), Availability: availability, } items = append(items, i) } return items } <file_sep>/models/item/item.go package item import ( "fmt" "log" "strconv" "github.com/maxtrussell/gym-stock-bot/models/product" ) var STOCK_EMOJIS = map[bool]string{ true: "00002705", false: "0000274C", } type Item struct { Product *product.Product Name string Price string Availability string } func (i Item) IsAvailable() bool { out_of_stock := map[string]bool{ "Notify Me": true, "Out of Stock": true, "Out of stock": true, "OUT OF STOCK": true, } return !out_of_stock[i.Availability] } func (i Item) String() string { return fmt.Sprintf( "%s @ %s, in stock: %s", i.Name, i.Price, get_emoji(STOCK_EMOJIS[i.IsAvailable()]), ) } func (i Item) ID() string { return fmt.Sprintf("%s: %s", i.Product.Name, i.Name) } func get_emoji(s string) string { r, err := strconv.ParseInt(s, 16, 32) if err != nil { log.Fatal(err) } return string(r) } <file_sep>/telegram/telegram.go package telegram import ( "fmt" "io/ioutil" "log" "net/http" "net/url" tgbot "github.com/go-telegram-bot-api/telegram-bot-api" ) func ListenAndServe(api_token string) { bot, err := tgbot.NewBotAPI(api_token) if err != nil { log.Fatal(err) } u := tgbot.NewUpdate(0) u.Timeout = 60 updates, _ := bot.GetUpdatesChan(u) for update := range updates { if update.Message == nil { continue } if !update.Message.IsCommand() { continue } msg := tgbot.NewMessage(update.Message.Chat.ID, "") switch update.Message.Command() { case "hi": msg.Text = "Howdy world!" case "latest": msg.Text = readLatestLog() default: msg.Text = "I don't know that command" } if _, err := bot.Send(msg); err != nil { log.Fatal(err) } } } func SendMessage(api_token, chat_id, msg string) { endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", api_token) data := url.Values{ "chat_id": {chat_id}, "text": {msg}, } _, err := http.PostForm(endpoint, data) if err != nil { log.Fatal(err) } } func readLatestLog() string { content, err := ioutil.ReadFile("latest_log.txt") if err != nil { log.Fatal(err) } return string(content) } <file_sep>/analytics/analytics.go package analytics import ( "database/sql" "fmt" "log" "time" "github.com/maxtrussell/gym-stock-bot/database" ) func ItemReport(db *sql.DB, id string) { rows := database.QueryItemByID(db, id) since := rows[len(rows)-1].Timestamp last_in_stock := "never" last_out_of_stock := "never" times_in_stock := 0 times_out_of_stock := 0 time_in_stock := 0.0 time_out_of_stock := 0.0 for i, r := range rows { // 1. update last in/out of stock if r.InStock && last_in_stock == "never" { last_in_stock = r.Timestamp } else if !r.InStock && last_out_of_stock == "never" { last_out_of_stock = r.Timestamp } // 2. update times in/out of stock if r.InStock { times_in_stock++ } else { times_out_of_stock++ } // 3. update time in/out of stock if i != 0 { timeSince := parseTime(rows[i-1].Timestamp).Sub(parseTime(r.Timestamp)) if r.InStock { time_in_stock += timeSince.Seconds() } else { time_out_of_stock += timeSince.Seconds() } } } // update to present time timeSince := time.Now().Sub(parseTime(rows[0].Timestamp)) if rows[0].InStock { time_in_stock += timeSince.Seconds() } else { time_out_of_stock += timeSince.Seconds() } fmt.Printf("Printing report for \"%s\"\n", id) fmt.Printf("Data since: %s\n", since) fmt.Printf("In stock: %t\n", rows[0].InStock) // 1. Last in stock/Last out of stock fmt.Printf("Last in stock: %s\n", last_in_stock) fmt.Printf("Last out of stock: %s\n", last_out_of_stock) // 2. Number of times in stock fmt.Printf("Times in stock: %d\n", times_in_stock) fmt.Printf("Times out of stock: %d\n", times_out_of_stock) // 3. Average days in/out of stock avg_in_stock := time_in_stock / float64(times_in_stock) avg_out_of_stock := time_out_of_stock / float64(times_out_of_stock) fmt.Printf("Time in stock: %s\n", formatSeconds(int(time_in_stock))) fmt.Printf("Time out of stock: %s\n", formatSeconds(int(time_out_of_stock))) if times_in_stock > 0 { fmt.Printf("Avg time in stock: %s\n", formatSeconds(int(time_in_stock)/times_in_stock)) } if times_out_of_stock > 0 { fmt.Printf("Avg time out of stock: %s\n", formatSeconds(int(time_out_of_stock)/times_out_of_stock)) } // 4. Predicted next in/out of stock var predicted float64 if rows[0].InStock { predicted = avg_in_stock - timeSince.Seconds() } else { predicted = avg_out_of_stock - timeSince.Seconds() } fmt.Printf("Predicted next stock change: %s\n", formatSeconds(int(predicted))) } func formatSeconds(s int) string { // Converts seconds to a xhyy format secs_per_day := 24 * 60 * 60 days := s / secs_per_day hours := (s % secs_per_day) / 3600 mins := (s % 3600) / 60 msg := fmt.Sprintf("%dh%d", hours, mins) if days > 0 { msg = fmt.Sprintf("%dd %s", days, msg) } return msg } func parseTime(s string) time.Time { t, err := time.ParseInLocation("2006-01-02 15:04:05", s, time.Local) if err != nil { log.Fatal(err) } return t } <file_sep>/vendors/rep/rep.go package rep import ( "strings" "github.com/PuerkitoBio/goquery" "github.com/maxtrussell/gym-stock-bot/models/item" "github.com/maxtrussell/gym-stock-bot/models/product" ) func MakeRep(doc *goquery.Document, product product.Product) []item.Item { var items []item.Item switch product.Category { case "multi": items = makeRepMulti(doc, product) case "single": items = makeRepSingle(doc, product) case "rack": items = makeRepRack(doc, product) } return items } func makeRepMulti(doc *goquery.Document, product product.Product) []item.Item { var items []item.Item doc.Find("#super-product-table tr").Each(func(index int, selection *goquery.Selection) { i := item.Item{ Product: &product, Name: selection.Find(".product-item-name").Text(), Price: selection.Find(".price").Text(), Availability: strings.Trim(selection.Find(".qty-container").Text(), " \n"), } if i.Availability == "" { i.Availability = doc.Find(".product-info-stock-sku span").Text() } if i.Name != "" { items = append(items, i) } }) return items } func makeRepSingle(doc *goquery.Document, product product.Product) []item.Item { // TODO: I don't know what it looks like when it is in stock var items []item.Item i := item.Item{ Product: &product, Name: product.Name, // temporary Price: doc.Find(".price").Text(), Availability: doc.Find(".product-info-stock-sku span").Text(), } items = append(items, i) return items } func makeRepRack(doc *goquery.Document, product product.Product) []item.Item { // TODO: I don't know what it looks like when it is in stock var items []item.Item i := item.Item{ Product: &product, Name: product.Name, // temporary Price: doc.Find(".price-to .price").Text(), Availability: doc.Find(".product-info-stock-sku span").Text(), } items = append(items, i) return items } <file_sep>/vendors/titan/titan.go package titan import ( "github.com/PuerkitoBio/goquery" "github.com/maxtrussell/gym-stock-bot/models/item" "github.com/maxtrussell/gym-stock-bot/models/product" ) func MakeTitan(doc *goquery.Document, product product.Product) []item.Item { var items []item.Item switch product.Category { case "rack": items = makeTitanRack(doc, product) } return items } <file_sep>/database/database.go package database import ( "database/sql" "log" "strings" _ "github.com/mattn/go-sqlite3" "github.com/maxtrussell/gym-stock-bot/models/item" ) type StockRow struct { ProductName string ItemName string Price string InStock bool Timestamp string } func (r StockRow) ID() string { return r.ProductName + ": " + r.ItemName } func Setup() *sql.DB { db := connect("db.sqlite") createTable(db) return db } func UpdateStock(db *sql.DB, items []item.Item) { rows := queryLatestStock(db) for _, i := range items { r, ok := rows[i.ID()] if ok && i.IsAvailable() != r.InStock { // Insert row when availability is mismatched InsertStockRow(db, i) } else if !ok { // Insert new items, not yet in db InsertStockRow(db, i) } } } func InsertStockRow(db *sql.DB, i item.Item) { q := ` INSERT INTO stock( ProductName, ItemName, Price, InStock ) values (?, ?, ?, ?);` stmt, err := db.Prepare(q) if err != nil { log.Fatal(err) } defer stmt.Close() _, err = stmt.Exec(i.Product.Name, i.Name, i.Price, i.IsAvailable()) if err != nil { log.Fatal(err) } } func QueryItemByID(db *sql.DB, id string) []StockRow { id_parts := strings.Split(id, ": ") q := ` SELECT ProductName, ItemName, Price, InStock, DATETIME(Timestamp, 'localtime') FROM stock WHERE ProductName = ? and ItemName = ? ORDER BY Timestamp DESC;` return queryStock(db, q, id_parts[0], id_parts[1]) } func queryLatestStock(db *sql.DB) map[string]StockRow { q := ` SELECT ProductName, ItemName, Price, InStock, DATETIME(Timestamp, 'localtime') FROM stock ORDER BY Timestamp DESC;` rows := queryStock(db, q) m := map[string]StockRow{} for _, r := range rows { if _, ok := m[r.ID()]; !ok { m[r.ID()] = r } } return m } func connect(path string) *sql.DB { db, err := sql.Open("sqlite3", path) if err != nil { log.Fatal(err) } if db == nil { panic("db nil") } return db } func queryStock(db *sql.DB, q string, parameters ...interface{}) []StockRow { rows, err := db.Query(q, parameters...) if err != nil { log.Fatal(err) } defer rows.Close() var stock_rows []StockRow for rows.Next() { stock_row := StockRow{} err = rows.Scan( &stock_row.ProductName, &stock_row.ItemName, &stock_row.Price, &stock_row.InStock, &stock_row.Timestamp, ) if err != nil { log.Fatal(err) } stock_rows = append(stock_rows, stock_row) } return stock_rows } func createTable(db *sql.DB) { sql_table := ` CREATE TABLE IF NOT EXISTS stock( ID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT NOT NULL, ItemName TEXT NOT NULL, Price TEXT, InStock INTEGER NOT NULL, Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP );` if _, err := db.Exec(sql_table); err != nil { log.Fatal(err) } } <file_sep>/models/product/product.go package product import ( "fmt" "strings" ) type Product struct { Name string URL string Brand string Category string } func (p Product) GetTestFile() string { url_parts := strings.Split(p.URL, "/") return fmt.Sprintf("test_pages/%s.html", url_parts[len(url_parts)-1]) } var Products = []Product{ Product{ Name: "Rogue Olympic Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-olympic-plates", }, Product{ Name: "Rogue Deep Dish Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-deep-dish-plates", }, Product{ Name: "Rogue Steel Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-calibrated-lb-steel-plates", }, Product{ Name: "Rogue HG Bumper Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-hg-2-0-bumper-plates", }, Product{ Name: "Rogue Fleck Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-fleck-plates", }, Product{ Name: "Rogue Echo Bumper Plate v2", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-echo-bumper-plates-with-white-text", }, Product{ Name: "Rogue Color Echo Bumper Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-color-echo-bumper-plate", }, Product{ Name: "Rogue Mil Spec Bumper Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-us-mil-sprc-bumper-plates", }, Product{ Name: "Rogue Mil Spec Echo Bumper Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-mil-echo-bumper-plates-black", }, Product{ Name: "Rogue Ohio Power Bar 45LB Stainless Steel", Brand: "Rogue", Category: "script", URL: "https://www.roguefitness.com/rogue-45lb-ohio-power-bar-stainless", }, Product{ Name: "Rogue Ohio Power Bar 45LB Black Zinc", Brand: "Rogue", Category: "single", URL: "https://www.roguefitness.com/rogue-45lb-ohio-power-bar-black-zinc", }, Product{ Name: "Rogue Ohio Power Bar 45LB Bare Steel", Brand: "Rogue", Category: "single", URL: "https://www.roguefitness.com/rogue-45lb-ohio-power-bar-bare-steel", }, Product{ Name: "Rogue Ohio Power Bar 45LB E Coat", Brand: "Rogue", Category: "single", URL: "https://www.roguefitness.com/rogue-ohio-power-bar-e-coat", }, Product{ Name: "Rogue Curl Bar", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/rogue-curl-bar", }, Product{ Name: "York Legacy Iron Plates", Brand: "Rogue", Category: "multi", URL: "https://www.roguefitness.com/york-legacy-iron-plates", }, Product{ Name: "Rep Fitness Iron Plates", Brand: "RepFitness", Category: "multi", URL: "https://www.repfitness.com/bars-plates/olympic-plates/iron-plates/rep-iron-plates", }, Product{ Name: "Rep Fitness Black Bumper Plates", Brand: "RepFitness", Category: "multi", URL: "https://www.repfitness.com/bars-plates/olympic-plates/bumper-plates/rep-black-bumper-plates", }, Product{ Name: "Rep Fitness Color Bumper Plates", Brand: "RepFitness", Category: "mutli", URL: "https://www.repfitness.com/bars-plates/olympic-plates/rep-color-bumper-plates", }, Product{ Name: "Rep Fitness PR 1100", Brand: "RepFitness", Category: "rack", URL: "https://www.repfitness.com/strength-equipment/power-racks/rep-pr-1100", }, Product{ Name: "Rep Fitness PR 1100 Lat Row Attachment", Brand: "RepFitness", Category: "single", URL: "https://www.repfitness.com/strength-equipment/rack-attachments/1000-series-attachments/rep-lat-pull-down-low-row-attachment", }, Product{ Name: "Rep Fitness PR 1100 Dip Attachment", Brand: "RepFitness", Category: "single", URL: "https://www.repfitness.com/catalog/product/view/id/355/s/rep-power-rack-dip-attachment/category/544/", }, Product{ Name: "Rep Fitness Weight Tree", Brand: "RepFitness", Category: "single", URL: "https://www.repfitness.com/bar-and-bumper-plate-tree", }, Product{ Name: "Rep Fitness Curl Bar", Brand: "RepFitness", Category: "multi", URL: "https://www.repfitness.com/bars-plates/olympic-bars/rep-ez-curl-barbell", }, }
2b7d371d4fdd59094048853a35baef2ee48b4c27
[ "Makefile", "Go", "Shell" ]
12
Shell
maxtrussell/gym-stock-bot
12fe991970335b118c000439c7bc498a90924db5
db2e30a86a5f1e5c03c0a80f16d6897d25b2c306
refs/heads/master
<file_sep>class ShowResults def initialize(student_names_with_letter_grades) @letter_grades = student_names_with_letter_grades @a_students = [] @b_students = [] @c_students = [] @d_students = [] @f_students = [] end def print_each_grade_count @letter_grades.class_stats.each do |person| if person[:grade] == 'A' @a_students << person[:name] elsif person[:grade] == 'B' @b_students << person[:name] elsif person[:grade] == 'C' @c_students << person[:name] elsif person[:grade] == 'D' @d_students << person[:name] else @f_students << person[:name] end end puts "90: #{@a_students.count}" puts "80: #{@b_students.count}" puts "70: #{@c_students.count}" puts "60: #{@d_students.count}" puts "50: #{@f_students.count}" end def print_student_names if @a_students.count >= 1 puts '' puts "A Students" puts "===================" @a_students.each do |person| puts person end end if @b_students.count >= 1 puts '' puts "B Students" puts "===================" @b_students.each do |person| puts person end end if @c_students.count >= 1 puts '' puts "C Students" puts "===================" @c_students.each do |person| puts person end end if @d_students.count >= 1 puts '' puts "D Students" puts "===================" @d_students.each do |person| puts person end end if @f_students.count >= 1 puts '' puts 'F Students' puts "===================" @f_students.each do |person| puts person end end end end<file_sep>require 'csv' class LoadGrades attr_reader :students_and_grades def initialize @students_and_grades =[] end def load_file(grade_data) CSV.foreach(grade_data, :headers => true) do |row| each_student = {} each_student = {:name => row['Name'], :grade => row['Grade'].to_i} @students_and_grades << each_student end end end<file_sep>test_scores =========== Launch Academy Challenge. Read Student Grades in from a CSV, and calculate there final average and letter grade. <file_sep>class CalculateClassStats attr_reader :class_stats def initialize(grades) @all_students_and_grades = grades @class_stats = [] end def calculate_class_stats @all_students_and_grades.students_and_grades.each do |student| grade_group = {} if student[:grade] >= 90 grade_group = {:grade => 'A', :name => student[:name]} @class_stats << grade_group elsif student[:grade] >= 80 && student[:grade] < 90 grade_group = {:grade => 'B', :name => student[:name]} @class_stats << grade_group elsif student[:grade] >= 70 && student[:grade] < 80 grade_group = {:grade => 'C', :name => student[:name]} @class_stats << grade_group elsif student[:grade] >= 60 && student[:grade] < 70 grade_group = {:grade => 'D', :name => student[:name]} @class_stats << grade_group else grade_group = {:grade => 'F', :name => student[:name]} @class_stats << grade_group end end end end<file_sep>require 'csv' require_relative 'load_grade_class' require_relative 'calculate_class_stats_class' require_relative 'show_results_class' grades = LoadGrades.new grades.load_file('grades.csv') class_stats = CalculateClassStats.new(grades) class_stats.calculate_class_stats grades_report = ShowResults.new(class_stats) grades_report.print_each_grade_count grades_report.print_student_names
ccacd2704eec7faac24697cfbc9b649a3ac87445
[ "Markdown", "Ruby" ]
5
Ruby
sdanko11/test_scores
5301cc5bd52fac002154fd79656897d0b2de3c06
a3c50832f2b67fa1e6d8c57a9b220db1243c8fe7
refs/heads/master
<repo_name>SuperITMan/Linux<file_sep>/Debian/Scripts/networkInterfaceConf.sh #!/bin/bash #Script permettant la configuration de l'interface réseau pour un VPS sur un Serveur dédié chez OVH GREEN="\\033[1;32m" NORMAL="\\033[0m" BOLD="\\033[1m" interfacesDir="/etc/network/interfaces" tmpInterfacesDir="/tmp/tmpInterfaces" #ifconfig -a | egrep '^[^ ]' | awk '{ if($1 != "lo") print $1}' if [ -f "$tmpInterfacesDir" ]; then rm "$tmpInterfacesDir" touch "$tmpInterfacesDir" fi while [ "$isGoodConfig" != "o" ] && [ "$isGoodConfig" != "O" ]; do while [ "$isGoodIp" != "o" ] && [ "$isGoodIp" != "O" ]; do tmpIpAddress="$ipAddress" echo -n "Veuillez entrer l'adresse ip à configurer [$ipAddress] : " read ipAddress if [ -z "$ipAddress" ] then ipAddress="$tmpIpAddress" fi echo -e "Confirmez-vous l'adresse ""$BOLD""$ipAddress""$NORMAL"" comme adresse ip ? ([O]ui ou [Non]) : \c" read -n1 isGoodIp echo "" while [ "$isGoodIp" != "n" ] && [ "$isGoodIp" != "N" ] && [ "$isGoodIp" != "o" ] && [ "$isGoodIp" != "O" ]; do echo "Erreur ! Veuillez répondre [O]ui ou [N]on." echo -e "Confirmez-vous l'adresse ""$BOLD""$ipAddress""$NORMAL"" comme adresse ip ? ([O]ui ou [Non]) : \c" read -n1 isGoodIp echo "" done if [ "$isGoodIp" == "n" ] || [ "$isGoodIp" == "N" ] then echo "Erreur ! Veuillez recommencer." fi done while [ "$isGoodGW" != "o" ] && [ "$isGoodGW" != "O" ]; do tmpGWAddress="$gwAddress" echo -n "Veuillez entrer l'adresse du gateway à configurer (Chez OVH : xxx.xxx.xxx.254) [$gwAddress] : " read gwAddress if [ -z "$gwAddress" ] then gwAddress="$tmpGWAddress" fi echo -e "Confirmez-vous l'adresse ""$BOLD""$gwAddress""$NORMAL"" comme gateway ? ([O]ui ou [Non]) : \c" read -n1 isGoodGW echo "" while [ "$isGoodGW" != "n" ] && [ "$isGoodGW" != "N" ] && [ "$isGoodGW" != "o" ] && [ "$isGoodGW" != "O" ]; do echo "Erreur ! Veuillez répondre [O]ui ou [N]on" echo -e "Confirmez-vous l'adresse ""$BOLD""$gwAddress""$NORMAL"" comme gateway ? ([O]ui ou [Non]) : \c" read -n1 isGoodGW echo "" done if [ "$isGoodGW" == "n" ] || [ "$isGoodGW" == "N" ] then echo "Erreur ! Veuillez recommencer." fi done touch "$tmpInterfacesDir" printf "auto eth0\niface eth0 inet static\n\n" > "$tmpInterfacesDir" printf "address $ipAddress\nnetmask 255.255.255.255\nbroadcast $ipAddress\n\n" >> "$tmpInterfacesDir" printf "post-up route add $gwAddress dev eth0\npost-up route add default gw $gwAddress\n" >> "$tmpInterfacesDir" printf "post-down route del $gwAddress dev eth0\npost-down route del default gw $gwAddress" >> "$tmpInterfacesDir" echo "Voici votre configuration de l'interface reseau. Merci de confirmer celle-ci plus bas." echo "" echo "-------------------------------------------------------------" cat "$tmpInterfacesDir" echo "" echo "-------------------------------------------------------------" read -p "Confirmez-vous la configuration de l'interface reseau ? ([O]ui ou [Non]) : " -n1 isGoodConfig echo "" while [ "$isGoodConfig" != "n" ] && [ "$isGoodConfig" != "N" ] && [ "$isGoodConfig" != "o" ] && [ "$isGoodConfig" != "O" ]; do echo "Erreur ! Veuillez répondre [O]ui ou [N]on" read -p "Confirmez-vous la configuration de l'interface reseau ? ([O]ui ou [Non]) : " -n1 isGoodConfig echo "" done if [ "$isGoodConfig" == "n" ] || [ "$isGoodConfig" == "N" ] then echo "Erreur ! Veuillez recommencer." isGoodGW="n" isGoodIp="n" fi done echo -ne "Configuration de votre interface reseau...\r" if [ -f "$interfacesDir" ]; then mv "$interfacesDir" "$interfacesDir".old fi mv "$tmpInterfacesDir" "$interfacesDir" echo -ne "Configuration de votre interface reseau... ""$GREEN""fait""$NORMAL""\r" echo "" echo -ne "Redémarrage de votre interface reseau...\r" ifup eth0 echo -ne "Redémarrage de votre interface reseau... ""$GREEN""fait""$NORMAL""\r" echo "" <file_sep>/Debian/Scripts/sourcesListConf.sh #!/bin/bash #Script permettant la configuration du fichier source list pour un VPS Debian GREEN="\\033[1;32m" NORMAL="\\033[0m" BOLD="\\033[1m" sourceListDir="/etc/apt/sources.list" tmpSourceListDir="/tmp/tmpSourcesList" if [ -f "$tmpSourceListDir" ]; then rm "$tmpSourceListDir" fi touch "$tmpSourceListDir" while [ "$isGoodSourcesList" != "o" ] && [ "$isGoodSourcesList" != "O" ]; do echo "#Sources list\n" > "$tmpSourceListDir" #Sources pour un serveur chez OVH while [ "$isGoodOVH" != "o" ] && [ "$isGoodOVH" != "O" ] && [ "$isGoodOVH" != "n" ] && [ "$isGoodOVH" != "N" ]; do echo -e "Votre serveur est-il hébergé chez OVH ? ([O]ui ou [Non]) : \c" read -n1 isGoodOVH echo "" if [ "$isGoodOVH" != "o" ] && [ "$isGoodOVH" != "O" ] && [ "$isGoodOVH" != "n" ] && [ "$isGoodOVH" != "N" ] then echo "Erreur ! Veuillez répondre [O]ui ou [N]on." fi done if [ "$isGoodOVH" == "o" ] || [ "$isGoodOVH" == "O" ] then printf "deb http://debian.mirrors.ovh.net/debian/ jessie main\n" >> "$tmpSourceListDir" printf "deb-src http://debian.mirrors.ovh.net/debian/ jessie main\n\n" >> "$tmpSourceListDir" printf "deb http://debian.mirrors.ovh.net/debian/ jessie-updates main\n" >> "$tmpSourceListDir" printf "deb-src http://debian.mirrors.ovh.net/debian/ jessie-updates main\n\n" >> "$tmpSourceListDir" else printf "deb http://http.debian.net/debian jessie main\n" >> "$tmpSourceListDir" printf "deb-src http://http.debian.net/debian jessie main\n\n" >> "$tmpSourceListDir" printf "deb http://http.debian.net/debian jessie-updates main\n" >> "$tmpSourceListDir" printf "deb-src http://http.debian.net/debian jessie-updates main\n\n" >> "$tmpSourceListDir" fi printf "deb http://security.debian.org/ jessie/updates main\n" >> "$tmpSourceListDir" printf "deb-src http://security.debian.org/ jessie/updates main\n\n" >> "$tmpSourceListDir" echo "Voici votre configuration du liste de sources. Merci de confirmer celle-ci plus bas." echo "" echo "-------------------------------------------------------------" cat "$tmpSourceListDir" echo "" echo "-------------------------------------------------------------" read -p "Confirmez-vous la configuration de la liste de sources ? ([O]ui ou [Non]) : " -n1 isGoodSourcesList echo "" while [ "$isGoodSourcesList" != "n" ] && [ "$isGoodSourcesList" != "N" ] && [ "$isGoodSourcesList" != "o" ] && [ "$isGoodSourcesList" != "O" ]; do echo "Erreur ! Veuillez répondre [O]ui ou [N]on." read -p "Confirmez-vous la configuration de la liste de sources ? ([O]ui ou [Non]) : " -n1 isGoodSourcesList echo "" done if [ "$isGoodSourcesList" == "n" ] || [ "$isGoodSourcesList" == "N" ] then echo "Erreur ! Veuillez recommencer." isGoodOVH="" fi done echo -ne "Configuration de votre liste de sources...\r" if [ -f "$sourceListDir" ] then mv "$sourceListDir" "$sourceListDir".old fi mv "$tmpSourceListDir" "$sourceListDir" echo -ne "Configuration de votre liste de sources... ""$GREEN""fait""$NORMAL""\r" echo ""<file_sep>/Debian/Scripts/firewallConfiguration.sh #!/bin/bash #Script permettant la configuration d'un firewall (iptables) pour Debian GREEN="\\033[1;32m" NORMAL="\\033[0m" BOLD="\\033[1m" firewallDir="/etc/init.d/firewall" tmpFirewallDir="/tmp/tmpFirewall" if [ -f "$tmpFirewallDir" ]; then rm "$tmpFirewallDir" fi touch "$tmpFirewallDir" while [ "$isGoodConfig" != "o" ] && [ "$isGoodConfig" != "O" ]; do #Règles de base d'un script s'exécutant au démarrage de Debian 8" printf "#!/bin/sh\n" > "$tmpFirewallDir" printf "### BEGIN INIT INFO\n" >> "$tmpFirewallDir" printf "# Provides: firewall\n" >> "$tmpFirewallDir" printf "# Required-Start: $local_fs $remote_fs $network $syslog $named\n" >> "$tmpFirewallDir" printf "# Required-Stop: $local_fs $remote_fs $network $syslog $named\n" >> "$tmpFirewallDir" printf "# Default-Start: 2 3 4 5\n" >> "$tmpFirewallDir" printf "# Default-Stop: 0 1 6\n" >> "$tmpFirewallDir" printf "# X-Interactive: true\n" >> "$tmpFirewallDir" printf "# Short-Description: firewall - iptables\n" >> "$tmpFirewallDir" printf "# Description: Start the web server and associated helpers\n" >> "$tmpFirewallDir" printf "# This script will start apache2, and possibly all associated instances.\n" >> "$tmpFirewallDir" printf "# Moreover, it will set-up temporary directories and helper tools such as\n" >> "$tmpFirewallDir" printf "# htcacheclean when required by the configuration.\n" >> "$tmpFirewallDir" printf "### END INIT INFO\n\n" >> "$tmpFirewallDir" #Réinitialise toutes les règles existantes printf "# Vider les tables actuelles\n" >> "$tmpFirewallDir" printf "iptables -t filter -F\n\n" >> "$tmpFirewallDir" printf "# Vider les règles personnelles\n" >> "$tmpFirewallDir" printf "iptables -t filter -X\n\n" >> "$tmpFirewallDir" printf "# Interdire toute connexion entrante et sortante\n" >> "$tmpFirewallDir" printf "iptables -t filter -P INPUT DROP\n" >> "$tmpFirewallDir" printf "iptables -t filter -P FORWARD DROP\n" >> "$tmpFirewallDir" printf "iptables -t filter -P OUTPUT DROP\n\n" >> "$tmpFirewallDir" printf "# ---\n\n" >> "$tmpFirewallDir" #Maintient des connexions déjà établies printf "# Ne pas casser les connexions etablies\n" >> "$tmpFirewallDir" printf "iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" >> "$tmpFirewallDir" printf "iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n\n" >> "$tmpFirewallDir" printf "# ---\n\n" >> "$tmpFirewallDir" #Loopback printf "# Autoriser loopback\n" >> "$tmpFirewallDir" printf "iptables -t filter -A INPUT -i lo -j ACCEPT\n" >> "$tmpFirewallDir" printf "iptables -t filter -A OUTPUT -o lo -j ACCEPT\n\n" >> "$tmpFirewallDir" printf "# ---\n\n" >> "$tmpFirewallDir" #Ping printf "# ICMP (Ping)\n" >> "$tmpFirewallDir" printf "iptables -t filter -A INPUT -p icmp -j ACCEPT\n" >> "$tmpFirewallDir" printf "iptables -t filter -A OUTPUT -p icmp -j ACCEPT\n\n" >> "$tmpFirewallDir" printf "# ---\n\n" >> "$tmpFirewallDir" #SSH printf "# Autoriser les connexions SSH\n" >> "$tmpFirewallDir" printf "iptables -A INPUT -p tcp --dport ${SSH_CLIENT##* } -j ACCEPT" >> "$tmpFirewallDir" printf "# ---\n\n" >> "$tmpFirewallDir" echo "Voici votre configuration du pare-feu. Merci de confirmer celle-ci plus bas." echo "" echo "-------------------------------------------------------------" cat "$tmpFirewallDir" echo "" echo "-------------------------------------------------------------" read -p "Confirmez-vous la configuration du pare-feu ? ([O]ui ou [Non]) : " -n1 isGoodConfig echo "" while [ "$isGoodConfig" != "n" ] && [ "$isGoodConfig" != "N" ] && [ "$isGoodConfig" != "o" ] && [ "$isGoodConfig" != "O" ]; do echo "Erreur ! Veuillez répondre [O]ui ou [N]on" read -p "Confirmez-vous la configuration du pare-feu ? ([O]ui ou [Non]) : " -n1 isGoodConfig echo "" done if [ "$isGoodConfig" == "n" ] || [ "$isGoodConfig" == "N" ] then echo "Erreur ! Veuillez recommencer." fi done echo -ne "Configuration de votre pare-feu...\r" if [ -f "$firewallDir" ]; then mv "$firewallDir" "$firewallDir".old fi mv "$tmpFirewallDir" "$firewallDir" echo -ne "Configuration de votre interface pare-feu... ""$GREEN""fait""$NORMAL""\r" echo ""<file_sep>/Debian/Scripts/downloadScripts.sh #!/bin/bash #Script permettant le téléchargement de tous les scripts de configuration VERT="\\033[1;32m" ROUGE="\\033[1;31m" NORMAL="\\033[0;39m" ping -c3 8.8.8.8 >/dev/null test_ping=$? if ! [ $test_ping -ne 0 ] then #Téléchargement des scripts sur github echo "Téléchargement des scripts pour le fonctionnement du panel." echo -ne '0% [ >]\r' sleep 1 wget -q https://raw.githubusercontent.com/SuperITMan/Linux/master/Debian/Scripts/networkInterfaceConf.sh -O networkInterfaceConf.sh echo -ne '25% [================= >]\r' sleep 1 wget -q https://raw.githubusercontent.com/SuperITMan/Linux/master/Debian/Scripts/networkNameserverConf.sh -O networkNameserverConf.sh echo -ne '50% [================================== >]\r' sleep 1 wget -q https://raw.githubusercontent.com/SuperITMan/Linux/master/Debian/Scripts/firewallConfiguration.sh -O firewallConfiguration.sh echo -ne '75% [=================================================== >]\r' sleep 1 wget -q https://raw.githubusercontent.com/SuperITMan/Linux/master/Debian/Scripts/sourcesListConf.sh -O sourcesListConf.sh echo -ne '100% [======================================================================>]\r' sleep 1 fi #Attribution des droits nécessaires à l'exécution des scripts chmod +x networkInterfaceConf.sh chmod +x networkNameserverConf.sh chmod +x sourcesListConf.sh chmod +x firewallConfiguration.sh while : do clear cat<<EOF ============================================================== Configuration Debian ============================================================== Veuillez choisir votre option [1] Configuration reseau - interface eth0 + nameserver [2] Configuration des sources de Debian - sources.list [3] Configuration du pare-feu - iptables [Q]uitter le script -------------------------------------------------------------- EOF read -n1 -s choice case "$choice" in #Configuration réseau "1") ./networkInterfaceConf.sh ./networkNameserverConf.sh ;; "2") ./sourcesListConf.sh ;; "3") ./firewallConfiguration.sh ;; "Q") exit ;; "q") exit ;; * ) echo "Choix invalide ! "$choice ;; esac sleep 1 done<file_sep>/Debian/Scripts/networkNameserverConf.sh #!/bin/bash #Script permettant la configuration du nameserver pour un VPS Debian GREEN="\\033[1;32m" NORMAL="\\033[0m" BOLD="\\033[1m" nameServerDir="/etc/resolv.conf" tmpNmServerDir="/tmp/tmpNameServer" if [ -f "$tmpNmServerDir" ]; then rm "$tmpNmServerDir" fi touch "$tmpNmServerDir" while [ "$isGoodNameServer" != "o" ] && [ "$isGoodNameServer" != "O" ]; do print "#Name Servers\n" > "$tmpNmServerDir" #NameServer OVH 172.16.58.3 while [ "$isGoodOVH" != "o" ] && [ "$isGoodOVH" != "O" ] && [ "$isGoodOVH" != "n" ] && [ "$isGoodOVH" != "N" ]; do echo -e "Desirez-vous avoir le $BOLDDNS OVH$NORMAL en nameserver [172.16.58.3] ? ([O]ui ou [Non]) : \c" read -n1 isGoodOVH echo "" if [ "$isGoodOVH" != "o" ] && [ "$isGoodOVH" != "O" ] && [ "$isGoodOVH" != "n" ] && [ "$isGoodOVH" != "N" ] then echo "Erreur ! Veuillez répondre [O]ui ou [N]on." fi done if [ "$isGoodOVH" == "o" ] || [ "$isGoodOVH" == "O" ] then printf "nameserver 172.16.58.3\n" >> "$tmpNmServerDir" fi #NameServer Google 8.8.8.8 while [ "$isGoodGoogle1" != "o" ] && [ "$isGoodGoogle1" != "O" ] && [ "$isGoodGoogle1" != "n" ] && [ "$isGoodGoogle1" != "N" ]; do echo -e "Desirez-vous avoir le $BOLDDNS Google$NORMAL en nameserver [8.8.8.8] ? ([O]ui ou [Non]) : \c" read -n1 isGoodGoogle1 echo "" if [ "$isGoodGoogle1" != "o" ] && [ "$isGoodGoogle1" != "O" ] && [ "$isGoodGoogle1" != "n" ] && [ "$isGoodGoogle1" != "N" ] then echo "Erreur ! Veuillez répondre [O]ui ou [N]on." fi done if [ "$isGoodGoogle1" == "o" ] || [ "$isGoodGoogle1" == "O" ] then printf "nameserver 8.8.8.8\n" >> "$tmpNmServerDir" fi echo "Voici votre configuration du nameserver. Merci de confirmer celle-ci plus bas." echo "" echo "-------------------------------------------------------------" cat "$tmpNmServerDir" echo "" echo "-------------------------------------------------------------" read -p "Confirmez-vous la configuration de l'interface reseau ? ([O]ui ou [Non]) : " -n1 isGoodNameServer echo "" while [ "$isGoodNameServer" != "n" ] && [ "$isGoodNameServer" != "N" ] && [ "$isGoodNameServer" != "o" ] && [ "$isGoodNameServer" != "O" ]; do echo "Erreur ! Veuillez répondre [O]ui ou [N]on." read -p "Confirmez-vous la configuration de l'interface reseau ? ([O]ui ou [Non]) : " -n1 isGoodNameServer echo "" done if [ "$isGoodNameServer" == "n" ] || [ "$isGoodNameServer" == "N" ] then echo "Erreur ! Veuillez recommencer." isGoodOVH="" isGoodGoogle1="" fi done echo -ne "Configuration de votre nameserver...\r" if [ -f "$nameServerDir" ] then mv "$nameServerDir" "$nameServerDir".old fi mv "$tmpNmServerDir" "$nameServerDir" echo -ne "Configuration de votre nameserver... ""$GREEN""fait""$NORMAL""\r" echo ""
b036d03ab459218fcbe8dc777e623c338f25e40b
[ "Shell" ]
5
Shell
SuperITMan/Linux
ad2da403c5d16fc8288ef961629633adc6ba0739
7bd8906822731d483a821368ff62af4c10201613
refs/heads/master
<repo_name>cdawen/vmall<file_sep>/js/privilege.js window.onload = function(){ // banner部分开始 var animat = false; var index = 0; var list = document.getElementById('list').getElementsByTagName('a'); var dots = document.getElementById('dot').getElementsByTagName('span'); document.getElementById('next').onclick = function(){next()}; document.getElementById('pre').onclick = function(){pre()}; var int = setInterval(function(){next()},5000); function next(){ if(animat){ return false; } var new_index = (index+1 >2)?0:index+1; animation(index, new_index); index = new_index; checkIndex(); } function pre(){ var new_index = (index - 1 <0)?2:index-1; animation(index, new_index); index = new_index; checkIndex(); if(animat){ return false; } } function animation(index, new_index){ animat = true; var interval = 10; var one_time = 1000; var offset = 1/(1000/10); list[index].style.opacity = 1; list[new_index].style.opacity = 0; list[new_index].style.display = 'block'; var x = 0; go(); function go(){ x += offset; list[index].style.opacity -= offset; list[new_index].style.opacity = x; if (list[index].style.opacity >= 0){ setTimeout(function(){go()},10); }else{ list[index].style.display = 'none'; animat = false; } console.log(list[index].style.opacity,list[new_index].style.opacity); } } function checkIndex(){ for (var i=0; i<dots.length; i++){ dots[i].className = ''; } dots[index].className = 'on'; } for(var i=0; i<dots.length; i++){ dots[i].onclick = function(){ if(animat){ return false; } var new_index = Number(this.getAttribute('index')); animation(index,new_index); index = new_index; checkIndex(); } dots[i].onmouseover = function(){ if(animat){ return false; } var new_index = Number(this.getAttribute('index')); animation(index,new_index); index = new_index; checkIndex(); } } var banners = document.getElementById('banner'); banners.onmouseover = function(){ clearInterval(int); }; banners.onmouseout = function(){ int = setInterval(function(){next()},3000) } // banner部分结束 // 抽奖部分开始 $(function() { var $plateBtn = $('#plateBtn'); var $result = $('#result'); var $resultTxt = $('#resultTxt'); var $resultBtn = $('#resultBtn'); $plateBtn.click(function() { var data = [0, 1, 2, 3, 4, 5, 6, 7]; data = data[Math.floor(Math.random() * data.length)]; switch(data) { case 1: rotateFunc(1, 157, '再接再励'); break; case 2: rotateFunc(2, 65, '继续努力'); break; case 3: rotateFunc(3, 335, '再接再励'); break; case 4: rotateFunc(4, 247, '谢谢参与'); break; case 5: rotateFunc(5, 114, '恭喜你中了 <em>华为自拍杆</em>'); break; case 6: rotateFunc(6, 24, '恭喜你中了 <em>华为手环B2商务版</em>'); break; case 7: rotateFunc(7, 292, '恭喜你中了 <em>旅行6件套</em>'); break; default: rotateFunc(0, 203, '恭喜你中了 <em>华为降噪耳机</em>'); } }); var rotateFunc = function(awards, angle, text) { //awards:奖项,angle:奖项对应的角度 $plateBtn.stopRotate(); $plateBtn.rotate({ angle: 0, duration: 5000, animateTo: angle + 1440, //angle是图片上各奖项对应的角度,1440是让指针固定旋转4圈 callback: function() { $resultTxt.html(text); $result.show(); } }); }; $resultBtn.click(function() { $result.hide(); }); }); // 抽奖部分结束 //公告列表无缝滚动开始 var speed=40; var demo=document.getElementById("demo"); var demo2=document.getElementById("demo2"); var demo1=document.getElementById("demo1"); demo2.innerHTML=demo1.innerHTML ; function Marquee(){ if(demo.scrollTop>=demo1.offsetHeight){ demo.scrollTop=0; } else{ demo.scrollTop=demo.scrollTop+1; } } var MyMar=setInterval(function(){Marquee()},speed) demo.onmouseover=function(){clearInterval(MyMar)} demo.onmouseout=function(){MyMar=setInterval(Marquee,speed)} //公告列表无缝滚动结束 // 悬浮工具栏开始 var toTops = document.getElementById('toTop'); var clientHeight = document.documentElement.clientHeight; var timer = null; var isTop = true; window.onscroll = function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; if(osTop>=clientHeight){ toTops.style.display = 'block'; }else{ toTops.style.display = 'none'; } if(!isTop){ clearInterval(timer); } isTop = false; } toTops.onclick = function(){ timer = setInterval(function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; var ispeed = Math.floor( -osTop / 6 ); document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed; console.log(osTop + ispeed); isTop = true; if(osTop == 0){ clearInterval(timer); } },30); } }<file_sep>/js/honor.js window.onload = function(){ // banner部分开始 var animat = false; var index = 0; var list = document.getElementById('list').getElementsByTagName('a'); var dots = document.getElementById('dot').getElementsByTagName('span'); document.getElementById('next').onclick = function(){next()}; document.getElementById('pre').onclick = function(){pre()}; var int = setInterval(function(){next()},5000); function next(){ if(animat){ return false; } var new_index = (index+1 >5)?0:index+1; animation(index, new_index); index = new_index; checkIndex(); } function pre(){ var new_index = (index - 1 <0)?5:index-1; animation(index, new_index); index = new_index; checkIndex(); if(animat){ return false; } } function animation(index, new_index){ animat = true; var interval = 10; var one_time = 1000; var offset = 1/(1000/10); list[index].style.opacity = 1; list[new_index].style.opacity = 0; list[new_index].style.display = 'block'; var x = 0; go(); function go(){ x += offset; list[index].style.opacity -= offset; list[new_index].style.opacity = x; if (list[index].style.opacity >= 0){ setTimeout(function(){go()},10); }else{ list[index].style.display = 'none'; animat = false; } console.log(list[index].style.opacity,list[new_index].style.opacity); } } function checkIndex(){ for (var i=0; i<dots.length; i++){ dots[i].className = ''; } dots[index].className = 'on'; } for(var i=0; i<dots.length; i++){ dots[i].onclick = function(){ if(animat){ return false; } var new_index = Number(this.getAttribute('index')); animation(index,new_index); index = new_index; checkIndex(); } dots[i].onmouseover = function(){ if(animat){ return false; } var new_index = Number(this.getAttribute('index')); animation(index,new_index); index = new_index; checkIndex(); } } var banners = document.getElementById('banner'); banners.onmouseover = function(){ clearInterval(int); }; banners.onmouseout = function(){ int = setInterval(function(){next()},3000) } // banner部分结束 // 悬浮工具栏开始 var toTops = document.getElementById('toTop'); var clientHeight = document.documentElement.clientHeight; var timer = null; var isTop = true; window.onscroll = function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; if(osTop>=clientHeight){ toTops.style.display = 'block'; }else{ toTops.style.display = 'none'; } if(!isTop){ clearInterval(timer); } isTop = false; } toTops.onclick = function(){ timer = setInterval(function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; var ispeed = Math.floor( -osTop / 6 ); document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed; console.log(osTop + ispeed); isTop = true; if(osTop == 0){ clearInterval(timer); } },30); } }<file_sep>/js/phone.js window.onload = function(){ // var productLists = document.getElementById('productList'); // document.getElementById('allProduct').onmouseover = function(){ // productLists.style.display = 'block'; // document.getElementById('allProduct').onmouseout = function(){ // productLists.style.display = 'none'; // } (function(){ var time = null; var list = $("#allProduct"); var box = $("#productList"); var lista = list.find("a"); for(var i=0,j=lista.length;i<j;i++){ if(lista[i].className == "now"){ var olda = i; } } var box_show = function(hei){ box.stop().animate({ height:hei, opacity:1 },400); } var box_hide = function(){ box.stop().animate({ height:0, opacity:0 },400); } lista.hover(function(){ lista.removeClass("now"); $(this).addClass("now"); clearTimeout(time); var index = list.find("a").index($(this)); box.find(".cont").hide().eq(index).show(); var _height = box.find(".cont").eq(index).height()+54; box_show(_height) },function(){ time = setTimeout(function(){ box.find(".cont").hide(); box_hide(); },50); lista.removeClass("now"); lista.eq(olda).addClass("now"); }); box.find(".cont").hover(function(){ var _index = box.find(".cont").index($(this)); lista.removeClass("now"); lista.eq(_index).addClass("now"); clearTimeout(time); $(this).show(); var _height = $(this).height()+54; box_show(_height); },function(){ time = setTimeout(function(){ $(this).hide(); box_hide(); },50); lista.removeClass("now"); lista.eq(olda).addClass("now"); }); })(); // 悬浮工具栏开始 var toTops = document.getElementById('toTop'); var clientHeight = document.documentElement.clientHeight; var timer = null; var isTop = true; window.onscroll = function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; if(osTop>=clientHeight){ toTops.style.display = 'block'; }else{ toTops.style.display = 'none'; } if(!isTop){ clearInterval(timer); } isTop = false; } toTops.onclick = function(){ timer = setInterval(function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; var ispeed = Math.floor( -osTop / 6 ); document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed; console.log(osTop + ispeed); isTop = true; if(osTop == 0){ clearInterval(timer); } },30); } } <file_sep>/js/club.js window.onload = function(){ // banner部分开始 var animat = false; var index = 0; var list = document.getElementById('list').getElementsByTagName('a'); var dots = document.getElementById('dot').getElementsByTagName('span'); document.getElementById('next').onclick = function(){next()}; document.getElementById('pre').onclick = function(){pre()}; var int = setInterval(function(){next()},5000); function next(){ if(animat){ return false; } var new_index = (index+1 >4)?0:index+1; animation(index, new_index); index = new_index; checkIndex(); } function pre(){ var new_index = (index - 1 <0)?4:index-1; animation(index, new_index); index = new_index; checkIndex(); if(animat){ return false; } } function animation(index, new_index){ animat = true; var interval = 10; var one_time = 1000; var offset = 1/(1000/10); list[index].style.opacity = 1; list[new_index].style.opacity = 0; list[new_index].style.display = 'block'; var x = 0; go(); function go(){ x += offset; list[index].style.opacity -= offset; list[new_index].style.opacity = x; if (list[index].style.opacity >= 0){ setTimeout(function(){go()},10); }else{ list[index].style.display = 'none'; animat = false; } console.log(list[index].style.opacity,list[new_index].style.opacity); } } function checkIndex(){ for (var i=0; i<dots.length; i++){ dots[i].className = ''; } dots[index].className = 'on'; } for(var i=0; i<dots.length; i++){ dots[i].onclick = function(){ if(animat){ return false; } var new_index = Number(this.getAttribute('index')); animation(index,new_index); index = new_index; checkIndex(); } dots[i].onmouseover = function(){ if(animat){ return false; } var new_index = Number(this.getAttribute('index')); animation(index,new_index); index = new_index; checkIndex(); } } // var banners = document.getElementById('banner'); // banners.onmouseover = function(){ // clearInterval(int); // }; // banners.onmouseout = function(){ // int = setInterval(function(){next()},3000) // } // banner部分结束 // 版块的Tab菜单部分开始 function $(id){ return typeof id==='string'?document.getElementById(id):id; } // var index=0; var timer=null; // var lis=$('Section_title').getElementsByTagName('span'); var divs=$('section_nr').getElementsByTagName('div'); // for(var i=0;i<lis.length;i++){ lis[i].id=i; lis[i].onmouseover=function(){ clearInterval(timer); changeOption(this.id); } // lis[i].onmouseout=function(){ // timer=setInterval(autoPlay,2000); // } } // if(timer){ // clearInterval(timer); // timer=null; // } // // timer=setInterval(autoPlay,2000); function autoPlay(){ index++; if(index>=lis.length){ index=0; } changeOption(index); } function changeOption(curIndex){ for(var j=0;j<lis.length;j++){ lis[j].className=''; divs[j].style.display='none'; } // lis[curIndex].className='select'; divs[curIndex].style.display='block'; index=curIndex; } // 版块的Tab菜单部分结束 // 悬浮工具栏开始 var toTops = document.getElementById('toTop'); var clientHeight = document.documentElement.clientHeight; var timer = null; var isTop = true; window.onscroll = function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; if(osTop>=clientHeight){ toTops.style.display = 'block'; }else{ toTops.style.display = 'none'; } if(!isTop){ clearInterval(timer); } isTop = false; } toTops.onclick = function(){ timer = setInterval(function(){ var osTop = document.documentElement.scrollTop || document.body.scrollTop; var ispeed = Math.floor( -osTop / 6 ); document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed; console.log(osTop + ispeed); isTop = true; if(osTop == 0){ clearInterval(timer); } },30); } // 固定边栏滚动 // var $ = function(id){ // return document.getElementById(id); // } var addEvent = function(obj,event,fn){ if(obj.addEventListener){ obj.addEventListener(event,fn,false); }else if(obj.attachEvent){ obj.attachEvent('on'+ event,fn); } } var domSider = $('content_right'); var scrollEvent = function(){ var sideHeight = domSider.offsetHeight; var screenHeight = document.documentElement.clientHeight||document.body.clientHeight; var scrollHeight = document.documentElement.scrollTop||document.body.scrollTop; if(scrollHeight+screenHeight >sideHeight + 487){ domSider.style.cssText = 'position:fixed;right:230px;top:'+(-(sideHeight-screenHeight))+'px'; }else{ domSider.style.position='static'; } } addEvent(window,'scroll',function(){ scrollEvent(); }); addEvent(window,'resize',function(){ scrollEvent(); }); // 固定边栏滚动结束 }
75bb718228daf11308ffe88f95104cc1e392e146
[ "JavaScript" ]
4
JavaScript
cdawen/vmall
7310c8c2318a660f2daa7d88e3cd9ab2def62779
242220a0fd6e30c1765ad6cca30821d0e550f551
refs/heads/master
<repo_name>Naman-12911/TextUtil-react-app<file_sep>/src/Components/About.js function About(props) { /* const [mystyle, setMystyle] = useState({ color: "white", backgroundColor: "black", }); const [btntext, setBtntext] = useState("set dark theme"); */ let mystyle = { color: props.mode === "dark" ? "white" : "#042743", backgroundColor: props.mode === "dark" ? "rgb(36 74 104)" : "white", }; return ( <div className="container" style={{ color: props.mode === "dark" ? "white" : "#042743" }} > <h3> About Us</h3> <div className="accordion my-2" id="accordionExample"> <div className="accordion-item"> <h2 className="accordion-header" id="headingOne"> <button className="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne" style={mystyle} > <strong>Analyze your text</strong> </button> </h2> <div id="collapseOne" className="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample" > <div className="accordion-body" style={mystyle}> Textutil gives you a way to analyse your text quickly and eficiently. Be it word count, character count. </div> </div> </div> <div className="accordion-item"> <h2 className="accordion-header" id="headingTwo"> <button className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" style={mystyle} > <strong>Free to use</strong> </button> </h2> <div id="collapseTwo" className="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample" > <div className="accordion-body" style={mystyle}> Textutils is a free character counter tool that provide instant chnaracter count & word count statistics for a given text. Textutils reports the number of words and character. Thus it is suitable for writing text with word/ character limit. </div> </div> </div> <div className="accordion-item"> <h2 className="accordion-header" id="headingThree"> <button className="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree" style={mystyle} > <strong>Brower Compatible</strong> </button> </h2> <div id="collapseThree" className="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample" > <div className="accordion-body" style={mystyle}> This word counter software works in any Brower such as chrome, Firefox, Interet Exploler, Safari, opera.Its suits to count character in facebook, blog, excel, document, pdf document, essaya, etc. </div> </div> </div> </div> </div> ); } export default About;
14978480c07d144fdcffd78df549fd6140f42f32
[ "JavaScript" ]
1
JavaScript
Naman-12911/TextUtil-react-app
623efb42f399a4886bfa460e9f2f29b1ef57c040
8a713891ee30823b7b461d17fe0eebd16eb28af6
refs/heads/main
<repo_name>valerianaGit/ASP.NETMVC5Fundamentals<file_sep>/OdeToFood.Data/Models/Restaurant.cs using System; namespace OdeToFood.Data.Models { public class Restaurant { public Restaurant() { } public int Id { get; set; } public string Name { get; set; } public CuisineType Cuisine { get; set; } } } <file_sep>/OdeToFood.Data/Services/InMemoryRestaurantData.cs using System; using System.Collections.Generic; using System.Linq; using OdeToFood.Data.Models; namespace OdeToFood.Data.Services { public class InMemoryRestaurantData : IRestaurantData { List<Restaurant> restaurants; public InMemoryRestaurantData() { restaurants = new List<Restaurant>() { new Restaurant { Id = 1, Name = "<NAME> ", Cuisine = CuisineType.Italian}, new Restaurant { Id = 2, Name = "Macciano's ", Cuisine = CuisineType.French}, new Restaurant { Id = 3, Name = "Patty's corner ", Cuisine = CuisineType.Indian} }; } IEnumerable<Restaurant> IRestaurantData.GetAll() { return restaurants.OrderBy(restaurants => restaurants.Name); } } } <file_sep>/README.md # ASP.NETMVC5Fundamentals practice from course asp.net MVC 5 FUndamentals link for course https://app.pluralsight.com/course-player?clipId=4f710dfb-8964-4a06-a780-6b270f17cb14 <file_sep>/OdeToFood.Web/Controllers/HomeController.cs using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using OdeToFood.Web.Models; using OdeToFood.Data.Services;// to add this reference to a separate project, // go to the project root, // in this case OdeToFood.Web and click add and then in the settings section // add the project you'd like to use - that will allow you to use the // other projects namespace OdeToFood.Web.Controllers { public class HomeController : Controller { IRestaurantData db; public HomeController() { db = new InMemoryRestaurantData(); } //private readonly ILogger<HomeController> _logger; //public HomeController(ILogger<HomeController> logger) //{ // _logger = logger; //} public IActionResult Index() { var model = db.GetAll(); return View(model); } public IActionResult Privacy() { return View(); } public IActionResult Eloquent() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
a31d9bfa93eeb2ccaa24ec08cb64734ba0db73df
[ "Markdown", "C#" ]
4
C#
valerianaGit/ASP.NETMVC5Fundamentals
2f249db8c127910cd8b7729d5b4f93e7372fbb80
d1dfeea6a3c89474a4842763221e14dbaf609ea0
refs/heads/master
<repo_name>victorparedes/magneto<file_sep>/app/dataStorage/mongoose.js const Bb = require("bluebird"); const mongoose = require("mongoose"); require('dotenv').config() mongoose.Promise = Bb; mongoose.connect(process.env.DB_URL, { useNewUrlParser: true }); //mongoose.connect(process.env.DB_URL); const connection = mongoose.connection; connection.once("open", () => { console.log("Connected to mongoDB/Common"); }); connection.on("error", err => { console.log(`connection error: ${err.message}`); }); module.exports = mongoose; <file_sep>/app/app.js const express = require('express') const mutantRoute = require('./routes/mutant') const checkRoute = require('./routes/check') const statsRoute = require('./routes/stats') const app = express() app.use(express.json()) app.use('/check', checkRoute); app.use('/mutant', mutantRoute); app.use('/stats', statsRoute); module.exports = app;<file_sep>/app/model.js const IsHorizontalDnaMutantSecuence = function (text, column, letter) { return text[column + 1] === letter && text[column + 2] === letter && text[column + 3] === letter; } const IsVerticalDnaMutantSecuence = function (dnaSecuence, row, column, letter) { if (dnaSecuence.length - column <= 3) { return false; } if (dnaSecuence[column + 1].charAt(row) == letter && dnaSecuence[column + 2].charAt(row) == letter && dnaSecuence[column + 3].charAt(row) == letter) { return true; } return false; } const GenericAcrossDnaCheck = function (dnaSecuence, row, column, letter, increment) { if (dnaSecuence.length - column <= 3) { return false; } if (dnaSecuence[column + 1].charAt(row + (1 * increment)) == letter && dnaSecuence[column + 2].charAt(row + (2 * increment)) == letter && dnaSecuence[column + 3].charAt(row + (3 * increment)) == letter) { return true; } return false; } const IsAcrossRightDnaMutantSecuence = function (dnaSecuence, row, column, letter) { return GenericAcrossDnaCheck(dnaSecuence, row, column, letter, 1) } const IsAcrossLeftDnaMutantSecuence = function (dnaSecuence, row, column, letter) { return GenericAcrossDnaCheck(dnaSecuence, row, column, letter, -1) } var modelFunctions = { isMutant: (dna) => { let dnaSecuenceFound = 0; let dnaSecuence = dna.dna; // each row for (let rowCount = 0; rowCount < dnaSecuence.length; rowCount++) { let currenFile = dnaSecuence[rowCount]; // each column for (var columnCount = 0; columnCount < currenFile.length; columnCount++) { var currenLetter = currenFile[columnCount]; // Find horizontal if (IsHorizontalDnaMutantSecuence(currenFile, columnCount, currenLetter)) { dnaSecuenceFound++; } // Find vertical if (IsVerticalDnaMutantSecuence(dnaSecuence, columnCount, rowCount, currenLetter)) { dnaSecuenceFound++; } // Find right acrossed if (IsAcrossRightDnaMutantSecuence(dnaSecuence, columnCount, rowCount, currenLetter)) { dnaSecuenceFound++; } // Find left acrossed if (IsAcrossLeftDnaMutantSecuence(dnaSecuence, columnCount, rowCount, currenLetter)) { dnaSecuenceFound++; } } } return dnaSecuenceFound > 1; } }; module.exports = modelFunctions;<file_sep>/app/routes/mutant.js const express = require("express"); const router = express.Router(); const validate = require('express-validation'); const dnaValidator = require('../dnaValidator'); const mutantModel = require('../model') const transaction = require('../dataStorage/transaction'); router.post('/', validate(dnaValidator), function (req, res) { if (mutantModel.isMutant(req.body)) { res.sendStatus(200); transaction.AddAnalizedDnaSecuence(req.body, true) } else { res.sendStatus(403); transaction.AddAnalizedDnaSecuence(req.body, false) } }); module.exports = router;<file_sep>/test/mutantRoute.js const request = require('supertest'); const mockery = require('mockery') before(function () { mockery.enable({ warnOnUnregistered: false, useCleanCache: true }) var model = { isMutant: function (dna) { if (dna.dna[0] == "MUTANT") { return true; } return false; } } var transaction = { AddAnalizedDnaSecuence: async (dna, isMutant) => { } } mockery.registerMock('../model', model) mockery.registerSubstitute('../dataStorage/transaction', '../../test/transactionFake'); }) after(function () { mockery.deregisterAll(); mockery.disable() }) describe("Magneto try to send dna and find mutants.", function () { it("Receive a dna mutant, response ok.", function (done) { var app = require("../app/app"); request(app) .post('/mutant') .send({ dna: ["MUTANT"] }) .expect(200) .end(function (err, res) { if (err) throw err else done() }); }); it("Receive a dna human, response forbidden.", function (done) { var app = require("../app/app"); request(app) .post('/mutant') .send({ dna: ["HUMAN"] }) .expect(403) .end(function (err, res) { if (err) throw err else done() }); }); })<file_sep>/test/transactionFake.js module.exports = { AddAnalizedDnaSecuence: async (dna, isMutant) => { }, GetSecuenceDna: async (isMutant) => { if (isMutant) { return 10; } return 5; } }<file_sep>/app/dataStorage/transaction.js const dataModel = require('./dataModel') const _ = require("underscore") module.exports = { AddAnalizedDnaSecuence: async (dna, isMutant) => { var dnaSecuence = dna.dna.join(''); var currentSubject = await dataModel.findOne({ dnaSecuence: dnaSecuence }); if (currentSubject) { currentSubject.count++; } else { currentSubject = new dataModel({ dnaSecuence: dnaSecuence, dna: dna, count: 1, isMutant: isMutant }) } currentSubject.save({}) }, GetSecuenceDna: async (isMutant) => { var results = await dataModel.find({ isMutant: isMutant }); return _.reduce(results, (current, dnaSecuence) => { return current + dnaSecuence.count; }, 0); } }<file_sep>/app/routes/stats.js const express = require('express') const router = express.Router() const transaction = require('../dataStorage/transaction'); router.get('/', async function (req, res) { var dnaMutant = await transaction.GetSecuenceDna(true) var dnaHuman = await transaction.GetSecuenceDna(false) var ratio = dnaHuman == 0 ? dnaMutant : (dnaMutant / dnaHuman).toFixed(2) res.json({ count_mutant_dna: dnaMutant, count_human_dna: dnaHuman, ratio: ratio }) }); module.exports = router;<file_sep>/README.md # Mercadolibre Mutant Challenge Web App used by Magneto to detect dna mutant in a dna sequence. Developed by Quicksilver ( AKA <NAME> ) # Prerequisites - [Node.js 8](https://nodejs.org/es/) - [NPM Package manager](https://www.npmjs.com/) # How to install Download from GIT and install all dependency ```cmd $ md magneto $ cd magneto $ git clone hhttps://github.com/VictorParedes/magneto.git $ npm install ``` # How to config Create a .env file in /git/escobar with this values | key | default value | description | |---|---|---| | PORT | 8080 | Number of Port where app is running | | DB_URL | mongodb://localhost:27017/Magneto | Url to mongo db | # How to run local ```cmd $ npm start ```
233b3bf1374a11662ed1e50a30e23f96f2681fca
[ "JavaScript", "Markdown" ]
9
JavaScript
victorparedes/magneto
8ead973143e118d54ef77065420fa492821f4961
820f34c11934066178e494288f3ef345851c5935
refs/heads/master
<repo_name>qinxian1989/csv-nix-tools<file_sep>/doc/csv-lstree.1.md <!-- SPDX-License-Identifier: BSD-3-Clause Copyright 2021, <NAME> <<EMAIL>> --> --- title: csv-lstree section: 1 ... # NAME # csv-lstree - list files in hierarchical manner # SYNOPSIS # **csv-lstree** [OPTION]... [FILE]... # DESCRIPTION # Recursively list FILEs (starting from current directory by default). -f : add parent directory prefix to file names -s : print output in table format -S : print output in table format with pager # EXAMPLES # `csv-lstree` `csv-lstree -s /usr/local` # SEE ALSO # **csv-ls**(1), **csv-tree**(1), **csv-show**(1), **csv-nix-tools**(7) <file_sep>/src/csv-lstree #!/bin/bash -e # SPDX-License-Identifier: BSD-3-Clause # Copyright 2021, <NAME> <<EMAIL>> set -o pipefail show= indentcol=name OPTIND=1 while getopts "fsS" opt; do case "$opt" in f) indentcol=full_path ;; s) show=-s ;; S) show=-S ;; esac done shift $((OPTIND-1)) csv-ls -a -c full_path,parent,name,size -R "$@" | \ csv-grep -v -c name -x -F . -c name -x -F .. | \ csv-tree --key full_path --parent parent --indent $indentcol --sum size | \ csv-cut -c size,$indentcol $show <file_sep>/tests/add-concat/add-concat.cmake # # SPDX-License-Identifier: BSD-3-Clause # # Copyright 2019-2020, <NAME> <<EMAIL>> # test("csv-add-concat" data/empty.txt data/empty.csv add-concat/help.txt 2 add-concat_no_args) test("csv-add-concat new_column = %name ' - ' %id" data/3-columns-3-rows.csv add-concat/2-cols.csv data/empty.txt 0 add-concat_2_cols) test("csv-add-concat new_column = %name ' - ' %id -s" data/3-columns-3-rows.csv add-concat/2-cols-s.txt data/empty.txt 0 add-concat_2_cols-s) test("csv-add-concat new_column = %name ', ' %id" data/3-columns-3-rows.csv add-concat/2-cols-comma.csv data/empty.txt 0 add-concat_2_cols_comma) test("csv-add-concat -T t1 -- new = 'X ' %name ' Y'" data/2-tables.csv add-concat/2-tables-add1.csv data/empty.txt 0 add-concat_2tables-add1) test("csv-add-concat --help" data/empty.csv add-concat/help.txt data/empty.txt 2 add-concat_help) test("csv-add-concat --version" data/empty.csv data/git-version.txt data/empty.txt 0 add-concat_version) <file_sep>/src/parse.h /* * SPDX-License-Identifier: BSD-3-Clause * * Copyright 2019-2021, <NAME> <<EMAIL>> */ #ifndef CSV_PARSE_H #define CSV_PARSE_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> struct csv_ctx; struct col_header { const char *name; const char *type; bool had_type; }; struct csv_ctx *csv_create_ctx(FILE *in, FILE *err); struct csv_ctx *csv_create_ctx_nofail(FILE *in, FILE *err); int csv_read_header(struct csv_ctx *s); void csv_read_header_nofail(struct csv_ctx *s); size_t csv_get_headers(struct csv_ctx *s, const struct col_header **headers); typedef int (*csv_row_cb)(const char *buf, const size_t *col_offs, size_t ncols, void *arg); int csv_read_all(struct csv_ctx *s, csv_row_cb cb, void *arg); void csv_read_all_nofail(struct csv_ctx *s, csv_row_cb cb, void *arg); void csv_destroy_ctx(struct csv_ctx *s); #endif <file_sep>/src/csv-pstree #!/bin/bash -e # SPDX-License-Identifier: BSD-3-Clause # Copyright 2021, <NAME> <<EMAIL>> set -o pipefail filter= filteropt= show= OPTIND=1 while getopts "f:sS" opt; do case "$opt" in f) filter=--filter filteropt="$OPTARG" ;; s) show=-s ;; S) show=-S ;; esac done shift $((OPTIND-1)) csv-ps -c pid,ppid,command,vm_rss_KiB "$@" | \ csv-tree --key pid --parent ppid --indent command --sum vm_rss_KiB $filter "$filteropt" | \ csv-cut -c pid,vm_rss_KiB,command $show <file_sep>/src/show_ncurses.c /* * SPDX-License-Identifier: BSD-3-Clause * * Copyright 2019-2021, <NAME> <<EMAIL>> */ #include <curses.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "ht.h" #include "show.h" #include "utils.h" struct slow_params { struct cb_params *params; const char *txt; }; static int h2i(char c) { if (c >= '0' && c <= '9') return c - '0'; return c - 'A' + 10; } static void * get_color_slow(void *p_) { struct slow_params *p = p_; int color; const char *col = p->txt; if (strcmp(col, "black") == 0) color = COLOR_BLACK; else if (strcmp(col, "red") == 0) color = COLOR_RED; else if (strcmp(col, "green") == 0) color = COLOR_GREEN; else if (strcmp(col, "yellow") == 0) color = COLOR_YELLOW; else if (strcmp(col, "blue") == 0) color = COLOR_BLUE; else if (strcmp(col, "magenta") == 0) color = COLOR_MAGENTA; else if (strcmp(col, "cyan") == 0) color = COLOR_CYAN; else if (strcmp(col, "white") == 0) color = COLOR_WHITE; else if (strcmp(col, "default") == 0) color = -1; else if (strlen(col) == 6) { if (!can_change_color()) { endwin(); fprintf(stderr, "Your terminal doesn't support changing colors\n"); exit(2); } if (p->params->used_colors >= COLORS) { endwin(); fprintf(stderr, "reached maximum number of colors %d\n", p->params->used_colors); exit(2); } color = p->params->used_colors++; for (unsigned i = 0; i < 6; ++i) if (!((col[i] >= '0' && col[i] <= '9') || (col[i] >= 'A' && col[i] <= 'F'))) goto err; int r = h2i(col[0]) * 16 + h2i(col[1]); int g = h2i(col[2]) * 16 + h2i(col[3]); int b = h2i(col[4]) * 16 + h2i(col[5]); r = (int)(1000.0 * r / 255.0); g = (int)(1000.0 * g / 255.0); b = (int)(1000.0 * b / 255.0); init_color(color, r, g, b); } else if (strtoi_safe(col, &color, 10) == 0) { ; } else { goto err; } /* we have to allocate, because COLOR_BLACK == 0 (and 0 casted to * void * is NULL, which is considered an error by csv_ht_get_value) */ int *color_ptr = xmalloc_nofail(1, sizeof(*color_ptr)); *color_ptr = color; return color_ptr; err: endwin(); fprintf(stderr, "Can't parse '%s' as color - it must be either a predefined name, in RRGGBB format or be a decimal number\n", col); exit(2); } static int get_color(struct cb_params *params, char *txt) { struct slow_params p; p.params = params; p.txt = txt; return *(int *)csv_ht_get_value(params->colors, txt, get_color_slow, &p); } static void * get_color_pair_slow(void *p_) { struct slow_params *p = p_; int fg = -1, bg = -1; int color_pair; char *txt = xstrdup_nofail(p->txt); size_t nresults; util_split_term(txt, ",", &p->params->split_results, &nresults, &p->params->split_results_max_size); for (size_t i = 0; i < nresults; ++i) { char *desc = txt + p->params->split_results[i].start; if (strncmp(desc, "fg=", 3) == 0) fg = get_color(p->params, desc + 3); else if (strncmp(desc, "bg=", 3) == 0) bg = get_color(p->params, desc + 3); else fg = get_color(p->params, desc); } free(txt); if (p->params->used_pairs >= COLOR_PAIRS - 1) { endwin(); fprintf(stderr, "reached maximum number of color pairs %d\n", p->params->used_pairs); exit(2); } color_pair = p->params->used_pairs++; init_pair(color_pair, fg, bg); return (void *)(intptr_t)color_pair; } static int get_color_pair(struct cb_params *params, char *txt) { struct slow_params p; p.params = params; p.txt = txt; return (int)(intptr_t)csv_ht_get_value(params->color_pairs, txt, get_color_pair_slow, &p); } static void nprint(int y, int x, const char *str, bool *truncated) { size_t len = strlen(str); *truncated = false; if (x < 0) { /* no part of the string will be visible */ if (len < -x) return; str += -x; len -= -x; x = 0; } if (x + len >= COLS) { len = COLS - x; *truncated = true; } mvaddnstr(y, x, str, len); } static void show(struct cb_params *params, const struct col_header *headers, size_t nheaders, size_t first_line, /* index of the first line to show */ size_t nlines, /* number of lines to show */ int xoff, size_t spacing, bool print_header, bool print_types, enum alignment *alignments, bool use_color_columns, bool *is_color_column, size_t *color_column_index, size_t *col_offsets) { char **data = params->lines; size_t *max_lengths = params->max_lengths; int *col_color_pairs = params->col_color_pairs; size_t ypos = 0; clear(); if (print_header) { int xpos = 0; attron(A_BOLD); for (size_t i = 0; i < nheaders; ++i) { int prev_xpos = xpos; bool truncated; if (use_color_columns && is_color_column[i]) continue; if (col_color_pairs[i] != -1) attron(COLOR_PAIR(col_color_pairs[i])); size_t len = strlen(headers[i].name); if (print_types) len += 1 + strlen(headers[i].type); if (alignments[i] == RIGHT) for (size_t j = 0; j < max_lengths[i] - len; ++j) mvaddch(ypos, xpos - xoff + j, ' '); if (alignments[i] == RIGHT) xpos += max_lengths[i] - len; nprint(0, xpos - xoff, headers[i].name, &truncated); if (truncated) break; xpos += strlen(headers[i].name); if (print_types) { attroff(A_BOLD); nprint(0, xpos - xoff, ":", &truncated); if (truncated) break; xpos++; nprint(0, xpos - xoff, headers[i].type, &truncated); if (truncated) break; xpos += strlen(headers[i].type); attron(A_BOLD); } if (alignments[i] == LEFT) for (size_t j = 0; j < max_lengths[i] - len; ++j) mvaddch(ypos, xpos - xoff + j, ' '); if (i < nheaders - 1) xpos = prev_xpos + max_lengths[i] + spacing; if (col_color_pairs[i] != -1) attroff(COLOR_PAIR(col_color_pairs[i])); } attroff(A_BOLD); ypos++; } for (size_t ln = first_line; ln < first_line + nlines; ++ln, ++ypos) { char *buf = data[ln]; int xpos = 0; col_offsets[0] = 0; for (size_t i = 1; i < nheaders + 1; ++i) { size_t len = strlen(buf + col_offsets[i - 1]); col_offsets[i] = col_offsets[i - 1] + len + 1; } for (size_t i = 0; i < nheaders; ++i) { bool truncated; size_t len = col_offsets[i + 1] - col_offsets[i] - 1; if (use_color_columns && is_color_column[i]) continue; int colpair = col_color_pairs[i]; if (use_color_columns && color_column_index[i] != SIZE_MAX) { char *col = buf + col_offsets[color_column_index[i]]; if (col[0]) colpair = get_color_pair(params, col); } if (colpair != -1) attron(COLOR_PAIR(colpair)); if (alignments[i] == RIGHT) for (size_t j = 0; j < max_lengths[i] - len; ++j) mvaddch(ypos, xpos - xoff + j, ' '); if (alignments[i] == RIGHT) xpos += max_lengths[i] - len; nprint(ypos, xpos - xoff, buf + col_offsets[i], &truncated); if (truncated) { if (colpair != -1) attroff(COLOR_PAIR(colpair)); break; } if (alignments[i] == LEFT) for (size_t j = len; j < max_lengths[i]; ++j) mvaddch(ypos, xpos - xoff + j, ' '); xpos += len; if (alignments[i] == LEFT) if (i < nheaders - 1) xpos += max_lengths[i] - len; if (i < nheaders - 1) xpos += spacing; if (colpair != -1) attroff(COLOR_PAIR(colpair)); } } } void curses_ui(struct cb_params *params, const struct col_header *headers, size_t nheaders, bool print_header, bool print_types, size_t spacing, enum alignment *alignments, char **set_colorpair, size_t set_colorpairs_num, bool use_color_columns) { if (close(0)) { perror("close"); exit(2); } char *tty = ttyname(1); if (!tty) { perror("ttyname"); exit(2); } int fd = open(tty, O_RDONLY); if (fd < 0) { perror("open"); exit(2); } if (fd != 0) /* impossible */ abort(); params->used_pairs = 1; params->used_colors = COLOR_WHITE + 1; initscr(); params->col_color_pairs = xmalloc_nofail(nheaders, sizeof(params->col_color_pairs[0])); for (size_t i = 0; i < nheaders; ++i) params->col_color_pairs[i] = -1; if (set_colorpairs_num || use_color_columns) { if (!has_colors()) { endwin(); fprintf(stderr, "Your terminal doesn't support colors\n"); exit(2); } start_color(); use_default_colors(); if (csv_ht_init(&params->color_pairs, NULL, 0)) { endwin(); exit(2); } if (csv_ht_init(&params->colors, free, 0)) { endwin(); exit(2); } for (size_t i = 0; i < set_colorpairs_num; ++i) { struct split_result *results = NULL; size_t nresults; util_split_term(set_colorpair[i], ":", &results, &nresults, NULL); if (nresults != 2) { endwin(); fprintf(stderr, "Color not in name:spec format\n"); exit(2); } char *x = set_colorpair[i] + results[0].start; size_t idx = csv_find_loud(headers, nheaders, NULL, x); if (idx == CSV_NOT_FOUND) { endwin(); exit(2); } x = set_colorpair[i] + results[1].start; free(results); params->col_color_pairs[idx] = get_color_pair(params, x); } } bool *is_color_column = NULL; size_t *color_column_index = NULL; size_t *col_offsets_buf = xmalloc_nofail(nheaders + 1, sizeof(col_offsets_buf[0])); if (use_color_columns) { is_color_column = xcalloc_nofail(nheaders, sizeof(is_color_column[0])); color_column_index = xmalloc_nofail(nheaders, sizeof(color_column_index[0])); for (size_t i = 0; i < nheaders; ++i) { size_t len = strlen(headers[i].name); is_color_column[i] = len >= strlen("_color") && strcmp(headers[i].name + len - strlen("_color"), "_color") == 0; color_column_index[i] = SIZE_MAX; for (size_t j = 0; j < nheaders; ++j) { if (strncmp(headers[i].name, headers[j].name, len) != 0) continue; if (strcmp(headers[j].name + len, "_color") != 0) continue; color_column_index[i] = j; break; } } } cbreak(); noecho(); clear(); keypad(stdscr, TRUE); curs_set(0); int ch = 0; size_t first_line = 0; size_t nlines; /* number of lines to show */ int xoff = 0; #define STEP (COLS / 2) size_t max_line = 0; for (size_t i = 0; i < nheaders; ++i) { if (is_color_column && is_color_column[i]) continue; max_line += params->max_lengths[i] + spacing; } if (max_line >= INT_MAX) { fprintf(stderr, "max line length exceeds %d\n", INT_MAX); exit(2); } do { /* * determine how many lines of data we can show, * max is the height of the window minus 1 if header must be shown */ nlines = LINES - print_header; /* is there enough data to fill one screen? */ if (nlines > params->nlines) nlines = params->nlines; /* * is there enough data to fill one screen starting from * the desired line? */ if (first_line + nlines > params->nlines) { /* * no, so calculate where should we start to fill * one screen */ if (params->nlines < nlines) first_line = 0; else first_line = params->nlines - nlines; } show(params, headers, nheaders, first_line, nlines, xoff, spacing, print_header, print_types, alignments, use_color_columns, is_color_column, color_column_index, col_offsets_buf); refresh(); if (params->logfd >= 0) { if (write(params->logfd, &ch, sizeof(ch)) != sizeof(ch)) { endwin(); perror("write"); exit(2); } } ch = getch(); if (ch == KEY_DOWN || ch == 'j') { if (first_line + nlines >= params->nlines) beep(); else first_line++; } else if (ch == KEY_UP || ch == 'k') { if (first_line > 0) first_line--; else beep(); } else if (ch == KEY_RIGHT) { if (xoff + COLS < max_line) xoff += STEP; else beep(); } else if (ch == KEY_LEFT) { if (xoff >= STEP) xoff -= STEP; else if (xoff == 0) beep(); else xoff = 0; } else if (ch == KEY_NPAGE || ch == ' ') { if (first_line + nlines >= params->nlines) beep(); else first_line += LINES - 1 - print_header; } else if (ch == KEY_PPAGE || ch == KEY_BACKSPACE) { if (first_line >= LINES - 1 - print_header) first_line -= LINES - 1 - print_header; else if (first_line == 0) beep(); else first_line = 0; } else if (ch == KEY_HOME) { if (first_line == 0) beep(); else first_line = 0; } else if (ch == KEY_END) { if (first_line == params->nlines - nlines) beep(); else first_line = params->nlines - nlines; } else if (ch == KEY_SHOME) { if (xoff == 0) beep(); else xoff = 0; } else if (ch == KEY_SEND) { int newxoff; if (max_line > COLS) newxoff = max_line - COLS; else newxoff = 0; if (newxoff == xoff) beep(); else xoff = newxoff; } else if (ch == '[') { /* move by one column left */ int old_xoff = xoff; int new_off = 0; for (size_t i = 0; i < nheaders; ++i) { if (is_color_column && is_color_column[i]) continue; size_t len = params->max_lengths[i] + spacing; if (new_off + len >= xoff) { xoff = new_off; break; } new_off += len; } if (old_xoff == xoff) beep(); } else if (ch == ']') { /* move by one column right */ int old_xoff = xoff; int new_off = 0; for (size_t i = 0; i < nheaders; ++i) { if (is_color_column && is_color_column[i]) continue; new_off += params->max_lengths[i] + spacing; if (new_off > xoff) { if (new_off < max_line) xoff = new_off; break; } } if (old_xoff == xoff) beep(); } else if (ch == '/') { // TODO implement search } else if (ch == 'h') { // TODO implement help } } while (ch != 'q'); if (params->logfd >= 0) { if (write(params->logfd, &ch, sizeof(ch)) != sizeof(ch)) { endwin(); perror("write"); exit(2); } close(params->logfd); } for (size_t i = 0; i < params->nlines; ++i) free(params->lines[i]); endwin(); if (set_colorpairs_num || use_color_columns) { csv_ht_destroy(&params->color_pairs); csv_ht_destroy(&params->colors); } free(col_offsets_buf); free(is_color_column); free(color_column_index); free(params->col_color_pairs); } void curses_ui_exit() { #if defined(NCURSESW62_OR_LATER) exit_curses(0); #endif }
c96f004f6194c21f18e52f095cef3cf407f41f4e
[ "Markdown", "C", "CMake", "Shell" ]
6
Markdown
qinxian1989/csv-nix-tools
1672789c51c570f4ad5cb854e642e59d2c726fed
433e342249b561ca3575e27b3b83316f8c7db6e4
refs/heads/main
<repo_name>Alistair017/Color-Game<file_sep>/color_Game.js // NOTE: spaces in arrays matter, // lack of these spaces results in a bug // non-selectors var numSquares = 6; var colorAnswer; var colors = []; // colors and squares var squares = document.querySelectorAll(".square"); var colorDisplay = document.getElementById("colorDisplay"); // #line var messageDisplay = document.querySelector("#message") var h1 = document.querySelector("h1") // buttons var resetButton = document.querySelector(".reset"); var modeButtons = document.querySelectorAll(".mode"); activateButtons(); function activateButtons(){ setModeButtons(); setUpSquares(); reset(); } function setModeButtons(){ for(var i = 0; i < modeButtons.length; i ++){ modeButtons[i].addEventListener("click", function(){ modeButtons[0].classList.remove("selected"); modeButtons[1].classList.remove("selected"); this.classList.add("selected"); // ternary operator this.textContent === "Easy" ? numSquares = 3: numSquares = 6; reset(); }); } } function setUpSquares(){ for (var i = 0; i < squares.length; i++){ // adding specific colors squares[i].style.backgroundColor = colors[i]; // adding the click event squares[i].addEventListener("click", function(){ // establishing a variable var clickedColor = this.style.backgroundColor; if(clickedColor === colorAnswer){ messageDisplay.textContent = "Well Done!"; // only runs if the clickedColor is colorAnswer changeColors(clickedColor); h1.style.backgroundColor = clickedColor; resetButton.textContent = "Play again?" } else{ this.style.backgroundColor = "#232323"; messageDisplay.textContent = "try again"; } }) }; } // super-important // with this, I won't need to repeat so much function reset(){ colors = generateRandomColors(numSquares) // pick new answer from array of new colors colorAnswer = pickColor(); // change colorDisplay to match colorAnswer colorDisplay.textContent = colorAnswer; resetButton.textContent = "New Colors"; messageDisplay.textContent = ""; // change colors of squares for (var i = 0; i < squares.length; i++){ if(colors[i]){ squares[i].style.display = "block"; squares[i].style.backgroundColor = colors[i]; } else{ squares[i].style.display = "none"; } }; h1.style.backgroundColor = "steelblue"; } resetButton.addEventListener("click", function(){ reset(); }) function changeColors(color){ // loop through squares for(var i = 0; i < squares.length; i++){ // assign each square to the clicked color squares[i].style.backgroundColor = color; } } function pickColor(){ var random = Math.floor(Math.random() * colors.length); return colors[random]; } function generateRandomColors(num){ // make array var arr = []; // add random colors to array for(var i = 0; i < num; i++){ // get random colors and push to array arr.push(randomColorMake()); } // return array return arr; } function randomColorMake(){ // pick a kind of red from 0 - 255 var r = Math.floor(Math.random() * 256); // pick a kind of green from 0 - 255 var g = Math.floor(Math.random() * 256); // pick a kind of blue from 0 - 255 var b = Math.floor(Math.random() * 256); return "rgb(" + r + ", " + g + ", " + b + ")" }
36f26113d3bbd6493bc6063a8c33ea30c63b9b3d
[ "JavaScript" ]
1
JavaScript
Alistair017/Color-Game
dca02eb79ed558948f66a379ec221731e214e595
e08abe13119c97d7ea11a1f88492f100946e0bc1
refs/heads/master
<repo_name>Plummat/koa-react-example<file_sep>/src/index.js "use strict"; const React = require('react'); var App = require('./components/App'); React.render(<App />, document.body); // React.render(<App items = {TODOITEMS} />, document.body); <file_sep>/src/actions/ViewActionCreators.js var { ActionTypes } = require('../Constants'); var AppDispatcher = require('../AppDispatcher'); var ApiUtil = require('../utils/ApiUtil'); var ViewActionCreators = { loadItems () { AppDispatcher.handleViewAction({ type: ActionTypes.LOAD_ITEMS }); ApiUtil.loadItems(); }, deleteItem (item) { AppDispatcher.handleViewAction({ type: ActionTypes.DELETE_ITEM, item: item }); ApiUtil.deleteItem(item); }, createItem (item) { console.log(item); AppDispatcher.handleViewAction({ type: ActionTypes.CREATE_ITEM, item: item }); ApiUtil.createItem(item); }, completeItem(item){ AppDispatcher.handleViewAction({ type: ActionTypes.COMPLETE_ITEM, item: item }); ApiUtil.completeItem(item); } }; module.exports = ViewActionCreators;<file_sep>/src/components/App.js "use strict"; const React = require('react'); const warning = require('react/lib/warning'); var ItemsStore = require('../stores/ItemsStore'); var ViewActionCreators = require('../actions/ViewActionCreators'); var App = React.createClass({ getInitialState() { console.log('getInitial was called') return ItemsStore.getState(); }, componentDidMount() { ItemsStore.addChangeListener(this.handleStoreChange); ViewActionCreators.loadItems(); }, componentWillUnmount() { ContactsStore.removeChangeListener(this.handleStoreChange); }, handleStoreChange () { this.setState(ItemsStore.getState()); }, render (){ if (!this.state.loaded) { return <div>Loading...</div>; } // var items = this.props.items.map((item) => { console.log(this.state.items) var items = this.state.items.map((item) => { return( <Item key={item.id} item={item}/> ) }); return( <div> <NewItem itemCount= {items.length} /> <ul> {items} </ul> </div> ); } }); var Item = React.createClass({ propTypes: { item: React.PropTypes.shape({ text: React.PropTypes.string.isRequired, complete: React.PropTypes.bool.isRequired, }).isRequired }, complete() { console.log(this.props.item.complete); ViewActionCreators.completeItem(this.props.item) }, delete() { ViewActionCreators.deleteItem(this.props.item); }, render(){ var { text, complete } = this.props.item; if (complete == false){ return ( <li> {text} Complete: {complete.toString()} <button onClick={this.complete}> COMPLETE ME </button> </li> ) } return ( <li> {text} Complete: {complete.toString()} <button onClick={this.delete}> DELETE ME </button> </li> ) } }); var NewItem = React.createClass({ propTypes: { itemCount: React.PropTypes.number.isRequired, }, createItem(event){ event.preventDefault(); var text = this.refs.itemText.getDOMNode().value; var id = this.props.itemCount + 1; var complete = false; var item = { id, text, complete }; ViewActionCreators.createItem(item) this.refs.itemText.getDOMNode().value = ''; }, render(){ return ( <form onSubmit={this.createItem}> <p> <input type="text" ref="itemText" placeholder="Item"/> </p> <p> <button type="submit">Save</button> </p> </form> ); } }); module.exports = App;<file_sep>/src/actions/ServerActionCreators.js var { ActionTypes } = require('../Constants'); var AppDispatcher = require('../AppDispatcher'); var ServerActionCreators = { loadedItems (items) { AppDispatcher.handleServerAction({ type: ActionTypes.ITEMS_LOADED, items: items }); }, deletedItem (item) { AppDispatcher.handleServerAction({ type: ActionTypes.ITEM_DELETED, item: item }); }, createItem (item){ console.log('create item in SAC was called'); console.log(item); AppDispatcher.handleServerAction({ type: ActionTypes.ITEM_CREATED, item: item }); }, completeItem (item){ console.log('complete item in SAC was called'); console.log(item); AppDispatcher.handleServerAction({ type: ActionTypes.ITEM_COMPLETED, item: item }); } }; module.exports = ServerActionCreators;<file_sep>/src/stores/ItemsStore.js var AppDispatcher = require('../AppDispatcher'); const { EventEmitter } = require('events'); var { ActionTypes } = require('../Constants'); const assign = require('react/lib/Object.assign'); var events = new EventEmitter(); var CHANGE_EVENT = 'CHANGE'; var state = { items: [], loaded: false }; var setState = (newState) => { assign(state, newState); events.emit(CHANGE_EVENT); }; var ItemsStore = { addChangeListener (fn) { events.addListener(CHANGE_EVENT, fn); }, removeChangeListener (fn) { events.removeListener(CHANGE_EVENT, fn); }, getState () { return state; } }; ItemsStore.dispatchToken = AppDispatcher.register((payload) => { var { action } = payload; console.log(action) console.log(action.item); if (action.type === ActionTypes.ITEMS_LOADED) { setState({ loaded: true, items: action.items }); } if (action.type === ActionTypes.ITEM_DELETED) { var newItems = state.items.filter((item) => { return item.id !== action.item.id; }); setState({ items: newItems }); } if (action.type === ActionTypes.ITEM_CREATED) { state.items.push(action.item); setState({ items: state.items }); } if (action.type === ActionTypes.ITEM_COMPLETED) { var newItems = state.items.map((item) => { if (item.id === action.item.id){ item.complete = true; } return item; }) console.log(newItems) setState({items: newItems}) } }); module.exports = ItemsStore;
1904e0efb5e9f3ead337dd2a139fb687c682fa29
[ "JavaScript" ]
5
JavaScript
Plummat/koa-react-example
d86ab2a92b51e8fa19041b885b0767eeeb79fd45
0c35c43ed55fd3f6b1720be11770982f3965aba2
refs/heads/master
<file_sep>package com.jeff.covidtracker.database.local import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = Cases.TABLE_NAME) data class Cases ( @PrimaryKey @ColumnInfo(name = "country_code") var countryCode: String, @ColumnInfo(name = "country_name") var country: String, @ColumnInfo(name = "date") var date: String, @ColumnInfo(name = "country_details") var details: CountryDetails? = null, @ColumnInfo(name = "new_cases") var newCases: NewCases? = null, @ColumnInfo(name = "total_cases") var totalCases: TotalCases? = null ) { constructor(): this("", "", "", null, null, null) data class CountryDetails( var province: String? = null, var city: String? = null, var cityCode: String? = null, var lat: String? = null, var lon: String? = null) companion object { const val COUNTRY_CODE = "country_code" const val TABLE_NAME = "country_cases" } }<file_sep>package com.jeff.covidtracker.main.mapper import com.jeff.covidtracker.database.local.* import com.jeff.covidtracker.webservices.dto.CasesDto import com.jeff.covidtracker.webservices.dto.CountryDto import com.jeff.covidtracker.webservices.dto.PhotoDto import io.reactivex.Observable import io.reactivex.functions.Function import timber.log.Timber class CasesDtoToCasesMapper : Function<CasesDto, Observable<Cases>> { @Throws(Exception::class) override fun apply(casesDto: CasesDto): Observable<Cases> { return Observable.fromCallable { val cases: Cases if (casesDto.active != null) { cases = Cases( casesDto.countryCode, casesDto.country, casesDto.date!!, Cases.CountryDetails( casesDto.province, casesDto.city, casesDto.cityCode, casesDto.lat, casesDto.lon), null, TotalCases( casesDto.confirmed!!, casesDto.deaths!!, casesDto.recovered!!, casesDto.active) ) } else { cases = Cases( casesDto.countryCode, casesDto.country, casesDto.date!!, null, NewCases( casesDto.slug, casesDto.newConfirmed, casesDto.newDeaths, casesDto.newRecovered ), TotalCases( casesDto.totalConfirmed!!, casesDto.totalDeaths!!, casesDto.totalRecovered!! ) ) } cases } } }<file_sep>package com.jeff.covidtracker.utilities.exception class EmptyResultException : Throwable("Empty Result Exception")<file_sep>package com.jeff.covidtracker import android.app.Application import com.jeff.covidtracker.database.DatabaseModule import com.jeff.covidtracker.webservices.internet.RxInternetModule import com.jeff.covidtracker.main.MainModule import com.jeff.covidtracker.supplychain.SupplyChainModule import com.jeff.covidtracker.utilities.UtilityModule import com.jeff.covidtracker.webservices.api.ApiModule import com.jeff.covidtracker.webservices.usecase.WebServiceUseCaseModule import dagger.BindsInstance import dagger.Component import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton @Component(modules = [AndroidSupportInjectionModule::class, AndroidSupportInjectionModule::class, MainModule::class, AppModule::class, RxInternetModule::class, UtilityModule::class, DatabaseModule::class, ApiModule::class, WebServiceUseCaseModule::class, SupplyChainModule::class]) @Singleton interface AppComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } fun inject(myApplication: MyApplication) }<file_sep>package com.jeff.covidtracker.webservices.observer interface BaseSessionAwareObserver { fun onSessionExpiredError() fun onCommonError(e: Throwable) } <file_sep>package com.jeff.covidtracker.database.usecase.local.saver import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.database.room.dao.PhotoDao import io.reactivex.Completable import io.reactivex.Observable import timber.log.Timber import javax.inject.Inject class DefaultPhotoLocalSaver @Inject constructor(private val dao: PhotoDao) : PhotoLocalSaver { override fun save(photo: Photo): Completable { return Completable.fromAction { dao.insert(photo)} } override fun saveAll(photos: List<Photo>): Observable<List<Photo>> { return Completable.fromCallable { dao.insert(photos) Timber.d("==q saveAll Done") Completable.complete() }.andThen(Observable.fromCallable { photos }) } }<file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.dto.CountryDto import com.jeff.covidtracker.webservices.dto.SummaryDto import io.reactivex.Single interface CountryRemoteLoader { fun loadCountries(): Single<List<CountryDto>> } <file_sep>package com.jeff.covidtracker.utilities import com.jeff.covidtracker.utilities.rx.RxSchedulerUtilsModule import dagger.Module @Module(includes = [RxSchedulerUtilsModule::class]) abstract class UtilityModule { }<file_sep>package com.jeff.covidtracker.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.jakewharton.picasso.OkHttp3Downloader import com.jeff.covidtracker.R import com.jeff.covidtracker.adapter.CustomAdapter.CustomViewHolder import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.databinding.CustomRowBinding import com.squareup.picasso.Picasso internal class CustomAdapter( private val context: Context, private val dataList: List<Photo> ) : RecyclerView.Adapter<CustomViewHolder>() { internal inner class CustomViewHolder(binding: CustomRowBinding) : ViewHolder(binding.root) { var txtTitle: TextView = binding.customRowTitle val coverImage: ImageView = binding.coverImage } override fun onCreateViewHolder(p0: ViewGroup, p1: Int): CustomViewHolder { val binding = DataBindingUtil.inflate<CustomRowBinding>(LayoutInflater.from(p0.context), R.layout.custom_row, p0, false) return CustomViewHolder(binding) } override fun onBindViewHolder(holder: CustomViewHolder, position: Int) { holder.txtTitle.text = dataList[position].title val builder = Picasso.Builder(context) builder.downloader(OkHttp3Downloader(context)) builder.build().load(dataList[position].thumbnailUrl) .placeholder(R.drawable.ic_launcher_background) .error(R.drawable.ic_launcher_background) .into(holder.coverImage) } override fun getItemCount(): Int { return dataList.size } }<file_sep>package com.jeff.covidtracker.webservices.internet import io.reactivex.Completable import javax.inject.Inject import com.jeff.covidtracker.webservices.exception.NoInternetException import io.reactivex.schedulers.Schedulers import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Url import java.util.concurrent.TimeUnit class DefaultRxInternet @Inject constructor(): RxInternet{ override fun isConnected(): Completable = Completable .defer { Retrofit.Builder() .baseUrl("https://www.google.com") .client(OkHttpClient.Builder().build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(Google::class.java) .homepage() } .onErrorResumeNext { Completable.error(NoInternetException()) } .subscribeOn(Schedulers.io()) /** * Simply pings google.com and waits for a response. */ override fun connected(): Completable = Completable .defer { Retrofit.Builder() .baseUrl("https://www.google.com") .client(OkHttpClient.Builder().build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(Google::class.java) .homepage() } .subscribeOn(Schedulers.io()) override fun notConnected(delayBetweenChecksInSeconds: Long): Completable = connected() .delay(delayBetweenChecksInSeconds, TimeUnit.SECONDS) .repeat() .onErrorComplete() .subscribeOn(Schedulers.io()) interface Google { @GET("") fun homepage(@Url url: String = ""): Completable } } <file_sep>package com.jeff.covidtracker import android.app.Activity import android.app.Application import android.app.Service import androidx.fragment.app.Fragment import dagger.android.* import dagger.android.support.HasSupportFragmentInjector import timber.log.Timber import javax.inject.Inject class MyApplication : Application(), HasActivityInjector, HasServiceInjector, HasSupportFragmentInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> @Inject lateinit var dispatchingServiceInjector: DispatchingAndroidInjector<Service> @Inject lateinit var dispatchingSupportFragmentInjector: DispatchingAndroidInjector<Fragment> override fun onCreate() { super.onCreate() //initializeCalligraphy() if (BuildConfig.DEBUG) { initializeTimber() } DaggerAppComponent.builder() .application(this) .build() .inject(this) } override fun activityInjector(): AndroidInjector<Activity> { return dispatchingAndroidInjector } override fun serviceInjector(): AndroidInjector<Service> { return dispatchingServiceInjector } override fun supportFragmentInjector(): AndroidInjector<Fragment> { return dispatchingSupportFragmentInjector } private fun initializeTimber() { Timber.plant(Timber.DebugTree()) } }<file_sep>package com.jeff.covidtracker.supplychain import com.jeff.covidtracker.supplychain.country.detail.CasesLoader import com.jeff.covidtracker.supplychain.country.detail.DefaultCasesLoader import com.jeff.covidtracker.supplychain.country.list.CountryLoader import com.jeff.covidtracker.supplychain.country.list.DefaultCountryLoader import com.jeff.covidtracker.supplychain.country.list.DefaultSummaryLoader import com.jeff.covidtracker.supplychain.country.list.SummaryLoader import com.jeff.covidtracker.supplychain.photo.DefaultPhotoLoader import com.jeff.covidtracker.supplychain.photo.PhotoLoader import dagger.Binds import dagger.Module @Module abstract class SupplyChainModule { @Binds abstract fun bindPhotoLoader(defaultPhotoLoader: DefaultPhotoLoader): PhotoLoader @Binds abstract fun bindCountryLoader(defaultCountryLoader: DefaultCountryLoader): CountryLoader @Binds abstract fun bindCasesLoader(defaultCasesLoader: DefaultCasesLoader): CasesLoader @Binds abstract fun bindSummaryLoader(defaultSummaryLoader: DefaultSummaryLoader): SummaryLoader }<file_sep>package com.jeff.covidtracker.database import android.app.Application import androidx.room.Room import com.jeff.covidtracker.R import com.jeff.covidtracker.database.room.AppDatabase import com.jeff.covidtracker.database.room.dao.CasesDao import com.jeff.covidtracker.database.room.dao.CountryDao import com.jeff.covidtracker.database.room.dao.PhotoDao import com.jeff.covidtracker.database.usecase.local.LocalUseCaseModule import dagger.Module import dagger.Provides import javax.inject.Singleton @Module(includes = [LocalUseCaseModule::class]) class DatabaseModule { @Provides @Singleton fun provideDatabase(application: Application): AppDatabase { return Room.databaseBuilder(application, AppDatabase::class.java, application.getString(R.string.db_name)) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun providePhotoDao(appDatabase: AppDatabase): PhotoDao { return appDatabase.photoDao() } @Provides @Singleton fun providCountryDao(appDatabase: AppDatabase): CountryDao { return appDatabase.countryDao() } @Provides @Singleton fun providCasesDao(appDatabase: AppDatabase): CasesDao { return appDatabase.casesDao() } }<file_sep>package com.jeff.covidtracker.supplychain.photo import com.jeff.covidtracker.database.local.Photo import io.reactivex.Single interface PhotoLoader { fun loadAllFromRemote(): Single<List<Photo>> fun loadAllFromLocal(): Single<List<Photo>> }<file_sep>package com.jeff.covidtracker.main.list.presenter import dagger.Binds import dagger.Module @Module abstract class MainPresenterModule { @Binds abstract fun bindMainPresenter( defaultSplashPresenter: DefaultMainPresenter): MainPresenter }<file_sep>package com.jeff.covidtracker.main import com.jeff.covidtracker.ActivityScope import com.jeff.covidtracker.main.detail.presenter.CountryDetailPresenterModule import com.jeff.covidtracker.main.detail.view.CountryDetailActivity import com.jeff.covidtracker.main.list.presenter.MainPresenterModule import com.jeff.covidtracker.main.list.view.MainActivity import dagger.Module import dagger.android.ContributesAndroidInjector @Module interface MainModule { @ActivityScope @ContributesAndroidInjector(modules = [MainPresenterModule::class]) fun mainActivity(): MainActivity @ActivityScope @ContributesAndroidInjector(modules = [CountryDetailPresenterModule::class]) fun countryDetailActivity(): CountryDetailActivity }<file_sep>package com.jeff.covidtracker.database.usecase.local.saver import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Photo import io.reactivex.Completable import io.reactivex.Observable interface CasesLocalSaver { fun save(cases: Cases): Completable fun saveAll(casesList: List<Cases>): Observable<List<Cases>> } <file_sep>package com.jeff.covidtracker.webservices.dto import com.google.gson.annotations.SerializedName data class CountryDto( @field:SerializedName("Country") var country: String, @field:SerializedName("Slug") var slug: String, @field:SerializedName("ISO2") var iso2: String)<file_sep>package com.jeff.covidtracker.webservices.exception class SessionExpiredException : Throwable("Session has expired") <file_sep>package com.jeff.covidtracker.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.blongho.country_data.World import com.jakewharton.picasso.OkHttp3Downloader import com.jeff.covidtracker.R import com.jeff.covidtracker.android.base.extension.substringWithDots import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.databinding.ItemCountryBinding import com.jeff.covidtracker.main.detail.view.CountryDetailActivity import com.squareup.picasso.Picasso import timber.log.Timber import java.util.* internal class CountryCasesListAdapter( private val context: Context, private var dataList: List<Cases> ) : RecyclerView.Adapter<CountryCasesListAdapter.CountryCasesListViewHolder>() { internal inner class CountryCasesListViewHolder(binding: ItemCountryBinding) : ViewHolder(binding.root) { var txtTitle: TextView = binding.country var confirmedCases: TextView = binding.confirmedCases var confirmedCasesIcon: TextView = binding.confirmedCasesIcon var menu: ConstraintLayout = binding.menu var flag: ImageView = binding.flag } override fun onCreateViewHolder(p0: ViewGroup, p1: Int): CountryCasesListViewHolder { val binding = DataBindingUtil.inflate<ItemCountryBinding>(LayoutInflater.from(p0.context), R.layout.item_country, p0, false) sort() return CountryCasesListViewHolder(binding) } override fun onBindViewHolder(holder: CountryCasesListViewHolder, position: Int) { val cases = dataList[position] holder.confirmedCasesIcon.text = String.format("\uD83D\uDCBC") holder.confirmedCases.text = String.format("%,d", cases.totalCases!!.totalConfirmed) holder.txtTitle.text = String.substringWithDots(cases.country, 27) World.init(context.applicationContext) val flag = World.getFlagOf(dataList[position].countryCode) holder.flag.setImageResource(flag) holder.menu.setOnClickListener { Timber.d("==q ${dataList[position].country}") val selectedCountry = dataList[position] val intent = CountryDetailActivity.getStartIntent(context, selectedCountry.country, selectedCountry.countryCode, "") context.startActivity(intent) } } fun sort() { Collections.sort(dataList, Comparator<Cases> { obj1, obj2 -> // ## Ascending order obj2.totalCases!!.totalConfirmed.toInt() .compareTo(obj1.totalCases!!.totalConfirmed.toInt()) // To compare string values // return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values // ## Descending order // return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values // return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values }) } //This method will filter the list //here we are passing the filtered data //and assigning it to the list with notifydatasetchanged method fun update(countries: List<Cases>) { this.dataList = countries notifyDataSetChanged() } override fun getItemCount(): Int { return dataList.size } fun clear() { this.dataList = emptyList() notifyDataSetChanged() } }<file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.api.ApiFactory import com.jeff.covidtracker.webservices.api.photos.Covid19Api import com.jeff.covidtracker.webservices.dto.SummaryDto import com.jeff.covidtracker.webservices.transformer.NullResultTransformer import com.jeff.covidtracker.webservices.transformer.ResponseCodeNot200SingleTransformer import io.reactivex.Single import javax.inject.Inject class DefaultSummaryRemoteLoader @Inject constructor(private val apiFactory: ApiFactory): SummaryRemoteLoader { override fun loadSummary(): Single<SummaryDto> { return apiFactory.create(Covid19Api::class.java) .flatMap { it.loadSummary() } .compose(ResponseCodeNot200SingleTransformer()) .compose(NullResultTransformer()) .flatMap { response -> Single.just(response.body()!!) } } } <file_sep>package com.jeff.covidtracker.supplychain.country.list import android.provider.Settings import androidx.room.EmptyResultSetException import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.GlobalCases import com.jeff.covidtracker.database.local.Summary import com.jeff.covidtracker.database.usecase.local.loader.CasesLocalLoader import com.jeff.covidtracker.database.usecase.local.saver.CasesLocalSaver import com.jeff.covidtracker.main.mapper.CasesDtoToCasesMapper import com.jeff.covidtracker.main.mapper.GlobalCasesDtoToGlobalCasesMapper import com.jeff.covidtracker.webservices.dto.GlobalCasesDto import com.jeff.covidtracker.webservices.dto.SummaryDto import com.jeff.covidtracker.webservices.internet.RxInternet import com.jeff.covidtracker.webservices.usecase.loader.SummaryRemoteLoader import io.reactivex.Observable import io.reactivex.Single import timber.log.Timber import javax.inject.Inject class DefaultSummaryLoader @Inject constructor( private val internet: RxInternet, private val remoteLoader: SummaryRemoteLoader, private val countryCasesLocalSaver: CasesLocalSaver, private val countryCasesLocalLoader: CasesLocalLoader ) : SummaryLoader { override fun loadCountryCases(): Single<List<Cases>> { return loadCountryCasesRemotely() .onErrorResumeNext { loadCountryCasesLocally() } } override fun loadCountryCasesRemotely(): Single<List<Cases>> { return internet.isConnected() .andThen(remoteLoader.loadSummary()) .flatMapObservable { list -> Observable.fromIterable(list.countryCases) } .flatMap(CasesDtoToCasesMapper()) .toList() .flatMap { Single.fromObservable(countryCasesLocalSaver.saveAll(it)) } .flatMap { Timber.d("==q Countries loaded remotely. ${it.size}") Single.just(it) } } override fun loadCountryCasesLocally() : Single<List<Cases>> { return countryCasesLocalLoader.loadAll() .flatMap { Timber.d("==q Countries loaded locally. ${it.size}") Single.just(it) } } override fun loadGlobal(): Single<GlobalCases> { return internet.isConnected() .andThen(remoteLoader.loadSummary()) .map { mapToGlobalCases(it) } //.flatMap { Single.fromObservable(countryCasesLocalSaver.saveAll(it)) } .flatMap { Timber.d("==q Countries loaded remotely. ${it.date}") Single.just(it) } } private fun mapToGlobalCases(it: SummaryDto): GlobalCases { val globalCases = GlobalCases() globalCases.date = it.date globalCases.newCases!!.newConfirmed = it.globalCases.newConfirmed globalCases.newCases!!.newDeaths = it.globalCases.newDeaths globalCases.newCases!!.newRecovered = it.globalCases.newRecovered return globalCases } } <file_sep>package com.jeff.covidtracker.supplychain.photo import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.database.usecase.local.loader.PhotoLocalLoader import com.jeff.covidtracker.database.usecase.local.saver.PhotoLocalSaver import com.jeff.covidtracker.main.mapper.PhotoDtoToPhotoMapper import com.jeff.covidtracker.utilities.exception.EmptyResultException import com.jeff.covidtracker.webservices.internet.RxInternet import com.jeff.covidtracker.webservices.usecase.loader.PhotoRemoteLoader import io.reactivex.Observable import io.reactivex.Single import javax.inject.Inject class DefaultPhotoLoader @Inject constructor(private val remoteLoader: PhotoRemoteLoader, private val localLoader: PhotoLocalLoader, private val localSaver: PhotoLocalSaver, private val rxInternet: RxInternet): PhotoLoader{ override fun loadAllFromRemote(): Single<List<Photo>> { return rxInternet.isConnected() .andThen(remoteLoader.loadAll()) .flatMapObservable { list -> Observable.fromIterable(list) } .flatMap(PhotoDtoToPhotoMapper()) .toList() .flatMap { photos -> Single.fromObservable(localSaver.saveAll(photos)) } .flatMap { photos -> Single.just(photos) } //return session.activeAdministeredAccount() //.map { administeredAccount -> administeredAccount.tenantId } //.flatMap { tenantId -> remoteLoader.loadAvailableExpenses(tenantId) } } override fun loadAllFromLocal(): Single<List<Photo>> { return rxInternet.notConnected() .andThen(localLoader.loadAll()) /*.flatMap { when { it.isEmpty() -> Single.error( Throwable(EmptyResultException())) else -> Single.just(it) } }*/ .flatMap { photos -> Single.just(photos)} } }<file_sep>package com.jeff.covidtracker.main.detail.view import android.app.ProgressDialog import android.app.ProgressDialog.show import android.content.Context import android.content.Intent import android.os.Bundle import androidx.databinding.DataBindingUtil import com.hannesdorfmann.mosby.mvp.MvpActivity import com.jeff.covidtracker.R import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.databinding.ActivityCountryDetailBinding import com.jeff.covidtracker.main.detail.presenter.DefaultCountryDetailPresenter import com.jeff.covidtracker.utilities.extensions.toDisplay import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.item_country.* import javax.inject.Inject class CountryDetailActivity : MvpActivity<CountryDetailView, DefaultCountryDetailPresenter>(), CountryDetailView { @Inject internal lateinit var countryDetailPresenter: DefaultCountryDetailPresenter private lateinit var progressDialog: ProgressDialog lateinit var binding : ActivityCountryDetailBinding companion object { var EXTRA_COUNTRY_NAME = "EXTRA_COUNTRY_NAME" var EXTRA_COUNTRY_CODE = "EXTRA_COUNTRY_CODE" var EXTRA_COUNTRY_ISO2 = "EXTRA_COUNTRY_ISO2" fun getStartIntent( context: Context, country : String, countryCode : String, iso2 : String ): Intent { return Intent(context, CountryDetailActivity::class.java) .putExtra(EXTRA_COUNTRY_NAME, country) .putExtra(EXTRA_COUNTRY_CODE, countryCode) .putExtra(EXTRA_COUNTRY_ISO2, iso2) } } override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_country_detail) binding = DataBindingUtil.setContentView(this, R.layout.activity_country_detail) setToolbarTitle() val countryCode = intent.getStringExtra(EXTRA_COUNTRY_CODE) if (countryCode != null) { countryDetailPresenter.loadCases(countryCode) } } override fun setToolbarTitle() { setSupportActionBar(binding.countryDetailToolbar) var countryName = intent.getStringExtra(EXTRA_COUNTRY_NAME) countryName = countryName?.capitalize() ?: getString(R.string.missing_country_name) supportActionBar!!.title = countryName binding.countryDetailToolbar.setNavigationOnClickListener { onBackPressed() } } override fun createPresenter(): DefaultCountryDetailPresenter { return countryDetailPresenter } override fun setCases(cases: Cases) { binding.countryDate.text = String.format("As of ${cases.date.toDisplay("MMM dd, yyyy")}") binding.countryConfirmedTotal.text = cases.totalCases!!.totalConfirmed.toString() binding.countryConfirmedToday.text = get(cases.newCases!!.newConfirmed) binding.countryDeathsTotal.text = cases.totalCases!!.totalDeaths.toString() binding.countryDeathsToday.text = get(cases.newCases!!.newDeaths) binding.countryRecoveredTotal.text = cases.totalCases!!.totalRecovered.toString() binding.countryRecoveredToday.text = get(cases.newCases!!.newRecovered) } fun get(x: Int?, y: Int?): String{ return String.format("+${(x!! - y!!)}") } fun get(x: Int?): String{ return String.format("+${x!!}") } override fun hideProgress() { progressDialog.dismiss() } override fun showProgress() { progressDialog = show( this, getString(R.string.app_name), "Loading Cases...") } } <file_sep>package com.jeff.covidtracker.main.detail.presenter import dagger.Binds import dagger.Module @Module abstract class CountryDetailPresenterModule { @Binds abstract fun bindCountryDetailPresenter( defaultCountryDetailPresenter: DefaultCountryDetailPresenter): CountryDetailPresenter }<file_sep>package com.jeff.covidtracker.main.list.view import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.jeff.covidtracker.R import com.jeff.covidtracker.main.RecyclerViewItemCountAssertion import org.hamcrest.CoreMatchers import org.hamcrest.Matcher import org.hamcrest.Matchers.greaterThan import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MainActivityTest { @Rule @JvmField var activityRule = ActivityTestRule(MainActivity::class.java) private fun sleep() { Thread.sleep(3000) } @Test fun brazil() { onView(withId(R.id.country_recycler_view)).perform( RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>( 1, click())); onView( CoreMatchers.allOf( CoreMatchers.instanceOf(TextView::class.java), ViewMatchers.withParent(withId(R.id.country_detail_toolbar)) ) ) .check(ViewAssertions.matches(ViewMatchers.withText("Brazil"))) } @Test fun countryListIsNotEmpty() { sleep() onView(withId(R.id.country_recycler_view)).check( RecyclerViewItemCountAssertion.withItemCount(greaterThan(0) as Matcher<Int?>?) ) } }<file_sep>package com.jeff.covidtracker.webservices.transformer import io.reactivex.Observable import io.reactivex.ObservableSource import io.reactivex.ObservableTransformer import retrofit2.HttpException import retrofit2.Response class ResponseCodeNot200ObservableTransformer<T> : ObservableTransformer<Response<T>, Response<T>> { override fun apply(upstream: Observable<Response<T>>): ObservableSource<Response<T>> { return upstream.flatMap {response -> val notSuccess = response.code() != 200 && response.code() != 201 && response.code() != 202 if (notSuccess) { return@flatMap Observable.error<Response<T>>(HttpException(response)) } return@flatMap Observable.just(response) } } }<file_sep>package com.jeff.covidtracker.webservices.api.photos import com.jeff.covidtracker.webservices.dto.PhotoDto import io.reactivex.Single import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path interface PhotosApi { @GET("photos") fun loadPhotos(): Single<Response<List<PhotoDto>>> @GET("photos/{id}") fun loadPhotoById(@Path("id") id: Int): Single<Response<PhotoDto>> }<file_sep>package com.jeff.covidtracker.main.list.presenter import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.webservices.internet.RxInternet import com.jeff.covidtracker.main.list.view.MainView import com.jeff.covidtracker.supplychain.country.list.CountryLoader import com.jeff.covidtracker.supplychain.country.list.SummaryLoader import com.jeff.covidtracker.supplychain.photo.PhotoLoader import com.jeff.covidtracker.webservices.dto.PhotoDto import com.jeff.covidtracker.utilities.rx.RxSchedulerUtils import com.jeff.covidtracker.webservices.exception.NoInternetException import io.reactivex.* import io.reactivex.disposables.Disposable import timber.log.Timber import javax.inject.Inject class DefaultMainPresenter @Inject constructor( private val internet: RxInternet, private val schedulerUtils: RxSchedulerUtils, private val loader: PhotoLoader, private val countryLoader: CountryLoader, private val summaryLoader: SummaryLoader ) : MvpBasePresenter<MainView>(), MainPresenter { lateinit var view: MainView lateinit var disposable: Disposable override fun loadCountryCases() { summaryLoader.loadCountryCasesRemotely() .compose(schedulerUtils.forSingle()) .subscribe(object : SingleObserver<List<Cases>>{ override fun onSuccess(t: List<Cases>) { Timber.d("==q getSummary() onSuccess ${t.size}") view.hideProgress() view.generateDataList(t) view.showLoadedRemotely() dispose() } override fun onSubscribe(d: Disposable) { view.clearDataList() view.showProgress() disposable = d } override fun onError(e: Throwable) { Timber.d("==q getSummary() onError $e") if (e is NoInternetException) { view.showNoInternetError() } else { view.showError(e.message!!) } view.clearDataList() dispose() view.hideProgress() } }) } override fun loadCountryCasesLocally() { summaryLoader.loadCountryCasesLocally() .compose(schedulerUtils.forSingle()) .subscribe(object : SingleObserver<List<Cases>>{ override fun onSuccess(t: List<Cases>) { Timber.d("==q getSummary() onSuccess ${t.size}") view.hideProgress() if (t.isEmpty()) { Timber.d("==q getSummary() isEmpty ${t.size}") view.showEmptyListError() } else { view.generateDataList(t) view.showLoadedLocally() } dispose() } override fun onSubscribe(d: Disposable) { view.showProgress() disposable = d } override fun onError(e: Throwable) { Timber.d("==q getSummary() onError $e") view.showError(e.message!!) dispose() view.hideProgress() } }) } override fun getCountries() { countryLoader.loadAll() .compose(schedulerUtils.forSingle()) .subscribe(object : SingleObserver<List<Country>>{ override fun onSuccess(t: List<Country>) { view.hideProgress() //view.generateCountryList(t) dispose() } override fun onSubscribe(d: Disposable) { view.showProgressRemote() disposable = d } override fun onError(e: Throwable) { Timber.d("==q getCountries() onError ${e}") dispose() view.hideProgress() } }) } fun getCountriesFromLocal() { countryLoader.loadAllFromLocal() .compose(schedulerUtils.forSingle()) .subscribe(object : SingleObserver<List<Country>>{ override fun onSuccess(t: List<Country>) { Timber.d("==q getCountriesFromLocal onSuccess : ${t.size}") view.hideProgress() //view.generateDataList(t) dispose() } override fun onSubscribe(d: Disposable) { view.showProgressLocal() disposable = d } override fun onError(e: Throwable) { Timber.d("==q getCountriesFromLocal onError ${e}") view.hideProgress() dispose() } }) } private fun mapPhotoDtosToPhotos(photoDtos: List<PhotoDto>): List<Photo> { val photos = mutableListOf<Photo>() for (photoDto in photoDtos) { val photo = Photo( photoDto.id, photoDto.albumId, photoDto.title, photoDto.url, photoDto.thumbnailUrl ) photos.add(photo) } return photos } override fun attachView(view: MainView) { super.attachView(view) this.view = view } private fun dispose() { if (!disposable.isDisposed) disposable.dispose() } override fun detachView(retainInstance: Boolean) { dispose() } }<file_sep>package com.jeff.covidtracker.webservices.observer.single import androidx.annotation.CallSuper import com.jeff.covidtracker.webservices.exception.SessionExpiredException import com.jeff.covidtracker.webservices.observer.BaseSessionAwareObserver import io.reactivex.SingleObserver abstract class SessionAwareSingleObserver<T> : BaseSessionAwareObserver, SingleObserver<T> { @CallSuper override fun onError(e: Throwable) { if (e is SessionExpiredException) { onSessionExpiredError() } else { onCommonError(e) } } override fun onSessionExpiredError() {} override fun onCommonError(e: Throwable) { } } <file_sep>package com.jeff.covidtracker.database.local import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = Country.TABLE_NAME) data class Country constructor( @PrimaryKey @ColumnInfo(name = "country") var country: String, @ColumnInfo(name = "slug") var slug: String, @ColumnInfo(name = "iso2") var iso2: String) : Comparable<Country> { companion object { const val COLUMN_DEAL_ID = "country_id" const val COLUMN_ID = "id" const val TABLE_NAME = "country" } override fun compareTo(other: Country): Int { return other.compareTo(other) } } <file_sep>package com.jeff.covidtracker.database.usecase.local.loader import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Photo import io.reactivex.Single interface CasesLocalLoader { fun loadAll(): Single<List<Cases>> fun loadByCountryCode(countryCode: String): Single<Cases> }<file_sep>package com.jeff.covidtracker.database.usecase.local.saver import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.local.Photo import io.reactivex.Completable import io.reactivex.Observable interface CountryLocalSaver { fun save(country: Country): Completable fun saveAll(countries: List<Country>): Observable<List<Country>> } <file_sep>package com.jeff.covidtracker.database.usecase.local.loader import com.jeff.covidtracker.database.local.Photo import io.reactivex.Single interface PhotoLocalLoader { fun loadAll(): Single<List<Photo>> }<file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.api.ApiFactory import com.jeff.covidtracker.webservices.api.photos.Covid19Api import com.jeff.covidtracker.webservices.dto.CasesDto import com.jeff.covidtracker.webservices.transformer.NullResultTransformer import com.jeff.covidtracker.webservices.transformer.ResponseCodeNot200SingleTransformer import io.reactivex.Single import javax.inject.Inject class DefaultCasesRemoteLoader @Inject constructor(private val apiFactory: ApiFactory): CasesRemoteLoader { override fun loadCases(slug: String): Single<List<CasesDto>> { return apiFactory.create(Covid19Api::class.java) .flatMap { it.loadCasesBySlug(slug) } .compose(ResponseCodeNot200SingleTransformer()) .compose(NullResultTransformer()) .flatMap { response -> Single.just(response.body()!!) } } } <file_sep>package com.jeff.covidtracker.database.local import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = Photo.TABLE_NAME) data class Photo constructor( @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) var id: Int, @ColumnInfo(name = "album_id") var albumId: Int, @ColumnInfo(name = "title") var title: String, @ColumnInfo(name = "url") var url: String, @ColumnInfo(name = "thumbnail_url") var thumbnailUrl: String) { companion object { const val COLUMN_DEAL_ID = "photo_id" const val COLUMN_ID = "id" const val TABLE_NAME = "photos" } } <file_sep>package com.jeff.covidtracker.database.local data class NewCases( var slug: String? = null, var newConfirmed: Int? = null, var newDeaths: Int? = null, var newRecovered: Int? = null ) {}<file_sep>package com.jeff.covidtracker.database.room.dao import androidx.room.* import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Photo @Dao interface CasesDao { @Query("Select * FROM " + Cases.TABLE_NAME) fun loadAll(): List<Cases> @Query("SELECT * FROM " + Cases.TABLE_NAME + " WHERE " + Cases.COUNTRY_CODE +" LIKE :countryCode") fun loadByCountryCOde(countryCode: String): Cases @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(cases: List<Cases>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(cases: Cases) @Delete fun delete(cases: Cases) }<file_sep>package com.jeff.covidtracker.main.detail.presenter import com.hannesdorfmann.mosby.mvp.MvpPresenter import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.main.detail.view.CountryDetailView import io.reactivex.Single interface CountryDetailPresenter : MvpPresenter<CountryDetailView>{ fun loadCases(countryCode: String) } <file_sep>package com.jeff.covidtracker.main.detail.view import com.hannesdorfmann.mosby.mvp.MvpView import com.jeff.covidtracker.database.local.Cases interface CountryDetailView: MvpView { fun setCases(cases: Cases) fun setToolbarTitle() fun showProgress() fun hideProgress() }<file_sep>package com.jeff.covidtracker.supplychain.country.list import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.usecase.local.loader.CountryLocalLoader import com.jeff.covidtracker.database.usecase.local.saver.CountryLocalSaver import com.jeff.covidtracker.main.mapper.CountryDtoToCountryMapper import com.jeff.covidtracker.webservices.internet.RxInternet import com.jeff.covidtracker.webservices.usecase.loader.CountryRemoteLoader import io.reactivex.Observable import io.reactivex.Single import timber.log.Timber import javax.inject.Inject class DefaultCountryLoader @Inject constructor( private val internet: RxInternet, private val remoteLoader: CountryRemoteLoader, private val localSaver: CountryLocalSaver, private val localLoader: CountryLocalLoader ) : CountryLoader { override fun loadAll(): Single<List<Country>> { return loadAllFromLocal() .flatMap { if (it.isNotEmpty()) { Timber.d("==q Countries loaded locally.") Single.just(it) } else { Timber.d("==q No existing Countries locally.") loadAllFromRemote() } } } override fun loadAllFromRemote(): Single<List<Country>> { return internet.isConnected() .andThen(remoteLoader.loadCountries()) .flatMapObservable { list -> Observable.fromIterable(list) } .flatMap(CountryDtoToCountryMapper()) .toList() .flatMap { Single.fromObservable(localSaver.saveAll(it)) } .flatMap { Timber.d("==q Countries loaded remotely. ${it.size}") Single.just(it) } } override fun loadAllFromLocal(): Single<List<Country>> { return localLoader.loadAll() /*.flatMap { when { it.isEmpty() -> Single.error( Throwable(EmptyResultException())) else -> Single.just(it) } }*/ .flatMap { countries -> Single.just(countries)} } } <file_sep>package com.jeff.covidtracker.webservices.dto import com.google.gson.annotations.SerializedName data class GlobalCasesDto ( @field:SerializedName("NewConfirmed") var newConfirmed: Int, @field:SerializedName("TotalConfirmed") var totalConfirmed: Int, @field:SerializedName("NewDeaths") var newDeaths: Int, @field:SerializedName("TotalDeaths") var totalDeaths: Int, @field:SerializedName("NewRecovered") var newRecovered: Int, @field:SerializedName("TotalRecovered") var totalRecovered: Int )<file_sep>package com.jeff.covidtracker.webservices.dto import com.google.gson.annotations.SerializedName class PhotoDto( @field:SerializedName("albumId") var albumId: Int, @field:SerializedName("id") var id: Int, @field:SerializedName("title") var title: String, @field:SerializedName("url") var url: String, @field:SerializedName("thumbnailUrl") var thumbnailUrl: String )<file_sep>package com.jeff.covidtracker.main.detail.view import android.content.Intent import android.widget.TextView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import com.jeff.covidtracker.R import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.instanceOf import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class CountryDetailActivityTest { @Rule @JvmField var activityRule = ActivityTestRule( CountryDetailActivity::class.java, true, false) @Test fun toolbarTitleNull() { val intent = Intent() activityRule.launchActivity(intent) onView(allOf(instanceOf(TextView::class.java), withParent(withId(R.id.country_detail_toolbar)))) .check(matches(withText(R.string.missing_country_name))) } @Test fun toolbarTitleSettingSucceeds() { val intent = Intent() intent.putExtra(CountryDetailActivity.EXTRA_COUNTRY_NAME, "Brazil") activityRule.launchActivity(intent) onView(allOf(instanceOf(TextView::class.java), withParent(withId(R.id.country_detail_toolbar)))) .check(matches(withText("Brazil"))) } }<file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.api.ApiFactory import com.jeff.covidtracker.webservices.api.photos.Covid19Api import com.jeff.covidtracker.webservices.api.photos.PhotosApi import com.jeff.covidtracker.webservices.dto.CountryDto import com.jeff.covidtracker.webservices.dto.PhotoDto import com.jeff.covidtracker.webservices.dto.SummaryDto import com.jeff.covidtracker.webservices.transformer.NullResultTransformer import com.jeff.covidtracker.webservices.transformer.ResponseCodeNot200SingleTransformer import io.reactivex.Single import javax.inject.Inject class DefaultCountryRemoteLoader @Inject constructor(private val apiFactory: ApiFactory): CountryRemoteLoader { override fun loadCountries(): Single<List<CountryDto>> { return apiFactory.create(Covid19Api::class.java) .flatMap { it.loadCountries() } .compose(ResponseCodeNot200SingleTransformer()) .compose(NullResultTransformer()) .flatMap { response -> Single.just(response.body()!!) } } } <file_sep>package com.jeff.covidtracker.utilities.rx import dagger.Binds import dagger.Module import javax.inject.Singleton /** * Note: [object] keyword is a class that is singleton/single-instance */ @Module interface RxSchedulerUtilsModule { @Singleton @Binds fun bindRxSchedulerUtils(defaultRxSchedulerUtils: DefaultRxSchedulerUtils): RxSchedulerUtils }<file_sep>package com.jeff.covidtracker.webservices.transformer import com.jeff.covidtracker.webservices.exception.SessionExpiredException import io.reactivex.Single import io.reactivex.SingleSource import io.reactivex.SingleTransformer import retrofit2.Response import java.net.HttpURLConnection /** * Makes a [Single] that throws an error due to the [Response.code] being * [HttpURLConnection.HTTP_UNAUTHORIZED] to instead throw a [SessionExpiredException]. */ class SessionExpiredSingleTransformer<T> : SingleTransformer<Response<T>, Response<T>> { override fun apply(upstream: Single<Response<T>>): SingleSource<Response<T>> { return upstream.flatMap { response: Response<T> -> if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) { return@flatMap Single.error<Response<T>>(SessionExpiredException()) } return@flatMap Single.just(response) } } }<file_sep>package com.jeff.covidtracker class Constants private constructor() { object Gateways { const val COVID19API = "https://api.covid19api.com" const val JSONPLACEHOLDER = "https://jsonplaceholder.typicode.com" } object DaoExceptions { const val ERROR_EMPTY_RESULT = "Empty results[] from DAO request" const val ERROR_NULL_RESULT = "Null results[] from DAO request" } }<file_sep>package com.jeff.covidtracker.utilities.rx import io.reactivex.CompletableTransformer import io.reactivex.FlowableTransformer import io.reactivex.ObservableTransformer import io.reactivex.SingleTransformer import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject /** * @author <NAME> */ class DefaultRxSchedulerUtils @Inject constructor() : RxSchedulerUtils { override fun <T> forFlowable(): FlowableTransformer<T, T> { return FlowableTransformer { it.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) } } override fun forCompletable(): CompletableTransformer { return CompletableTransformer { it.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) } } override fun <T : Any?> forObservable(): ObservableTransformer<T, T> { return ObservableTransformer { it.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) } } override fun <T : Any?> forSingle(): SingleTransformer<T, T> { return SingleTransformer { it.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) } } override fun <T : Any?> forObservableWithDelayError(): ObservableTransformer<T, T> { return ObservableTransformer { it.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) } } } <file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.dto.PhotoDto import io.reactivex.Single interface PhotoRemoteLoader { fun loadAll(): Single<List<PhotoDto>> }<file_sep>package com.jeff.covidtracker.supplychain.country.list import android.provider.Settings import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.GlobalCases import io.reactivex.Single interface SummaryLoader { fun loadCountryCases() : Single<List<Cases>> fun loadCountryCasesLocally() : Single<List<Cases>> fun loadCountryCasesRemotely() : Single<List<Cases>> //TODO Make Models for Global and Summary fun loadGlobal() : Single<GlobalCases> //fun loadSummary() : Single<Summary> } <file_sep>package com.jeff.covidtracker.supplychain.country.list import com.jeff.covidtracker.database.local.Country import io.reactivex.Single interface CountryLoader { fun loadAll() : Single<List<Country>> fun loadAllFromRemote() : Single<List<Country>> fun loadAllFromLocal() : Single<List<Country>> } <file_sep>package com.jeff.covidtracker.database.usecase.local import com.jeff.covidtracker.database.usecase.local.loader.* import com.jeff.covidtracker.database.usecase.local.saver.* import dagger.Binds import dagger.Module @Module interface LocalUseCaseModule { @Binds fun bindPhotoLocalLoader(implementation: DefaultPhotoLocalLoader): PhotoLocalLoader @Binds fun bindPhotoLocalSaver(implementation: DefaultPhotoLocalSaver): PhotoLocalSaver @Binds fun bindCountryLocalSaver(implementation: DefaultCountryLocalSaver): CountryLocalSaver @Binds fun bindCountryLocalLoader(implementation: DefaultCountryLocalLoader): CountryLocalLoader @Binds fun bindCasesLocalSaver(implementation: DefaultCasesLocalSaver): CasesLocalSaver @Binds fun bindCasesLocalLoader(implementation: DefaultCasesLocalLoader): CasesLocalLoader }<file_sep>package com.jeff.covidtracker.database.room.dao import androidx.room.* import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.local.Photo @Dao interface CountryDao { @Query("Select * FROM " + Country.TABLE_NAME) fun loadAll(): List<Country> /*@Query("Select * FROM " + Country.TABLE_NAME + " WHERE "+ Country.COLUMN_ID +" IN (:id)") fun loadAllByIds(id: IntArray): List<Country> @Query("SELECT * FROM " + Country.TABLE_NAME + " WHERE title LIKE :title AND title LIMIT 1") fun findByTitle(title: String): Country*/ @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(countries: List<Country>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(country: Country) @Delete fun delete(country: Country) }<file_sep>package com.jeff.covidtracker.main.detail.presenter import com.hannesdorfmann.mosby.mvp.MvpBasePresenter import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.main.detail.view.CountryDetailView import com.jeff.covidtracker.supplychain.country.detail.CasesLoader import com.jeff.covidtracker.supplychain.country.list.CountryLoader import com.jeff.covidtracker.utilities.rx.RxSchedulerUtils import io.reactivex.Single import io.reactivex.SingleObserver import io.reactivex.disposables.Disposable import timber.log.Timber import javax.inject.Inject class DefaultCountryDetailPresenter @Inject constructor( private val casesLoader: CasesLoader, private val schedulers: RxSchedulerUtils ): MvpBasePresenter<CountryDetailView>(), CountryDetailPresenter { lateinit var disposable: Disposable override fun loadCases(countryCode: String) { casesLoader.loadByCountryCode(countryCode) .compose(schedulers.forSingle()) .subscribe(object : SingleObserver<Cases>{ override fun onSuccess(t: Cases) { Timber.d("==q countryCode $t") view!!.setCases(t) view!!.hideProgress() dispose() } override fun onSubscribe(d: Disposable) { disposable = d view!!.showProgress() Timber.d("==q onSubscribe countryCode") } override fun onError(e: Throwable) { view!!.hideProgress() Timber.e(e) e.printStackTrace() dispose() } }) } private fun dispose() { if (!disposable.isDisposed) disposable.dispose() } } <file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.api.ApiFactory import com.jeff.covidtracker.webservices.api.photos.PhotosApi import com.jeff.covidtracker.webservices.dto.PhotoDto import com.jeff.covidtracker.webservices.transformer.NullResultTransformer import com.jeff.covidtracker.webservices.transformer.ResponseCodeNot200SingleTransformer import io.reactivex.Single import javax.inject.Inject class DefaultPhotoRemoteLoader @Inject constructor(private val apiFactory: ApiFactory): PhotoRemoteLoader { override fun loadAll(): Single<List<PhotoDto>> { return apiFactory.create(PhotosApi::class.java) .flatMap { it.loadPhotos() } .compose(ResponseCodeNot200SingleTransformer()) .compose(NullResultTransformer()) .flatMap { response -> Single.just(response.body()!!) } } }<file_sep>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 29 dataBinding { enabled = true } defaultConfig { applicationId "com.jeff.covidtracker" minSdkVersion 21 targetSdkVersion 29 versionCode 3 versionName "1.0.3" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.core:core-ktx:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' testImplementation 'junit:junit:4.12' testImplementation 'org.mockito:mockito-core:2.8.47' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'com.android.support.test:rules:1.0.2' implementation 'org.fluttercode.datafactory:datafactory:0.8' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.jakewharton.timber:timber:4.7.1' implementation 'com.google.dagger:dagger:2.24' implementation "com.google.dagger:dagger-android-support:2.16" //new kapt "com.google.dagger:dagger-android-processor:2.16" //new kapt 'com.google.dagger:dagger-compiler:2.16' kaptTest 'com.google.dagger:dagger-compiler:2.16' androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.2' //you need this to use RxAndroid with retrofit. implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0" // RxJava implementation "io.reactivex.rxjava2:rxjava:2.2.9" // RxAndroid implementation "io.reactivex.rxjava2:rxandroid:2.0.2" def room_version = "2.2.5" def mosby_mvp = "2.0.0" implementation "com.hannesdorfmann.mosby:mvp:$mosby_mvp" implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor // optional - Kotlin Extensions and Coroutines support for Room implementation "androidx.room:room-ktx:$room_version" // optional - RxJava support for Room implementation "androidx.room:room-rxjava2:$room_version" // optional - Guava support for Room, including Optional and ListenableFuture implementation "androidx.room:room-guava:$room_version" // Test helpers testImplementation "androidx.room:room-testing:$room_version" implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'com.squareup.picasso:picasso:2.5.2' implementation 'com.jakewharton.timber:timber:4.7.1' implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0' implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0' //noinspection GradleDependency implementation 'com.github.blongho:worldCountryData:1.4' implementation 'com.google.android.material:material:1.1.0' androidTestImplementation('com.android.support.test.espresso:espresso-contrib:3.0.2') { exclude group: 'com.android.support', module: 'appcompat' exclude group: 'com.android.support', module: 'support-v4' exclude module: 'recyclerview-v7' } } <file_sep>package com.jeff.covidtracker.utilities.extensions import com.jeff.covidtracker.utilities.extensions.DateExtensions.Companion.LOCALE import java.text.ParseException import java.text.SimpleDateFormat import java.util.* class DateExtensions { companion object { val LOCALE: Locale = Locale.getDefault() } } fun String.toDisplay(format: String): String = try { //2020-05-09T00:00:00Z val defaultParseFormat = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'", LOCALE) SimpleDateFormat(format, LOCALE).format( defaultParseFormat.parse(this)) } catch (e: ParseException) { "" } fun Date.toDisplay(format: String): String = SimpleDateFormat(format, LOCALE).format(this) fun String.toDisplay(parseFormat: String, displayFormat: String): String { return try { SimpleDateFormat(displayFormat, LOCALE) .format(SimpleDateFormat(parseFormat, LOCALE).parse(this)) } catch (e: ParseException) { "" } } <file_sep>package com.jeff.covidtracker.main.mapper import com.jeff.covidtracker.database.local.* import com.jeff.covidtracker.webservices.dto.CasesDto import com.jeff.covidtracker.webservices.dto.CountryDto import com.jeff.covidtracker.webservices.dto.GlobalCasesDto import com.jeff.covidtracker.webservices.dto.PhotoDto import io.reactivex.Observable import io.reactivex.functions.Function import timber.log.Timber class GlobalCasesDtoToGlobalCasesMapper : Function<GlobalCasesDto, Observable<GlobalCases>> { @Throws(Exception::class) override fun apply(dto: GlobalCasesDto): Observable<GlobalCases> { return Observable.fromCallable { val globalCases = GlobalCases() globalCases.newCases!!.newConfirmed = dto.newConfirmed globalCases.newCases!!.newDeaths = dto.newDeaths globalCases.newCases!!.newRecovered = dto.newRecovered globalCases } } }<file_sep>package com.jeff.covidtracker.database.usecase.local.saver import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.room.dao.CasesDao import io.reactivex.Completable import io.reactivex.Observable import timber.log.Timber import javax.inject.Inject class DefaultCasesLocalSaver @Inject constructor(private val dao: CasesDao) : CasesLocalSaver { override fun save(cases: Cases): Completable { return Completable.fromAction { dao.insert(cases)} } override fun saveAll(casesList: List<Cases>): Observable<List<Cases>> { return Completable.fromCallable { dao.insert(casesList) Timber.d("==q saveAll Done") Completable.complete() }.andThen(Observable.fromCallable { casesList }) } }<file_sep>package com.jeff.covidtracker.webservices.exception class NoInternetException : Throwable("No internet connection") <file_sep>package com.jeff.covidtracker.utilities.rx import io.reactivex.CompletableTransformer import io.reactivex.FlowableTransformer import io.reactivex.ObservableTransformer import io.reactivex.SingleTransformer /** * Transformer for any RxJava stream so it subscribes to a separate thread and is * observed on the android UI thread. * * @author <NAME> */ interface RxSchedulerUtils { fun forCompletable(): CompletableTransformer fun <T> forFlowable(): FlowableTransformer<T, T> fun <T> forObservable(): ObservableTransformer<T, T> fun <T> forSingle(): SingleTransformer<T, T> fun <T> forObservableWithDelayError(): ObservableTransformer<T, T> } <file_sep>package com.jeff.covidtracker.webservices.internet import io.reactivex.Completable import io.reactivex.annotations.SchedulerSupport interface RxInternet { /** * A stream that completes if the device is currently connected to the internet, otherwise * emits an error. It is the subscriber's responsibility to add a delay, timeout, or to repeat * the stream as it only executes once. * * This always uses [SchedulerSupport.IO] to make sure the network call doesn't fail on the * device due to main-thread-network-call exceptions. */ @SchedulerSupport(SchedulerSupport.IO) fun connected(): Completable /** * The complete opposite of [connected], except it waits until the device is not connected to * the internet, emitting a complete signal. The delay between checks is defined through * [delayBetweenChecksInSeconds], with a default value of 5 seconds. * * This always uses [SchedulerSupport.IO] to make sure the network call doesn't fail on the * device due to main-thread-network-call exceptions. */ @SchedulerSupport(SchedulerSupport.IO) fun notConnected(delayBetweenChecksInSeconds: Long = 5): Completable @SchedulerSupport(SchedulerSupport.IO) fun isConnected(): Completable } <file_sep>package com.jeff.covidtracker.webservices.transformer import io.reactivex.Single import io.reactivex.SingleSource import io.reactivex.SingleTransformer import retrofit2.HttpException import retrofit2.Response /** * Makes a [io.reactivex.Single] that emits a [retrofit2.Response.code] that is not * [java.net.HttpURLConnection.HTTP_OK] to instead throw an [HttpException]. */ class ResponseCodeNot200SingleTransformer<T> : SingleTransformer<Response<T>, Response<T>> { override fun apply(upstream: Single<Response<T>>): SingleSource<Response<T>> { return upstream.flatMap { response: Response<T> -> val notSuccess = response.code() != 200 && response.code() != 201 && response.code() != 202 if (notSuccess) { return@flatMap Single.error<Response<T>>(HttpException(response)) } return@flatMap Single.just(response) } } }<file_sep>package com.jeff.covidtracker.main.mapper import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.webservices.dto.PhotoDto import io.reactivex.Observable import io.reactivex.functions.Function class PhotoDtoToPhotoMapper : Function<PhotoDto, Observable<Photo>> { @Throws(Exception::class) override fun apply(photoDto: PhotoDto): Observable<Photo> { return Observable.fromCallable { val photo = Photo( photoDto.id, photoDto.albumId, photoDto.title, photoDto.url, photoDto.thumbnailUrl ) photo } } }<file_sep>package com.jeff.covidtracker.webservices.internet import dagger.Binds import dagger.Module import javax.inject.Singleton @Module abstract class RxInternetModule { @Binds @Singleton abstract fun bindRxInternet(defaultRxInternet: DefaultRxInternet): RxInternet }<file_sep>package com.jeff.covidtracker.webservices.api; import com.jeff.covidtracker.BuildConfig; import com.jeff.covidtracker.Constants; import javax.inject.Inject; import io.reactivex.Single; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; class DefaultApiFactory implements ApiFactory { @Inject DefaultApiFactory() {} @Override public <T> Single<T> create(Class<T> apiClass) { return retrofit() .map(retrofit -> retrofit.create(apiClass)); } private Single<OkHttpClient.Builder> addLoggingInterceptor(OkHttpClient.Builder builder) { return Single.fromCallable( () -> { if (BuildConfig.DEBUG) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(loggingInterceptor); } return builder; }); } private Single<OkHttpClient> client() { return Single.fromCallable(OkHttpClient.Builder::new) .flatMap(this::addLoggingInterceptor) .map(OkHttpClient.Builder::build); } private Single<Retrofit> intoRetrofit(OkHttpClient client) { return Single.fromCallable( () -> new Retrofit.Builder() .baseUrl(Constants.Gateways.COVID19API) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() ); } private Single<Retrofit> retrofit() { return client().flatMap(this::intoRetrofit); } } <file_sep>This is Covid-19 Pandemic Status Tracker. Get your update on Covid Cases all over the world. I used jeffarce1991/Project420 as template. <file_sep>package com.jeff.covidtracker.main.mapper import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.webservices.dto.CountryDto import com.jeff.covidtracker.webservices.dto.PhotoDto import io.reactivex.Observable import io.reactivex.functions.Function class CountryDtoToCountryMapper : Function<CountryDto, Observable<Country>> { @Throws(Exception::class) override fun apply(countryDto: CountryDto): Observable<Country> { return Observable.fromCallable { val country = Country( countryDto.country, countryDto.slug, countryDto.iso2 ) country } } }<file_sep>package com.jeff.covidtracker.supplychain.country.detail import com.jeff.covidtracker.database.local.Cases import io.reactivex.Single interface CasesLoader { fun loadByCountryCode(countryCode: String): Single<Cases> }<file_sep>package com.jeff.covidtracker.database.usecase.local.loader import com.jeff.covidtracker.database.local.Country import io.reactivex.Single interface CountryLocalLoader { fun loadAll(): Single<List<Country>> } <file_sep>package com.jeff.covidtracker.main.list.view import com.hannesdorfmann.mosby.mvp.MvpView import com.jeff.covidtracker.database.local.Cases interface MainView : MvpView { fun hideProgress() fun showProgress() fun showProgressRemote() fun showProgressLocal() fun showEmptyListError() fun showNoInternetError() fun showError(message: String) fun showLoadedLocally() fun showLoadedRemotely() fun generateDataList(cases: List<Cases>) fun clearDataList() }<file_sep>package com.jeff.covidtracker.main.list.view import android.app.ProgressDialog import android.app.ProgressDialog.show import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.EditText import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.core.view.MenuItemCompat import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import com.hannesdorfmann.mosby.mvp.MvpActivity import com.jeff.covidtracker.R import com.jeff.covidtracker.adapter.CountryCasesListAdapter import com.jeff.covidtracker.android.base.extension.hide import com.jeff.covidtracker.android.base.extension.shortToast import com.jeff.covidtracker.android.base.extension.show import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.databinding.ActivityMainBinding import com.jeff.covidtracker.main.list.presenter.MainPresenter import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.activity_main.* import java.util.* import javax.inject.Inject import kotlin.collections.ArrayList class MainActivity : MvpActivity<MainView, MainPresenter>(), MainView { private var adapter: CountryCasesListAdapter = CountryCasesListAdapter(this, emptyList()) private lateinit var progressDialog: ProgressDialog lateinit var mainBinding : ActivityMainBinding lateinit var photos : List<Photo> lateinit var countries : List<Country> private lateinit var searchView: SearchView @Inject internal lateinit var mainPresenter: MainPresenter override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) setUpToolbarTitle() setOnRefreshListener() mainPresenter.loadCountryCases() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) initializeSearchView(menu) return true } private fun initializeSearchView(menu: Menu?) { val searchItem: MenuItem = menu!!.findItem(R.id.action_search) searchView = MenuItemCompat.getActionView(searchItem) as SearchView searchView.setOnCloseListener { true } val searchPlate = searchView.findViewById(androidx.appcompat.R.id.search_src_text) as EditText searchPlate.hint = "Country, Country Code" searchPlate.setHintTextColor(resources.getColor(R.color.light_gray)) searchPlate.setTextColor(resources.getColor(R.color.white)) val searchPlateView: View = searchView.findViewById(androidx.appcompat.R.id.search_plate) searchPlateView.setBackgroundColor( ContextCompat.getColor( this, android.R.color.transparent ) ) } private fun setSearchQueryListener(list: List<Cases>) { searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { // do your logic here shortToast("Submitted $query") return false } override fun onQueryTextChange(newText: String?): Boolean { filter(newText!!, list) return false } }) } private fun setUpToolbarTitle() { setSupportActionBar(mainBinding.toolbar) supportActionBar!!.title = "Select Country" } private fun setOnRefreshListener() { mainBinding.swipeRefreshLayout.setOnRefreshListener { mainPresenter.loadCountryCases() } } //Method to generate List of data using RecyclerView with custom com.project.retrofit.adapter*//* override fun generateDataList(cases: List<Cases>) { hideErrorImage() adapter = CountryCasesListAdapter(this, cases) val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this@MainActivity) mainBinding.countryRecyclerView.layoutManager = layoutManager mainBinding.countryRecyclerView.adapter = adapter adapter.sort() setSearchQueryListener(cases) } override fun clearDataList() { adapter.clear() } private fun filter(text: String, countries: List<Cases>) { //new array list that will hold the filtered data val filteredCountries: ArrayList<Cases> = ArrayList() //looping through existing elements for (s in countries) { //if the existing elements contains the search input if (s.country.toLowerCase(Locale.getDefault()).contains(text.toLowerCase(Locale.getDefault())) || s.countryCode.toLowerCase(Locale.getDefault()).contains(text.toLowerCase(Locale.getDefault())) ) { //adding the element to filtered list filteredCountries.add(s) } } //calling a method of the adapter class and passing the filtered list adapter.update(filteredCountries) } override fun createPresenter(): MainPresenter { return mainPresenter } override fun showNoInternetError() { Snackbar.make(mainBinding.coordLayout, resources.getString(R.string.no_internet_connection), Snackbar.LENGTH_LONG) .setAction("Load cache") { presenter.loadCountryCasesLocally() } .setActionTextColor(resources.getColor(R.color.green)) .show() showErrorImage() } override fun showEmptyListError() { Snackbar.make(mainBinding.coordLayout, resources.getString(R.string.no_data_saved_locally), Snackbar.LENGTH_LONG) .show() showErrorImage() } override fun showError(message: String) { Snackbar.make(mainBinding.coordLayout, message, Snackbar.LENGTH_INDEFINITE) .show() } override fun showLoadedLocally() { //longToast(message) Snackbar.make(mainBinding.coordLayout, resources.getString(R.string.loaded_data_from_cache), Snackbar.LENGTH_SHORT) .show() } override fun showLoadedRemotely() { //longToast(message) Snackbar.make(mainBinding.coordLayout, resources.getString(R.string.loaded_data_from_remote), Snackbar.LENGTH_SHORT) .show() } override fun hideProgress() { //mainBinding.progressBar.hide() swipe_refresh_layout.isRefreshing = false } override fun showProgress() { //mainBinding.progressBar.show() swipe_refresh_layout.isRefreshing = true } override fun showProgressRemote() { progressDialog = show( this, "Project420", "Loading data remotely...") } override fun showProgressLocal() { progressDialog = show( this, "Project420", "Loading data locally...") } private fun hideErrorImage() { mainBinding.errorImage.hide() mainBinding.errorMessage.hide() } private fun showErrorImage() { mainBinding.errorImage.show() mainBinding.errorMessage.show() } } <file_sep>package com.jeff.covidtracker.webservices.dto import com.google.gson.annotations.SerializedName data class SummaryDto ( @field:SerializedName("Global") var globalCases: GlobalCasesDto, @field:SerializedName("Countries") var countryCases: List<CasesDto>, @field:SerializedName("Date") var date: String ) <file_sep>package com.jeff.covidtracker.webservices.usecase import com.jeff.covidtracker.webservices.usecase.loader.* import dagger.Binds import dagger.Module @Module interface WebServiceUseCaseModule { @Binds fun bindPhotoRemoteLoader( defaultPhotoRemoteLoader: DefaultPhotoRemoteLoader): PhotoRemoteLoader @Binds fun bindCountryRemoteLoader( defaultCountryRemoteLoader: DefaultCountryRemoteLoader ): CountryRemoteLoader @Binds fun bindCasesRemoteLoader( defaultCasesRemoteLoader: DefaultCasesRemoteLoader ): CasesRemoteLoader @Binds fun bindSummaryRemoteLoader( defaultSummaryRemoteLoader: DefaultSummaryRemoteLoader ): SummaryRemoteLoader }<file_sep>package com.jeff.covidtracker.webservices.dto import androidx.annotation.Nullable import com.google.gson.annotations.SerializedName data class CasesDto( @field:SerializedName("Country") var country: String, @field:SerializedName("CountryCode") var countryCode: String, @Nullable @field:SerializedName("Slug") var slug: String? = null, @field:SerializedName("Date") var date: String? = null, @Nullable @field:SerializedName("Province") var province: String? = null, @Nullable @field:SerializedName("City") var city: String? = null, @Nullable @field:SerializedName("CityCode") var cityCode: String? = null, @Nullable @field:SerializedName("Lat") var lat: String? = null, @Nullable @field:SerializedName("Lon") var lon: String? = null, @Nullable @field:SerializedName("Confirmed") var confirmed: Int? = null, @Nullable @field:SerializedName("Deaths") var deaths: Int? = null, @Nullable @field:SerializedName("Recovered") var recovered: Int? = null, @Nullable @field:SerializedName("Active") var active: Int? = null, @Nullable @field:SerializedName("NewConfirmed") var newConfirmed: Int? = null, @Nullable @field:SerializedName("TotalConfirmed") var totalConfirmed: Int? = null, @Nullable @field:SerializedName("NewDeaths") var newDeaths: Int? = null, @Nullable @field:SerializedName("TotalDeaths") var totalDeaths: Int? = null, @Nullable @field:SerializedName("NewRecovered") var newRecovered: Int? = null, @Nullable @field:SerializedName("TotalRecovered") var totalRecovered: Int? = null ) { constructor(): this("", "", "", null, null, null) } <file_sep>package com.jeff.covidtracker.database.local data class TotalCases( var totalConfirmed: Int, var totalDeaths: Int, var totalRecovered: Int, var totalActive: Int? = null )<file_sep>package com.jeff.covidtracker.webservices.api.photos import com.jeff.covidtracker.webservices.dto.CasesDto import com.jeff.covidtracker.webservices.dto.CountryDto import com.jeff.covidtracker.webservices.dto.SummaryDto import io.reactivex.Single import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path interface Covid19Api { @GET("countries") fun loadCountries(): Single<Response<List<CountryDto>>> @GET("summary") fun loadSummary(): Single<Response<SummaryDto>> @GET("total/country/{iso2}") fun loadCountryCasesByIso2( @Path("iso2") iso2: String): Single<Response<List<CasesDto>>> @GET("total/country/{slug}") fun loadCasesBySlug( @Path("slug") slug: String): Single<Response<List<CasesDto>>> }<file_sep>package com.jeff.covidtracker.webservices.api import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory object RetrofitClientInstance { fun getRxRetrofitInstance(baseUrl: String?): Retrofit? { return Retrofit.Builder() .baseUrl(baseUrl!!) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client( getClient() .build()) .build() } private fun getClient(): OkHttpClient.Builder { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY return OkHttpClient.Builder() .addInterceptor(loggingInterceptor) } }<file_sep>package com.jeff.covidtracker.supplychain.country.detail import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.usecase.local.loader.CasesLocalLoader import com.jeff.covidtracker.main.mapper.CasesDtoToCasesMapper import com.jeff.covidtracker.webservices.internet.RxInternet import com.jeff.covidtracker.webservices.usecase.loader.CasesRemoteLoader import io.reactivex.Observable import io.reactivex.Single import timber.log.Timber import javax.inject.Inject class DefaultCasesLoader @Inject constructor( private val localLoader: CasesLocalLoader ): CasesLoader{ override fun loadByCountryCode(countryCode: String): Single<Cases> { return localLoader.loadByCountryCode(countryCode) } } <file_sep>package com.jeff.covidtracker.database.usecase.local.loader import com.jeff.covidtracker.database.local.Cases import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.database.room.dao.CasesDao import com.jeff.covidtracker.database.room.dao.PhotoDao import io.reactivex.Single import javax.inject.Inject class DefaultCasesLocalLoader @Inject constructor(private val dao: CasesDao): CasesLocalLoader { override fun loadAll(): Single<List<Cases>> { return Single.fromCallable { dao.loadAll() } } override fun loadByCountryCode(countryCode: String): Single<Cases> { return Single.fromCallable { dao.loadByCountryCOde(countryCode) } } }<file_sep>package com.jeff.covidtracker.database.usecase.local.saver import com.jeff.covidtracker.database.local.Photo import io.reactivex.Completable import io.reactivex.Observable interface PhotoLocalSaver { fun save(photo: Photo): Completable fun saveAll(photos: List<Photo>): Observable<List<Photo>> } <file_sep>package com.jeff.covidtracker.database.usecase.local.saver import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.database.room.dao.CountryDao import io.reactivex.Completable import io.reactivex.Observable import timber.log.Timber import javax.inject.Inject class DefaultCountryLocalSaver @Inject constructor(private val dao: CountryDao): CountryLocalSaver{ override fun save(country: Country): Completable { TODO("Not yet implemented") } override fun saveAll(countries: List<Country>): Observable<List<Country>> { return Completable.fromCallable { dao.insert(countries) Completable.complete() }.andThen(Observable.fromCallable { Timber.d("==q Countries saved locally.") countries }) } } <file_sep>package com.jeff.covidtracker.database.local import androidx.room.ColumnInfo import androidx.room.Entity @Entity(tableName = Summary.TABLE_NAME) data class Summary( @ColumnInfo(name = "global_cases") var global: GlobalCases?, @ColumnInfo(name = "countries_cases") var countries: List<Cases>, @ColumnInfo(name = "date") var date: String ){ constructor(): this(null, emptyList(), "") companion object { const val TABLE_NAME = "summary" } }<file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.dto.SummaryDto import io.reactivex.Single interface SummaryRemoteLoader { fun loadSummary(): Single<SummaryDto> } <file_sep>package com.jeff.covidtracker.database.local import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = GlobalCases.TABLE_NAME) data class GlobalCases ( @PrimaryKey @ColumnInfo(name = "date") var date: String, @ColumnInfo(name = "new_cases") var newCases: NewCases? = null, @ColumnInfo(name = "total_cases") var totalCases: TotalCases? = null ) { constructor(): this("", null, null) companion object { const val COLUMN_DEAL_ID = "global_cases_id" const val COLUMN_ID = "id" const val TABLE_NAME = "global_cases" } }<file_sep>package com.jeff.covidtracker.database.usecase.local.loader import com.jeff.covidtracker.database.local.Country import com.jeff.covidtracker.database.room.dao.CountryDao import io.reactivex.Single import javax.inject.Inject class DefaultCountryLocalLoader @Inject constructor(private val dao: CountryDao): CountryLocalLoader{ override fun loadAll(): Single<List<Country>> { return Single.fromCallable { dao.loadAll() } } } <file_sep>package com.jeff.covidtracker.database.room.converter; import androidx.room.TypeConverter; import com.jeff.covidtracker.database.local.Photo; import com.jeff.covidtracker.utilities.ConverterUtil; public class PhotoConverter { private PhotoConverter() { } @TypeConverter public static String fromPhoto(Photo photo) { return ConverterUtil.serialise(photo); } @TypeConverter public static Photo toPhoto(String serialised) { return ConverterUtil.deserialise(serialised, Photo.class); } } <file_sep>package com.jeff.covidtracker.utilities.exception class NullResultException : Throwable("Null Result Exception") <file_sep>package com.jeff.covidtracker.database.usecase.local.loader import com.jeff.covidtracker.database.local.Photo import com.jeff.covidtracker.database.room.dao.PhotoDao import io.reactivex.Single import javax.inject.Inject class DefaultPhotoLocalLoader @Inject constructor(private val dao: PhotoDao): PhotoLocalLoader { override fun loadAll(): Single<List<Photo>> { return Single.fromCallable { dao.loadAll() } } }<file_sep>package com.jeff.covidtracker.android.base.extension import android.app.Activity import android.view.View import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import com.jeff.covidtracker.R import java.util.* fun Activity.invokeSimpleDialog(title: String, positiveButtonText: String, message: String, onApprove: () -> Unit) { AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton(positiveButtonText) { dialog, which -> onApprove.invoke() } .setNegativeButton(getString(R.string.cancel)) { dialog, which -> dialog.dismiss() } .show() } fun Activity.invokeSimpleDialog(title: String, positiveButtonText: String, negativeButtonText: String, message: String, onApprove: () -> Unit) { AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton(positiveButtonText) { dialog, which -> onApprove.invoke() } .setNegativeButton(negativeButtonText) { dialog, which -> dialog.dismiss() } .show() } fun Activity.invokeSimpleDialog(title: String, positiveButtonText: String, message: String) { AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton(positiveButtonText) { dialog, which -> dialog.dismiss() } .show() } fun Activity.longToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } fun Activity.shortToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun String.Companion.substringWithDots(s: String, maxLength: Int) : String { return when { s.length >= maxLength -> { String.format("${s.substring(0, maxLength)}…") } else -> { s } } } @OptIn(ExperimentalStdlibApi::class) fun String.toTitleCase(): String = this.capitalize(Locale.ROOT) fun View.hide() { this.visibility = View.GONE } fun View.show() { this.visibility = View.VISIBLE }<file_sep>package com.jeff.covidtracker.database.room.dao import androidx.room.* import com.jeff.covidtracker.database.local.Photo @Dao interface PhotoDao { @Query("Select * FROM " + Photo.TABLE_NAME) fun loadAll(): List<Photo> @Query("Select * FROM " + Photo.TABLE_NAME + " WHERE "+ Photo.COLUMN_ID +" IN (:id)") fun loadAllByIds(id: IntArray): List<Photo> @Query("SELECT * FROM " + Photo.TABLE_NAME + " WHERE title LIKE :title AND title LIMIT 1") fun findByTitle(title: String): Photo @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(photos: List<Photo>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(photo: Photo) @Delete fun delete(photo: Photo) }<file_sep>package com.jeff.covidtracker.webservices.usecase.loader import com.jeff.covidtracker.webservices.dto.CasesDto import io.reactivex.Single interface CasesRemoteLoader { fun loadCases(slug: String): Single<List<CasesDto>> } <file_sep>package com.jeff.covidtracker.main.list.presenter import com.hannesdorfmann.mosby.mvp.MvpPresenter import com.jeff.covidtracker.main.list.view.MainView interface MainPresenter: MvpPresenter<MainView> { fun getCountries() fun loadCountryCases() fun loadCountryCasesLocally() }
e4ca0c6efa7ee7ac4a1ef4427f83f6d883855e5f
[ "Markdown", "Java", "Kotlin", "Gradle" ]
94
Kotlin
jeffarce1991/covid-tracker
1dfa2933444e2c982441bc4f2fde8e5e0715f953
25015446ce17c5ff51cb131650eb1b90957e1b3c
refs/heads/master
<file_sep>export class FunThing { public x = 5; } <file_sep># istnlt ## Incredibly Simple TypeScript Node Library Template Almost zero fluff template for people who just want to make a TypeScript library in Node and are too lazy to care about other things. Includes: - CommonJS and ESM exports. - Jest testing in TypeScript with coverage. - ESLint with recommended rules and some of my own rules. - Some configurations. - That's about it. Change whatever as you see fit. You should change the `person` and `library` placeholders in `package.json` and `LICENSE`. <file_sep>import { FunThing } from '../src'; describe("Fun test", () => { it("works if true is truthy", () => { expect(true).toBeTruthy(); }); it("FunThing is instantiable", () => { expect(new FunThing()).toBeInstanceOf(FunThing); }); it("FunThing.x is 5", () => { expect(new FunThing().x).toBe(5); }); }); <file_sep>import library from '../dist/lib/index.js'; export const { FunThing } = library;
32ef57ddf4b238c58e7332a760853f452c197abd
[ "Markdown", "TypeScript", "JavaScript" ]
4
TypeScript
1Computer1/istnlt
126092c0f1b80611ee9f4a0b6f905bb02ed1f65b
29d806a1b1bcf3b61cf1f5db2f82f0ac3d893a44
refs/heads/master
<repo_name>flarelint/flarelint.github.io<file_sep>/oldstable/Content/Topics/RulesAdding.html <!DOCTYPE html> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" lang="en" xml:lang="en" class="no-feedback" data-mc-search-type="Stem" data-mc-help-system-file-name="index.xml" data-mc-path-to-help-system="../../" data-mc-target-type="WebHelp2" data-mc-runtime-file-type="Topic" data-mc-preload-images="false" data-mc-in-preview-mode="false" data-mc-toc-path="Managing Rules"> <head> <meta charset="utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Adding Rules</title> <link href="../../Skins/Default/Stylesheets/TextEffects.css" rel="stylesheet" /> <link href="../../Skins/Default/Stylesheets/Topic.css" rel="stylesheet" /> <link href="../Resources/Stylesheets/Styles.css" rel="stylesheet" /> <script src="../../Resources/Scripts/jquery.min.js"> </script> <script src="../../Resources/Scripts/plugins.min.js"> </script> <script src="../../Resources/Scripts/MadCapAll.js"> </script> </head> <body> <div class="content"> <h1>Adding Rules</h1> <p>You can add new rules or restore previously ignored rules. You do this by copying or moving them into your personal rule folder.</p> <p class="Task"><span class="MCToggler MCTogglerHead MCTogglerHotSpot MCToggler_Open toggler MCTogglerHotSpot_" data-mc-targets="AddRules">To add rules:</span> </p> <ol style="display: none;" data-mc-target-name="AddRules"> <li value="1"> <p>Use <span class="VarFlareLint">FlareLint</span> on any project. See <a href="Using.html">Using</a>.</p> <p>Running <span class="VarFlareLint">FlareLint</span> ensures that, at a minimum, the default rules get installed in your personal rule folder.</p> </li> <li value="2"> <p>In Windows Explorer, navigate to the folder that contains the Python modules of the rules that you want to add to <span class="VarFlareLint">FlareLint</span>, then select them.</p> </li> <li value="3"> <p>Copy the rules into the clipboard.</p> </li> <li value="4"> <p>Click the Windows Start button and in the search field, type <code>%APPDATA%\FlareLint</code> then press Enter. </p> <p>A Windows Explorer window appears displaying the contents of your personal rule folder.</p> </li> <li value="5"> <p>Paste your rule files from your clipboard into your personal rule folder.</p> </li> </ol> </div> </body> </html><file_sep>/oldstable/Content/Topics/RulesIgnoring.html <!DOCTYPE html> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" lang="en" xml:lang="en" class="no-feedback" data-mc-search-type="Stem" data-mc-help-system-file-name="index.xml" data-mc-path-to-help-system="../../" data-mc-target-type="WebHelp2" data-mc-runtime-file-type="Topic" data-mc-preload-images="false" data-mc-in-preview-mode="false" data-mc-toc-path="Managing Rules"> <head> <meta charset="utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Ignoring Rules</title> <link href="../../Skins/Default/Stylesheets/TextEffects.css" rel="stylesheet" /> <link href="../../Skins/Default/Stylesheets/Topic.css" rel="stylesheet" /> <link href="../Resources/Stylesheets/Styles.css" rel="stylesheet" /> <script src="../../Resources/Scripts/jquery.min.js"> </script> <script src="../../Resources/Scripts/plugins.min.js"> </script> <script src="../../Resources/Scripts/MadCapAll.js"> </script> </head> <body> <div class="content"> <h1>Ignoring Rules</h1> <p>You can specify which rules to ignore by removing them from your personal rule folder, <code><span class="VarPersonalRuleFolder">%APPDATA%\FlareLint</span></code>. <span class="VarFlareLint">FlareLint</span> applies only the rules that it finds in this folder and ignores all other rules on your computer.</p> <p><span class="Admonishment">Warning: </span>Do not modify the contents of the rules folder in the <span class="VarFlareLint">FlareLint</span> package. Modifying the installed package could prevent you from upgrading and uninstalling <span class="VarFlareLint">FlareLint</span>.</p> <p class="Task"><span class="MCToggler MCTogglerHead MCTogglerHotSpot MCToggler_Open toggler MCTogglerHotSpot_" data-mc-targets="ToIgnore">To specify which rules to ignore: </span> </p> <ol style="display: none;" data-mc-target-name="ToIgnore"> <li value="1"> <p>Use <span class="VarFlareLint">FlareLint</span> on any project. See <a href="Using.html">Using</a>.</p> <p>Running <span class="VarFlareLint">FlareLint</span> ensures that, at a minimum, the default rules get installed in your personal rule folder.</p> </li> <li value="2"> <p>Click the Windows Start button and in the search field, type <code><span class="VarPersonalRuleFolder">%APPDATA%\FlareLint</span></code> then press Enter.</p> <p>A Windows Explorer windows appears to display the contents of your personal rule folder.</p> </li> <li value="3"> <p>Select the Python modules for the rules that you want <span class="VarFlareLint">FlareLint</span> to ignore.</p> </li> <li value="4"> <p>Do one of the following:</p> <ul> <li value="1">To ignore the rules without deleting them, move them to a folder outside of your personal rules folder. For example, drag your selected files to your desktop.</li> <li value="2">To delete your rules, press the Delete key.</li> </ul> </li> </ol> </div> </body> </html><file_sep>/stable/Content/Topics/Predicates/attribute.html <!DOCTYPE html> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" lang="en" xml:lang="en" data-mc-search-type="Stem" data-mc-help-system-file-name="index.xml" data-mc-path-to-help-system="../../../" data-mc-target-type="WebHelp2" data-mc-runtime-file-type="Topic" data-mc-preload-images="false" data-mc-in-preview-mode="false" data-mc-toc-path="[%=System.LinkedTitle%]"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>pov-attribute</title> <link href="../../../Skins/Default/Stylesheets/Slideshow.css" rel="stylesheet" /> <link href="../../../Skins/Default/Stylesheets/TextEffects.css" rel="stylesheet" /> <link href="../../../Skins/Default/Stylesheets/Topic.css" rel="stylesheet" /> <link href="../../../Skins/Default/Stylesheets/Components/Styles.css" rel="stylesheet" /> <link href="../../Resources/Stylesheets/Styles.css" rel="stylesheet" /> <script src="../../../Resources/Scripts/custom.modernizr.js"> </script> <script src="../../../Resources/Scripts/jquery.min.js"> </script> <script src="../../../Resources/Scripts/require.min.js"> </script> <script src="../../../Resources/Scripts/require.config.js"> </script> <script src="../../../Resources/Scripts/foundation.min.js"> </script> <script src="../../../Resources/Scripts/plugins.min.js"> </script> <script src="../../../Resources/Scripts/MadCapAll.js"> </script> </head> <body> <div class="content"> <h1><em>pov</em>-attribute</h1><pre xml:space="preserve"><em>pov</em>-attribute <em>tag</em> <em>name</em> <em>pov</em>-attribute * <em>name</em></pre> <p>True when an element <em>tag</em> has a <em>name</em> attribute with a value that is not empty, false otherwise. </p> <p>Use the wildcard (“*”) to match any element tag.</p> <p>The point of view, <em>pov</em> may be one of the following: <code>after</code>, <code>ancestor</code>, <code>before</code>, <code>child</code>, <code>descendant</code>, <code>next</code>, <code>parent</code>, <code>previous</code>, and <code>self</code>.</p> <p>For example:</p><pre>&lt;p style="color: blue;"&gt;Pelee Island&lt;/p&gt;</pre> <p>the predicate <code>self-attribute p style</code> gives true and <code>self-attribute h1 style</code> gives false.</p> <p>In the following:</p><pre xml:space="preserve">&lt;h1 style=""&gt;Wolf Island&lt;/h1&gt;</pre> <p>the predicate <code>self-attribute p style</code> gives false, <code>self-attribute h1 style</code> gives false, and <code>self-attribute * style</code> gives false.</p> <p>In the following:</p><pre xml:space="preserve">&lt;li&gt;Manitoulin Island&lt;/li&gt;</pre> <p>the predicate <code>self-attribute li style</code> gives false and <code>self-attribute * style</code> gives false.</p> <p>Spaces and line breaks at the beginning and end of the attribute value are ignored. </p> <p>For example:</p><pre xml:space="preserve">&lt;a href="&#160;&#160;&#160;" title=" Population 30"&gt;Dorval Island&lt;/a&gt;</pre> <p>For the <code>a</code> element, the following gives false:</p><pre>self-attribute a href</pre> <p>And the following gives true:</p><pre>self-attribute a title</pre> </div> </body> </html><file_sep>/index.md # Welcome to FlareLint ![What do you think of the logo? I drew it myself, can you tell?](logo.png) FlareLint scans a [MadCap Flare](https://www.madcapsoftware.com/products/flare/) project for adherence to your style rules then displays a report in your preferred web browser. It's like picking the lint off your sweater, only more fun. Build projects faster and more consistently. Use the FlareLint report to make sure that your content, and the rest of your project, will give consistent output and won't delay production. For example, FlareLint reports when a topic does not start with an `h1` element. FlareLint works independently of Flare. It inspects source files in Flare projects directly and does not rely on Flare's output. FlareLint does not modify your Flare project or its source files. You don't have to open a project in Flare or build a Flare target before using FlareLint. ## FlareLint 2.0 (stable) *Note:* This is the official version of FlareLint, ready to use for the ordinary tech writer. This version has a completely new way for defining rules. There is no need for you to learn Python programming to customize rules. You can create and modify rules using a simple, straightforward language. (You still need to Python to install and run the Flarelint app.) [More details](stable/index.html#Topics/WhatsNew.html) [Download the installer](https://github.com/flarelint/flarelint/releases/download/2.0/FlareLint-2.0.zip) [FlareLint 2.0 User Guide](stable/index.html) ## FlareLint 1.2 (previous release) [Download the installer](https://github.com/flarelint/flarelint/releases/download/1.2/FlareLint-1.2.zip) [FlareLint 1.2 User Guide](oldstable/index.html) ## Support Get support, announcements, and share on the [mailing list](https://www.freelists.org/list/flarelint). ## Development Get, fork, or request a pull of the FlareLint [source code](https://github.com/flarelint/flarelint). <file_sep>/stable/Content/Topics/RulesCreating.html <!DOCTYPE html> <html xmlns:MadCap="http://www.madcapsoftware.com/Schemas/MadCap.xsd" lang="en" xml:lang="en" data-mc-search-type="Stem" data-mc-help-system-file-name="index.xml" data-mc-path-to-help-system="../../" data-mc-target-type="WebHelp2" data-mc-runtime-file-type="Topic" data-mc-preload-images="false" data-mc-in-preview-mode="false" data-mc-toc-path=""> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Creating and Customizing Rules</title> <link href="../../Skins/Default/Stylesheets/Slideshow.css" rel="stylesheet" /> <link href="../../Skins/Default/Stylesheets/TextEffects.css" rel="stylesheet" /> <link href="../../Skins/Default/Stylesheets/Topic.css" rel="stylesheet" /> <link href="../../Skins/Default/Stylesheets/Components/Styles.css" rel="stylesheet" /> <link href="../Resources/Stylesheets/Styles.css" rel="stylesheet" /> <script src="../../Resources/Scripts/custom.modernizr.js"> </script> <script src="../../Resources/Scripts/jquery.min.js"> </script> <script src="../../Resources/Scripts/require.min.js"> </script> <script src="../../Resources/Scripts/require.config.js"> </script> <script src="../../Resources/Scripts/foundation.min.js"> </script> <script src="../../Resources/Scripts/plugins.min.js"> </script> <script src="../../Resources/Scripts/MadCapAll.js"> </script> </head> <body> <div class="content"> <h1>Creating and Customizing Rules</h1> <p>You can create new rules and modify existing ones. Each <span class="VarFlareLint">FlareLint</span> rule is defined in a <span class="VarFlareLint">FlareLint</span> rule file. A rule file is a plain text file that you can view and edit with any text editor, such as Microsoft Notepad. The name of a rule file ends with <code>rule.txt</code>. For example, the <code>flarelint_h1_missing_rule.txt</code> file specifies that in topic files, the <code>body</code> element must contain an <code>h1</code> element.</p> <p>A rule file is composed of sections, with each section starting with a section name. For example, the following is a comment section:</p><pre xml:space="preserve">comment: See other rules for checking for the position of the header in the topic body.<![CDATA[ ]]></pre> <p>The content of a section may have any amount of spaces and line breaks. You can use the extra spaces and line breaks to make it clearer for you to read. For example, the following specifies the same section as the previous example:</p><pre xml:space="preserve">comment: See other rules for checking for the position of the header in the topic body. <![CDATA[ ]]></pre> <p>There is only one exception to where to you can put extra spaces:&#160;a section name must start at the beginning of a line. Also, it must immediately end with a colon (“:”). Sometimes a section contains text that includes a colon but you do not intend it to start a section. In this case, make sure that word preceding the colon does not start at the beginning of a line.</p><pre xml:space="preserve">comment: The following phrase does not start a new section: it is still in the comment section.</pre> <p>A rule file has the following sections. In a rule file, you must organize sections in the following order:</p> <ul> <li value="1"><code>comment</code>: A description, annotation, or other information for you and other people. <span class="VarFlareLint">FlareLint</span> ignores the text in the comment section. This section is optional.</li> <li value="2"><code>rule</code>: The type of rule, either <code>error</code> or <code>warning</code>. This section is required.</li> <li value="3"><code>extensions</code>: The file name extensions of the types of files to which to apply this rule. You must specify at least one file name extension. Do not include the dot (“.”) in the extensions. This section is required.</li> <li value="4"><code>when</code>: An expression that describes the HTML or XML element in a Flare file that this rule applies to. You must specify at least one <code>when</code> section. You can specify more <code>when</code> sections if necessary. </li> <li value="5"><code>test</code>: An expression that specifies requirements for the element that was matched in the <code>when</code> section. You must specify at least one <code>test</code> section. You can specify more <code>test</code> sections if necessary.</li> <li value="6"><code>message</code>:&#160;Text that describes why the <code>test</code> sections failed. This is the text that appears in a <span class="VarFlareLint">FlareLint</span> report. This section is required.</li> </ul> </div> </body> </html><file_sep>/stable/Resources/Scripts/require.config.js require.config({ urlArgs: 't=636742654785941622' });
1c6f8e8401e3033622cd8a21005d4fc0f5661bac
[ "Markdown", "JavaScript", "HTML" ]
6
HTML
flarelint/flarelint.github.io
941baf26c6637c104ac8a58bb4bbaaf7c11cc982
aa0aeb382ab78021680865c6a1437a23aed0422a
refs/heads/master
<repo_name>spqr-team/SPQR-Team-2019<file_sep>/utility/bt_test/bt_test.ino long t = 0; byte i = 0; byte b = 0; long last = 0; bool comrade = false; void setup() { Serial.begin(9600); Serial3.begin(9600); } void read() { while(Serial3.available()){ Serial.write((char)Serial3.read()); last = millis(); } } void loop() { digitalWrite(13, 1); if(millis() - last > 500) comrade = false; if(millis() - t >= 250){ b = 48+i; Serial3.write(b); t = millis(); i = (i+1)%9; } read(); } <file_sep>/include/test.h void testMenu(); <file_sep>/src/music.cpp #include "vars.h" #include "music.h" void imperial_march() { //tone(pin, note, duration) tone(buzzer, LA3, Q); delay(1 + Q / 2); //delay duration should always be 1 ms more than the note in order to separate them. noTone(buzzer); delay(1 + Q / 2); tone(buzzer, LA3, Q); delay(1 + Q/2); noTone(buzzer); delay(1 + Q / 2); tone(buzzer, LA3, Q); delay(1 + Q/2); noTone(buzzer); delay(1 + Q / 2); tone(buzzer, F3, E + S); delay(1 + (E + S) / 2); noTone(buzzer); delay(1 + (E + S) / 2); tone(buzzer, C4, S); delay(1 + S / 2); noTone(buzzer); delay(1 + S / 2); tone(buzzer, LA3, Q); delay(1 + Q / 2); noTone(buzzer); delay(1 + Q / 2); tone(buzzer, F3, E + S); delay(1 + (E + S) / 2); noTone(buzzer); delay(1 + (E + S) / 2); tone(buzzer, C4, S); delay(1 + S / 2); noTone(buzzer); delay(1+S/2); tone(buzzer, LA3, H); delay(1 + H/2); noTone(buzzer); delay(1 + H/2); noTone(buzzer); } void super_mario() { tone(buzzer, 660 ,100); delay ( 150); tone(buzzer, 660 ,100); delay ( 300); tone(buzzer, 660 ,100); delay ( 300); tone(buzzer, 510 ,100); delay ( 100); tone(buzzer, 660 ,100); delay ( 300); tone(buzzer, 770 ,100); delay ( 550); tone(buzzer, 3160 ,100); delay ( 575); } void startSetup(){ tone(30, LA3, 100); delay (100); noTone(30); tone(30, LA3, 100); delay (100); noTone(30); tone(30, LA5, 100); delay (100); noTone(303); } void stopSetup() { tone(30, LA5, 100); delay (100); noTone(30); tone(30, LA5, 100); delay (100); noTone(30); tone(30, LA2, 100); delay (100); noTone(30); } void miiChannel() { tone(buzzer, F3, 500); delay(500); noTone(buzzer); tone(buzzer, LA3, 200); delay(200); noTone(buzzer); tone(buzzer, B5, 600); delay(600); noTone(buzzer); tone(buzzer, LA3, 450); delay(450); noTone(buzzer); tone(buzzer, F3, 500); delay(500); noTone(buzzer); tone(buzzer, C2, 350); delay(350); noTone(buzzer); tone(buzzer, C2, 350); delay(350); noTone(buzzer); tone(buzzer, C2, 350); delay(350); noTone(buzzer); } <file_sep>/utility/AVR12/AVR12.ino #define SPI_SS 4 #define SPI_MOSI 5 #define SPI_MISO 6 #define SPI_SCK 7 #define SENS0 (PINC & 128) //PC7 #define SENS1 (PINC & 64) //PC6 #define SENS2 (PINC & 32)//PC5 #define SENS3 (PINC & 16) //PC4 #define SENS4 (PINC & 8) //PC3 #define SENS5 (PINC & 4) //PC2 #define SENS6 (PINC & 2) //PC1 #define SENS7 (PINC & 1) //PC0 #define SENS8 (PIND & 128) //PD7 #define SENS9 (PIND & 64) //PD6 #define SENS10 (PIND & 32) //PD5 #define SENS11 (PIND & 16) //PD4 #define SENS12 (PINA & 1) //PA0 #define SENS13 (PINA & 2) //PA1 #define SENS14 (PINA & 4) //PA2 #define SENS15 (PINA & 8)//PA3 #define SENS16 (PINA & 16) //PA4 #define SENS17 (PINA & 32) //PA5 #define SENS18 (PINA & 64) //PA6 #define SENS19 (PINA & 128) //PA7 #define SOGLIA_SENSOREROTTO 230 #define SOGLIA_PALLAINVISTA 35 #define SOGLIA_PALLA0 200 // attaccato ma non sempre funziona #define SOGLIA_PALLA1 170 // circa 5-15cm #define SOGLIA_PALLA2 150 // circa 15-80cm #define SOGLIA_PALLA3 125 // circa 80-140cm #define SOGLIA_PALLA4 100 // circa oltre 140cm #define SOGLIA_PALLA5 75 // lontanissima #define SOGLIA_PALLA6 7 //palla non vista #define LETTURE 250 #include <avr/interrupt.h> int contatore[20]; //array contenete conteggi sensori palla durante acquisizione dati // sensori 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 int angoli[20] = { 0, 15, 30, 45, 60, 75, 90, 113, 135, 158, 180, 202, 225, 247, 270, 285, 300, 315, 330, 345}; byte sensmax = 0; byte distanza = 0; volatile byte infoball = 0; volatile byte intcalled = 0; volatile byte oldinfoball = 0; void setup() { pinMode(SPI_MOSI, INPUT); pinMode(SPI_MISO, OUTPUT); pinMode(SPI_SCK, INPUT); pinMode(SPI_SS, INPUT); pinMode(0, OUTPUT); pinMode(1, OUTPUT); MCUCR = MCUCR | 128; DDRC=0; DDRA=0; DDRD&=15; //Serial.begin(9600); Serial1.begin(9600);//seriale per debug xbee SPCR |= 64; // abilito SPI // SPCR |= 192; //SLAVE E INTERRUPTS // sei(); } byte osc = 0; void loop() { // Serial1.println("ciao"); // digitalWrite(1,osc); // osc ^=1; leggiSens(); // Serial1.write(255); // Serial1.write(infoball); // for(int i=0;i<20;i++) // { // Serial1.write(byte(contatore[i]/10)); // } // Serial1.write(254); } void blinkTest(){ digitalWrite(1,1); delay(500); digitalWrite(1,0); delay(500); } void leggiSens() { //intcalled = 0; for(int i = 0;i<20;i++)contatore[i]=0; for(int i = 0; i<LETTURE;i++){ contatore[0] += (!SENS0); contatore[1] += (!SENS1); contatore[2] += (!SENS2); contatore[3] += (!SENS3); contatore[4] += (!SENS4); contatore[5] += (!SENS5); contatore[6] += (!SENS6); contatore[7] += (!SENS7); contatore[8] += (!SENS8); contatore[9] += (!SENS9); contatore[10] += (!SENS10); contatore[11] += (!SENS11); contatore[12] += (!SENS12); contatore[13] += (!SENS13); contatore[14] += (!SENS14); contatore[15] += (!SENS15); contatore[16] += (!SENS16); contatore[17] += (!SENS17); contatore[18] += (!SENS18); contatore[19] += (!SENS19); } // if(contatore[0] == LETTURE)sensmax=1; //se il sensore zero è rotto incomincio a confrontare con il sensore numero 1 for (byte i = 0; i < 20; i++) //confronto il valore di ogni sensore con quello più alto, in modo da stabilire qual'è realmente il più alto fra i 20 { if ((contatore[i] > contatore[sensmax])&& (contatore[i] != LETTURE)) // ignoro il dato se un sensore e' sempre attivo sensmax = i; } if (contatore[sensmax] < SOGLIA_PALLA6) { // sotto il valore di 60 = palla non in vista sensmax = 0; // se la palla non e' in vista uscita = 0; distanza = 6; digitalWrite(1,0); } else { digitalWrite(1,1); //toggle led palla in vista if (contatore[sensmax] < SOGLIA_PALLA0) distanza=0; if (contatore[sensmax] < SOGLIA_PALLA1) distanza=1; if (contatore[sensmax] < SOGLIA_PALLA2) distanza=2; if (contatore[sensmax] < SOGLIA_PALLA3) distanza=3; if (contatore[sensmax] < SOGLIA_PALLA4) distanza=4; if (contatore[sensmax] < SOGLIA_PALLA5) distanza=5; if (contatore[sensmax] < SOGLIA_PALLA6) distanza=6; } distanza=distanza<<5; infoball=distanza | sensmax; oldinfoball = infoball; SPDR= infoball; } //************************ ISR(SPI_STC_vect ) { intcalled = 1; SPCR = 64 & 127; // disabilita interrupt SPDR= infoball; // SPDR=PINC; SPCR = 64 |128; // abilita interrupt } <file_sep>/utility/kirkhammett/space_invaders.ino /* * void space_invaders() { if (compagno == true) { if (us_px >= 25) centroporta(); if (ball_sensor == 0) recenter(1.0); if ((ball_sensor >= 1) && (ball_sensor <= 8)) drivePID(90, GOALIE_P); if ((ball_sensor >= 12) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor >= 9) && (ball_sensor <= 11)) palla_dietro(); } else { if ((ball_distance <= 3) && (ball_sensor == 0)) menamoli(); else recenter(1.0); if ((ball_sensor >= 1) && (ball_sensor <= 7)) drivePID(90, GOALIE_P); if ((ball_sensor >= 13) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor >= 8) && (ball_sensor <= 12)) palla_dietro(); } }*/ void space_invaders() { us_read(); if (us_px >= 15) centroporta(); if ((ball_sensor >= 1) && (ball_sensor <= 8)) drivePID(90, GOALIE_P); if ((ball_sensor >= 12) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor > 8) && (ball_sensor < 12)) palla_dietro(); } /* BACKUP void space_invaders() { unsigned long t4; unsigned long t5; int tira=300; if (compagno == true) { if (us_px >= 25) centroporta(); if(((ball_sensor==0)||(ball_sensor==19)||(ball_sensor==1))&&(ball_distance<=1)) { t4=millis(); do { drivePID (0,255); } while ( (millis() - t4) < tira); if(us_px<=75) tira=150; t5=millis(); do { drivePID (180,255); } while ( (millis() - t5) < tira); } if ((ball_sensor >= 1) && (ball_sensor <= 7)) drivePID(90, GOALIE_P); if ((ball_sensor >= 12) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor > 8) && (ball_sensor < 12)) palla_dietro(); else recenter(1.0); } else { if ((ball_distance <= 4) && ((ball_sensor == 19)||(ball_sensor == 0)||(ball_sensor == 1))) menamoli(); if ((ball_sensor > 1) && (ball_sensor <= 7)) drivePID(90, GOALIE_P); if ((ball_sensor >= 13) && (ball_sensor < 19)) drivePID(270, GOALIE_P); if ((ball_sensor >= 8) && (ball_sensor <= 12)) palla_dietro(); } } /* PROBABILE FUNZIONANTE void space_invaders() { if (compagno == true) { if (us_px >= 25) centroporta(); if ((ball_sensor >= 1) && (ball_sensor <= 8)) drivePID(90, GOALIE_P); if ((ball_sensor >= 12) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor >= 9) && (ball_sensor <= 11)) palla_dietro(); } else { if ((ball_distance <= 2) && (ball_sensor == 0)) menamoli(); if ((ball_sensor >= 1) && (ball_sensor <= 7)) drivePID(90, GOALIE_P); if ((ball_sensor >= 13) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor >= 8) && (ball_sensor <= 12)) palla_dietro(); } } */ /* BACKUP void space_invaders() { unsigned long t4; unsigned long t5; int tira=300; if (compagno == true) { if (us_px >= 25) centroporta(); if(((ball_sensor==0)||(ball_sensor==19)||(ball_sensor==1))&&(ball_distance<=1)) { t4=millis(); do { drivePID (0,255); } while ( (millis() - t4) < tira); if(us_px<=75) tira=150; t5=millis(); do { drivePID (180,255); } while ( (millis() - t5) < tira); } if ((ball_sensor >= 1) && (ball_sensor <= 7)) drivePID(90, GOALIE_P); if ((ball_sensor >= 12) && (ball_sensor <= 19)) drivePID(270, GOALIE_P); if ((ball_sensor > 8) && (ball_sensor < 12)) palla_dietro(); else recenter(1.0); } else { if ((ball_distance <= 4) && ((ball_sensor == 19)||(ball_sensor == 0)||(ball_sensor == 1))) menamoli(); if ((ball_sensor > 1) && (ball_sensor <= 7)) drivePID(90, GOALIE_P); if ((ball_sensor >= 13) && (ball_sensor < 19)) drivePID(270, GOALIE_P); if ((ball_sensor >= 8) && (ball_sensor <= 12)) palla_dietro(); } } */ void centroporta() { int larghezza = 0; if (status_x == CENTRO) { if (status_y == CENTRO) { drivePID(180, 150); } else if (status_y == SUD) { if (us_px > 20) drivePID(180, 110); else if (us_px < 15) drivePID(0, 130); else recenter(1.0); } else ritornacentro(); } else if (status_x == 255) { if (us_px > 50) drivePID(180, 110); else if (us_px < 30) drivePID(0, 130); else recenter(1.0); } else ritornacentro(); } <file_sep>/src/position.cpp #include "pid.h" #include "us.h" #include "camera.h" #include "imu.h" #include "vars.h" #include "config.h" #include "nano_ball.h" #include "position.h" int zone[3][3]; void increaseIndex(int i, int j, int ammount){ if(i < 3 && j < 3){ zone[i][j] += ammount; zone[i][j] = constrain(zone[i][j], 0, ZONE_MAX_VALUE); } } void decreaseIndex(int i, int j, int ammount){ increaseIndex(i, j, -ammount); } void increaseRow(int i, int ammount){ if(i < 3){ for(int a = 0; a < 3; a++){ increaseIndex(a, i, ammount); } } } void decreaseRow(int i, int ammount){ increaseRow(i, -ammount); } void increaseCol(int i, int ammount){ if(i < 3){ for(int a = 0; a < 3; a++){ increaseIndex(i, a, ammount); } } } void decreaseCol(int i, int ammount){ increaseCol(i, -ammount); } void increaseColWithLimit(int i, int ammount){ if(zone[i][0] + ammount < ZONE_MAX_VALUE && zone[i][1] + ammount < ZONE_MAX_VALUE && zone[i][2] + ammount < ZONE_MAX_VALUE){ increaseCol(i, ammount); } } void increaseRowWithLimit(int i, int ammount){ if(zone[0][1] + ammount < ZONE_MAX_VALUE && zone[1][i] + ammount < ZONE_MAX_VALUE && zone[2][i] + ammount < ZONE_MAX_VALUE){ increaseRow(i, ammount); } } void decreaseColWithLimit(int i, int ammount){ if(zone[i][0] - ammount >= 0 && zone[i][1] - ammount >= 0 && zone[i][2] - ammount >= 0){ decreaseCol(i, ammount); } } void decreaseRowWithLimit(int i, int ammount){ if(zone[0][i] - ammount >= 0 && zone[1][i] - ammount >= 0 && zone[2][i] - ammount >= 0){ decreaseRow(i, ammount); } } void increaseAll(int val){ //decrease all for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ increaseIndex(i, j, val); } } } void decreaseAll(int val){ increaseAll(-val); } void calculateLogicZone(){ decreaseAll(ZONE_LOOP_DECREASE_VALUE); readPhyZone(); //calculates guessed_x and guessed_y and zoneIndex //zoneIndex is just 2D to 1D of the guessed x and y //(y_position * width + x_position) int top = 0; for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ if(zone[i][j] > top){ guessed_x = i; guessed_y = j; top = zone[i][j]; } } } zoneIndex = guessed_y * 3 + guessed_x; } void readPhyZone(){ phyZoneUS(); phyZoneCam(); phyZoneLines(); // phyZoneDirection(); } //old WhereAmI. Renamed to be coerent. Now also adds to the logic zone void phyZoneUS(){ // decide la posizione in orizzontale e verticale // Aggiorna i flag : good_field_x good_field_y non utilizzata da altre // routines // goal_zone non utilizzata da altre // routines // Aggiorna le variabili: // status_x (con valori CENTER EAST WEST 255 = non lo so) // status_y (con valori CENTER NORTH SOUTH 255 = non lo so) int Lx_mis; // larghezza totale stimata dalle misure int Ly_mis; // lunghezza totale stimata dalle misure int Ly_min; // Limite inferiore con cui confrontare la misura y int Ly_max; // Limite inferiore con cui confrontare la misura y int Dy; // Limite per decidere NORTH SOUTH in funzione della posizione // orizzontale old_status_x = status_x; old_status_y = status_y; good_field_x = false; // non é buona x good_field_y = false; // non é buona y goal_zone = false; // non sono davanti alla porta avversaria if (role == HIGH) DxF = DxF_Atk; else DxF = DxF_Def; Lx_mis = us_dx + us_sx + robot; // larghezza totale stimata Ly_mis = us_fr + us_px + robot; // lunghezza totale stimata // controllo orizzontale if ((Lx_mis < Lx_max) && (Lx_mis > Lx_min) && (us_dx > 25) && (us_sx > 25)) { // se la misura orizzontale é accettabile good_field_x = true; status_x = CENTER; if (us_dx < DxF) // robot é vicino al bordo dEASTro status_x = EAST; if (us_sx < DxF) // robot é vicino al bordo sinistro status_x = WEST; if (status_x == CENTER) { // imposto limiti di controllo lunghezza verticale tra le porte Ly_min = LyP_min; Ly_max = LyP_max; Dy = DyP; } else { // imposto limiti di controllo lunghezza verticale in fascia Ly_min = LyF_min; Ly_max = LyF_max; Dy = DyF; } } else { // la misura non é pulita per la presenza di un ostacolo if ((us_dx >= (DxF + 10)) || (us_sx >= (DxF + 10))) { // se ho abbastanza spazio a dEASTra o a sinistra // devo stare per forza al cento status_x = CENTER; // imposto limiti di controllo lunghezza verticale tra le porte Ly_min = LyP_min; Ly_max = LyP_max; Dy = DyP; } else { status_x = 255; // non so la coordinata x // imposto i limiti di controllo verticale in base alla posizione // orizzontale precedente if (old_status_x == CENTER) { // controlla la posizione precedente per decidere limiti di controllo y // imposto limiti di controllo lunghezza verticale tra le porte Ly_min = LyP_min; Ly_max = LyP_max; Dy = DyP; } else { // imposto limiti di controllo lunghezza verticale in fascia anche per x // incognita Ly_min = LyF_min; Ly_max = LyF_max; Dy = DyF; } } } // controllo verticale if ((Ly_mis < Ly_max) && (Ly_mis > Ly_min)) { // se la misura verticale é accettabile good_field_y = true; status_y = CENTER; if (us_fr < Dy) { status_y = NORTH; // robot é vicino alla porta avversaria if (Dy == DyP) goal_zone = true; // davanti alla porta in zona goal } if (us_px < Dy) status_y = SOUTH; // robot é vicino alla propria porta } else { // la misura non é pulita per la presenza di un ostacolo status_y = 255; // non so la coordinata y if (us_fr >= (Dy + 0)) status_y = CENTER; // ma se ho abbastanza spazio dietro o avanti if (us_px >= (Dy + 0)) status_y = CENTER; // e'probabile che stia al CENTER } //now operates on the matrix if (status_x == 255 && status_y != 255) { increaseRow(status_y, ZONE_US_UNKNOWN_INCREASE_VALUE); } else if (status_x != 255 && status_y == 255) { increaseCol(status_x, ZONE_US_UNKNOWN_INCREASE_VALUE); } else { increaseIndex(status_x, status_y, ZONE_US_INDEX_INCREASE_VALUE); } } int p = 4; int camA; int camD; void phyZoneCam(){ //IMU-fixed attack angle camA = fixCamIMU(pAtk); //IMU-fixed defence angle camD = fixCamIMU(pDef); //Negative angle means that the robot is positioned to the right of the goalpost //Positive angle means that the robot is positioned to the left of the goalpost p = 4; if(abs(diff(camA, camD)) <= ZONE_CAM_CENTER_RANGE){ //at center row, you can consider both camA and camD p = 1; }else if(camA > camD){ p = 0; }else if(camD > camA){ p = 2; } increaseColWithLimit(p, ZONE_CAM_INCREASE_VALUE); calcPhyZoneCam = false; } void phyZoneLines(){ //ZONE_LINES_ERROR_VALUE is a random error code not used in line exit direction calculations if(lineSensByteBak != ZONE_LINES_ERROR_VALUE){ switch(lineSensByteBak) { case 1: //NORTH increaseRow(0, ZONE_LINES_INCREASE_VALUE); decreaseRow(1, ZONE_LINES_INCREASE_VALUE); decreaseRow(2, ZONE_LINES_INCREASE_VALUE); break; case 2: //EAST decreaseCol(0, ZONE_LINES_INCREASE_VALUE); decreaseCol(1, ZONE_LINES_INCREASE_VALUE); increaseCol(2, ZONE_LINES_INCREASE_VALUE); break; case 4: //SOUTH decreaseRow(0, ZONE_LINES_INCREASE_VALUE); decreaseRow(1, ZONE_LINES_INCREASE_VALUE); decreaseRow(2, ZONE_LINES_INCREASE_VALUE); break; case 8: //WEST increaseCol(0, ZONE_LINES_INCREASE_VALUE); decreaseCol(1, ZONE_LINES_INCREASE_VALUE); decreaseCol(2, ZONE_LINES_INCREASE_VALUE); break; case 3: decreaseAll(ZONE_LINES_INCREASE_VALUE); increaseIndex(0, 2, 2*ZONE_LINES_INCREASE_VALUE); break; case 6: decreaseAll(ZONE_LINES_INCREASE_VALUE); increaseIndex(2, 2, 2*ZONE_LINES_INCREASE_VALUE); break; case 9: decreaseAll(ZONE_LINES_INCREASE_VALUE); increaseIndex(0, 0, 2*ZONE_LINES_INCREASE_VALUE); break; default: break; } //Last thing to do, sets the var to an error code, so next time it will be called will be because of the outOfBounds function being called lineSensByteBak = ZONE_LINES_ERROR_VALUE; } } void phyZoneDirection(){ int val = 5; int x = sin(prevPidDir) * prevPidSpeed; int y = cos(prevPidSpeed) * prevPidSpeed; if(y > 0) decreaseRow(2, val); if(y < 0) decreaseRow(0, val); if(x > 0) increaseCol(2, val); if(x < 0) increaseCol(0, val); } void testPhyZone(){ readBallNano(); readUS(); readIMU(); goalPosition(); readPhyZone(); DEBUG_PRINT.print("Measured US location:\t"); DEBUG_PRINT.print(status_x); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(status_y); DEBUG_PRINT.print("Measured Cam Column (4 is error):\t"); DEBUG_PRINT.println(p); } void testLogicZone(){ calculateLogicZone(); DEBUG_PRINT.println("-----------------"); for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { DEBUG_PRINT.print(zone[i][j]); DEBUG_PRINT.print(" | "); } DEBUG_PRINT.println(); } DEBUG_PRINT.println("-----------------"); DEBUG_PRINT.print("Guessed location:\t"); DEBUG_PRINT.print(guessed_x); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(guessed_y); DEBUG_PRINT.print("Zone Index: "); DEBUG_PRINT.println(zoneIndex); } unsigned long ao; void gigaTestZone(){ //outpus the matrix if (millis() - ao >= 500) { DEBUG_PRINT.println("------"); for (int i = 0; i < 4; i++) { DEBUG_PRINT.print("US: "); DEBUG_PRINT.print(us_values[i]); DEBUG_PRINT.print(" | "); } DEBUG_PRINT.println(); testPhyZone(); testLogicZone(); testIMU(); // if (comrade){ // DEBUG_PRINT.print("FriendZone: "); // DEBUG_PRINT.println(friendZone); // } DEBUG_PRINT.println("------"); ao = millis(); } } void goCenter() { if (zoneIndex == 8) preparePID(330, GOCENTER_VEL); if (zoneIndex == 7) preparePID(0, GOCENTER_VEL); if (zoneIndex == 6) preparePID(45, GOCENTER_VEL); if (zoneIndex == 5) preparePID(270, GOCENTER_VEL); if (zoneIndex == 4) preparePID(0, 0); if (zoneIndex == 3) preparePID(90, GOCENTER_VEL); if (zoneIndex == 2) preparePID(255, GOCENTER_VEL); if (zoneIndex == 1) preparePID(180, GOCENTER_VEL); if (zoneIndex == 0) preparePID(135, GOCENTER_VEL); } void centerGoalPostCamera(bool checkBack) { digitalWrite(Y, HIGH); if (fixCamIMU(pDef) > CENTERGOALPOST_CAM_MAX) { preparePID(270, CENTERGOALPOST_VEL1); } else if (fixCamIMU(pDef) < CENTERGOALPOST_CAM_MIN) { preparePID(90, CENTERGOALPOST_VEL1); }else if(fixCamIMU(pDef) > CENTERGOALPOST_CAM_MIN && fixCamIMU(pDef) < CENTERGOALPOST_CAM_MAX){ if(!ball_seen) preparePID(0, 0, 0); if(checkBack){ if(us_px > CENTERGOALPOST_US_MAX){ preparePID(180, CENTERGOALPOST_VEL2); } else{ if(us_px < CENTERGOALPOST_US_CRITIC) preparePID(0, CENTERGOALPOST_VEL3); keeper_backToGoalPost = false; keeper_tookTimer = false; } } } } // int vel = 160; // int usDist = 70; // void centerGoalPost() { // x = 1; // y = 1; // int vel = 255; // if ((zoneIndex >= 0 && zoneIndex <= 2) || zoneIndex == 4) { // preparePID(180, vel); // } else if (zoneIndex == 3 || zoneIndex == 6) { // preparePID(90, vel); // } else if (zoneIndex == 5 || zoneIndex == 8) { // preparePID(270, vel); // } else { // stop_menamoli = false; // if (us_px >= 25) // preparePID(180, vel); // else // preparePID(0, 0); // } // } void update_sensors_all() { readBallNano(); readIMU(); readUS(); return; } void AAANGOLO() { if((us_px <= 45) && ((us_dx <= 50) || (us_sx <= 50))) preparePID(0, 350, 0); }<file_sep>/src/keeper.cpp #include "keeper.h" #include "vars.h" #include "config.h" #include "position.h" #include "pid.h" #include "us.h" #include "camera.h" #include "nano_ball.h" #include "goalie.h" #include "math.h" #include <Arduino.h> int defSpeed = 0; int defDir = 0; byte defDistance = 160; float angle = 0; float angleX = 0, angleY = 0; elapsedMillis t = 0; elapsedMillis toh = 0; void keeper() { if(ball_distance > KEEPER_ATTACK_DISTANCE){ // Ball is quite near goalie(); if(!keeper_tookTimer){ keeperAttackTimer = 0; keeper_tookTimer = true; } if(keeperAttackTimer > KEEPER_ALONE_ATTACK_TIME && keeper_tookTimer && !comrade) keeper_backToGoalPost = true; if(keeperAttackTimer > KEEPER_COMRADE_ATTACK_TIME && keeper_tookTimer && comrade) keeper_backToGoalPost = true; }else{ angle = (90 + ball_degrees) * M_PI / 180; angleX = abs(cos(angle)); if(ball_degrees >= 0 && ball_degrees <= KEEPER_ANGLE_DX && fixCamIMU(pDef) < 30) preparePID(90, KEEPER_BASE_VEL*angleX*KEEPER_VEL_MULT); else if(ball_degrees >= KEEPER_ANGLE_SX && ball_degrees <= 360 && fixCamIMU(pDef) > -30) preparePID(270, KEEPER_BASE_VEL*angleX*KEEPER_VEL_MULT); else if(ball_degrees < KEEPER_ANGLE_SX && ball_degrees > KEEPER_ANGLE_DX){ ballBack(); // int ball_degrees2 = ball_degrees > 180? ball_degrees-360:ball_degrees; // int dir = ball_degrees2 > 0 ? ball_degrees + KEEPER_BALL_BACK_ANGLE : ball_degrees - KEEPER_BALL_BACK_ANGLE; // dir = dir < 0? dir + 360: dir; // preparePID(dir, KEEPER_BASE_VEL); } else preparePID(0,0,0); centerGoalPostCamera(true); } if(keeper_tookTimer && keeper_backToGoalPost && comrade) centerGoalPostCamera(true); }<file_sep>/utility/kirkhammett/menamoli.ino void menamoli() { int atk_direction = 0; //direzione di attacco in funzione del sensore che vede la palla int atk_speed = 0; //velocitá di attacco in funzione del sensore che vede la palla int goaliedirection[20] = { AA0, AA1 , AA2, AA3, AA4, AA5, AA6, AA7, AA8, AA9, AA10, AA11, AA12, AA13, AA14, AA15, AA16, AA17, AA18, AA19 }; //direzioni going around the ball long tm; if(flag_interrupt==true) centroporta(); //GESTIONE PALLA DIETRO if (ball_sensor == 10) { if(ball_distance<=3){ if(us_sx>us_dx) atk_direction=225; else atk_direction=135; atk_speed=GOALIE_SLOW1; } else { atk_direction=180; atk_speed=GOALIE_SLOW2; } } if(ball_sensor == 9) { if(ball_distance<=3) { atk_direction=225; atk_speed=GOALIE_SLOW1; } else { atk_direction=200; atk_speed=GOALIE_SLOW2; } } if(ball_sensor == 11) { if(ball_distance<=3) { atk_direction=135; atk_speed=GOALIE_SLOW1; } else { atk_direction=160; atk_speed=GOALIE_SLOW2; } } //GESTIONE PALLA DAVANTI if (ball_sensor == 0) { if(ball_distance>=3) atk_speed = 180; atk_speed = GOALIE_MAX; } else { if(ball_distance>=3) atk_speed = 180; atk_speed = GOALIE_MIN; } atk_direction = goaliedirection[ball_sensor]; //going around the ball // controllo per ridurre oscillazione quando ha la palla in avanti if (ball_sensor == 1) { if (ball_distance <= 2) { //se la palla è vicina atk_speed = GOALIE_MAX; atk_direction = 15; } } if (ball_sensor == 19) { if (ball_distance <= 2) { //se la palla è vicina atk_speed = GOALIE_MAX; atk_direction = 345; } } update_sensors_all(); x_porta(); //leggo la posizione della porta // se ha la palla vicino e davanti cerca di centrare la porta if ((ball_distance<=2) && ((ball_sensor == 19)||(ball_sensor == 0)||(ball_sensor == 1))) { if ((XP_SX==true)||(status_x==EST)) // sto in fascia destra convergo a sinistra { if(status_x==EST){ if(status_y==CENTRO) { //(x>141)&&(x<190) atk_direction=345; atk_speed=255; } if(status_y==NORD) { //(x>111)&&(x<140) atk_direction=340; atk_speed=255; } } if(status_x==CENTRO){ if(status_y==CENTRO) { //(x>141)&&(x<190) atk_direction=355; atk_speed=255; } if(status_y==NORD) { //(x>111)&&(x<140) atk_direction=345; atk_speed=255; } } } if ((XP_DX==true)||(status_x==OVEST)) // sto in fascia sinistra convergo a destra { if(status_x==OVEST) { if(status_y==CENTRO) { //(x>35)&&(x<60) atk_direction=15; atk_speed=255; } if(status_y==NORD) { //(x>8)&&(x<34) atk_direction=30; atk_speed=255; } } if(status_x==CENTRO) { if(status_y==CENTRO) { //(x>35)&&(x<60) atk_direction=5; atk_speed=255; } if(status_y==NORD) { //(x>8)&&(x<34) atk_direction=15; atk_speed=255; } } } } // -------------------------- if ((millis() - tdanger) > 500) danger = false; // dichiara esaurito il pericolo dall'ultimo interrupt if (danger == true) atk_speed = GOALIE_DANGER; // se ha terminato da poco la gestione interrupt rallenta // __________________________ drivePID(atk_direction, atk_speed); return; } <file_sep>/utility/kirkhammett/irsensors.ino void readBallNano() { spi_readfrom644l(); //getting our data from our spi slave ball_seen = true; //in any other case the ball is seen by the robot if (ball_distance == 6) { ball_seen = false; //if the distance is 6 it means that the robot doesnt see the ball } if (old_s_ball != ball_sensor) { old_s_ball = ball_sensor; time_s_ball = millis(); // per quanto tempo lo stesso sensore vede la palla >usata in keeper e non in goalie< } return; }//-------------------------------------------------------------- void update_sensors_all() { us_read(); //reads the ultrasonic sensors every 70 ms >us_fr,us_px,us_dx,us_sx< imu_current_euler = read_euler(); //reads the imu euler angle >imu_current_euler< readBallNano(); //reads the ball sensor >ball_sensor, ball_distance, ball_seen< return; }//-------------------------------------------------------------- <file_sep>/src/test.cpp #include <Arduino.h> #include "vars.h" #include "chat.h" #include "us.h" #include "bluetooth.h" #include "nano_ball.h" #include "goalie.h" #include "camera.h" #include "position.h" #include "imu.h" #include "motors.h" #include "pid.h" #include "position.h" #include "linesensor.h" int testDelay = 10; elapsedMillis ao3 = 0; void testMenu(){ brake(); DEBUG_PRINT.println(); DEBUG_PRINT.println("Velocitá 9600 e NESSUN FINE RIGA >no LF<"); DEBUG_PRINT.println("Digitare il test (1-->7) da eseguire e premere ENTER >no LF<"); DEBUG_PRINT.println("Digitare 0 per uscire dai test >no LF<"); DEBUG_PRINT.println(); DEBUG_PRINT.println("Test Menu: "); DEBUG_PRINT.println("0)Esci dai test e gioca"); DEBUG_PRINT.println("1)Test Palla"); DEBUG_PRINT.println("2)Test US"); DEBUG_PRINT.println("3)Test IMU"); DEBUG_PRINT.println("4)Test Motori"); DEBUG_PRINT.println("5)Recenter"); DEBUG_PRINT.println("6)Test BT"); DEBUG_PRINT.println("7)GigaTestZone"); DEBUG_PRINT.println("8)Test Camera"); DEBUG_PRINT.println("9)Test Sensori Linea"); do{ test = DEBUG_PRINT.read(); DEBUG_PRINT.println(); DEBUG_PRINT.print("Test "); DEBUG_PRINT.print(test); DEBUG_PRINT.println(" "); if (test == '0') DEBUG_PRINT.println("Esce dal test e torna a giocare"); else if (test == '1') DEBUG_PRINT.println("Test Palla, accendere la palla e girarla tra i sensori"); else if (test == '2') DEBUG_PRINT.println("Test US, tenere il robot fermo ed in piano"); else if (test == '3') DEBUG_PRINT.println("Test IMU, tenere il robot in piano"); else if (test == '4') DEBUG_PRINT.println("Test Motori, accendere I MOTORI e tenerlo sospeso"); else if (test == '5') DEBUG_PRINT.println("Recenter, accendere il robot e storcerlo"); else if (test == '6') DEBUG_PRINT.println("Test BT, connettersi al BT"); else if (test == '7') DEBUG_PRINT.println("GigaTestZone, test grafico matrice zone (1-->9), US, IMU e zona compagno (se presente)"); else if (test == '8') DEBUG_PRINT.println("CAMERA"); else if (test == '9') DEBUG_PRINT.println("Linee"); else if (test == 'l') DEBUG_PRINT.println("Taratura Linee"); else { DEBUG_PRINT.println(" Comando sconosciuto"); flagtest = false; } } while (DEBUG_PRINT.available() > 0); do{ switch(test){ case '0': DEBUG_PRINT.println("Fine test"); flagtest = false; return; break; case '1'://test palla testBallNano(); delay(testDelay); break; case '2'://test us testUS(); delay(testDelay); break; case '3'://test imu testIMU(); delay(testDelay); break; case '4'://test motori testMotors(); delay(testDelay); break; case '5'://test recenter readIMU(); delay(5); drivePID(0,0); //delay(testDelay); break; case '6'://test bt testBluetooth(); delay(testDelay); break; case '7'://gigaTestZone gigaTestZone(); delay(10); break; case '8': goal_orientation = digitalRead(SWITCH_SX); //se HIGH attacco gialla, difendo blu goalPosition(); readIMU(); DEBUG_PRINT.print(pAtk); DEBUG_PRINT.print(" | "); DEBUG_PRINT.print(fixCamIMU(pAtk)); DEBUG_PRINT.print(" --- "); DEBUG_PRINT.print(pDef); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(fixCamIMU(pDef)); // DEBUG_PRINT.print(" | Delta: ");; // DEBUG_PRINT.println(delta); delay(100); break; case '9': testLineSensors(); delay(100); break; case 'l': DEBUG_PRINT.print("Sensore 1 In - Out"); DEBUG_PRINT.print(analogRead(S1I)); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(analogRead(S1O)); DEBUG_PRINT.print("Sensore 2 In - Out"); DEBUG_PRINT.print(analogRead(S2I)); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(analogRead(S2O)); DEBUG_PRINT.print("Sensore 3 In - Out"); DEBUG_PRINT.print(analogRead(S3I)); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(analogRead(S3O)); DEBUG_PRINT.print("Sensore 4 In - Out"); DEBUG_PRINT.print(analogRead(S4I)); DEBUG_PRINT.print(" | "); DEBUG_PRINT.print(analogRead(S4O)); DEBUG_PRINT.print("\n--------------------------"); DEBUG_PRINT.println(" "); delay(100); break; default://default, todo, maybe break; case 'b': goalPosition(); if(cameraReady == 1) { storcimentoPorta(); calcPhyZoneCam = true; cameraReady = 0; } calculateLogicZone(); Ao(); friendo(500); if(ao3 >= 200){ Serial.print(comrade); Serial.print(" | "); Serial.println(friendZone); ao3 = 0; } break; } } while (DEBUG_PRINT.available() == 0); } /* elapsedMicros t1,t2,t3,t4,t5,t6,t7,t8,t9; role = digitalRead(SWITCH_DX); //se HIGH sono attaccante goal_orientation = digitalRead(SWITCH_SX); //se HIGH attacco gialla, difendo blu if(Serial.available() > 0) testMenu(); Serial.print("IMU"); t1 = 0; readIMU(); Serial.print(t1); Serial.print("| US |"); t2 = 0; readUS(); Serial.print(t2); Serial.print("| NANO |"); t3 = 0; readBallNano(); Serial.print(t3); Serial.print("| CAMERA |"); t4 = 0; goalPosition(); Serial.print(t4); Serial.print("| STORCIMENTO |"); t5 = 0; if(cameraReady == 1) { storcimentoPorta(); calcPhyZoneCam = true; cameraReady = 0; } Serial.print(t5); Serial.print("| ZONA LOGICA |"); t6 = 0; calculateLogicZone(); Serial.print(t6); Serial.print("| GIOCO |"); t7 = 0; if(ball_seen){ if(role) goalie(); else keeper(); } else { if(role) preparePID(0, 0, 0); else centerGoalPost(); } Serial.print(t7); Serial.print("| LINESENSOR |"); t8 = 0; checkLineSensors(); //Last thing in loop, for priority Serial.print(t8); Serial.print("| SAFETYSAFE |"); t9 = 0; safetysafe(); Serial.println(t9); */<file_sep>/utility/kirkhammett/main.ino void setup() { SerialTest.begin(115200); //Velocità default di 115200 I2c.begin(); //inizializza I2C I2c.timeOut(12); //fissa a 12 ms il tempo di attesa della risposta gpio_setup(); //inizializza GPIO init_gpio_motors(); //inizializza GPIO motori init_linesensors(); //abilita i sensori di linea a chiamare interrupt come PCINT2 init_spi(); //inizializza comunicazione spi init_imu(); //inizializza imu test_toggle_outputs(1); //on tutti gli ouput init_omnidirectional_sins(); //inizializza seni test_toggle_outputs(0); //off tutti gli output linea[0] = 63; //prima degli interrupt sensori linea ok SWS = digitalRead(SWITCH_SX); //lettura switch sinistro init_bluetooth(); //inizializza comunicazione BT valStringY.reserve(30); //riserva 30byte per le stringhe valStringB.reserve(30); //initial_p(); //inizializza sensore presa palla tone(22, 1000, 500); //tone iniziale //take_on_me(); //TAKE ON ME - AHA //imperial_march(); //IMPERIAL MARCH - STAR WARS //super_mario(); //SUPER MARIO - NINTENDO return; } void loop() { motori_test(); /* SWD = digitalRead(SWITCH_DX); //lettura switch destro per cambio porta if (SWD == HIGH) p = 1; else p = 0; //controllo e test------------------- if ((flagtest == true) || (SerialTest.available() > 0)) rtest(); //test update_sensors_all(); if (flag_interrupt == true ) //c'e' stato un interrupt { gest_interrupt(); //va a gestire l'interrupt } SWS = digitalRead(SWITCH_SX); //lettura switch sinistro role = SWS; //cambio role update_location_complete(); //COMUNICAZIONE BT if (count < 30 ) { count++; } else { count = 0; bluetooth.write(42); } //comunicazione(500); compagno=true; if (ball_seen == true) //SCELTA DEI RUOLI TRAMITE SWITCH E BT { if (role == HIGH) { if (compagno == true) goalie(); else space_invaders(); } else { if (compagno == true) space_invaders(); else space_invaders(); } } else { if (role == HIGH) { if (compagno == true) ritornacentro(); else centroporta(); } else { if (compagno == true) centroporta(); else centroporta(); } } return;*/ } //SETTING PINS TO INPUT OR OUTPUT void gpio_setup() { pinMode(PIN_LED_R, OUTPUT); pinMode(PIN_LED_Y, OUTPUT); pinMode(PIN_LED_G, OUTPUT); pinMode(PIN_PIEZO, OUTPUT); pinMode(PIN_BUTTON1, INPUT_PULLUP); pinMode(PIN_BUTTON2, INPUT_PULLUP); pinMode(PIN_BUTTON3, INPUT_PULLUP); pinMode(SWITCH_SX, INPUT_PULLUP); pinMode(SWITCH_DX, INPUT_PULLUP); pinMode(A8, INPUT); pinMode(A9, INPUT); pinMode(A10, INPUT); pinMode(A11, INPUT); pinMode(A12, INPUT); pinMode(A13, INPUT); return; } <file_sep>/include/imu.h void initIMU(); void readIMU(); void testIMU(); <file_sep>/src/imu.cpp #include "imu.h" #include "vars.h" #include <Adafruit_BNO055.h> #include <Arduino.h> elapsedMillis readingIMU; Adafruit_BNO055 bno = Adafruit_BNO055(); void initIMU() { bno.begin(bno.OPERATION_MODE_IMUPLUS); //Posizione impostata a P7 alle righe 105,107 di Adafruit_BNO55.cpp bno.setExtCrystalUse(true); } void readIMU() { if(readingIMU > 5) { imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER); if (euler.x() != imu_current_euler) { imu_current_euler = euler.x(); } readingIMU = 0; } return; } void testIMU() { readIMU(); DEBUG_PRINT.print("IMU: "); DEBUG_PRINT.println(imu_current_euler); } <file_sep>/include/config.h //All defines go here //Multiply the speed by this factor to make the robot go a bit slower or faster, without having to change all the variables manually #define GLOBAL_SPD_MULT 0.9 //LINES #define LINES_EXIT_SPD 350 //STRIKER #define GOALIE_ATKSPD_LAT 255 #define GOALIE_ATKSPD_BAK 350 #define GOALIE_ATKSPD_FRT 345 #define GOALIE_ATKSPD_STRK 355 #define GOALIE_ATKDIR_PLUSANG1 20 #define GOALIE_ATKDIR_PLUSANG2 35 #define GOALIE_ATKDIR_PLUSANG3 40 #define GOALIE_ATKDIR_PLUSANGBAK 40 #define GOALIE_ATKDIR_PLUSANG1_COR 60 #define GOALIE_ATKDIR_PLUSANG2_COR 70 #define GOALIE_ATKDIR_PLUSANG3_COR 70 //KEEPER #define KEEPER_ATTACK_DISTANCE 190 #define KEEPER_ALONE_ATTACK_TIME 5000 //in millis #define KEEPER_COMRADE_ATTACK_TIME 3000//in millis #define KEEPER_BASE_VEL 320 #define KEEPER_VEL_MULT 1.4 #define KEEPER_BALL_BACK_ANGLE 30 #define KEEPER_ANGLE_SX 265 #define KEEPER_ANGLE_DX 85 //POSITION #define CENTERGOALPOST_VEL1 220 #define CENTERGOALPOST_VEL2 220 #define CENTERGOALPOST_VEL3 220 #define CENTERGOALPOST_CAM_MIN -40 #define CENTERGOALPOST_CAM_MAX 40 #define CENTERGOALPOST_US_MAX 60 #define CENTERGOALPOST_US_CRITIC 25 #define GOCENTER_VEL 280 #define ZONE_MAX_VALUE 150 #define ZONE_LOOP_DECREASE_VALUE 4 #define ZONE_US_UNKNOWN_INCREASE_VALUE 4 #define ZONE_US_INDEX_INCREASE_VALUE 9 #define ZONE_CAM_INCREASE_VALUE 3 #define ZONE_CAM_CENTER_RANGE 25 #define ZONE_LINES_INCREASE_VALUE 100 #define ZONE_LINES_ERROR_VALUE 30 // You can modify this if you need // LIMITI DEL CAMPO #define Lx_min 115 // valore minimo accettabile di larghezza #define Lx_max 195 // valore massimo accettabile di larghezza (larghezza campo) #define LyF_min 190 // valore minimo accettabile di lunghezza sulle fasce #define LyF_max 270 // valore massimo accettabile di lunghezza sulle fasce (lunghezza campo) #define LyP_min 139 // valore minimo accettabile di lunghezza tra le porte #define LyP_max 250 // valore massimo accettabile di lunghezza tra le porte// con misura x OK con us_dx o us_sx < DxF sto nelle fasce 30 + 30 - 1/2 robot #define DyF 91 // con misura y OK e robot al CENTER (tra le porte) con us_fx o us_px < DyP sto a NORTH o a SOUTH era - 22 #define DyP 69 #define DxF_Atk 48 // per attaccante, fascia centrale allargata #define DxF_Def 48 // per portiere, fascia centrale ristretta quEASTa roba viene fatta dentro WhereAmI #define robot 21 // diametro del robot // ZONE DEL CAMPO // codici utilizzabili per una matice 3x3 #define EAST 2 #define WEST 0 #define CENTER 1 #define NORTH 0 #define SOUTH 2 #define NORTH_WEST 1 #define NORTH_CENTER 2 #define NORTH_EAST 3 #define CENTER_WEST 4 #define CENTER_CENTER 5 // codici zona nuovi #define CENTER_EAST 6 #define SOUTH_WEST 7 #define SOUTH_CENTER 8 #define SOUTH_EAST 9 <file_sep>/utility/kirkhammett/kirkhammett.ino //LIBRERIE------------------------------------ #include "libraries/BNO055.cpp" //LIBRERIE IMU,I2C,PRESA PALLA #include "libraries/BNO055.h" #include "libraries/I2C.cpp" #include "libraries/I2C.h" //#include "libraries/VL53L0X.h" #define SerialTest Serial //SERIALE TEST #define SerialOMV Serial1 //SERIALE CAMERA #define bluetooth Serial3 //SERIALE COMUNICAZIONE BT //MAPPATURA PIN SHIELD------------------------------- #define PIN_LED_R 40 #define PIN_LED_Y 39 #define PIN_LED_G 38 #define PIN_BUTTON1 28 #define PIN_BUTTON2 27 #define PIN_BUTTON3 26 //PIN IR BOARD------------------------------- #define PIN_PIEZO 22 #define SWITCH_SX 24 #define SWITCH_DX 25 //VARIABILI PER GESTIONE SWITCH--------------- int SWS = 0; int SWD = 0; //PIN SPI------------------------------------ //#define Nbyte 1 #define _SCK 52 #define _MISO 50 #define _MOSI 51 #define _SS 53 //MASCHERE DEI SENSORI DI LINEA------------------------------- //maschera per la porta PINK per ricavare il valore del pin di Arduino #define S1 1 // A8 bit 0 di PINK #define S2 2 // A9 bit 1 di PINK #define S3 4 // A10 bit 2 di PINK #define S4 8 // A11 bit 3 di PINK #define S5 16 // A12 bit 4 di PINK #define S6 32 // A13 bit 5 di PINK //FLAG DEI TEST------------------------------------ bool flagtest = false; // Necessario per i test //PIN MOTORI---------------------------------------- // 1 2 3 motori byte INA_MOT [4] = {0, 2, 10, 12}; //pin INA byte INB_MOT [4] = {0, 3, 11, 13}; //pin INB byte PWM_MOT [4] = {0, 6, 7, 8}; //pin PWM //VARIABILI DEI MOTORI------------------------------- float speed1; // velocitá motore 1 float speed2; // velocitá motore 2 float speed3; // velocitá motore 3 float pidfactor; // fattore di PID float sins[360]; // array dei seni a gradi interi da O a 359 per velocizzare //da utilizzare per sviluppi futuri------------------- signed int old_Dir = 0; // angolo di direzione precedente a quella attuale signed int new_Dir = 0; // angolo di direzione corrente del moto float old_vMot; // velocitá di moto precedente float new_vMot; // velocitá di moto corrente //VARIABILI RELATIVE ALLA LETTURA DELLA PALLA--------------- byte spi_temp_byte = 0; // dato grezzo letto da SPI byte ball_sensor = 0; // sensore che vede la palla byte ball_distance = 0; // distanza della palla con valore da 0 a 6 bool ball_seen = false; // palla in vista si/no era byte byte old_s_ball; // sensore che vedeva la palla in precedenza, paragonato con ball_sensor unsigned long time_s_ball; // millisecondipassati dal cambiamento di sensore che vede la palla (KEEPER) //VARIABILI PER IMU------------------------------------------- BNO055 IMU(0x28); //crea oggetto IMU dalla classe BNO055 con indirizzo I2C 0x28 int imu_temp_euler = 0; int imu_current_euler = 0; //VARIABILI PER I SENSORI A ULTRASUONI---------------------- long us_t0 = 0; // inizio misura ultrasuoni long us_t1 = 0; // misura del tempo durante la misura byte us_flag = false; // misura in corso si/no int us_values[4]; // array delle misure degli ultrasuoni int us_sx, us_dx, us_px, us_fr;// copie con altro nome dell'array //COSTANTI PER ATTACCANTE (GOALIE & MENAMOLI)----------------------------- #define GOALIE_MAX 130 #define GOALIE_MIN 200 #define GOALIE_SLOW1 130 #define GOALIE_SLOW2 150 #define GOALIE_DANGER 100 #define VEL_RET 180 #define GOALIE_P 255 // velocità portiere #define AA0 0 // angoli di attacco in funzione del sensore palla #define AA1 30 #define AA2 60 #define AA3 80 #define AA4 90 #define AA5 120 #define AA6 130 #define AA7 160 #define AA8 170 #define AA9 999 #define AA10 999 #define AA11 999 #define AA12 190 #define AA13 200 #define AA14 230 #define AA15 240 #define AA16 270 #define AA17 280 #define AA18 300 #define AA19 337 //VARIABILI E COSTANTI DEL PID-------------------------------- #define KP 0.7 // K proporzionale #define KI 0.001 // K integrativo #define KD 0.001 // K derivativo float errorePre = 0.0; // angolo di errore precedente float integral = 0.0; // somisa degli angoli di errore bool reaching_ball = false; // serve per aumentare il PID del 20% GOALIE int st = 0; // storcimento sulle fasce //VARIABILI E COSTANTI POSIZIONI CAMPO------------------------------------- //ZONE DEL CAMPO #define EST 2 // codici utilizzabili per una matice 3x3 #define OVEST 0 #define CENTRO 1 #define NORD 0 #define SUD 2 #define NORD_OVEST 1 #define NORD_CENTRO 2 #define NORD_EST 3 #define CENTRO_OVEST 4 #define CENTRO_CENTRO 5 // codici zona nuovi #define CENTRO_EST 6 #define SUD_OVEST 7 #define SUD_CENTRO 8 #define SUD_EST 9 // LIMITI DEL CAMPO #define Lx_min 115 // valore minimo accettabile di larghezza #define Lx_max 195 // valore massimo accettabile di larghezza (larghezza campo) #define LyF_min 190 // valore minimo accettabile di lunghezza sulle fasce #define LyF_max 270 // valore massimo accettabile di lunghezza sulle fasce (lunghezza campo) #define LyP_min 139 // valore minimo accettabile di lunghezza tra le porte #define LyP_max 250 // valore massimo accettabile di lunghezza tra le porte #define DxF 48 // con misura x OK con us_dx o us_sx < DxF sto nelle fasce 30 + 30 - 1/2 robot #define DyF 91 // con misura y OK e robot a EST o A OVEST con us_fx o us_px < DyF sto a NORD o a SUD era - 10 #define DyP 69 // con misura y OK e robot al CENTRO (tra le porte) con us_fx o us_px < DyP sto a NORD o a SUD era - 22 #define robot 21 // diametro del robot int status_x = CENTRO; // posizione nel campo vale EST, OVEST o CENTRO o 255 int status_y = CENTRO; // posizione nel campo vale SUD, NORD o CENTRO o 255 int currentlocation = CENTRO_CENTRO; // risultato misure zone campo da 1 a 9 o 255 se undefined int guessedlocation = CENTRO_CENTRO; // risultato misure zone campo da 1 a 9 (da CENTRO_CENTRO a SUD_OVEST) int old_status_x = CENTRO; // posizione precedente nel campo vale EST, OVEST o CENTRO o 255 >USI FUTURI< int old_status_y = CENTRO; // posizione precedente nel campo vale SUD, NORD o CENTRO o 255 >USI FUTURI< int old_currentlocation; // zona precedente del robot in campo da 1 a 9 o 255 se undefined >USI FUTURI< int old_guessedlocation = CENTRO_CENTRO; // zona precedente del robot in campo da 1 a 9 (da CENTRO_CENTRO a SUD_OVEST) >USI FUTURI< bool goal_zone = false; // sto al centro rispetto alle porte assegnata da WhereAmI ma non usata bool good_field_x = true; // vedo tutta la larghezza del campo si/no bool good_field_y = true; // vedo tutta la lunghezza del campo si/no //MATRICE DI PROBABILITÁ------------------------------- byte zone [3] [3] {1, 2, 3, 4, 5, 6, 7, 8, 9}; // il primo indice = NORD SUD CENTRO il secondo indice EST OVEST CENTRO signed int zone_prob[3] [3] {0, 0, 0, 0, 5, 0, 0, 0, 0}; //VARIABILI INTERRUPT SENSORI LINEE--------------------- volatile byte linesensor = 0; // sensore che ha dato interrupt byte perché da 1 a 6 volatile byte linea_new; // stato dei sensori di linea all'ultimo interrupt volatile byte linea_old = 63; // stato dei sensori di linea all'interrupt precedente volatile int ISx; // valore ultrasuoni quando scatta il primo interrupt volatile int IDx; volatile int IPx; volatile int IFr; volatile bool flag_interrupt = false; volatile byte Nint = 0; // numero di interrupt consecutivi prima della fine della gestione volatile byte linea [100]; // letture consecutive all'interrupt dei sensori di linea int VL_INT; // velocitá di uscita dalle linee int EXT_LINEA; // direzione di uscita dalla linea byte n_us; // ultrasuono da controllare dopo la fuga dalla linea int attesa = 0; // tempo di attesa palla dopo un interrupt (utilizzata dallo switch destro) bool danger; // avviso che terminata da poco la gestione interrupt unsigned long tdanger; // misura il tempo dal termine della gestione interrupt //VARIABILI PER LA GESTIONE DEL role TRAMITE BLUETOOTH----- int role = 0, a, count; long timer, old_timer; unsigned long tt = 0; //tempo tra una trasmissione e l'altra bool compagno = false; // ritiene compagno vero se riceve un carattere in datoArrivato int datoArrivato; // per la ricezione byte tent = 0; // contatore dei tentativi //VARIABILI PER IL PORTIERE float bd = 0; long ta; bool atk_p = false; byte ball_array[5]; short i; byte vel_por = 255; long diff; float ball_distance_precise; long ti; long tf; bool flag_atkp; int paratozza_ang; int paratozza_vel; //VARIABILI PORTA int x = 0; //posizione x della porta ricevuta dalla telecamera bool XP_SX = false; //bool porta a sinistra o destra rispetto al robot bool XP_DX = false; bool XP_CENTRO = false; bool dangergoalie = false; //VARIABILI CAMERA String valStringY = ""; //stringa dove si vanno a mettere i pacchetti di dati ricevuti String valStringB = ""; int startpY = 0; //inizio del dato int startpB = 0; int endpY = 0; //fine del dato int endpB = 0; int datavalid = 0; //segnalo se il dato ricevuto è valido int valY; //variabile a cui attribuisco momentaneamente il valore dell x della porta int valB; int p = 0; //variabile dello switch che decide dove bisogna attaccare bool attack = false; <file_sep>/utility/test_ir_v2/test_ir_v2_software-serial/test_ir_v2_software-serial.ino /* test_ir_v2.ino This code takes data from 12 IR sensors in a circle 30 deg apart from each other, than converts the data into a byte, containing the direction of the ball in degrees and its distance, that is then transferred to the main control via serial communication. This code is to be used only on the ATMEGA328P and equivalents and it is meant for the ball recognition part of the SPQR robotics team robots. Created by: <NAME> Day 6/12/2018 (DD/MM/YY) Modified by: <NAME> Day 19/12/2018 Modified by: <NAME>, <NAME> & <NAME> Day 9/1/2018 Added Software Serial control, with map from -180, 180 to 0,360 */ #include <math.h> #include <SoftwareSerial.h> #define TOUT 100 #define DEBUG 0 #define THRL 30 #define THRH 253 byte tx_data = 0; float tmp_y, tmp_x; int pins[] = {A0, 2, 3, 4, 5, 6, 7, 8, 9, A1, 0, 1}, t; float vect[2], s_data[12], dist, angle, angle2; const float sins[12] = {0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5}, cosins[12] = {1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, 0.866}; SoftwareSerial mySerial(10 ,11); // RX, TX long ssDegree = 0b000000011, ssDist = 0b00000001; long mess; char mystr[20]; void setup(){ Serial.begin(9600); mySerial.begin(115200); for (byte x = 0; x < 12; x++) pinMode(pins[x], INPUT); } void loop() { t = millis(); readSensors_old(); // print unmodiefied values for debug if (DEBUG == 1){ Serial.println("-----------"); Serial.println(angle); Serial.println(dist); Serial.println("-----------"); } t = millis() - t; if (DEBUG == 11) Serial.println(t); dataConstruct(); //Serial.println(tx_data); if (DEBUG == 1) delay(1000); } void readSensors_old(){ for (int i = 0; i < 255; i++){ s_data[0] += !digitalRead(pins[0]); s_data[1] += !digitalRead(pins[1]); s_data[2] += !digitalRead(pins[2]); s_data[3] += !digitalRead(pins[3]); s_data[4] += !digitalRead(pins[4]); s_data[5] += !digitalRead(pins[5]); s_data[6] += !digitalRead(pins[6]); s_data[7] += !digitalRead(pins[7]); s_data[8] += !digitalRead(pins[8]); s_data[9] += !digitalRead(pins[9]); s_data[10] += !digitalRead(pins[10]); s_data[11] += !digitalRead(pins[11]); } for (byte i = 0; i < 12; i++){ if ((s_data[i] < THRL) || (s_data[i] > THRH)){ s_data[i] = 0; } if ((DEBUG == 1) && (s_data[i] != 0)){ Serial.print(i); Serial.print(" | "); Serial.println(s_data[i]); } tmp_y = (s_data[i] * sins[i]); tmp_x = (s_data[i] * cosins[i]); vect[0] += tmp_y; vect[1] += tmp_x; s_data[i] = 0; } if (DEBUG == 1){ Serial.print("x: "); Serial.print(vect[1]); Serial.print(" | "); Serial.print("y: "); Serial.println(vect[0]); } angle = atan2(vect[0], vect[1]); angle = (angle * 4068) / 71; dist = sqrt(square(vect[0]) + square(vect[1])); //cast da 0 a 360 ;) angle = map(angle,-179,180,0,360); vect[0] = 0; vect[1] = 0; //ssDegree = angle; //ssDist = dist; sendData(); } void sendData(){ //constructing the data int. Shift the distance by 9 bits (size of degree int), then ORs the degree int, and voilà mess = ssDist; mess = mess << 9; mess |= ssDegree; //long to string, SERIAL COMMUNICATION CAN ONLY SEND A BYTE, NOT MORE THAN THAT, but a char array can be sent String s = String(mess); //string to char array s.toCharArray(mystr, 20); Serial.println(mystr); //send the char array, so the full data can be sent mySerial.write(mystr, 20); //bit of delay delay(1000); } void dataConstruct(){ //WIP: need more data } <file_sep>/utility/kirkhammett/bluetooth.ino void init_bluetooth() { //inizializza bluetooth bluetooth.begin(115200); tt=millis(); } bool comunicazione (int intervallo) { //funzione di comunicazione if (bluetooth.available() > 0) { a = bluetooth.read(); } if (a == 42) { compagno = true; digitalWrite(PIN_LED_G, HIGH); digitalWrite(PIN_LED_R, LOW); a = 0; old_timer = millis(); } if ((millis() - old_timer ) > intervallo) { old_timer = millis(); compagno = false; digitalWrite(PIN_LED_G, LOW); digitalWrite(PIN_LED_R, HIGH); } return compagno ; } <file_sep>/utility/kirkhammett/int.ino void gest() //utilizzato in semifinale { long t0; // istante inizio frenata long dt; // tempo di fuga byte sens; // sensori attivi contemporaneamente int delta; // angolo di rotazione del robot float tolleranza = 5.0; //PRIMA ERA 10 OCCHIO byte si, sf ; // sensore iniziale e finale da mascherare per il tipo di uscita byte di, df; // sensore iniziale e finale da mascherare intorno a quello che vede la palla byte ds = 2; // numero di sensori da mascherare intorno a quello che vede la palla boolean d_uscita; // se true la palla si trova in zona da cui e' uscito in precedenza boolean d_palla; // se true la palla non si e' mossa rispetto a uscita precedente attesa=0; t0 = millis(); tone(buzzer,1800,500); //suona a una frequenza di 1800 do { update_sensors_all(); } while ((millis() - t0) <= 100) ; //attesa per la frenata di 100 ms digitalWrite(buzzer, LOW); sens = 255; for (byte i = 1; i <= Nint; i++) // calcola quanti sensori si sono attivati nella frenata { sens = sens & linea[i]; } sens = ~( sens + 192 ); // sens contiene 1 in corrispondenza dei sensori attivati // controllo se il robot si trova storto e calcolo di che angolo if (imu_current_euler < 180) delta = imu_current_euler; else delta = imu_current_euler - 360; if ((delta >= -tolleranza) && (delta <= tolleranza)) delta = 0; // se si trova poco storto non correggo if((us_sx<75)&&((ball_sensor==0)||(ball_sensor==1)||(ball_sensor==2))) goalie(); if((us_dx<75)&&((ball_sensor==18)||(ball_sensor==19)||(ball_sensor==0))) goalie(); switch (sens) { case 0b000001: // sensori singoli 1 EXT_LINEA = 180; if ((ball_sensor > 14) || (ball_sensor < 6)) // vede la palla in avanti { si = 1; sf = 4; } else // vede la palla dietro { EXT_LINEA = 0; si = 10; sf = 13; } dt = 300; break; case 0b000010: // sensori singoli 2 si = 4; sf = 7; if ((us_dx < 35) && (us_dx > 25)) //sto vicino al bordo destro { EXT_LINEA = 270; status_x = EST; } else // inverto il moto { EXT_LINEA = new_Dir + 180 ; if ( EXT_LINEA > 360) EXT_LINEA = EXT_LINEA - 360; } break; case 0b000100: // sensori singoli 3 if ((ball_sensor > 14) || (ball_sensor < 6)) // vede la palla in avanti { EXT_LINEA = 150; si = 6; sf = 19; } else // palla dietro { EXT_LINEA = 330; si = 7; sf = 10; } break; case 0b001000: // sensori singoli 4 if ((ball_sensor > 14) || (ball_sensor < 6)) // vede la palla in avanti { EXT_LINEA = 220; si = 6; sf = 19; } else // palla dietro { EXT_LINEA = 30; si = 1; sf = 4; } break; case 0b010000: // sensori singoli 5 si = 13; sf = 16; if ((us_sx < 35) && (us_sx > 25)) //sto vicino al bordo sinistro { EXT_LINEA = 90; status_x = OVEST; } else // inverto il moto { EXT_LINEA = new_Dir + 180 ; if ( EXT_LINEA > 360) EXT_LINEA = EXT_LINEA - 360; } break; case 0b100000: // sensori singoli 6 EXT_LINEA = 180; if ((ball_sensor > 14) || (ball_sensor < 6)) // vede la palla in avanti { si = 6; sf = 19; } else // vede la palla dietro { EXT_LINEA = 0; si = 7; sf = 10; } dt = 300; break; case 0b000011: // attivati i sensori 1 e 2 // sta uscendo a destra case 0b000110: // attivati i sensori 2 e 3 case 0b000111: // attivati i sensori 1 2 e 3 dt = 340; si = 4; sf = 7; EXT_LINEA = 270; status_x = EST; break; case 0b110000: // attivati i sensori 5 e 6 // sta uscendo a sinistra case 0b011000: // attivati i sensori 5 e 4 case 0b111000: // attivati i sensori 6 5 e 4 dt = 340; si = 13; sf = 16; EXT_LINEA = 90; status_x = OVEST; break; case 0b100001: // attivati i sensori 6 1 sta uscendo in avanti dt = 360; si = 18; sf = 2; EXT_LINEA = 180; status_y = NORD; break; case 0b001100: // attivati i sensori 4 3 sta uscendo indietro dt = 340; si = 9; sf = 11; if (us_px < 40) EXT_LINEA = 0; else EXT_LINEA = 180; status_y = SUD; break; case 0b100010: // attivati 6 2 case 0b100011: //attivati i sensori 6 2 1 sta in angolo Nord Est dt = 340; si = 1; sf = 4; EXT_LINEA = 225; status_x = EST; status_y = NORD; break; case 0b010001: //attivati 6 5 case 0b110001: // attivati i sensori 6 5 1 sta in angolo Nord Ovest dt = 340; si = 16; sf = 19; EXT_LINEA = 135; status_x = OVEST; status_y = NORD; break; case 0b001010: // attivati 4 2 case 0b001110: //attivati i sensori 4 3 2 sta in angolo Sud Est dt = 340; si = 7; sf = 10; EXT_LINEA = 315; status_x = EST; status_y = SUD; break; case 0b010100: // attivati i sensori 5 3 case 0b011100: // attivati i sensori 5 4 3 sta in angolo Sud Ovest dt = 340; si = 10; sf = 13; EXT_LINEA = 60; status_x = OVEST; status_y = SUD; break; case 0b011110: //attivati i sensori 5 4 3 2 sta fuori quasi tutto dietro dt = 500; si = 7; sf = 13; if (us_px < 40) EXT_LINEA = 0; else EXT_LINEA = 180; status_y = SUD; break; case 0b001011: //attivati i sensori 4 2 1 case 0b001111: //attivati i sensori 4 3 2 1 dt = 500; si = 6; sf = 9; EXT_LINEA = 330; status_x = EST; break; case 0b110100: //attivati i sensori 6 5 3 case 0b111100: //attivati i sensori 6 5 4 3 dt = 500; si = 11; sf = 14; EXT_LINEA = 60; status_x = OVEST; break; case 0b011001: //attivati i sensori 5 4 1 case 0b111001: //attivati i sensori 6 5 4 1 dt = 500; si = 15; sf = 18; EXT_LINEA = 120; status_x = OVEST; break; case 0b100110: //attivati i sensori 6 3 2 1 case 0b100111: //attivati i sensori 6 3 2 1 dt = 500; si = 2; sf = 5; EXT_LINEA = 225; status_x = EST; break; case 0b110011: // attivati i sensori 6 1 5 e 2 sta fuori quasi tutto avanti dt = 500; si = 16; sf = 4; EXT_LINEA = 180; status_y = NORD; break; case 0b101111: // attivati i sensori 6 1 2 3 4 sta fuori a destra con solo 5 in campo dt = 600; si = 3; sf = 8; EXT_LINEA = 270; status_x = EST; break; case 0b111101: // attivati i sensori 6 1 3 4 5 sta fuori a sinistra con solo 2 in campo dt = 600; si = 12; sf = 17; EXT_LINEA = 90; status_x = OVEST; break; case 0b110111: // attivati i sensori 5 6 1 2 3 sta fuori a destra con solo 4 in campo (angolo NORD EST?) dt = 600; si = 18; sf = 6; EXT_LINEA = 220; status_x = EST; status_y = NORD; break; case 0b111011: // attivati i sensori 4 5 6 1 2 sta fuori a sinistra con solo 3 in campo (angolo NORD OVEST?) dt = 600; si = 15; sf = 0; EXT_LINEA = 140; status_x = OVEST; status_y = NORD; break; case 0b111110: // attivati i sensori 6 5 4 3 2 sta fuori indietro con solo 1 in campo (angolo SUD OVEST?) dt = 600; si = 10; sf = 13; EXT_LINEA = 30; status_x = OVEST; status_y = SUD; break; case 0b011111: // attivati i sensori 1 2 3 4 5 sta fuori indietro con solo 6 in campo (angolo SUD EST?) dt = 600; si = 7; sf = 10; EXT_LINEA = 330; status_x = EST; status_y = SUD; break; case 0b000000: // Tutti i sensori sono disattivi interrupt strano (line sensor =0)? // sporco sul campo? flag_interrupt = false;//considera conclusa la gestione dell'interrupt Nint = 0; danger = false; return; break; case 0b000101: //robot a cavallo della linea con fuori o solo il 2 oppure il 4,5,6 if (us_dx <= 40) { status_x = EST; EXT_LINEA = 270; si = 4; sf = 7; } if (us_sx <= 30) { status_x = OVEST; EXT_LINEA = 90; si = 13; sf = 16; } break; case 0b101000: //robot a cavallo della linea con fuori o solo il 5 oppure 1,2,3 if (us_dx <= 30) { status_x = EST; EXT_LINEA = 270; si = 4; sf = 7; } if (us_sx <= 40) { status_x = OVEST; EXT_LINEA = 90; si = 13; sf = 16; } break; case 0b010010: //robot a cavallo della linea con fuori solo o 1,6 oppure 4,3 (attivi 5 e 2) if ((delta >= -60) && (delta <= 60)) //sta dritto? { if ((ball_sensor > 14) || (ball_sensor < 6)) // vede la palla in avanti valutare && (us_fr<50) { status_y = NORD; EXT_LINEA = 180; si = 18; sf = 2; } if ((ball_sensor > 7) && (ball_sensor < 13)) // vede la palla dietro valutare && (us_px<50) { status_y = SUD; EXT_LINEA = 0; si = 8; sf = 12; } } else //sta storto a destra o a sinistra { if (delta > 60) // girato verso destra { status_x = EST; EXT_LINEA = 270; si = 18; sf = 2; } if (delta < - 60) // girato a sinistra { status_x = OVEST; EXT_LINEA = 90; si = 8; sf = 12; } } break; default: // Si sono attivati 6 sensori o caso non previsto inverto il moto dt = 450; EXT_LINEA = new_Dir + 180 ; if ( EXT_LINEA > 360) EXT_LINEA = EXT_LINEA - 360; tone(buzzer,20000,500); // avviso che sono uscito si = 0; // aggiustare sf = 1; } //CONTROLLO CON ULTRASUONI if ((us_fr <= 40) && (us_sx <= 40)) EXT_LINEA = 135; if ((us_fr <= 40) && (us_dx <= 40)) EXT_LINEA = 225; if ((us_px <= 40) && (us_dx <= 40)) EXT_LINEA = 330; if ((us_px <= 40) && (us_sx <= 40)) EXT_LINEA = 30; if ((status_x == EST) && (status_y == NORD)) EXT_LINEA = 203; if ((status_x == OVEST) && (status_y == NORD)) EXT_LINEA = 135; if ((status_x == EST) && (status_y == SUD)) EXT_LINEA = 330; if ((status_x == OVEST) && (status_y == SUD)) EXT_LINEA = 30; if ((status_x == EST) && (status_y == CENTRO)) EXT_LINEA = 270; if ((status_x == OVEST) && (status_y == CENTRO)) EXT_LINEA = 90; if ((us_sx >= 17) && (us_sx <= 35)) EXT_LINEA = 90; if ((us_dx >= 17) && (us_dx <= 35)) EXT_LINEA = 270; dt = 150; EXT_LINEA = EXT_LINEA - delta; // sostituzione del + if (EXT_LINEA >= 360) EXT_LINEA = EXT_LINEA - 360; if (EXT_LINEA < 0) EXT_LINEA = EXT_LINEA + 360; //va nella direzione EXT_LINEA per un tempo dt a una velocità crescente fino a 220 raddrizzandosi st = 0; // elimina storcimento nella fuga t0 = millis(); VL_INT = 100; //velocita di fuga iniziale (prima era 50) do { update_sensors_all(); // WhereAmI(); non conviene corro rischio di perdere informazione drivePID (EXT_LINEA, VL_INT); if (VL_INT < 255) VL_INT++; //limitazione velocita massima (prima era 220) } while ( (millis() - t0) < dt); digitalWrite(buzzer, LOW); // spero di essere rientrato brake(); for (int i = 0; i < 30; i++) { imu_current_euler = read_euler(); //reads the imu euler angle >imu_current_euler< recenter(1.0); delay(10); } brake(); // calcola i limiti di df dei sensori pericolosi attorno a quello che vede la palla if ( (ball_sensor < (20 - ds) ) && (ball_sensor > (ds - 1) )) // non scavalla { di = ball_sensor - ds; df = ball_sensor + ds; } else { if ( ball_sensor >= (20 - ds)) // scavalla in avanti { di = ball_sensor - ds; df = (ball_sensor - 20) + ds; } else // scavalla indietro { di = (20 - ball_sensor) - ds; df = ball_sensor + ds; } } t0 = millis(); // rimane in attesa ed esce se trascorso tempo > attesa oppure la palla viene vista con un sensore non pericoloso do { update_sensors_all(); // calcola le condizioni true/false da controllare per rimanere fermo if (si < sf) //sensori consecutivi { d_uscita = (ball_sensor >= si) && (ball_sensor <= sf); } else // sensori scavallano { d_uscita = ((ball_sensor >= si) && (ball_sensor <= 19)) || ((ball_sensor >= 0) && (ball_sensor <= sf)); } if (di < df) //sensori consecutivi { d_palla = (ball_sensor >= di) && (ball_sensor <= df); } else // sensori scavallano { d_palla = ((ball_sensor >= di) && (ball_sensor <= 19)) || ((ball_sensor >= 0) && (ball_sensor <= df)); } } while ( ((d_uscita == true) || (d_palla == true) ) && ((millis() - t0) < attesa)); /*----------------- CONTROLLO CHE NESSUN SENSORE DI LINEA SIA ATTIVO -------------------*/ // E CONTINUO A MUOVERMI FINO A CHE NON SONO TUTTI DISATTIVI if ((PINK & 63) != 63) { t0 = millis(); do { drivePID(EXT_LINEA, VL_INT); } while (((PINK & 63) != 63) && (millis() - t0) < 2000); } /*--------------------------------------------------------------------------------------*/ flag_interrupt = false;//considera conclusa la gestione dell'interrupt Nint = 0; danger = true; tdanger = millis(); return; } <file_sep>/utility/test_ir_v2/test_ir_v2/test_ir_v2.ino /* test_ir_v2.ino This code takes data from 12 IR sensors in a circle 30 deg apart from each other, than converts the data into a byte, containing the direction of the ball in degrees and its distance, that is then transferred to the main control via serial communication. This code is to be used only on the ATMEGA328P and equivalents and it is meant for the ball recognition part of the SPQR robotics team robots. Created by: <NAME> Day 6/12/2018 (DD/MM/YY) Modified by: <NAME> Day 19/12/2018 Modified by: <NAME>, <NAME> & <NAME> Day 9/1/2018 Added SPI control, with map from -180, 180 to 0,360 */ #include <math.h> #define TOUT 100 #define DEBUG 1 #define THRL 30 #define THRH 253 byte tx_data = 0; float tmp_y, tmp_x; int pins[] = {A0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1}, t; float vect[2], s_data[12], dist, angle, angle2; const float sins[12] = {0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5}, cosins[12] = {1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, 0.866}; void setup(){ Serial.begin(9600); for (byte x = 0; x < 12; x++) pinMode(pins[x], INPUT); } void loop() { t = millis(); readSensors_old(); // print unmodiefied values for debug if (DEBUG == 1){ Serial.println("-----------"); Serial.println(angle); Serial.println(dist); Serial.println("-----------"); } t = millis() - t; if (DEBUG == 11) Serial.println(t); dataConstruct(); //Serial.println(tx_data); if (DEBUG == 1) delay(1000); } void readSensors_old(){ for (int i = 0; i < 255; i++){ s_data[0] += !digitalRead(pins[0]); s_data[1] += !digitalRead(pins[1]); s_data[2] += !digitalRead(pins[2]); s_data[3] += !digitalRead(pins[3]); s_data[4] += !digitalRead(pins[4]); s_data[5] += !digitalRead(pins[5]); s_data[6] += !digitalRead(pins[6]); s_data[7] += !digitalRead(pins[7]); s_data[8] += !digitalRead(pins[8]); s_data[9] += !digitalRead(pins[9]); s_data[10] += !digitalRead(pins[10]); s_data[11] += !digitalRead(pins[11]); } for (byte i = 0; i < 12; i++){ if ((s_data[i] < THRL) || (s_data[i] > THRH)){ s_data[i] = 0; } if ((DEBUG == 1) && (s_data[i] != 0)){ Serial.print(i); Serial.print(" | "); Serial.println(s_data[i]); } tmp_y = (s_data[i] * sins[i]); tmp_x = (s_data[i] * cosins[i]); vect[0] += tmp_y; vect[1] += tmp_x; s_data[i] = 0; } if (DEBUG == 1){ Serial.print("x: "); Serial.print(vect[1]); Serial.print(" | "); Serial.print("y: "); Serial.println(vect[0]); } angle = atan2(vect[0], vect[1]); angle = (angle * 4068) / 71; dist = sqrt(square(vect[0]) + square(vect[1])); //cast da 0 a 360 ;) angle = map(angle,-179,180,0,360); angle2 = angle / 2; //divido per l'spi vect[0] = 0; vect[1] = 0; } void dataConstruct(){ //WIP: need more data } <file_sep>/include/changelog.h /* * Robot 2019 - <NAME>, <NAME>, <NAME> * * 3/12/2018 * * Stesura codice Kirkhammet convertito per Teensy * * IMU funziona su I2c-Wire * Ultrasuoni funzionano con I2c Wire2 senza problemi, wire.h e affini sono * richiamati tutti da bno, daje todo: ((per farlo giocare un minimo)) * motori * spi { * controlla codice atmega ma dovrebbe adare * } * * * 4/12/2018 * * Repository GitHub, codice tutto nel main per evitare errori, da rivedere * extern (non è un grande problema, è fattibile) Da adesso il codice rimane su * platformio, tutto sincronizzato tra i vari computer. la todo rimane * invariata, come del resto tutto il codice. -<NAME> * * * 5/12/2018 * * Effettuate modifiche a repo, motori completamente funzionanti (dal punto di * vista software) Aggiunta tab pid Riformattato codice con file .h includendo * nei vari file i necessari (se chiamate da funzioni in altri file) todo: spi * (team mauri, per farlo giocare) bluetooth sensori di linea camera * * 10/12/2018 * Testate nuova scheda interfaccia Teensy-vecchio hardware con IMU e * ultrasuoni. Codice funzionante per leggere i quattro ultrasuoni assieme e * mettere i valori nell'array. -<NAME> & <NAME> * * todo: * spi (team mauri, per farlo giocare) * bluetooth * sensori di linea * camera * sistemare commenti codice Ultrasuoni * da vedere la funzione millis() invece di delay() per i print in Seriale * (millis() non blocca il codice e potrebbe aiutare i print in serial) * * * 12/12/2018 * Realizzata SPI e interfaccia con AVR644 per i sensori palla. Sistemati i * commenti e tradotti in inglese. L'uso di millis richiede scrivere delle * funzioni apposite, magari usarlo solo per i test (solo lì serve la * comunicazione seriale) * * todo: * SENSORI DI LINEA * bluetooth * camera * * - <NAME> & <NAME> * * 13/12/2018 * La repo diventa privata, il nome ufficiale è SPQR 2019. * -Test per il fetch da repo privata delle 22:18 * -Test fetch manjaro II * * 19/12/2018 * Sistemati gli #include per far funzionare goalie e pid. * Un sacco di variabili erano mancanti non importate dal codice vecchio. * Ad alcune variabili sembra che venga assegnato un valore nei tab non ancora * importati. Da sistemare * * 16/1/2019 * Due big refactor del codice, header e cpp e variabili sono ora utilizzate * bene Sistemati US e zone, ora funzionano. Da investigare i sensori di linea * TODO: * SENSORI DI LINEA * bluetooth e camera, trascurabili per ora * * 21/1/2019 - 17:30 * Prima implementazione sensori di linea. Funzionano benino ma hanno portato un * paio di bug con la palla, investighiamo * TODO: * Fixare bug palla * bluetooth e camera, trascurabili per ora * * 4/2/2019 - 16:22 * Sotto consiglio di Flavio, ora c'è solo un drivePID per loop e ogni drivePID * è stato sostituito con un'impostazione della velocità globale. Prossimo passo * cambio interrupt * * 4/2/2019 - 19:51 * Con aiuto di Flavio, nuovi interrupt migliori con trigonometria. Da ultimare * il punto di stop se la palla di trova in un certo range di sensori rispetto a * quello dove era la palla a interrupt attivato * * 6/2/2019 - 19.51 * Tentantivo di sistemazione dei sensori di linea, fallimentare(probabilmente * per il campo orribile), e di space_invaders, fallimetare Approfondire la * prossima volta ULTRASUONI O I2C ROTTI, DA VERIFICARE * * 11/2/2019 * Nuova implementazione space_invaders, da sistemare. Fixati ultrasuoni (pin * collegato male) * TODO. * PIC e Camera(finalmente funzionante) * Fixare space space_invaders col metodo della somma vettoriale * * 25/2/2019 * Ennesimo space_invaders che funziona male, da rivedere per l'ennesima volta. * Nuovo PID, modificate le variabili ed ottimizzato il codice per un PID che * "svirgoli" di meno e sia più preciso Inizio nuovo codice AVR12 (AVRupgrade) * con interpolazione a 20 sensori, da testare con SPI perché seriale non * funzionante. Iniziata nuova SPI per comunicazione con AVRupgrade, da * ultimare. Apparentemente abbiamo una seconda scheda Teensy (testata e * funzionante) su cui fare esperimenti in parallelo, da montare il robot * completp * * TODO: * Data la vicinanza della Romecup bisogna decidere ciò che è da sistemare per * la gara * * * 27/2/2019 * Decisione ruoli (vedi lavagnetta o foto su whatsapp). Goalie con palla dietro * e storcimento. Storcimento strano a sinistra, da sistemare i calcoli. * Storcimento in goalie solo a distanza ravvicinata per evitare che scodi * pesantemente Space invaders circa funzionante, è una buona base da * migliorare. Linee sistemati, gli angoli lo mettono ancora in crisi * * TODO: * Vedi lavagnetta o foto su whatsapp * * 18/3/2019 * Sistemati i robot che non riuscivano a giocare. Telecamera su robot attaccante, * da sistemare ancora un po' lo storcimento nella fascia di sinistra (Ematino). * Iniziato bluetooth tra i due robot, si connettono ma non comunicano la zona * * TODO: * Migliorare comunicazione bluetooth * Migliorare tutto finché si può * * 27/3/2019 * Menu di test da Serial Monitor, a prova di scemo (Il Test 6 non serve a un cizzo) * Miglioramenti a space invaders per non uscire dietro * Miglioramenti storcimento incrementale per attaccante * * TODO: * Migliorare tutto quel che si può * Migliorare logica comrade col bluetooth * * * * * * */ <file_sep>/src/chat.cpp #include "chat.h" #include "bluetooth.h" #include "goalie.h" #include "position.h" #include "vars.h" #include <Arduino.h> int count = 0; elapsedMillis btd; bool com(int delay) { int d; // funzione di comunicazione if (BT.available() > 0) { d = BT.read(); } if (d == 42) { comrade = true; d = 0; old_timer = millis(); btd = 0; } if ((millis() - old_timer) > delay) { old_timer = millis(); comrade = false; } if (comrade) { digitalWrite(R, HIGH); } else { digitalWrite(R, LOW); } // if (btd > 5000) { // digitalWrite(G, HIGH); // BT.print("$"); // BT.print("$"); // BT.print("$"); // } // if (btd > 5500) BT.println("K, 1"); // if(btd > 5610) { // BT.print("$"); // BT.print("$"); // BT.print("$"); // // btd = 0; // } // if(btd > 5400) BT.print("C"); return comrade; } elapsedMillis ao2 = 0; void Ao() { // if(ao2 >= 200){ // BT.write((byte) zoneIndex); // ao2 = 0; // } if (topolino < 250) { topolino++; } else { topolino = 0; BT.write(42); } } void eoooo() { int nb; if(ao2 >= 200){ if(ball_distance > 190) nb = 2; else nb = 1; BT.write(nb); ao2 = 0; } } bool tempGoalie(int delay) { int z; while(BT.available() > 0) { z = int(BT.read()); old_timer = millis(); comrade = false; if(z > 0) comrade = true; } if((millis() - old_timer) > delay) { old_timer = millis(); comrade = false; } if (comrade) { digitalWrite(Y, HIGH); digitalWrite(R, LOW); } else { digitalWrite(R, HIGH); digitalWrite(Y, LOW); } if(z == 2) { return true; } else return false; } void friendo(int delay) { int z; while(BT.available() > 0){ z = (int) (BT.read()); old_timer = millis(); comrade = false; if(z >= 0 && z <= 8){ comrade = true; friendZone = z; } } if ((millis() - old_timer) > delay) { old_timer = millis(); comrade = false; } if (comrade) { digitalWrite(Y, HIGH); digitalWrite(R, LOW); } else { digitalWrite(R, HIGH); digitalWrite(Y, LOW); } } <file_sep>/utility/kirkhammett/changelog.ino /* STORIA DELLE VERSIONI E RELATIVE MODIFICHE Versione 01 Ripulitura errori e ordinamento variabili locali/globali rispetto a sw base di Flavio Introduzione test su monitor seriale Versione 02 Modifica del modo di attivazione dei test il flag di attivazione test é solo un bool e indica se gioco normale o test i test si selezionano con un comando da tastiera il comando é un solo byte ed é indicato da un carattere da 0 a 9 e poi a,b,c ecc. Versione 03 Modificata gestione di goalie e le routine di controllo posizione in field position Versione 04 Cambiata logica di scelta zona senza la matrice di probabilita introducendo matrice 3x3 Versione 05 Fa i test anche da remoto se montata la scheda bluetooth Consente di uscire e entrare nei test senza ricaricare il programma Inverte 140 e 220 nella gestione della palla vista dai sensori 9 e 11 Versione 05c Ridotta in goalie la oscillazione quando ha la palla davanti Introdotte commentate in gestioneinterrupt le visualizzazioni del sensore di linea e della zona Introdotta commentata nel loop la visualizzazione della zona Inserita costante MOTORI per semplificare il cambio di velocita' per motori diversi Inserita define condizionata al valore di MOTORI per cambio automatico velocitá Nel caso non conosca posizione x imposta per il controllo della y i limiti di fascia (piú ampia) Cambiati i valori di DyF e DyP con valori maggiori senza sottrazione di 22 (robot) e 10 (1/2 portiere) Versione 06 La ISR memorizza la situazione dei sensori al momento dell'interrupt linea_new La ISR memorizza la situazione dei sensori al precedente interrupt linea_old Al primo interrupt (che attiva il flag_interrupt) linea_new e linea_old diventano uguali La ISR memorizza la situazione degli ultrasuoni quando scatta il primo interrupt Versione 07 Aggiunti i test d e f g La ISR conteggia gli interrupt dopo il primo mentre attivo il flag dell' interrupt La ISR memorizza le letture dei sensori di linea all'interrupt in un array Versione 07c Modificata la routine di ritorna al centro in modo da tener conto di status_x e status_y Modificata la gestione dell' interrupt in modo da tener conto di status_x e status_y Angoli di attacco definiti automaticamente per robot veloce e lento Versione 08 Modificato il test d in modo da individuare tutti i sensori attivi durante la frenata Modificata ISR senza individuazione del primo sensore Modificata gestione interrupt tenendo conto dei sensori attivati durante la frenata Versione 09 Integrata la gestione interrupt per tener conto anche della uscita con 5 sensori Integrata la gestione interrupt in modo che aggiorni le variabili status_x e status_y Modificato il ritorno verso il centro La gestione dell'interrupt n.3 impedisce di andare sulla palla che sta fuori oscurando i sensori Modificato goalie in modo che tenti di convergere verso la porta sulle fasce Versione 10 Cambio di role tramite Switch sinistro Cambio di velocità tramite switch destro Modifica funzione portiere Modifica linee : i sensori mascherati dipendono solo dai sensori di linea (provvisoriamente si sono impostate le variabili d1,d2 e d3 a 99 per disabilitare nel while il mascheramento nel sensore palla) Latino: Modifica goalie: se palla dietro con distanza 4 o 5 valuta se andare in direzione 200 (sininstra) o 160 (destra) Modificati angoli di presa palla Messa in ordine delle varie costanti per velocità e angoli palla Aumento delle velocità di 20 su VEL_RET Gestione interrupt: aumentati tempo dt di 200 Integrazione della gestione del role del robot basandosi sul suo compagno in gara tramite il bluetooth DA VERIFICARE Modificati angoli 300 e 120 in 295 e 115. Portati i simmetrici 60 a 55 240 in 235. Modificati angoli di uscita e tempi di rientro nell'interrupt. Aumentato da 15 a 25 st che va a modificare il centro in drivePID nella tab pid. Implementato il drift. Ora a OVEST corregge a 45 e a EST a 315. Tolto al momento la gestione del role tramite BT. Creata funzione menamoli. Adesso se la palla va dietro il portiere torna in porta. Quando riceve un interrupt durante menamoli, il robot torna al centro porta per evitare che esca per tentare di prendere la palla o situazioni scomode in cui l'avversario si ritorva con la porta nostra scoperta Portato st in menamoli e goalie a EST a 25 e a OVEST a 35 Modificato completamente gestione interrupt apportate modifiche al drift in goalie e menamoli. Ora menamoli torna alla porta dopo un interrupt Modificate nuovamente velocità e angoli. Velocità portate al massimo e angoli tarati come vecchi motori veloci. Creata una nuova gestione dell'interrupt che si basa solamente su sensori palla e ultrasuoni. Funziona ma da rivedere, in caso di problemi utilizzare la gestione interrupt che utilizza solo sensori linee senza mie modifiche e sperare per il meglio. Commentate le attack rotation in goalie e menamoli - vedi se gioca meglio gestione interrupt spalla e us : adesso si mascherano i due sensori precedenti e i due successivi del sensore che vede la palla, così da evitare le uscite dalle linee bloccando il robot per 2500ms in caso la veda con lo stesso sensore. MODIFICHE POST PRIMO GIORNO ROMECUP Tempo dell'interrupt portato a un secondo (1000ms) Abilitato mascheramento dei sensori nella gestione dell'interrupt MODIFICHE SECONDO GIORNO ROMECUP Modificato completamente la decisione del drift in goalie e menamoli, da verificare Modifica in space invaders: tolleranza distanze portate da 2&3 a 3&4, così quando la palla sta a centro campo il robot non rimane fermo e fa goal Adesso lo switch destro viene utilizzato per variare i tempi di attesa dopo un interrupt: se HIGH, il robot attende il movimento della palla per due secondi. Se LOW, per un solo secondo. Modifica a goalie e menamoli: ora lo storcimento avviene con i sensori 19,0 e 1. Risolto problema del mancato drift. Modificata tolleranza in gest interrupt e velocità massima di rientro MODIFICHE CAMPIDOGLIO Modificate distanze del portiere, ora segna di più. Speriamo bene.. MODIFICA IN PARTITA: aumentato storcimento di 15 gradi da entrambi i settori a nord. atk_rot rimasta invariata. ---------------------------------------------------------------- CODICE VINCENTE ITALIANO----------------------------------------------------------------------- E.Latino, M.Tannino PRO TIP: LA RAUCH HA CAMBIATO LO STORCIMENTO ORA atk_rot E' IN DISUSO SONO TORNATO FATER MATER MODIFICHE RAUCH: Ritornati ai case individuali e migliorati Introdotto 1 secondo di rallentamento dopo interrupt Rientro migliorato MODIFICHE EUROPERO (v15.3): Aumentato storcimento portiere e attaccante Cerco di non fare autogoal durante il ritorno in porta Aumentate le velocità portiere rispetto GOALIE_MIN (GOALIE_P) Ridotta a due la distanza di attacco portiere Portiere si muove solo sulla linea della porta Se la palla non si muove per 3 secondi divento "menamoli" Sostituito goalie a menamoli Tentativo bluetooth (Non riescono a mandarsi il check, soluzione: forse check hardware sul led verde del modulo) Il portiere non si incaglia sulla porta Distanza precisa della palla con distanza media degli ultimi 5 valori (ball_distance_precise) Aggiustati i rispettivi valori usando ball_distance_precise --------------------------------------------------------------- CODICE VINCENTE EUROPEO ------------------------------------------------------------------------ <NAME>, <NAME> MODIFICHE MONDIALI (versione KIRK HAMMETT) Sostituito buzzer=HIGH con tone Comunicazione tra robot attraverso bluetooth per capire se è presente o no il compagno e gestire il role Aggiunto super_mario e tab buzzer Aggiunta telecamera e migliorate tattiche generali di presa palla, controllo palla e posizionamento Aggiunte più condizioni alla fase di attacco considerando la posizione esatta del centro del blob Telecamera decentrata: se in angolo nord ovest non trova l'obiettivo, risolto tramite utilizzo ultrasuoni Unita gestione interrupt europei con gestione interrupt rauch e gestione interrupt porcata di emanuele Modificato totalmente gestione palla dietro in goalie e menamoli Aggiunte strategie con la gestione dei ruoli tramite bluetooth in space_invaders Cambio di role BT in main Diminuite velocità in danger, palla dietro e rientro del portiere causa perdita palla o uscita dal campo violenta Create le costanti per più velocità, come la velocità in danger e quelle laterali a varie distanze Unificate le modifiche in goalie in menamoli Commenti generali in goalie, menamoli, space_invaders, effettuate modiifche alla logica di space invaders per renderlo più simile a quello scritto originariamente per i nazionali Gestione palla dietro nel ritorno Aggiunta TAKE ON ME Attesa dell'interrupt portata a 800 causa attse troppo lunghe in fase di attacco Sistemate coordinate della porta con valori universali per entrambe le telecamere Tornati angoli di attacco foglio magico Robot continua l'attacco in fase di storcimento sulle linee ----FINE SVILUPPO A ROMA, CI VEDIAMO A MONTEREAL----- ***MONTREAL*** *attesa interrupt portata da 800 a 500 *portata a 140 da 120 la velocità danger *ritarati gli angoli con scelta di attacco in base alla X della porta e non più con gli ultrasuoni, funziona ma da rivedere proprio la scelta degli angoli in base all'evenenienza *integrazione modifiche goalie in menamoli */ <file_sep>/src/pid.cpp #include "goalie.h" #include "imu.h" #include "motors.h" #include "pid.h" #include "vars.h" #include <Arduino.h> // TIMED PID CONTROL TESTING void drivePID(signed int direzione, float vMot) { /* vx+ robot avanti vx- robot indietro vy+ robot sinistra vy- robot destra Il flip x-y è dovuto al passaggio dalla circonferenza goniometrica a qulella del robot, che ha lo 0 a 90° della circonferenza Il cambio di verso dell'asse y è dovuto al segno meno nella formula sotto */ vx = ((vMot * cosin[direzione])); vy = ((-vMot * sins[direzione])); if((((vy < 0 && vxn == 1) || (vy > 0 && vxp == 1) || (vx < 0 && vyp == 1) || (vx > 0 && vyn == 1)) && canUnblock) || (millis() > unlockTime + UNLOCK_THRESH)) { vxn = 0; vxp = 0; vyp = 0; vyn = 0; } if((vy > 0 && vxn == 1) || (vy < 0 && vxp == 1)) vy = 0; if((vx > 0 && vyp == 1) || (vx < 0 && vyn == 1)) vx = 0; speed1 = ((vx * sins[45] ) + (vy * cosin[45] )); speed2 = ((vx * sins[135]) + (vy * cosin[135])); speed3 = -(speed1); speed4 = -(speed2); pidfactor = updatePid(); speed1 += pidfactor; speed2 += pidfactor; speed3 += pidfactor; speed4 += pidfactor; speed1 = constrain(speed1, -255, 255); speed2 = constrain(speed2, -255, 255); speed3 = constrain(speed3, -255, 255); speed4 = constrain(speed4, -255, 255); // speed1 = (int)speed1 > 0 ? map((int)speed1, 1, 255, 35, 255) : speed1; //maggiore efficienza dei motori // speed2 = (int)speed2 > 0 ? map((int)speed2, 1, 255, 35, 255) : speed2; //maggiore efficienza dei motori // speed3 = (int)speed3 > 0 ? map((int)speed3, 1, 255, 35, 255) : speed3; //maggiore efficienza dei motori // speed4 = (int)speed4 > 0 ? map((int)speed4, 1, 255, 35, 255) : speed4; //maggiore efficienza dei motori // speed1 = (int)speed1 < 0 ? map((int)speed1, -255, -1, -255, -35) : speed1; //maggiore efficienza dei motori // speed2 = (int)speed2 < 0 ? map((int)speed2, -255, -1, -255, -35) : speed2; //maggiore efficienza dei motori // speed3 = (int)speed3 < 0 ? map((int)speed3, -255, -1, -255, -35) : speed3; //maggiore efficienza dei motori // speed4 = (int)speed4 < 0 ? map((int)speed4, -255, -1, -255, -35) : speed4; //maggiore efficienza dei motori // Send every speed to his motor mot(1, int(speed1)); mot(2, int(speed2)); mot(3, int(speed3)); mot(4, int(speed4)); prevPidDir = direzione; prevPidSpeed = vMot; } float f = 0.6; void preparePID(int direction, int speed) { preparePID(direction, speed, 0); } void preparePID(int direction, int speed, int offset) { prevPidDir = globalDir; // globalDir = direction*f + prevPidDir* (1-f); globalDir = direction; globalSpeed = speed; st = offset; while(st < -180) st += 360; while(st > 180) st -= 360; // if(bounds) st = 0; } float updatePid() { float errorP, errorD, errorI; // assumiamo che la bussola dia un intero positivo, questo lo rende da -179 a +180 float delta; // calcola l'errore di posizione rispetto allo 0 delta = imu_current_euler; if(delta > 180) delta = delta-360; delta = delta -st; // calcola correzione proporzionale errorP = KP * delta; // calcola correzione derivativa errorD = KD * (delta - errorePre); errorePre = delta; // calcola correzione integrativa integral = 0.5 * integral + delta; errorI = KI * integral; // calcota correzione complessiva return errorD + errorP + errorI; } <file_sep>/utility/kirkhammett/palladietro.ino void palla_dietro(){ if((ball_sensor==8)||(ball_sensor==9)) drivePID(135,255); if((ball_sensor==11)||(ball_sensor==12)) drivePID(225,255); } <file_sep>/utility/kirkhammett/imu.ino //initialize the imu void init_imu() { IMU.init(); return; }//-------------------------------------------------------- //reading the euler angle and checking if the imu is disconnected int read_euler() { IMU.readEul(); //initializes the readings imu_temp_euler = IMU.euler.x; //puts the current euler x angle into a temporary variable return imu_temp_euler; //if nothing happened, returns the current x angle }//-------------------------------------------------------- <file_sep>/include/camera.h void goalPosition(); int fixCamIMU(int); <file_sep>/utility/interpolazione_pic/main.c /*SENSORS INTERPOLATION FOR BALL DETECTION. ARDUINO CODE BY <NAME>, PIC PORTING by <NAME> & <NAME>*/ #include <xc.h> //#include <p18f2550.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "usart_custom.h" #pragma config OSC = HS // Oscillator Selection bits (HS oscillator) #pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled) #pragma config IESO = OFF // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled) // CONFIG2L #pragma config PWRT = ON // Power-up Timer Enable bit (PWRT enabled) #pragma config BOREN = SBORDIS // Brown-out Reset Enable bits (Brown-out Reset enabled in hardware only (SBOREN is disabled)) #pragma config BORV = 2 // Brown Out Reset Voltage bits () // CONFIG2H #pragma config WDT = OFF // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit)) #pragma config WDTPS = 32768 // Watchdog Timer Postscale Select bits (1:32768) // CONFIG3H #pragma config CCP2MX = PORTC // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1) #pragma config PBADEN = ON // PORTB A/D Enable bit (PORTB<4:0> pins are configured as analog input channels on Reset) #pragma config LPT1OSC = OFF // Low-Power Timer1 Oscillator Enable bit (Timer1 configured for higher power operation) #pragma config MCLRE = OFF // MCLR Pin Enable bit (RE3 input pin enabled; MCLR disabled) // CONFIG4L #pragma config STVREN = ON // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset) #pragma config LVP = OFF // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled) #pragma config XINST = OFF // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled (Legacy mode)) // CONFIG5L #pragma config CP0 = OFF // Code Protection bit (Block 0 (000800-001FFFh) not code-protected) #pragma config CP1 = OFF // Code Protection bit (Block 1 (002000-003FFFh) not code-protected) #pragma config CP2 = OFF // Code Protection bit (Block 2 (004000-005FFFh) not code-protected) #pragma config CP3 = OFF // Code Protection bit (Block 3 (006000-007FFFh) not code-protected) // CONFIG5H #pragma config CPB = OFF // Boot Block Code Protection bit (Boot block (000000-0007FFh) not code-protected) #pragma config CPD = OFF // Data EEPROM Code Protection bit (Data EEPROM not code-protected) // CONFIG6L #pragma config WRT0 = OFF // Write Protection bit (Block 0 (000800-001FFFh) not write-protected) #pragma config WRT1 = OFF // Write Protection bit (Block 1 (002000-003FFFh) not write-protected) #pragma config WRT2 = OFF // Write Protection bit (Block 2 (004000-005FFFh) not write-protected) #pragma config WRT3 = OFF // Write Protection bit (Block 3 (006000-007FFFh) not write-protected) // CONFIG6H #pragma config WRTC = OFF // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) not write-protected) #pragma config WRTB = OFF // Boot Block Write Protection bit (Boot block (000000-0007FFh) not write-protected) #pragma config WRTD = OFF // Data EEPROM Write Protection bit (Data EEPROM not write-protected) // CONFIG7L #pragma config EBTR0 = OFF // Table Read Protection bit (Block 0 (000800-001FFFh) not protected from table reads executed in other blocks) #pragma config EBTR1 = OFF // Table Read Protection bit (Block 1 (002000-003FFFh) not protected from table reads executed in other blocks) #pragma config EBTR2 = OFF // Table Read Protection bit (Block 2 (004000-005FFFh) not protected from table reads executed in other blocks) #pragma config EBTR3 = OFF // Table Read Protection bit (Block 3 (006000-007FFFh) not protected from table reads executed in other blocks) // CONFIG7H #pragma config EBTRB = OFF // Boot Block Table Read Protection bit (Boot block (000000-0007FFh) not protected from table reads executed in other blocks) #define TOUT 100 #define DEBUG 1 #define THRL 30 #define THRH 253 void readSensors_old(); //byte tx_data = 0; float tmp_y, tmp_x; //int pins[] = {TRISB0, TRISB1, TRISB2, TRISB3, TRISB4, TRISB5, TRISB6, TRISB7, TRISC0, TRISC1, TRISC2, TRISC3}, t; int t; float vect[2], s_data[12], dist, angle, angle2; const float sins[12] = {0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5}, cosins[12] = {1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, 0.866}; void main() { // Sets all pin of port B and C to output, except for C6, used for Serial communication TRISB = 0b11111111; //PORTB as Input TRISC = 0b10111111; //PORTC as Input RC7 = RX, RC6 = TX // nRBPU = 0; //Enables PORTB Internal Pull Up Resistors UART_Init(38400); do { //Read from sensors readSensors_old(); //Bit of delay, should not be needed __delay_ms(100); } while (1); } void readSensors_old() { //Reades from sensors and constructs the array for (int i = 0; i < 255; i++) { s_data[0] += !LATBbits.LATB0; s_data[1] += !LATBbits.LATB1; s_data[2] += !LATBbits.LATB2; s_data[3] += !LATBbits.LATB3; s_data[4] += !LATBbits.LATB4; s_data[5] += !LATBbits.LATB5; s_data[6] += !LATBbits.LATB6; s_data[7] += !LATBbits.LATB7; s_data[8] += !LATCbits.LATC0; s_data[9] += !LATCbits.LATC1; s_data[10] += !LATCbits.LATC2; s_data[11] += !LATCbits.LATC3; } //printf(""); //Calculation magic by Alessandro for (int i = 0; i < 12; i++) { //Fix some offsets if ((s_data[i] < THRL) || (s_data[i] > THRH)) { s_data[i] = 0; } //adds all the sins and cosins of each reading together tmp_y = (s_data[i] * sins[i]); tmp_x = (s_data[i] * cosins[i]); //vector construct vect[0] += tmp_y; vect[1] += tmp_x; //Reset the array index s_data[i] = 0; } angle = atan2(vect[0], vect[1]); angle = (angle * 4068) / 71; dist = sqrt((vect[0] * vect[0]) + (vect[1] * vect[1])); //cast from [-180, 180] to [0,360]. Thanks stack overflow :D angle = ((int) angle + 360) % 360; //divided for single-byte communication angle2 = angle / 2; //Resets the vector array vect[0] = 0; vect[1] = 0; } /* Slave Code #include <xc.h> #include <pic16f877a.h> #include "uart.h" // BEGIN CONFIG #pragma config FOSC = HS #pragma config WDTE = OFF #pragma config PWRTE = OFF #pragma config BOREN = ON #pragma config LVP = OFF #pragma config CPD = OFF #pragma config WRT = OFF #pragma config CP = OFF //END CONFIG void main() { TRISB = 0x00; //PORTB as Output UART_Init(9600); do { if(UART_Data_Ready()) PORTB = UART_Read(); __delay_ms(100); }while(1); } */ <file_sep>/utility/PyChat/client.py import socket import sys <<<<<<< HEAD import threading as threading ======= from thread import * def receive(): while True: try: data = s.recv(1024) print(data) except socket.error: pass >>>>>>> a638e09ed8d4ce10f7da913b2b7a89765d8816cf def receive(): try: s.listen(10) s.recv(2014) except socket.error: s.close() sys.exit(); try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print("Failed to create socket ("+socket.error+")") sys.exit() HOST = "192.168.4.1" PORT = 9999 try: s.connect((HOST, PORT)) except socket.error: print("Connessione rifiutata") sys.exit() name = input("Inserisci il tuo nickname: ") #s.sendall(str(name + ' è entrato nella chat').encode('UTF-8')) threading._start_new_thread(receive, () ) while 1: try: print(s.recv(1024).decode('UTF-8')) st = input() s.sendall(str('<' + name + '> : '+ st).encode('UTF-8')) except socket.error: print("Errore indefinito") sys.exit() <file_sep>/utility/kirkhammett/position.ino void WhereAmI() { // decide la posizione in orizzontale e verticale // Aggiorna i flag : good_field_x good_field_y non utilizzata da altre routines // goal_zone non utilizzata da altre routines // Aggiorna le variabili: // status_x (con valori CENTRO EST OVEST 255 = non lo so) // status_y (con valori CENTRO NORD SUD 255 = non lo so) int Lx_mis; // larghezza totale stimata dalle misure int Ly_mis; // lunghezza totale stimata dalle misure int Ly_min; // Limite inferiore con cui confrontare la misura y int Ly_max; // Limite inferiore con cui confrontare la misura y int Dy ; // Limite per decidere NORD SUD in funzione della posizione orizzontale old_status_x = status_x; old_status_y = status_y; good_field_x = false; // non é buona x good_field_y = false; // non é buona y goal_zone = false; // non sono davanti alla porta avversaria Lx_mis = us_dx + us_sx + robot; // larghezza totale stimata Ly_mis = us_fr + us_px + robot; // lunghezza totale stimata // controllo orizzontale if ((Lx_mis < Lx_max ) && (Lx_mis > Lx_min) && (us_dx > 25) && (us_sx > 25)) // se la misura orizzontale é accettabile { good_field_x = true; status_x = CENTRO; if (us_dx < DxF) status_x = EST; // robot é vicino al bordo destro if (us_sx < DxF) status_x = OVEST; // robot é vicino al bordo sinistro if (status_x == CENTRO) { Ly_min = LyP_min; // imposto limiti di controllo lunghezza verticale tra le porte Ly_max = LyP_max; Dy = DyP; } else { Ly_min = LyF_min; // imposto limiti di controllo lunghezza verticale in fascia Ly_max = LyF_max; Dy = DyF; } } else { // la misura non é pulita per la presenza di un ostacolo if ((us_dx >= (DxF + 10)) || (us_sx >= (DxF + 10))) // se ho abbastanza spazio a destra o a sinistra { status_x = CENTRO; // devo stare per forza al cento Ly_min = LyP_min; // imposto limiti di controllo lunghezza verticale tra le porte Ly_max = LyP_max; Dy = DyP; } else { status_x = 255; // non so la coordinata x // imposto i limiti di controllo verticale in base alla posizione orizzontale precedente if (old_status_x == CENTRO) // controlla la posizione precedente per decidere limiti di controllo y { Ly_min = LyP_min; // imposto limiti di controllo lunghezza verticale tra le porte Ly_max = LyP_max; Dy = DyP; } else { Ly_min = LyF_min; // imposto limiti di controllo lunghezza verticale in fascia anche per x incognita Ly_max = LyF_max; Dy = DyF; } } } // controllo verticale if ((Ly_mis < Ly_max ) && (Ly_mis > Ly_min)) // se la misura verticale é accettabile { good_field_y = true; status_y = CENTRO; if (us_fr < Dy) { status_y = NORD; // robot é vicino alla porta avversaria if (Dy == DyP) goal_zone = true; // davanti alla porta in zona goal } if (us_px < Dy) status_y = SUD; // robot é vicino alla propria porta } else { // la misura non é pulita per la presenza di un ostacolo status_y = 255; // non so la coordinata y if (us_fr >= (Dy + 0)) status_y = CENTRO; // ma se ho abbastanza spazio dietro o avanti if (us_px >= (Dy + 0)) status_y = CENTRO; // e'probabile che stia al centro } return; }//---------------------------------------------------------------- void cerco_zona() // restituisce in currentlocation la zona o 255 se non lo sa { if ((status_x == 255) && (status_y == 255)) { currentlocation = 255; return; // non posso stabilire la zona } if ((status_x != 255) && (status_y == 255)) // se conosco solo posizione orizzontale { for ( byte i = 0; i < 3; i++) // aumento tutta la fascia nota di fattore 2 { zone_prob[i][status_x] = zone_prob[i][status_x] + 2; } if (old_status_y != 255) // se conosco la vecchia posizione verticale { status_y = old_status_y; // prendo la y precedente } else { currentlocation = 255; return ; // non posso stabilire la zona } } if ((status_x == 255) && (status_y != 255)) // se conosco solo posizione verticale { for ( byte i = 0; i < 3; i++) // aumento tutta la fascia nota di fattore 2 { zone_prob[status_y][i] = zone_prob[status_y][i] + 2; } if ((old_status_x != 255)) // se conosco la vecchia posizione orizzontale { status_x = old_status_x; // prendo la x precedente } else { currentlocation = 255; return; // non posso stabilire la zona } } currentlocation = zone[status_y][status_x]; // estraggo codice zona return ; }//___________________________________________________________________ void update_location_complete() { old_currentlocation = currentlocation; // per usi futuri old_guessedlocation = guessedlocation; // per usi futuri WhereAmI(); //stabilisce status_x e status_y per cerco_zona() cerco_zona(); // mette in current_location la zona in cui si trova il robot o 255 se non lo sa if (currentlocation == 255) { // resolve_statistics(); // aggiorna guessedlocation zona campo dedotta dalla matrice statistica guessedlocation = old_guessedlocation; } else //current location da 1 a 9 comunque non 255 { // update_statistics(); // aggiorna la matrice statistica avendo una posizione sicura guessedlocation = currentlocation; // zona campo dedotta dalle misure effettuate } return; }//__________________________________________________________________ void ritornacentro() // lavora su guessedlocation { if (status_x == EST) { if (status_y == SUD) { drivePID(330, VEL_RET); } else if (status_y == CENTRO) { drivePID(270, VEL_RET); } else if (status_y == NORD) { drivePID(225, VEL_RET); } else { //non conosco la y recenter(1.0); } } if (status_x == OVEST) { if (status_y == SUD) { drivePID(45, VEL_RET); } else if (status_y == CENTRO) { drivePID(90, VEL_RET); } else if (status_y == NORD) { drivePID(135, VEL_RET); } else { //non conosco la y recenter(1.0); } } if (status_x == CENTRO) { if (status_y == SUD) { drivePID(0, VEL_RET); } else if (status_y == CENTRO) { recenter(1.0); } else if (status_y == NORD) { drivePID(180, VEL_RET); } else { //non conosco la y recenter(1.0); } } if (status_x == 255) { if (status_y == SUD) { drivePID(0, VEL_RET); } else if (status_y == CENTRO) { recenter(1.0); } else if (status_y == NORD) { drivePID(180, VEL_RET); } else { //non conosco la y recenter(1.0); } } return; }//______________________________________________________________ void fuga_centro() { long t0; if (status_x == 255 && status_y == 255) // non so dove sto { do { brake(); //sto fermo in attesa di conoscere la x o la y meglio se guardo anche la palla update_sensors_all(); update_location_complete(); delay(1); } while (status_x == 255 && status_y == 255); } if (status_x != 255 && status_y != 255) // conosco sia la x che la y { for (byte i = 0; i < 200; i++) { update_sensors_all(); // serve per avere imu_current_euler aggiornata e gli ultrasuoni update_location_complete(); // vede dove si trova ritornacentro(); // ritorna al centro del campo per circa 200+ ms delay(1); } } else // conosco per lo meno una coordinata { t0 = millis(); // istante inizio ricentra piano solo su una coordinata if (status_x != 255) // conosco la x { do { switch (status_x) { case EST: drivePID(270, 100); delay(10); break; case OVEST: drivePID(90, 100); delay(10); break; } update_sensors_all(); WhereAmI(); } while ((status_x != CENTRO) && ((millis() - t0) < 200) ); } else // conosco la y { do { switch (status_y) { case NORD: drivePID(180, 100); delay(10); break; case SUD: drivePID(0, 100); delay(10); break; } update_sensors_all(); WhereAmI(); } while ((status_y != CENTRO) && ((millis() - t0) < 200) ); } } return; }//______________________________________________________________ void ritornaporta(int posizione) //chiamata da gestione portiere { if (posizione == 255) { recenter(1.0); } else { switch (posizione) { case NORD_CENTRO: drivePID(180, VEL_RET); break; case NORD_EST: drivePID(210, VEL_RET); break; case NORD_OVEST: drivePID(150, VEL_RET); break; case SUD_CENTRO: recenter(1.0); break; case SUD_EST: drivePID(270, VEL_RET); break; case SUD_OVEST: drivePID(90, VEL_RET); break; case CENTRO_CENTRO: drivePID(180, VEL_RET); break; case CENTRO_EST: drivePID(270, VEL_RET); break; case CENTRO_OVEST: drivePID(90, VEL_RET); break; } } return; }//-------------------------------------------------------------- <file_sep>/utility/kirkhammett/pid.ino //TIMED PID CONTROL TESTING void drivePID(signed int direzione, float vMot) // { // mette in variabili globali direzione e velocitá precedenti e attuali old_Dir = new_Dir; new_Dir = direzione; old_vMot = new_vMot; new_vMot = vMot; speed1 = ((-(sins[((direzione - 60 ) + 360) % 360])) * vMot); //mot 1 speed2 = ((sins[(direzione + 360) % 360]) * vMot); //mot 2 speed3 = ((-(sins[(direzione + 60 ) % 360])) * vMot); //mot 3 pidfactor = updatePid(); if (reaching_ball == true) //da valutare se é opportuno { pidfactor = pidfactor * 1.2; } speed1 += pidfactor; speed2 += pidfactor; speed3 += pidfactor; CheckSpeed(); // normalizza la velocita' a 255 max al motore piu' veloce e gli altri in proporzione //Send every speed to his motor mot(2, int(speed2)); mot(1, int(speed1)); mot(3, int(speed3)); }//___________________________________________________________ float updatePid() { float errorP, errorD, errorI; float delta; // assumiamo che la bussola dia un intero positivo, questo lo rende da -179 a +180 // calcola l'errore di posizione rispetto allo 0 if (imu_current_euler < 180) delta = float(imu_current_euler); else delta = float(imu_current_euler - 360); // calcola correzione proporzionale errorP = KP * delta; // calcola correzione derivativa errorD = KD * (delta - errorePre); errorePre = delta; // calcola correzione integrativa integral = 0.5 * integral + delta; // corretta per non far divergere il contributo errorI = KI * integral; // calcota correzione complessiva return errorD + errorP + errorI; }//________________________________________________________ void CheckSpeed() { float Max, Min; if ((speed1 <= 255.0 && speed1 >= -255.0) && (speed2 <= 255.0 && speed2 >= -255.0) && (speed3 <= 255.0 && speed3 >= -255.0)) return; Max = speed1; if (speed2 > Max) Max = speed2; if (speed3 > Max) Max = speed3; Min = speed1; if (speed2 < Min) Min = speed2; if (speed3 < Min) Min = speed3; if (Max > 255.0) { Max = 255.0 / Max; speed1 = speed1 * Max; speed2 = speed2 * Max; speed3 = speed3 * Max; //speedx = 255.0 * speedx / Max; } if (Min < -255.0) { Min = -255.0 / Min; speed1 = speed1 * Min; speed2 = speed2 * Min; speed3 = speed3 * Min; //speedx = -255.0 * speedx / Min; } }//__________________________________________________________________ void recenter(float spd) //recenter the robot while being steady; spd e' sempre 1 // da chiamare in test per vedere se raddrizza { pidfactor = updatePid(); speed1 = spd * pidfactor; speed2 = spd * pidfactor; speed3 = spd * pidfactor; CheckSpeed(); //Send every speed to his motor mot(2, int(speed2)); mot(1, int(speed1)); mot(3, int(speed3)); return; }//______________________________________________________ <file_sep>/src/linesensor.cpp #include "linesensor.h" #include "goalie.h" #include "position.h" #include "pid.h" #include "motors.h" #include "music.h" #include "vars.h" #include "nano_ball.h" #include "config.h" #include <Arduino.h> int linepinsI[4] = {S1I, S2I, S3I, S4I}; int linepinsO[4] = {S1O, S2O, S3O, S4O}; int linetriggerI[4]; int linetriggerO[4]; int lineCnt; int CNTY; int CNTX; int prevDir; int ai, ar; byte linesensbyteI; byte linesensbyteO; byte linesensbyte; byte linesensbytefst; byte linesensbyteOLDY; byte linesensbyteOLDX; bool fboundsX; bool fboundsY; int outDir; int outVel; elapsedMillis ltimer; void checkLineSensors() { linesensbyteI = 0; linesensbyteO = 0; for(int i = 0; i < 4; i++) { linetriggerI[i] = analogRead(linepinsI[i]) > LINE_THRESH; linetriggerO[i] = analogRead(linepinsO[i]) > LINE_THRESH; linesensbyteI = linesensbyteI | (linetriggerI[i]<<i); linesensbyteO = linesensbyteO | (linetriggerO[i]<<i); } if ((linesensbyteI > 0) || (linesensbyteO > 0)) { vyp = 0; vyn = 0; vxp = 0; vxn = 0; if(exitTimer > EXTIME) { fboundsX = true; fboundsY = true; } exitTimer = 0; } linesensbyte |= (linesensbyteI | linesensbyteO); outOfBounds(); } void outOfBounds(){ if(fboundsX == true) { if(linesensbyte & 0x02) linesensbyteOLDX = 2; else if(linesensbyte & 0x08) linesensbyteOLDX = 8; if(linesensbyteOLDX != 0) fboundsX = false; } if(fboundsY == true) { if(linesensbyte & 0x01) linesensbyteOLDY = 1; else if(linesensbyte & 0x04) linesensbyteOLDY = 4; if(linesensbyteOLDY != 0) fboundsY = false; } if (exitTimer <= EXTIME){ //fase di rientro if(linesensbyte == 15) linesensbyte = linesensbyteOLDY | linesensbyteOLDX; //ZOZZATA MAXIMA unlockTime = millis(); if(linesensbyte == 1) outDir = 180; else if(linesensbyte == 2) outDir = 270; else if(linesensbyte == 4) outDir = 0; else if(linesensbyte == 8) outDir = 90; else if(linesensbyte == 3) outDir = 225; else if(linesensbyte == 6) outDir = 315; else if(linesensbyte == 12) outDir = 45; else if(linesensbyte == 9) outDir = 135; else if(linesensbyte == 7) outDir = 270; else if(linesensbyte == 13) outDir = 90; else if(linesensbyte == 11) outDir = 180; else if(linesensbyte == 14) outDir = 0; else if(linesensbyte == 5){ if(linesensbyteOLDX == 2) outDir = 270; else if(linesensbyteOLDY == 8) outDir = 90; } else if(linesensbyte == 10){ if(linesensbyteOLDY == 4) outDir = 0; else if(linesensbyteOLDY == 1) outDir = 180; } outVel = LINES_EXIT_SPD; preparePID(outDir, outVel, 0); keeper_backToGoalPost = true; keeper_tookTimer = true; }else{ //<NAME> if(linesensbyte == 1) vyp = 1; else if(linesensbyte == 2) vxp = 1; else if(linesensbyte == 4) vyn = 1; else if(linesensbyte == 8) vxn = 1; else if(linesensbyte == 3) { vyp = 1; vxp = 1; } else if(linesensbyte == 6){ vxp = 1; vyn = 1; } else if(linesensbyte == 12) { vyn = 1; vxn = 1; } else if(linesensbyte == 9) { vyp = 1; vxn = 1; } else if(linesensbyte == 7) { vyp = 1; vyn = 1; vxp = 1; } else if(linesensbyte == 13){ vxp = 1; vxn = 1; vyn = 1; } else if(linesensbyte == 11) { vyp = 1; vxn = 1; vxp = 1; } else if(linesensbyte == 14) { vyn = 1; vxn = 1; vxp = 1; } else if(linesensbyte == 5){ if(linesensbyteOLDX == 2) vyp = 1; else if(linesensbyteOLDY == 8)vyn = 1; } else if(linesensbyte == 10){ if(linesensbyteOLDY == 4) vyn = 1; else if(linesensbyteOLDY == 1) vyp = 1; } linesensbyte = 0; linesensbyteOLDY = 0; linesensbyteOLDX = 0; lineSensByteBak = 30; canUnblock = true; } lineSensByteBak = linesensbyte; } void testLineSensors() { checkLineSensors(); DEBUG_PRINT.println("______________"); for(int i = 0; i<4; i++) { DEBUG_PRINT.print(linetriggerI[i]); DEBUG_PRINT.print("-"); DEBUG_PRINT.print(linetriggerO[i]); DEBUG_PRINT.print(" | "); } DEBUG_PRINT.println(); DEBUG_PRINT.println("________________"); DEBUG_PRINT.println("Byte: "); DEBUG_PRINT.print(linesensbyteO); DEBUG_PRINT.print(" Direzione: "); DEBUG_PRINT.println(outDir); delay(150); DEBUG_PRINT.println("______________"); }<file_sep>/utility/SPI example/multi_byte_spi/multi_byte_spi_slave/multi_byte_spi_slave.ino #include <SPI.h> #define DISTANCE 0b00001111 #define DEGREES 0b00001010 byte c; bool bSending = false; byte bSendingByte; void setup() { Serial.begin(9600); //THIS REGISTER IS ATMEGA-328P SPECIFIC SPCR |= bit (SPE); pinMode(MISO, OUTPUT); SPI.attachInterrupt(); } //REMOVED SERIAL PRINT TO SPEED UP ISR (SPI_STC_vect) { //the bool defines whether the slave is sending or not. //It's assumed by both master and slave that the first communication is from master to slave if(bSending) { //THOSE REGISTERS ARE ATMEGA-328P SPECIFIC //sends the previously prepared byte to the master SPCR = 64 & 127; // disble interrupt SPDR= bSendingByte; SPCR = 64 |128; // enable interrupt }else{ //prepares output for next time it's asked, based on the received byte switch(SPDR) { case DISTANCE: bSendingByte = 0b00111111; bSending = !bSending; break; case DEGREES: bSendingByte = 0b11100011; bSending = !bSending; break; default: break; } //sets SPDR (SPI byte) to be send next time SPDR = bSendingByte; } } void loop() { } <file_sep>/include/music.h //Costanti note, frequenza #define C0 16.35 #define Db0 17.32 #define D0 18.35 #define Eb0 19.45 #define E0 20.60 #define F0 21.83 #define Gb0 23.12 #define G0 24.50 #define Ab0 25.96 #define LA0 27.50 #define Bb0 29.14 //#define B0 30.87 #define C1 32.70 #define Db1 34.65 #define D1 36.71 #define Eb1 38.89 #define E1 41.20 #define F1 43.65 #define Gb1 46.25 #define G1 49.00 #define Ab1 51.91 #define LA1 55.00 #define Bb1 58.27 #define B1 61.74 #define C2 65.41 #define Db2 69.30 #define D2 73.42 #define Eb2 77.78 #define E2 82.41 #define F2 87.31 #define Gb2 92.50 #define G2 98.00 #define Ab2 103.83 #define LA2 110.00 #define Bb2 116.54 #define B2 123.47 #define C3 130.81 #define Db3 138.59 #define D3 146.83 #define Eb3 155.56 #define E3 164.81 #define F3 174.61 #define Gb3 185.00 #define G3 196.00 #define Ab3 207.65 #define LA3 220.00 #define Bb3 233.08 #define B3 246.94 #define C4 261.63 #define Db4 277.18 #define D4 293.66 #define Eb4 311.13 #define E4 329.63 #define F4 349.23 #define Gb4 369.99 #define G4 392.00 #define Ab4 415.30 #define LA4 440.00 #define Bb4 466.16 #define B4 493.88 #define C5 523.25 #define Db5 554.37 #define D5 587.33 #define Eb5 622.25 #define E5 659.26 #define F5 698.46 #define Gb5 739.99 #define G5 783.99 #define Ab5 830.61 #define LA5 850.00 #define Bb5 932.33 #define B5 987.77 #define C6 1046.50 #define Db6 1108.73 #define D6 1174.66 #define Eb6 1244.51 #define E6 1318.51 #define F6 1396.91 #define Gb6 1479.98 #define G6 1567.98 #define Ab6 1661.22 #define LA6 1760.00 #define Bb6 1864.66 #define B6 1975.53 #define C7 2093.00 #define Db7 2217.46 #define D7 2349.32 #define Eb7 2489.02 #define E7 2637.02 #define F7 2793.83 #define Gb7 2959.96 #define G7 3135.96 #define Ab7 3322.44 #define LA7 3520.01 #define Bb7 3729.31 #define B7 3951.07 #define C8 4186.01 #define Db8 4434.92 #define D8 4698.64 #define Eb8 4978.03 //Costanti durata note #define BPM 120 #define H 2*Q //half 2/4 #define Q 60000/BPM //quarter 1/4 #define E Q/2 //eighth 1/8 #define S Q/4 //sixteenth 1/16 #define W 4*Q //whole 4/4 #define buzzer 30 void imperial_march(); void super_mario(); void startSetup(); void stopSetup(); void miiChannel(); <file_sep>/utility/us_scan_test_reprogram/us_scan_test_reprogram.ino #include <Wire.h> void setup() { Serial.begin(9600); Wire.begin(); } void loop() { char a = 0; do { Serial.println("What to do?\n\t1) Scan for i2C devices\n\t2) Change US address\n\t3) Test US measures\nRemember to put the newline mode in \"no line ending\""); while (Serial.available() <= 0); while (Serial.available() > 0) a = (char) Serial.read(); } while (a != '1' && a != '2' && a != '3'); switch (a) { case '1': scanI2C(); break; case '2': changeAddressCLI(); break; case '3': readUSCLI(); break; } } void scanI2C() { byte error, address; int nDevices; Serial.println("Scanning..."); nDevices = 0; for (address = 1; address < 127; address++ ) { // The i2c_scanner uses the return value of // the Write.e ndTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address < 16) Serial.print("0"); Serial.print(address, HEX); Serial.println(" !"); Serial.print("I2C device found at address :"); Serial.print(address, DEC); Serial.println(" !"); nDevices++; } else if (error == 4) { Serial.print("Unknown error at address 0x"); if (address < 16) Serial.print("0"); Serial.println(address, HEX); } } if (nDevices == 0) Serial.println("No I2C devices found\n"); else Serial.println("done\n"); } void readUS(int address) { Serial.print("Measuring address "); Serial.print(address); Serial.println(" send any key to stop measuring"); while(Serial.available() <= 0) { int reading = 0; // step 1: instruct sensor to read echoes Wire.beginTransmission(address); Wire.write(byte(0x00)); Wire.write(byte(0x51)); Wire.endTransmission(); // step 2: wait for readings to happen delay(70); // step 3: instruct sensor to return a particular echo reading Wire.beginTransmission(address); Wire.write(byte(0x02)); Wire.endTransmission(); // step 4: request reading from sensor Wire.requestFrom(address, 2); // step 5: receive reading from sensor if (2 <= Wire.available()) { reading = Wire.read(); reading = reading << 8; reading |= Wire.read(); Serial.println(reading); } delay(50); } while(Serial.available() > 0) Serial.read(); } void readUSCLI() { Serial.println("Testing US measurement"); char a = 0; do { Serial.println("Please input the US address from the menu below\n\t1) 112\n\t2) 113\n\t3) 114\n\t4) 115"); while (Serial.available() <= 0); while (Serial.available() > 0) a = (char) Serial.read(); } while (a != '1' && a != '2' && a != '3' && a != '4'); switch (a) { case '1': readUS(112); break; case '2': readUS(113); break; case '3': readUS(114); break; case '4': readUS(115); break; } } void changeAddressCLI() { Serial.println("Changing US i2C address"); char a = 0; char b = 0; byte add1 = 0; byte add2 = 0; do { Serial.println("Please input the current US address from the menu below\n\t1) 112\n\t2) 113\n\t3) 114\n\t4) 115"); while (Serial.available() <= 0); while (Serial.available() > 0) a = (char) Serial.read(); } while (a != '1' && a != '2' && a != '3' && a != '4'); do { Serial.println("Please input the current US address from the menu below\n\t1) 112\n\t2) 113\n\t3) 114\n\t4) 115"); while (Serial.available() <= 0); while (Serial.available() > 0) b = (char) Serial.read(); } while (b != '1' && b != '2' && b != '3' && b != '4'); switch (a) { case '1': add1 = (112); break; case '2': add1 = (113); break; case '3': add1 = (114); break; case '4': add1 = (115); break; } switch (b) { case '1': add2 = (224); break; case '2': add2 = (226); break; case '3': add2 = (228); break; case '4': add2 = (230); break; } changeAddress(add1, add2); } // The following code changes the address of a Devantech Ultrasonic Range Finder (SRF10 or SRF08) // usage: changeAddress(0x70, 0xE6); void changeAddress(byte oldAddress, byte newAddress) { Wire.beginTransmission(oldAddress); Wire.write(byte(0x00)); Wire.write(byte(0xA0)); Wire.endTransmission(); Wire.beginTransmission(oldAddress); Wire.write(byte(0x00)); Wire.write(byte(0xAA)); Wire.endTransmission(); Wire.beginTransmission(oldAddress); Wire.write(byte(0x00)); Wire.write(byte(0xA5)); Wire.endTransmission(); Wire.beginTransmission(oldAddress); Wire.write(byte(0x00)); Wire.write(newAddress); Wire.endTransmission(); Serial.print("Changed address! From "); Serial.print(oldAddress); Serial.print(" to "); Serial.println(newAddress / 2); } <file_sep>/utility/test_ir_v2/test_ir_v2_spi.ino /* test_ir_v2.ino This code takes data from 12 IR sensors in a circle 30 deg apart from each other, than converts the data into a byte, containing the direction of the ball in degrees and its distance, that is then transferred to the main control via serial communication. This code is to be used only on the ATMEGA328P and equivalents and it is meant for the ball recognition part of the SPQR robotics team robots. Created by: <NAME> Day 6/12/2018 (DD/MM/YY) Modified by: <NAME> Day 19/12/2018 Modified by: <NAME>, <NAME> & <NAME> Day 9/1/2018 Added SPI control, with map from -180, 180 to 0,360 */ #include <math.h> #include <SPI.h> #define TOUT 100 #define DEBUG 1 #define THRL 30 #define THRH 253 #define DISTANCE 0b00001111 #define DEGREES 0b00001010 bool bSending = false; byte bSendingByte; byte tx_data = 0; float tmp_y, tmp_x; int pins[] = {A0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1}, t; float vect[2], s_data[12], dist, angle, angle2; const float sins[12] = {0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5}, cosins[12] = {1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, 0.866}; void setup(){ Serial.begin(9600); //THIS REGISTER IS ATMEGA-328P SPECIFIC SPCR |= bit (SPE); pinMode(MISO, OUTPUT); SPI.attachInterrupt(); for (byte x = 0; x < 12; x++) pinMode(pins[x], INPUT); } ISR (SPI_STC_vect) { //the bool defines whether the slave is sending or not. //It's assumed by both master and slave that the first communication is from master to slave if(bSending) { //THOSE REGISTERS ARE ATMEGA-328P SPECIFIC //sends the previously prepared byte to the master SPCR = 64 & 127; // disble interrupt SPDR= bSendingByte; SPCR = 64 |128; // enable interrupt }else{ //prepares output for next time it's asked, based on the received byte switch(SPDR) { case DISTANCE: bSendingByte = dist; bSending = !bSending; break; case DEGREES: bSendingByte = angle2; bSending = !bSending; break; default: break; } //sets SPDR (SPI byte) to be send next time SPDR = bSendingByte; } } void loop() { t = millis(); readSensors_old(); // print unmodiefied values for debug if (DEBUG == 1){ Serial.println("-----------"); Serial.println(angle); Serial.println(dist); Serial.println("-----------"); } t = millis() - t; if (DEBUG == 11) Serial.println(t); dataConstruct(); //Serial.println(tx_data); if (DEBUG == 1) delay(1000); } void readSensors_old(){ for (int i = 0; i < 255; i++){ s_data[0] += !digitalRead(pins[0]); s_data[1] += !digitalRead(pins[1]); s_data[2] += !digitalRead(pins[2]); s_data[3] += !digitalRead(pins[3]); s_data[4] += !digitalRead(pins[4]); s_data[5] += !digitalRead(pins[5]); s_data[6] += !digitalRead(pins[6]); s_data[7] += !digitalRead(pins[7]); s_data[8] += !digitalRead(pins[8]); s_data[9] += !digitalRead(pins[9]); s_data[10] += !digitalRead(pins[10]); s_data[11] += !digitalRead(pins[11]); } for (byte i = 0; i < 12; i++){ if ((s_data[i] < THRL) || (s_data[i] > THRH)){ s_data[i] = 0; } if ((DEBUG == 1) && (s_data[i] != 0)){ Serial.print(i); Serial.print(" | "); Serial.println(s_data[i]); } tmp_y = (s_data[i] * sins[i]); tmp_x = (s_data[i] * cosins[i]); vect[0] += tmp_y; vect[1] += tmp_x; s_data[i] = 0; } if (DEBUG == 1){ Serial.print("x: "); Serial.print(vect[1]); Serial.print(" | "); Serial.print("y: "); Serial.println(vect[0]); } angle = atan2(vect[0], vect[1]); angle = (angle * 4068) / 71; dist = sqrt(square(vect[0]) + square(vect[1])); //cast da 0 a 360 ;) angle = map(angle,-179,180,0,360); angle2 = angle / 2; //divido per l'spi vect[0] = 0; vect[1] = 0; } void dataConstruct(){ //WIP: need more data } <file_sep>/include/nano_ball.h void readBallNano(); void testBallNano(); bool inAngle(int, int, int); int diff(int, int);<file_sep>/utility/OpenMV/main.py # color tracking - By: paolix - ven mag 18 2018 # Automatic RGB565 Color Tracking Example # import sensor, image, time, pyb, math from pyb import UART uart = UART(3,19200, timeout_char = 1000) # LED Setup ################################################################## red_led = pyb.LED(1) green_led = pyb.LED(2) blue_led = pyb.LED(3) red_led.off() green_led.off() blue_led.on() ############################################################################## #thresholds = [ (30, 100, 15, 127, 15, 127), # generic_red_thresholds # (30, 100, -64, -8, -32, 32), # generic_green_thresholds # (0, 15, 0, 40, -80, -20)] # generic_blue_thresholds #thresholds = [ (54, 93, -10, 25, 55, 70), # thresholds yellow goal # (30, 45, 1, 40, -60, -19)] # thresholds blue goal # thresholds = [ (69, 99, -23, 17, 29, 101), # thresholds yellow goal (26, 65, -11, 47, -95, -36)] # thresholds blue goal (6, 31, -15, 4, -35, 0) roi = (0, 6, 318, 152) # Camera Setup ############################################################### '''sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time = 2000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking sensor.set_auto_exposure(False, 10000) #sensor.set_backlight(1) #sensor.set_brightness(+2) #sensor.set_windowing(roi) clock = time.clock()''' sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.set_contrast(+0) sensor.set_saturation(+3) sensor.set_brightness(+0) sensor.set_quality(0) sensor.set_auto_exposure(False, 8000) sensor.set_auto_gain(True) sensor.skip_frames(time = 300) clock = time.clock() ############################################################################## # [] list # () tupla while(True): clock.tick() blue_led.off() tt_yellow = [(0,999,0,1)] ## creo una lista di tuple per il giallo, valore x = 999 : non trovata tt_blue = [(0,999,0,2)] ## creo una lista di tuple per il blue, valore x = 999 : non trovata img = sensor.snapshot() for blob in img.find_blobs(thresholds, pixels_threshold=300, area_threshold=700, merge = True): img.draw_rectangle(blob.rect()) img.draw_cross(blob.cx(), blob.cy()) if (blob.code() == 1): tt_yellow = tt_yellow + [ (blob.area(),blob.cx(),blob.cy(),blob.code() ) ] if (blob.code() == 2): tt_blue = tt_blue + [ (blob.area(),blob.cx(),blob.cy(),blob.code() ) ] tt_yellow.sort(key=lambda tup: tup[0]) ## ordino le liste tt_blue.sort(key=lambda tup: tup[0]) ## ordino le liste ny = len(tt_yellow) nb = len(tt_blue) xY = 160 yY = 240 xB = 160 yB = 240 area,cx,cy,code = tt_yellow[ny-1] # coordinata x del piu' grande y se montata al contrario #Y = ((90 - (int((math.atan2(cy - yY, cx - xY))* 180 / math.pi))) * -1) #print(cy - yY,cx-xY) Y = int(-90-(math.atan2(cy-yY, cx-xY) * 180 / math.pi)) #print(Y) string_yellow = "Y"+str(Y)+"y" #string_yellow = str(cx) + " - " + str(cy); #for c in range( 0, ny): # print (tt_yellow[c]) area,cx,cy,code = tt_blue[nb-1] # coordinata x del piu' grande y se montata al contrario B = int(-90-(math.atan2(cy-yB, cx-xB) * 180 / math.pi)) #print(B) string_blue = "B"+str(B)+"b" uart.write(string_yellow) # scrivo su seriale uart.write(string_blue) # scrivo su seriale #print (string_yellow) # test on serial terminal #print (string_blue) # test on serial terminal #print ("..................................") print(clock.fps()) <file_sep>/src/main.cpp // Here to correctly init vars.h, do not remove #define MAIN #include "Wire.h" #include <Arduino.h> #include "bluetooth.h" #include "camera.h" #include "chat.h" #include "goalie.h" #include "imu.h" #include "linesensor.h" #include "motors.h" #include "music.h" #include "nano_ball.h" #include "pid.h" #include "position.h" #include "test.h" #include "keeper.h" #include "us.h" #include "vars.h" #include "config.h" // Switch management vars int SWS = 0; int SWD = 0; elapsedMillis timertest; int aiut = 0; void setup() { startSetup(); initVars(); // ;) analogWriteFrequency(2 , 15000); analogWriteFrequency(5 , 15000); analogWriteFrequency(6, 15000); analogWriteFrequency(23, 15000); // disable those pins, damaged teensy pinMode(A8, INPUT_DISABLE); // pin A8 in corto tra 3.3V e massa pinMode(16, INPUT_DISABLE); // pin 16 in corto tra 3.3V e massa pinMode(R, OUTPUT); pinMode(G, OUTPUT); pinMode(Y, OUTPUT); pinMode(SWITCH_DX, INPUT); pinMode(SWITCH_SX, INPUT); // Enable Serial for test Serial.begin(9600); // Enable Serial4 for the slave NANO_BALL.begin(57600); // Enable Serial2 for the camera CAMERA.begin(19200); // Misc inits initIMU(); initMotorsGPIO(); initUS(); initSinCos(); initBluetooth(); timertest = 0; delay(400); stopSetup(); } void loop() { role = digitalRead(SWITCH_DX); //se HIGH sono attaccante goal_orientation = digitalRead(SWITCH_SX); //se HIGH attacco gialla, difendo blu if(DEBUG_PRINT.available() > 0) testMenu(); readIMU(); readUS(); readBallNano(); goalPosition(); if(cameraReady == 1) { storcimentoPorta(); calcPhyZoneCam = true; cameraReady = 0; } calculateLogicZone(); comrade = true; if(comrade) { if(ball_seen){ if(role) goalie(); else keeper(); } else { if(role) preparePID(0,0,0); else centerGoalPostCamera(true); } }else{ if(ball_seen) keeper(); else centerGoalPostCamera(true); } //Modify the speed BEFORE the line sensors checking (lines need to go to max speed possible) // globalSpeed *= GLOBAL_SPD_MULT; globalSpeed *= GLOBAL_SPD_MULT; // AAANGOLO(); checkLineSensors(); //Last thing in loop, for priority drivePID(globalDir, globalSpeed); } //SQUARE TO TEST MOVEMENTS // if(timertest >= 0 && timertest < 1000) drivePID(0, 250); // else if(timertest >= 1000 && timertest < 2000) drivePID(90, 250); // else if(timertest >= 2000 && timertest < 3000) drivePID(180, 250); // else if(timertest >= 3000 && timertest < 4000) drivePID(270, 250); // else timertest = 0; <file_sep>/include/goalie.h void goalie(); void palla_dietro(); void palla_dietroP(); void storcimentoPorta(); void storcimentoPorta2(); void storcimentoZone(); void storcimentoPortaIncr(); void leaveMeAlone(); void ballBack(); <file_sep>/utility/kirkhammett/linesensors.ino void init_linesensors() { pinMode(A8, INPUT); pinMode(A9, INPUT); pinMode(A10, INPUT); pinMode(A11, INPUT); pinMode(A12, INPUT); pinMode(A13, INPUT); ADMUX = 7; //imposto che solo i pin dal A0:A7 siano collegati al comparatore sei();//abilita l'interrupt PCICR = 4; //imposto che i pin PCINT 16:23 (PCINT2) possono chiamare interrupt >> PCICR Pin Change Interrupt Control Register PCMSK2 = 0x3F; // solo i primi 6, fino a PCINT21 possono chiamare interrupt return; }//---------------------------------------------------- ISR(PCINT2_vect) { byte lettura; brakeI(); lettura = PINK & 63; // legge i sei sensori di linea al volo prima che cambino if (flag_interrupt == true) // se é giá attivo un interrupt aggiorna solo le variabili di stato sensori { Nint++; // aumenta il contatore degli interrupt linea[Nint] = lettura; // memorizza tutte le lettura successive return; } /* if ((lettura & S1) == 0) linesensor = 1; if ((lettura & S2) == 0) linesensor = 2; if ((lettura & S3) == 0) linesensor = 3; if ((lettura & S4) == 0) linesensor = 4; if ((lettura & S5) == 0) linesensor = 5; if ((lettura & S6) == 0) linesensor = 6; */ Nint = 1; // il primo interrupt ad essere servito linea[Nint] = lettura; // memorizza la prima lettura flag_interrupt = true; /* ISx = us_sx; // copia il valore degli ultrasuoni al momento del primo interrupt IDx = us_dx; IPx = us_px; IFr = us_fr; */ return; }//---------------------------------------------------- <file_sep>/src/bluetooth.cpp #include "bluetooth.h" #include "vars.h" // init bluetooth on Serial1, look in vars.h for define void initBluetooth() { BT.begin(115200); connectBT(); } void connectBT(){ BT.print("$"); // Print three times individually BT.print("$"); BT.print("$"); delay(100); BT.println("C"); } bool b = false; void reconnectBT(){ //tries to reconnect when he detects he has no comrade if(!comrade){ if(!b){ BT.print("$"); // Print three times individually BT.print("$"); BT.print("$"); }else{ BT.println("C"); } b = !b; }else{ //otherwhise exits command mode BT.println("---"); } } // prints the serial read to bluetooth and bluetooth to serial monitor void testBluetooth() { if (BT.available()) { Serial.println((char)BT.read()); } if (Serial.available()) { BT.write((char)Serial.read()); } } // Code to fix when we'll have two robots /* void btZone () { update_sensors_all(); WhereAmI(); guessZone(); if(millis() - ao >= 100){ Serial.println("------"); for(int i = 0; i < 4; i++){ Serial.print("US: "); Serial.print(us_values[i]); Serial.print(" | "); } Serial.println(); testPosition(); testGuessZone(); Serial.println("------"); ao = millis(); } }*/ <file_sep>/src/nano_ball.cpp #include <Arduino.h> #include "vars.h" #include "nano_ball.h" byte ballReadNano; void readBallNano() { while(NANO_BALL.available() > 0) { ballReadNano = NANO_BALL.read(); if((ballReadNano & 0x01) == 1){ ball_distance = ballReadNano; ball_seen = ball_distance > 1; }else{ ball_degrees = ballReadNano * 2; } /*ball_sensor = (ballReadNano & 0b00011111); ball_distance = ballReadNano >> 5; ball_seen = ball_distance != 5;*/ } } void testBallNano() { readBallNano(); if(ball_seen){ //DEBUG_PRINT.print(ball_sensor); DEBUG_PRINT.print(ball_degrees); DEBUG_PRINT.print(" | "); DEBUG_PRINT.println(ball_distance); }else{ DEBUG_PRINT.println("Not seeing ball"); } delay(100); } bool inAngle(int reachAngle, int startAngle, int range){ return diff(reachAngle, startAngle) <= range; } int diff(int a, int b){ int diffB = abs(min(a, b) - max(a, b)); int diffB1 = 360-diffB; int diff = min(diffB, diffB1); return diff; }<file_sep>/utility/kirkhammett/motors.ino //Motor pins initialization void init_gpio_motors() { pinMode(PWM_MOT [1] , OUTPUT); pinMode(INA_MOT [1] , OUTPUT); pinMode(INB_MOT [1] , OUTPUT); pinMode(PWM_MOT [2] , OUTPUT); pinMode(INA_MOT [2] , OUTPUT); pinMode(INB_MOT [2] , OUTPUT); pinMode(PWM_MOT [3] , OUTPUT); pinMode(INA_MOT [3] , OUTPUT); pinMode(INB_MOT [3] , OUTPUT); return; }//---------------------------------------------------------- //brake all the motors void brake() { digitalWrite(INA_MOT[1], 1); digitalWrite(INB_MOT[1], 1); digitalWrite(INA_MOT[2], 1); digitalWrite(INB_MOT[2], 1); digitalWrite(INA_MOT[3], 1); digitalWrite(INB_MOT[3], 1); analogWrite (PWM_MOT[1], 255); analogWrite (PWM_MOT[2], 255); analogWrite (PWM_MOT[3], 255); return; }//---------------------------------------------------------- void brakeI() // chiamato solo da dentro l'interrupt { digitalWrite(INA_MOT[1], 1); digitalWrite(INB_MOT[1], 1); digitalWrite(INA_MOT[2], 1); digitalWrite(INB_MOT[2], 1); digitalWrite(INA_MOT[3], 1); digitalWrite(INB_MOT[3], 1); analogWrite (PWM_MOT[1], 255); analogWrite (PWM_MOT[2], 255); analogWrite (PWM_MOT[3], 255); return; }//---------------------------------------------------------- float torad(float deg) //conversione da gradi a radianti { return (deg * PI / 180.0); }//_________________________________________________________ void init_omnidirectional_sins() // calcola i seni degli angoli interi da 0..359 { for (int i = 0; i < 360; i++) { sins[i] = sin(torad(i)); } }//_________________________________________________________ //Function to send the speed to the motor void mot (byte mot, int vel) { byte VAL_INA, VAL_INB; if (vel == 0) //no brake ma motore inerte corto a massa e vel=0 contro freno dove corto a VCC e vel=max { VAL_INA = 0; VAL_INB = 0; } else if (vel > 0) //clockwise { VAL_INA = 1; VAL_INB = 0; } else if (vel < 0) //counterclockwise { VAL_INA = 0; VAL_INB = 1; vel = -vel; } digitalWrite(INA_MOT[mot], VAL_INA); digitalWrite(INB_MOT[mot], VAL_INB); analogWrite (PWM_MOT[mot], vel); return; }//____________________________________________________________ <file_sep>/include/pid.h void CheckSpeed(); float updatePid(); void recenter(float); void drivePID(signed int, float); void preparePID(signed int, int); void preparePID(signed int, int, int); <file_sep>/include/bluetooth.h void initBluetooth(); void testBluetooth(); void connectBT(); void reconnectBT();<file_sep>/utility/kirkhammett/libraries/pcint.h /******************** <NAME> - <EMAIL>(<EMAIL> adapted from: http://playground.arduino.cc/Main/PcInt with many changes to make it compatible with arduino boards (original worked on Uno) not tested on many boards but has the code uses arduino macros for pin mappings it should be more compatible and also more easy to extend some boards migh need pcintPinMap definition Sept. 2014 small changes to existing PCINT library, supporting an optional cargo parameter Nov.2014 large changes - Use arduino standard macros for PCINT mapping instead of specific map math, broaden compatibility - array[a][b] is 17% faster than array[(a<<3)+b], same memory - reverse pin mappings for pin change check (not on arduino env. AFAIK) **/ #ifndef ARDUINO_PCINT_MANAGER #define ARDUINO_PCINT_MANAGER #if ARDUINO < 100 #include <WProgram.h> #else #include <Arduino.h> #endif #include "pins_arduino.h" typedef void (*voidFuncPtr)(void); #define HANDLER_TYPE mixHandler /*#if (defined (_mk20dx128_h_) || defined (__MK20DX128__)) && defined (CORE_TEENSY) #define RSITE_TEENSY3 #endif defined(RSITE_TEENSY3) || defined(ARDUINO_SAM_DUE)*/ #if defined(__arm__) #warning Compiling for arm #define PCINT_NO_MAPS #endif #ifndef PCINT_NO_MAPS // PCINT reverse map // because some avr's (like 2560) have a messed map we got to have this detailed pin reverse map // still this makes the PCINT automatization very slow, risking interrupt collision #if defined(digital_pin_to_pcint) #define digitalPinFromPCINTSlot(slot,bit) pgm_read_byte(digital_pin_to_pcint+(((slot)<<3)+(bit))) #define pcintPinMapBank(slot) ((uint8_t*)((uint8_t*)digital_pin_to_pcint+((slot)<<3))) #else #warning using maps! #if ( defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega16u4__) ) //UNO const uint8_t pcintPinMap[3][8] PROGMEM={{8,9,10,11,12,13,-1,-1},{14,15,16,17,18,19,20,21},{0,1,2,3,4,5,6,7}}; #elif ( defined(__AVR_ATmega2560__) ) const uint8_t pcintPinMap[3][8] PROGMEM={{53,52,51,50,10,11,12,13},{0,15,14,-1,-1,-1,-1,-1},{A8,A9,A10,A11,A12,A13,A14,A15}}; #elif ( defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega644__)) #error "uC PCINT REVERSE MAP IS NOT DEFINED, ATmega1284P variant unknown" //run the mkPCIntMap example to obtain a map for your board! #else #warning "uC PCINT REVERSE MAP IS NOT DEFINED" //run the mkPCIntMap example to obtain a map for your board! #endif #define digitalPinFromPCINTSlot(slot,bit) pgm_read_byte(pcintPinMap+(((slot)<<3)+(bit))) #define pcintPinMapBank(slot) ((uint8_t*)((uint8_t*)pcintPinMap+((slot)<<3))) #endif #define digitalPinFromPCINTBank(bank,bit) pgm_read_byte((uint8_t*)bank+bit) #endif //this handler can be used instead of any void(*)() and optionally it can have an associated void * //and use it to call void(*)(void* payload) struct mixHandler { union { void (*voidFunc)(void); void (*payloadFunc)(void*); } handler; void *payload; inline mixHandler():payload(NULL) {handler.voidFunc=NULL;} inline mixHandler(void (*f)(void)):payload(NULL) {handler.voidFunc=f;} inline mixHandler(void (*f)(void*),void *payload):payload(payload) {handler.payloadFunc=f;} inline void operator()() {payload?handler.payloadFunc(payload):handler.voidFunc();} inline bool operator==(void*ptr) {return handler.voidFunc==ptr;} inline bool operator!=(void*ptr) {return handler.voidFunc!=ptr;} }; #ifdef PCINT_NO_MAPS extern HANDLER_TYPE PCintFunc[NUM_DIGITAL_PINS]; template<uint8_t N> void PCint() {PCintFunc[N]();} #else void PCattachInterrupt(uint8_t pin,HANDLER_TYPE userFunc, uint8_t mode); void PCdetachInterrupt(uint8_t pin); // common code for isr handler. "port" is the PCINT number. // there isn't really a good way to back-map ports and masks to pins. // here we consider only the first change found ignoring subsequent, assuming no interrupt cascade static void PCint(uint8_t port); #endif /* * attach an interrupt to a specific pin using pin change interrupts. */ template<uint8_t PIN> void PCattachInterrupt(HANDLER_TYPE userFunc, uint8_t mode) { #ifdef PCINT_NO_MAPS attachInterrupt(digitalPinToInterrupt(PIN),PCint<PIN>,mode); #else PCattachInterrupt(PIN,userFunc,mode); #endif } template<uint8_t PIN> void PCdetachInterrupt() { #ifdef PCINT_NO_MAPS detachInterrupt(PIN); #else PCdetachInterrupt(PIN); #endif } #endif <file_sep>/utility/bluetooth/bluesmirf-rn42/bluesmirf-rn42.ino /* Example Bluetooth Serial Passthrough Sketch by: <NAME> SparkFun Electronics date: February 26, 2013 license: Public domain This example sketch converts an RN-42 bluetooth module to communicate at 9600 bps (from 115200), and passes any serial data between Serial Monitor and bluetooth module. */ #include <SoftwareSerial.h> int bluetoothTx = 2; // TX-O pin of bluetooth mate, Arduino D2 int bluetoothRx = 3; // RX-I pin of bluetooth mate, Arduino D3 //SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); <<<<<<< HEAD ======= #define bluetooth Serial3 >>>>>>> 5c0171dd181357ae6f20ec98cb5c060f067c30fc #define bluetooth Serial3 void setup() { Serial.begin(9600); // Begin the serial monitor at 9600bps <<<<<<< HEAD bluetooth.begin(9600); // Start bluetooth serial at 9600 ======= bluetooth.begin(9600); >>>>>>> 5c0171dd181357ae6f20ec98cb5c060f067c30fc } void read() { while (bluetooth.available()) { // Send any characters the bluetooth prints to the serial monitor Serial.print((char)bluetooth.read()); delay(50); } } void write() { while (Serial.available()) { // Send any characters the Serial monitor prints to the bluetooth bluetooth.print((char)Serial.read()); delay(50); } // and loop forever and ever! } void loop() { read(); write(); } <file_sep>/include/us.h void testUS(); void us_receive(); void us_trigger(); void us_scheduling(); void us_receive(); void readUS(); void initUS(); <file_sep>/utility/SPI example/multi_byte_spi/multi_byte_spi_master/multi_byte_spi_master.ino #include <SPI.h> #define DISTANCE 0b00001111 #define DEGREES 0b00001010 #define SPI_DELAY 1 #define SS 10 SPISettings settings(100000, MSBFIRST, SPI_MODE0); byte mess; //REMOVED SERIAL PRINT TO SPEED UP void setup (void) { //10 is the SS pin. Not the Gestapo one Serial.begin(9600); pinMode(SS, OUTPUT); digitalWrite(SS, HIGH); // ensure 10 stays high for now // Put SCK, MOSI, 10 pins into output mode // also put SCK, MOSI into LOW state, and 10 into HIGH state. // Then put SPI hardware into Master mode and turn SPI on SPI.begin (); // Slow down the master a bit SPI.setClockDivider(SPI_CLOCK_DIV8); } // end of setup void loop (void) { /**THIS PART COULD BE REFACTORED INTO A NICER THING, BUT IT'S JUST FOR EXAMPLE**/ //Sends a byte to the slave. The slave now prepares the response byte (The slave knows what to do) SPI.beginTransaction(settings); digitalWrite(SS, LOW); SPI.transfer(DISTANCE); digitalWrite(SS, HIGH); SPI.endTransaction(); delay(SPI_DELAY); //Sends a byte to get the response that the slave has prepared SPI.beginTransaction(settings); digitalWrite(SS, LOW); mess = SPI.transfer(0); digitalWrite(SS, HIGH); SPI.endTransaction(); delay(SPI_DELAY); Serial.println(mess); //Waits between the printing and the next SPI communication. Serial printing slows down a lot delay(SPI_DELAY); //Sends a byte to the slave. The slave now prepares the response byte (The slave knows what to do) SPI.beginTransaction(settings); digitalWrite(SS, LOW); SPI.transfer(DEGREES); digitalWrite(SS, HIGH); SPI.endTransaction(); delay(SPI_DELAY); //Sends a byte to get the response that the slave has prepared SPI.beginTransaction(settings); digitalWrite(SS, LOW); mess = SPI.transfer(0); digitalWrite(SS, HIGH); SPI.endTransaction(); delay(SPI_DELAY); Serial.println(mess); } <file_sep>/src/goalie.cpp #include "goalie.h" #include "pid.h" #include "position.h" #include "us.h" #include "vars.h" #include "imu.h" #include "camera.h" #include "config.h" #include "music.h" #include <Arduino.h> int SCY1 = 0; int SCY2 = 0; void goalie() { digitalWrite(Y, LOW); x = 1; y = 1; if(ball_degrees >= 350 || ball_degrees <= 10) { if(ball_distance > 190) atk_direction = 0; else atk_direction = ball_degrees; atk_speed = GOALIE_ATKSPD_FRT; } if(ball_degrees >= 90 && ball_degrees <= 270) { ballBack(); atk_speed = GOALIE_ATKSPD_BAK; } if(digitalRead(SWITCH_DX) == 1) { if(ball_degrees > 10 && ball_degrees < 30) { atk_direction = ball_degrees + GOALIE_ATKDIR_PLUSANG1; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees >= 30 && ball_degrees < 45) { atk_direction = ball_degrees + GOALIE_ATKDIR_PLUSANG2; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees >= 45 && ball_degrees < 90) { atk_direction = ball_degrees + GOALIE_ATKDIR_PLUSANG3; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees > 270 && ball_degrees <= 315) { atk_direction = ball_degrees - GOALIE_ATKDIR_PLUSANG3_COR; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees > 315 && ball_degrees <= 330) { atk_direction = ball_degrees - GOALIE_ATKDIR_PLUSANG2_COR; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees > 330 && ball_degrees < 350) { atk_direction = ball_degrees - GOALIE_ATKDIR_PLUSANG1_COR; atk_speed = GOALIE_ATKSPD_LAT; } } else { if(ball_degrees > 10 && ball_degrees < 30) { atk_direction = ball_degrees + GOALIE_ATKDIR_PLUSANG1_COR; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees >= 30 && ball_degrees < 45) { atk_direction = ball_degrees + GOALIE_ATKDIR_PLUSANG2_COR; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees >= 45 && ball_degrees < 90) { atk_direction = ball_degrees + GOALIE_ATKDIR_PLUSANG3_COR; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees > 270 && ball_degrees <= 315) { atk_direction = ball_degrees - GOALIE_ATKDIR_PLUSANG3; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees > 315 && ball_degrees <= 330) { atk_direction = ball_degrees - GOALIE_ATKDIR_PLUSANG2; atk_speed = GOALIE_ATKSPD_LAT; } if(ball_degrees > 330 && ball_degrees < 350) { atk_direction = ball_degrees - GOALIE_ATKDIR_PLUSANG1; atk_speed = GOALIE_ATKSPD_LAT; } } if((ball_degrees >= 330 || ball_degrees <= 30) && ball_distance > 190) { //storcimento atk_speed = GOALIE_ATKSPD_STRK; //dove i gigahertz hanno fallito preparePID(atk_direction, atk_speed, cstorc); } else preparePID(atk_direction, atk_speed); } void leaveMeAlone() { if (zoneIndex >= 6) goCenter(); } void storcimentoPorta() { if (fixCamIMU(pAtk) >= 3) cstorc+=9; else if (fixCamIMU(pAtk) < -3) cstorc-=9; else cstorc *= 0.7; // else { // if (cstorc > 0) cstorc -= 2; // else cstorc += 2; // } cstorc = constrain(cstorc, -30, 30); //SUPERTEAM // if (cstorc > 55) cstorc = 55; // if (cstorc < -55) cstorc = -55; } void ballBack() { int ball_degrees2; int dir; int plusang; if(ball_distance > 130) plusang = GOALIE_ATKDIR_PLUSANGBAK; else plusang = 0; if(ball_degrees > 180) ball_degrees2 = ball_degrees - 360; else ball_degrees2 = ball_degrees; if(ball_degrees2 > 0) dir = ball_degrees + plusang; //45 con 8 ruote else dir = ball_degrees - plusang; //45 con 8 ruote if(dir < 0) dir = dir + 360; else dir = dir; atk_direction = dir; } <file_sep>/src/motors.cpp #include "motors.h" #include "vars.h" #include "pid.h" #include <Arduino.h> byte INA_MOT[5] = {0, 12, 25, 27, 21}; //{0, 16, 5, 8}; // INA pin byte INB_MOT[5] = {0, 11, 24, 26, 22}; //{0, 15, 6, 9}; // INB pin byte PWM_MOT[5] = {0, 2, 5, 6, 23}; //{0, 4, 7, 10}; // PWM pin void initMotorsGPIO() { pinMode(PWM_MOT[1], OUTPUT); pinMode(INA_MOT[1], OUTPUT); pinMode(INB_MOT[1], OUTPUT); pinMode(PWM_MOT[2], OUTPUT); pinMode(INA_MOT[2], OUTPUT); pinMode(INB_MOT[2], OUTPUT); pinMode(PWM_MOT[3], OUTPUT); pinMode(INA_MOT[3], OUTPUT); pinMode(INB_MOT[3], OUTPUT); pinMode(PWM_MOT[4], OUTPUT); pinMode(INA_MOT[4], OUTPUT); pinMode(INB_MOT[4], OUTPUT); } /** * Combination of motor 1 / motor 2 /result * * 0 - 0 -----> Stopped - Neutral * 0 - 1 -----> Clockwise * 1 - 0 -----> Counter-Clockwise * 1 - 1 -----> Stopped - Brake * **/ void turnMotor(byte motorIndex, byte pinA, byte pinB, byte pwm) { digitalWrite(INA_MOT[motorIndex], pinA); digitalWrite(INB_MOT[motorIndex], pinB); analogWrite(PWM_MOT[motorIndex], pwm); } void brake() { digitalWrite(INA_MOT[1], 1); digitalWrite(INB_MOT[1], 1); digitalWrite(INA_MOT[2], 1); digitalWrite(INB_MOT[2], 1); digitalWrite(INA_MOT[3], 1); digitalWrite(INB_MOT[3], 1); digitalWrite(INA_MOT[4], 1); digitalWrite(INB_MOT[4], 1); analogWrite(PWM_MOT[1], 255); analogWrite(PWM_MOT[2], 255); analogWrite(PWM_MOT[3], 255); analogWrite(PWM_MOT[4], 255); return; } void brakeI() { digitalWrite(INA_MOT[1], 1); digitalWrite(INB_MOT[1], 1); digitalWrite(INA_MOT[2], 1); digitalWrite(INB_MOT[2], 1); digitalWrite(INA_MOT[3], 1); digitalWrite(INB_MOT[3], 1); digitalWrite(INA_MOT[4], 1); digitalWrite(INB_MOT[4], 1); analogWrite(PWM_MOT[1], 255); analogWrite(PWM_MOT[2], 255); analogWrite(PWM_MOT[3], 255); analogWrite(PWM_MOT[4], 255); return; } // degrees to radiant converting float torad(float deg) { return (deg * PI / 180.0); } // calculates sins of integer angles from 0 to 359 void initSinCos() { for (int i = 0; i < 360; i++) { sins[i] = sin(torad(i)); } for (int i = 0; i < 360; i++) { cosin[i] = cos(torad(i)); } } // Function to send the speed to the motor void mot(byte mot, int vel) { byte VAL_INA, VAL_INB; if (vel == 0) { // no brake ma motore inerte corto a massa e vel=0 contro freno // dove corto a VCC e vel=max VAL_INA = 0; VAL_INB = 0; } else if (vel > 0) { // clockwise VAL_INA = 1; VAL_INB = 0; } else if (vel < 0) { // counterclockwise VAL_INA = 0; VAL_INB = 1; vel = -vel; } digitalWrite(INA_MOT[mot], VAL_INA); digitalWrite(INB_MOT[mot], VAL_INB); analogWrite(PWM_MOT[mot], vel); return; } void testMotors() { for (int i = 1; i < 5; i++) { turnMotor(i, 0, 1, 100); delay(1000); turnMotor(i, 0, 0, 100); delay(300); turnMotor(i, 1, 0, 100); delay(1000); turnMotor(i, 0, 0, 100); delay(300); } // turnMotor(1, 0, 1, 80); // turnMotor(3, 0, 1, 200); // delay(1000); // turnMotor(1, 0, 0, 80); // turnMotor(3, 0, 0, 200); // delay(300); // turnMotor(1, 1, 0, 80); // turnMotor(3, 1, 0, 200); // delay(1000); // turnMotor(1, 0, 0, 80); // turnMotor(3, 0, 0, 200); // delay(300); // turnMotor(2, 0, 1, 80); // turnMotor(4, 0, 1, 200); // delay(1000); // turnMotor(2, 0, 0, 80); // turnMotor(4, 0, 0, 200); // delay(300); // turnMotor(2, 1, 0, 80); // turnMotor(4, 1, 0, 200); // delay(1000); // turnMotor(2, 0, 0, 80); // turnMotor(4, 0, 0, 200); // delay(300); // turnMotor(3, 0, 1, 80); // turnMotor(1, 0, 1, 200); // delay(1000); // turnMotor(3, 0, 0, 80); // turnMotor(1, 0, 0, 200); // delay(300); // turnMotor(3, 1, 0, 80); // turnMotor(1, 1, 0, 200); // delay(1000); // turnMotor(3, 0, 0, 80); // turnMotor(1, 0, 0, 200); // delay(300); // turnMotor(4, 0, 1, 80); // turnMotor(2, 0, 1, 200); // delay(1000); // turnMotor(4, 0, 0, 80); // turnMotor(2, 0, 0, 200); // delay(300); // turnMotor(4, 1, 0, 80); // turnMotor(2, 1, 0, 200); // delay(1000); // turnMotor(4, 0, 0, 80); // turnMotor(2, 0, 0, 200); // delay(300); }<file_sep>/README.md # SPQR-Team-2019 Official code 2018-2019 SPQR 1st at Romecup2019, Rome Best Robot Design at Robocup2019, Sydney #include <E.Latino> #include <A.Ghezzi> #include <E.Coletta> #include <D.Casagrande> #include <S.Sannino> #include <G.Treccape> <file_sep>/utility/bluetooth/reset_bluesmirf-rn42/reset_bluesmirf-rn42.ino #include <SoftwareSerial.h> int bluetoothTx = 2; // TX-O pin of bluetooth mate, Arduino D2 int bluetoothRx = 3; // RX-I pin of bluetooth mate, Arduino D3 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); void setup() { Serial.begin(9600); Serial.print("$"); Serial.print("$"); Serial.print("$"); delay(1000); Serial.println("SF,1"); delay(500); Serial.println("R,1"); delay(2500); Serial.println("---"); //bluetooth.begin(9600); } void read() { if (bluetooth.available()) { // Send any characters the bluetooth prints to the serial monitor Serial.print((char)bluetooth.read()); delay(75); } } void write() { if (Serial.available()) { // Send any characters the Serial monitor prints to the bluetooth bluetooth.print((char)Serial.read()); delay(75); } // and loop forever and ever! } void loop() { read(); write(); } <file_sep>/src/camera.cpp #include "camera.h" #include "vars.h" // inizio del dato int startpY = 0; int startpB = 0; // fine del dato int endpY = 0; int endpB = 0; // stringa dove si vanno a mettere i pacchetti di dati ricevuti String valStringY = ""; String valStringB = ""; // segnalo se il dato ricevuto è valido int datavalid = 0; int oldGoalY,oldGoalB; bool negateB = false; bool negateY = false; // variabile a cui attribuisco momentaneamente il valore dell x della porta int valY; int valB; void goalPosition() { portx = 999; while (CAMERA.available()) { // get the new byte: char inChar = (char)CAMERA.read(); // if the incoming character is a 'Y', set the start packet flag if (inChar == 'Y') { startpY = 1; } // if the incoming character is a 'Y', set the start packet flag if (inChar == 'B') { startpB = 1; } // if the incoming character is a '.', set the end packet flag if (inChar == 'y') { endpY = 1; } // if the incoming character is a '.', set the end packet flag if (inChar == 'b') { endpB = 1; } if ((startpY == 1) && (endpY == 0)) { if (isDigit(inChar)) { // convert the incoming byte to a char and add it to the string: valStringY += inChar; }else if(inChar == '-'){ negateY = true; } } if ((startpB == 1) && (endpB == 0)) { if (isDigit(inChar)) { // convert the incoming byte to a char and add it to the string: valStringB += inChar; }else if(inChar == '-'){ negateB = true; } } if ((startpY == 1) && (endpY == 1)) { valY = valStringY.toInt(); // valid data if(negateY) valY *= -1; valStringY = ""; startpY = 0; endpY = 0; negateY = false; datavalid ++; } if ((startpB == 1) && (endpB == 1)) { valB = valStringB.toInt(); // valid data if(negateB) valB *= -1; valStringB = ""; startpB = 0; endpB = 0; negateB = false; datavalid ++; } } // end of while if (valY != -74) oldGoalY = valY; if (valB != -74) oldGoalB = valB; if (valY == -74) valY = oldGoalY; if (valB == -74) valB = oldGoalB; // entro qui solo se ho ricevuto i pacchetti completi sia del blu che del giallo if (datavalid > 1 ) { if(goal_orientation == 1){ //yellow goalpost pAtk = valY; pDef = valB * -1; }else{ //blue goalpost pAtk = valB; pDef = valY * -1; } datavalid = 0; cameraReady = 1; //attivo flag di ricezione pacchetto } } // un numero grande equivale a stare a destra, piccolo a sinistra //fix the camera value change caused by the robot twist. Every degree of twist corresponds to a degree of the port change, more or less int imuOff; int fixCamIMU(int d){ if(imu_current_euler > 0 && imu_current_euler < 180) imuOff = imu_current_euler; else if (imu_current_euler <= 360 && imu_current_euler >= 180) imuOff = imu_current_euler - 360; imuOff = constrain(imuOff*0.8, -30, 30); return d + imuOff; } <file_sep>/utility/kirkhammett/test.ino // logica dei test con serial monitor (PC attaccato) // // 1 >test ultrasuoni< // 2 >test bussola< // 3 >test sensori linea< // 4 >test PID (recenter a fermo con SM)< // 5 >test PID (recenter veloce senza SM)< // 6 >test sensori palla< // 7 >test motori con il robot tenuto sospeso // 8 >test orizzontale/verticale< // 9 >test posizione campo (1..9)< // a >controllo pulsanti e sw< // b >controllo led e buzzer< // c >interrogazione I2C ultrasuoni e bussola< // d >test cosa vede dopo interrupt // e >visualizza interrupt // f >ferma i motori // g >tempo frenata // h >visualizzo interrupt in gioco // k >test camera porta // altri caratteri >usi futuri< void rtest() // utente puó digitare da tastiera il test da effettuare e cambiarlo durante il suo svolgimento { byte test; brake(); SerialTest.println(" Test disponibili"); SerialTest.println("1 test ultrasuoni"); SerialTest.println("2 test bussola"); SerialTest.println("3 test sensori linea"); SerialTest.println("4 test PID (recenter a fermo con SM)"); SerialTest.println("5 test PID (senza SM) Attenzione ricentro VELOCE"); SerialTest.println("6 test sensori palla"); SerialTest.println("7 test motori mantenere il robot sospeso"); SerialTest.println("8 test orizzontale/verticale"); SerialTest.println("9 test posizione campo (1..9)"); SerialTest.println("a controllo pulsanti e sw"); SerialTest.println("b controllo led e buzzer"); SerialTest.println("c interrogazione I2C ultrasuoni e bussola"); SerialTest.println("d test cosa vede dopo interrupt"); SerialTest.println("e visualizza interrupt dopo frenata"); SerialTest.println("f ferma i motori"); SerialTest.println("g tempo frenata"); SerialTest.println("h visualizzo interrupt in gioco"); SerialTest.println(); SerialTest.println("velocitá 115200 e NESSUN FINE RIGA >no LF<"); SerialTest.println("digitare il test (1..c) da eseguire e cliccare invia >no LF<"); SerialTest.println("digitare 0 per uscire dai test >no LF<"); SerialTest.println(); while (SerialTest.available() == 0); do { test = SerialTest.read(); SerialTest.println(); SerialTest.print("Test "); SerialTest.print(char(test)); if (test == '0') SerialTest.println(" Esce dal test e torna a giocare"); if (test == '1') SerialTest.println(" test ultrasuoni"); if (test == '2') SerialTest.println(" test bussola"); if (test == '3') SerialTest.println(" test sensori linea"); if (test == '4') SerialTest.println(" test PID (recenter a fermo con SM)"); if (test == '5') SerialTest.println(" test PID (senza SM) Attenzione ricentro VELOCE"); if (test == '6') SerialTest.println(" test sensori palla"); if (test == '7') SerialTest.println(" test motori mantenere il robot sospeso"); if (test == '8') SerialTest.println(" test orizzontale/verticale"); if (test == '9') SerialTest.println(" test posizione campo (1..9)"); if (test == 'a') SerialTest.println(" controllo pulsanti e sw"); if (test == 'b') SerialTest.println(" controllo led e buzzer"); if (test == 'c') SerialTest.println(" interrogazione I2C ultrasuoni e bussola"); if (test == 'd') SerialTest.println(" test cosa vede dopo interrupt"); if (test == 'e') SerialTest.println(" visualizza interrupt dopo frenata"); if (test == 'f') SerialTest.println(" ferma i motori"); if (test == 'g') SerialTest.println(" tempo frenata"); if (test == 'h') SerialTest.println(" visualizza interrupt in gioco"); if (test == '0') { SerialTest.println(" Fine test"); flagtest = false; return; } do // finché non riceve contrordine { switch (test) { case '1'://ultrasuoni us_test(); delay (2000); break; case '2'://bussola imu_test(); delay (2000); break; case '3'://sensori linea line_test(); delay (500); break; case '4'://PID recenter da fermo PID_test(true); delay (500); break; case '5'://PID recenter veloce no SM PID_test(false); break; case '6'://sensori palla palla_test(); delay (500); break; case '7'://motori motori_test(); break; case '8'://test X e Y XY_test(); delay (2000); break; case '9'://test zona (1..9) zona_test(); delay (2000); break; case 'a'://controllo pulsanti e sw switch_test(); delay (2000); break; case 'b'://controllo led e buzzer output_test(); delay (2000); break; case 'c'://interrogazione I2C ultrasuoni e bussola I2C_test(); delay (2000); break; case 'd'://test frenata dopo interrupt frenata_test(); fermo(); break; case 'e'://test visualizzo interrupt durante frenata visualizzo_interrupt(); break; case 'f'://ferma i motori fermo(); break; case 'g'://tempo frenata tempo_frenata(); break; case 'h'://visualizza interrupt in gioco visualizzo_gioco(); break; case 'k': test_porta(); break; default: break; } } while (SerialTest.available() == 0); } while (test != '0'); }//---------------------------------------------------------- void us_test() { us_start_measuring(); delay(70); us_receive(); us_fr = us_values[0]; //FRONT US us_dx = us_values[1]; //DX US us_px = us_values[2]; //BACK US us_sx = us_values[3]; //SX US SerialTest.print ("front : "); SerialTest.println(us_fr); SerialTest.print ("destro : "); SerialTest.println(us_dx); SerialTest.print ("posteriore : "); SerialTest.println(us_px); SerialTest.print ("sinistro : "); SerialTest.println(us_sx); SerialTest.print ("larghezza : "); SerialTest.println(us_sx + us_dx + robot); SerialTest.print ("lunghezza : "); SerialTest.println(us_fr + us_px + robot); SerialTest.println(); return; }//----------------------------------------------------------- void imu_test() { SerialTest.print ("angolo : "); SerialTest.println(read_euler()); return; }//----------------------------------------------------------- void line_test()//0 vede la linea e 1 no { SerialTest.println ("0 = vede la linea"); SerialTest.print ("sensore S1 : "); SerialTest.println(digitalRead(A8)); SerialTest.print ("sensore S2 : "); SerialTest.println(digitalRead(A9)); SerialTest.print ("sensore S3 : "); SerialTest.println(digitalRead(A10)); SerialTest.print ("sensore S4 : "); SerialTest.println(digitalRead(A11)); SerialTest.print ("sensore S5 : "); SerialTest.println(digitalRead(A12)); SerialTest.print ("sensore S6 : "); SerialTest.println(digitalRead(A13)); SerialTest.println(); return; }//------------------------------------------------------- void PID_test(bool SM)// ruotare il robot a mano una volta e vedere se si raddrizza { imu_current_euler = read_euler(); recenter(1.0); if (SM) { SerialTest.print ("bussola ante : "); SerialTest.print(imu_current_euler); SerialTest.print (" bussola post : "); SerialTest.println(read_euler()); } return; }//------------------------------------------------------- void palla_test() { spi_readfrom644l();//legge i sensori SerialTest.print ("sensore n. : "); SerialTest.print(ball_sensor); SerialTest.print(" distanza : "); SerialTest.println(ball_distance); return; }//------------------------------------------------------- void motori_test() { //test motore 1,2,3 for (int i = 1; i < 4; i++) { SerialTest.print("motore n. :"); SerialTest.print(i); SerialTest.print(" orario, "); digitalWrite(INA_MOT[i], 1); digitalWrite(INB_MOT[i], 0); analogWrite (PWM_MOT[i], 100); delay(1000); SerialTest.print(" stop "); digitalWrite(INA_MOT[i], 0); digitalWrite(INB_MOT[i], 0); analogWrite (PWM_MOT[i], 0); delay(300); SerialTest.print(", antiorario,"); digitalWrite(INA_MOT[i], 0); digitalWrite(INB_MOT[i], 1); analogWrite (PWM_MOT[i], 100); delay(1000); SerialTest.println(" stop."); digitalWrite(INA_MOT[i], 0); digitalWrite(INB_MOT[i], 0); analogWrite (PWM_MOT[i], 0); delay(300); } SerialTest.println(); return; }//------------------------------------------------------- void XY_test() { //lettura degli ultrasuoni us_start_measuring(); delay(70); us_receive(); us_fr = us_values[0]; //FRONT US us_dx = us_values[1]; //DX US us_px = us_values[2]; //BACK US us_sx = us_values[3]; //SX US /* us_fr = 40; //FRONT US us_dx = 80 ; //DX US us_px = 131; //BACK US us_sx = 80; //SX US */ old_status_x = status_x; old_status_y = status_y; WhereAmI(); //calcola la posizione x e y SerialTest.print ("larghezza : "); SerialTest.println(us_sx + us_dx + robot); SerialTest.print ("lunghezza : "); SerialTest.println(us_fr + us_px + robot); SerialTest.println(); SerialTest.print("x = "); SerialTest.print(status_x); switch (status_x) { case EST: SerialTest.println(" EST"); break; case OVEST: SerialTest.println(" OVEST"); break; case CENTRO: SerialTest.println(" CENTRO"); break; case 255: SerialTest.println(" NON LO SO"); break; } SerialTest.print("y = "); SerialTest.print(status_y); switch (status_y) { case NORD: SerialTest.println(" NORD"); break; case SUD: SerialTest.println(" SUD"); break; case CENTRO: SerialTest.println(" CENTRO"); break; case 255: SerialTest.println(" NON LO SO"); break; } return; }//------------------------------------------------------- void zona_test() { //lettura degli ultrasuoni us_start_measuring(); delay(70); us_receive(); us_fr = us_values[0]; //FRONT US us_dx = us_values[1]; //DX US us_px = us_values[2]; //BACK US us_sx = us_values[3]; //SX US /* us_fr = 40; //FRONT US us_dx = 30 ; //DX US us_px = 131; //BACK US us_sx = 100; //SX US */ old_status_x = status_x; old_status_y = status_y; WhereAmI(); //calcola la posizione x e y cerco_zona(); SerialTest.print("Zona n. : "); SerialTest.print(currentlocation); switch (currentlocation) { case CENTRO_CENTRO: SerialTest.println(" CENTRO_CENTRO"); break; case CENTRO_EST: SerialTest.println(" CENTRO_EST"); break; case CENTRO_OVEST: SerialTest.println(" CENTRO_OVEST"); break; case NORD_CENTRO: SerialTest.println(" NORD_CENTRO"); break; case NORD_EST: SerialTest.println(" NORD_EST"); break; case NORD_OVEST: SerialTest.println(" NORD_OVEST"); break; case SUD_CENTRO: SerialTest.println(" SUD_CENTRO"); break; case SUD_EST: SerialTest.println(" SUD_EST"); break; case SUD_OVEST: SerialTest.println(" SUD_OVEST"); break; case 255: SerialTest.println(" NON LO SO"); break; } return; }//------------------------------------------------------- //checking if some button/switch is pressed at the startup SOLO PER USI FUTURI void switch_test() { byte b1, b2, b3, bdx, bsx; b1 = digitalRead(PIN_BUTTON1); b2 = digitalRead(PIN_BUTTON2); b3 = digitalRead(PIN_BUTTON3); bdx = digitalRead(SWITCH_DX); bsx = digitalRead(SWITCH_SX); SerialTest.print("PIN_BUTTON1 "); SerialTest.println(b1); SerialTest.print("PIN_BUTTON2 "); SerialTest.println(b2); SerialTest.print("PIN_BUTTON3 "); SerialTest.println(b3); SerialTest.print("SWITCH_DX "); SerialTest.println(bdx); SerialTest.print("SWITCH_SX "); SerialTest.println(bsx); SerialTest.println(); return; }//-------------------------------------------------------- //turns off or on all the outputs (leds and stuff) (1 for on, 0 for off); void output_test() { SerialTest.println("Test LED ROSSO "); digitalWrite(PIN_LED_R, HIGH); delay(2000); digitalWrite(PIN_LED_R, LOW); SerialTest.println("Test LED GIALLO "); digitalWrite(PIN_LED_Y, HIGH); delay(2000); digitalWrite(PIN_LED_Y, LOW); SerialTest.println("Test LED VERDE "); digitalWrite(PIN_LED_G, HIGH); delay(2000); digitalWrite(PIN_LED_G, LOW); SerialTest.println("Test BUZZER "); tone(PIN_PIEZO,1000,500); delay(3000); digitalWrite(PIN_PIEZO, LOW); return; }//---------------------------------------------------------- void I2C_test() { //prova a far partire gli ultrasuoni SerialTest.println("Interrogazione dei sensori I2C"); if ((I2c.write(112, 0x00, 0x51) != 0)) { SerialTest.println("Sensore ultrasuoni FRONTALE indirizzo 112 NON RISPONDE"); } if ((I2c.write(113, 0x00, 0x51) != 0)) { SerialTest.println("Sensore ultrasuoni DESTRO indirizzo 113 NON RISPONDE"); } if ((I2c.write(114, 0x00, 0x51) != 0)) { SerialTest.println("Sensore ultrasuoni POSTERIORE indirizzo 114 NON RISPONDE"); } if ((I2c.write(115, 0x00, 0x51) != 0)) { SerialTest.println("Sensore ultrasuoni SINISTRO indirizzo 115 NON RISPONDE"); } //testing imu if ((IMU.checkconnection()) != 0) { SerialTest.println("LA BUSSOLA NON RISPONDE"); } return; }//--------------------------------------------------------- void frenata_test() // cosa vede dopo interrupt { long t0; // istante inizio frenata byte sens; // numero di sensori attivi contemporaneamente flag_interrupt = false; // gioca normalmente fino a che non arriva un interrupt do { update_sensors_all(); goalie(); } while (flag_interrupt == false); t0 = millis(); tone(PIN_PIEZO,1000,500); //suona while ((millis() - t0) <= 150) ; //attesa per la frenata di 100 ms digitalWrite(PIN_PIEZO, LOW); SerialTest.print("Il primo interrupt proviene dal sensore "); SerialTest.println(linesensor); SerialTest.print("Durante la frenata ho ricevuto "); SerialTest.print(Nint); SerialTest.println(" interrupt"); sens = linea[1]; for (byte i = 1; i <= Nint; i++) { SerialTest.println(linea[i], BIN); sens = sens & linea[i]; } SerialTest.println(); SerialTest.println(sens); sens = ~( sens + 192 ); SerialTest.println(sens); switch (sens) { case 0b000001: case 0b000010: case 0b000100: case 0b001000: case 0b010000: case 0b100000: SerialTest.println("Il robot ha toccato la linea solo con questo sensore" ); break; case 0b000011: SerialTest.println("Si sono attivati i sensori 1 e 2"); break; case 0b000110: SerialTest.println("Si sono attivati i sensori 2 e 3"); break; case 0b000111: SerialTest.println("Si sono attivati i sensori 1 2 e 3"); break; case 0b110000: SerialTest.println("Si sono attivati i sensori 5 e 6"); break; case 0b011000: SerialTest.println("Si sono attivati i sensori 5 e 4"); break; case 0b111000: SerialTest.println("Si sono attivati i sensori 6 5 e 4"); break; case 0b100001: SerialTest.println("Si sono attivati i sensori 6 e 1"); break; case 0b001100: SerialTest.println("Si sono attivati i sensori 4 e 3"); break; case 0b100011: SerialTest.println("Si sono attivati i sensori 6 1 e 2"); break; case 0b110001: SerialTest.println("Si sono attivati i sensori 6 1 e 5"); break; case 0b001110: SerialTest.println("Si sono attivati i sensori 4 3 e 2"); break; case 0b011100: SerialTest.println("Si sono attivati i sensori 4 3 e 5"); break; case 0b011110: SerialTest.println("Si sono attivati i sensori 4 3 5 e 2"); break; case 0b110011: SerialTest.println("Si sono attivati i sensori 6 1 5 e 2"); break; case 0b000000: SerialTest.println("Tutti i sensori sono disattivi"); break; default: SerialTest.println("Si sono attivati 5 o 6 sensori"); } flag_interrupt = false; Nint = 0; return; }//--------------------------------------------------------- void visualizzo_interrupt() { do { update_sensors_all(); goalie(); } while (flag_interrupt == false); //brake(); tone(PIN_PIEZO,1000,500); delay(500); digitalWrite(PIN_PIEZO, LOW); flag_interrupt = false; SerialTest.print("Interrupt rilevati "); SerialTest.println(Nint); for (byte i = 1; i <= Nint; i++) { SerialTest.println(linea[i], BIN); } SerialTest.println(); fermo(); return; }//--------------------------------------------------------- void fermo() { brake(); SerialTest.println("Motori disattivati"); SerialTest.println("Scegliere il test da eseguire successivamente"); while ( SerialTest.available() == 0); return; }//--------------------------------------------------------- void tempo_frenata() { long t0; // istante inizio frenata long t1; // istante fine frenata byte tasto; drivePID(0 , GOALIE_MAX); delay(1000); tone(PIN_PIEZO,1000,500); t0 = millis(); brake(); SerialTest.println("Premere un tasto quando il robot si ferma"); while ( SerialTest.available() == 0); t1 = millis(); digitalWrite(PIN_PIEZO, LOW); SerialTest.print("Tempo trascorso "); SerialTest.println(t1 - t0); SerialTest.println(); tasto = SerialTest.read(); // svuoto buffer seriale SerialTest.println("Scegliere il test da eseguire successivamente"); while ( SerialTest.available() == 0); return; }//--------------------------------------------------------- void visualizzo_gioco() { do { do { update_sensors_all(); goalie(); } while (flag_interrupt == false); gest_interrupt(); SerialTest.print("Interrupt rilevati "); SerialTest.println(Nint); for (byte i = 1; i <= Nint; i++) { SerialTest.print(i); SerialTest.print(" "); SerialTest.println(linea[i], BIN); } SerialTest.println(); } while (SerialTest.available() == 0); return; } //--------------------------------------------------------- //test automatico al setup //turns off or on all the outputs (leds and stuff) (1 for on, 0 for off); void test_toggle_outputs(byte onoff) { digitalWrite(PIN_LED_R, onoff); digitalWrite(PIN_LED_Y, onoff); digitalWrite(PIN_LED_G, onoff); digitalWrite(PIN_PIEZO, onoff); return; }//---------------------------------------------------------- void test_porta(){ p=digitalRead(SWD); x_porta(); Serial.print("X:"); Serial.println(valY); Serial.println(valB); Serial.print("1 blu 0 gialla"); Serial.println(p); Serial.print("XP_SX"); Serial.println(XP_SX); Serial.print("XP_DX"); Serial.println(XP_DX); delay(500); } <file_sep>/include/keeper.h void keeper();<file_sep>/include/position.h //calculations void increaseIndex(int, int, int); void increaseCol(int, int); void increaseRow(int, int); void increaseAll(int); void decreaseIndex(int, int, int); void decreaseCol(int, int); void decreaseRow(int, int); void decreaseAll(int); void increaseRowWithLimit(int, int); void increaseColWithLimit(int, int); void decreaseRowWithLimit(int, int); void decreaseColWithLimit(int, int); //reading void calculateLogicZone(); void readPhyZone(); void phyZoneDirection(); void phyZoneCam(); void phyZoneUS(); void phyZoneLines(); //testing void testPhyZone(); void testLogicZone(); void gigaTestZone(); //movement void goCenter(); void goGoalPost(); void centerGoalPost(); void centerGoalPostCamera(bool); //sensors (still needed?) void update_sensors_all(); void AAANGOLO();<file_sep>/src/vars.cpp #include "vars.h" void initVars(){ // Now assign value to variables, first thing to do // IMU imu_current_euler = 0; // Ball ball_distance = 0; ball_degrees = 0; ball_seen = false; // PID errorePre = 0.0; integral = 0.0; st = 0; // US reading = 0; us_t0 = 0; us_t1 = 0; us_flag = false; // Position old_status_x = CENTRO; old_status_y = CENTRO; // old_guessedlocation = CENTER_CENTER; goal_zone = false; good_field_x = true; good_field_y = true; status_x = CENTRO; status_y = CENTRO; // currentlocation = CENTER_CENTER; // guessedlocation = CENTER_CENTER; // Linesensors and interrupt // bluetooth misc a = 0; old_timer = 0; role = 0; friendZone = 0; iAmHere = 0; comrade = false; // global vars for angles globalDir = 0; globalSpeed = 0; st = 0; // attack atk_direction = 0; atk_speed = 0; // CAMERA pAtk = 0; pDef = 0; portx = 0; goal_orientation = 0; cameraReady = 0; // BT topolino = 0; fpos = 0; // stincr stincr = 0; cstorc = 0; // lines exitTimer = EXTIME; unlockTime = 0; keeper_tookTimer = false; keeper_backToGoalPost = false; //axis vxp = 1; vxn = 1; vyp = 1; vyn = 1; canUnblock = true; } <file_sep>/src/us.cpp #include "Wire.h" #include "us.h" #include "vars.h" #include <Arduino.h> // Start I2C On Wire1 for US void initUS() { Wire1.begin(); } void testUS() { // test from srf02_example for (int i = 0; i < 4; i++) { // step 1: instruct sensor to read echoes // transmit to device #112 (0x70) Wire1.beginTransmission(112 + i); // sets register pointer to the command register (0x00) Wire1.write(byte(0x00)); // command sensor to measure in "centimeters" (0x51). 0x50 inches and 0x52 // microseconds Wire1.write(byte(0x51)); // stop transmitting Wire1.endTransmission(); // step 2: wait for readings to happen // datasheet suggests at least 65 milliseconds delay(70); // step 3: instruct sensor to return a particular echo reading // transmit to device #112 Wire1.beginTransmission(112 + i); // sets register pointer to echo #1 register (0x02) Wire1.write(byte(0x02)); Wire1.endTransmission(); // step 4: request reading from sensor // request 2 bytes from slave device #112 Wire1.requestFrom(112 + i, 2); // step 5: receive reading from sensor if (2 <= Wire1.available()) { // if two bytes were received // receive high byte (overwrites previous reading) reading = Wire1.read(); // shift high byte to be high 8 bits reading = reading << 8; // receive low byte as lower 8 bit reading |= Wire1.read(); us_values[i] = reading; } } // putting US values into declared array index us_fr = us_values[0]; us_dx = us_values[1]; us_px = us_values[2]; us_sx = us_values[3]; // test Serial.println("---------------------"); for (int i = 0; i < 4; i++) { Serial.println(us_values[i]); delay(250); } Serial.println("---------------------"); } void us_trigger() { for (int i = 0; i < 4; i++) { // step 1: instruct sensor to read echoes // transmit to device #112 (0x70) Wire1.beginTransmission(112 + i); // sets register pointer to the command register (0x00) Wire1.write(byte(0x00)); // command sensor to measure in "centimeters" (0x51). 0x50 inches and 0x52 // microseconds Wire1.write(byte(0x51)); Wire1.endTransmission(); } } void us_scheduling() { if (us_flag == false) { us_trigger(); us_flag = true; us_t0 = millis(); } else { us_t1 = millis(); if ((us_t1 - us_t0) > 70) { us_receive(); us_flag = false; } } } void us_receive() { for (byte i = 0; i < 4; i++) { // transmit to device #112s Wire1.beginTransmission(112 + i); // sets register pointer to echo 1 register(0x02) Wire1.write(byte(0x02)); Wire1.endTransmission(); // step 4: request reading from sensor // request 2 bytes from slave device #112 Wire1.requestFrom(112 + i, 2); // step 5: receive reading from sensor // receive high byte (overwrites previous reading) reading = Wire1.read(); // shift high byte to be high 8 bits reading = reading << 8; // receive low byte as lower 8 bit reading |= Wire1.read(); us_values[i] = reading; } } void readUS() { us_scheduling(); us_fr = us_values[0]; // FRONT US us_dx = us_values[1]; // DX US us_px = us_values[2]; // BACK US us_sx = us_values[3]; // SX US } <file_sep>/utility/kirkhammett/ultrasonicsensors.ino void us_start_measuring() { //phase 1 of 2 for the us measures. This sends the "TRIGGER" for (byte i = 0 ; i < 4; i++) { I2c.write(112 + i, 0x00, 0x51); } } void us_scheduling() { //Non blocking delay. It starts phase 1 then after 70 msec it receives the data. if (us_flag == false) { us_start_measuring(); us_flag = true; us_t0 = millis(); } if (us_flag == true) { us_t1 = millis(); if ((us_t1 - us_t0) > 70) { us_receive(); us_flag = 0; } } } void us_receive() { //phase 2 of 2 for the us measures. This receives the "ECHO". In reality it received the already converted data in cm. for (byte i = 0; i < 4; i++) { I2c.read(112 + i, 0x02, 2); us_values[i] = I2c.receive() << 8; us_values[i] |= I2c.receive(); } } void us_read() { us_scheduling(); us_fr = us_values[0]; //FRONT US // us_fr =40; // Frontale non funzionante us_dx = us_values[1]; //DX US us_px = us_values[2]; //BACK US us_sx = us_values[3]; //SX US } <file_sep>/include/linesensor.h #include <Arduino.h> void initLineSensors(); void checkLineSensors(); void handleExtern(); void handleIntern(); void outOfBounds(); void playSafe(); void testLineSensors(); void ballMask(int); void safetysafe();<file_sep>/utility/kirkhammett/spi.ino //initializing the spi pins and setting spi in master mode void init_spi() { pinMode (_SCK, OUTPUT); pinMode (_MISO, INPUT); pinMode (_MOSI, OUTPUT); pinMode (_SS, OUTPUT); digitalWrite( _SS, HIGH); // Slave not selected SPCR = 81; //ARDUINO MEGA IS THE MASTER! }//------------------------------------------------------------ //read from the spi slave that gives us the ball position void spi_readfrom644l() //aggiorna ball_sensor e ball_distance { PORTB = PORTB & 254; //slave selected = digitalWrite( _SS, LOW) spi_temp_byte = spi_tx_rx(255); //sends 255 to the slave and stores the byte received PORTB = PORTB | 1; //slave disabled = digitalWrite( _SS, HIGH) if (spi_temp_byte == 255) return; //if the data received is 255, the slave wasn't ready, uses the old ball informations ball_sensor = spi_temp_byte & 31; //extracting the first 5 bits that tell us what ir sensor sees the ball ball_distance = (spi_temp_byte & 224) >> 5;//extracting the last 3 bits that tell us the ball distance return; }//------------------------------------------------------------ //general function to receive and send 1 byte to the slave byte spi_tx_rx( byte d) { SPDR = d; //sending 1 byte to the slave while ( (SPSR & 128) == 0); //wait until we got something back as a response return SPDR; //return the byte received }//------------------------------------------------------------ <file_sep>/utility/ball_read/ball_read/ball_read.ino /** Sensor Mapping Sensor Angle Pin Port S0 0 A3 C3 S1 A2 C2 S2 A1 C1 S3 A0 C0 S4 90 13 B5 S5 12 B4 S6 11 B3 S7 10 B2 S8 180 9 B1 S9 8 B0 S10 7 D7 S11 6 D6 S12 270 5 D5 S13 4 D4 S14 3 D3 S15 2 D2 loop cycle duration: 3.2 millis **/ #define S9 ((PINB & 1)) #define S8 ((PINB & 2) >> 1) #define S7 ((PINB & 4) >> 2) #define S6 ((PINB & 8) >> 3) #define S5 ((PINB & 16) >> 4) #define S4 ((PINB & 32) >> 5) #define S3 ((PINC & 1)) #define S2 ((PINC & 2) >> 1) #define S1 ((PINC & 4) >> 2) #define S0 ((PINC & 8) >> 3) #define S15 ((PIND & 4) >> 2) #define S14 ((PIND & 8) >> 3) #define S13 ((PIND & 16) >> 4) #define S12 ((PIND & 32) >> 5) #define S11 ((PIND & 64) >> 6) #define S10 ((PIND & 128) >> 7) #define NCYCLES 350 #define BROKEN 300 #define TOO_LOW 60 int counter[16]; int pins[] = {A3, A2, A1, A0, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2}; int distance; int nmax = 0; int sensor = 0; int oldIndex = 0; int oldDistance = 0; byte ballInfo = 0; float xs[16]; float ys[16]; float angle = 0, dist = 0; boolean sending = false; byte sendAngle = 0, sendDistance = 0; byte sendByte = 0; unsigned long t = 0; void setup() { delay(1000); Serial.begin(57600); pinMode(2, INPUT); pinMode(3, INPUT); pinMode(4, INPUT); pinMode(5, INPUT); pinMode(6, INPUT); pinMode(7, INPUT); pinMode(8, INPUT); pinMode(9, INPUT); pinMode(10, INPUT); pinMode(11, INPUT); pinMode(12, INPUT); pinMode(13, INPUT); pinMode(A0, INPUT); pinMode(A1, INPUT); pinMode(A2, INPUT); pinMode(A3, INPUT); pinMode(A4, OUTPUT); for (int i = 0; i < 16; i++) { xs[i] = cos((22.5 * PI / 180) * i); ys[i] = sin((22.5 * PI / 180) * i); } } void loop() { readBallInterpolation(); sendDataInterpolation(); } /**--- READ BALL USING SENSORS ANGLE INTERPOLATION ---**/ void readBallInterpolation() { for (int i = 0; i < 16; i++) { counter[i] = 0; } //reads from the register for (int i = 0; i < NCYCLES; i++) { counter[0] += !S0; counter[1] += !S1; counter[2] += !S2; counter[3] += !S3; counter[4] += !S4; counter[5] += !S5; counter[6] += !S6; counter[7] += !S7; counter[8] += !S8; counter[9] += !S9; counter[10] += !S10; counter[11] += !S11; counter[12] += !S12; counter[13] += !S13; counter[14] += !S14; counter[15] += !S15; } float x = 0, y = 0; for (int i = 0; i < 16; i++) { if (counter[i] > BROKEN || counter[i] < TOO_LOW) counter[i] = 0; x += xs[i] * counter[i]; y += ys[i] * counter[i]; } angle = atan2(y, x) * 180 / PI; angle = ((int)(angle + 360)) % 360; //distance is 0 when not seeing ball //dist = hypot(x, y); nmax = 0; //saves max value and sensor for (int i = 0; i < 16; i++) { if (counter[i] > nmax) { nmax = counter[i]; } } dist = nmax; //turn led on if (dist == 0) { digitalWrite(A4, LOW); } else { digitalWrite(A4, HIGH); } } void sendDataInterpolation() { if(sending){ sendAngle = ((byte) (angle / 2)) & 0b11111110; Serial.write(sendAngle); }else{ sendDistance = dist; if(sendDistance > 254) sendDistance = 254; sendDistance = sendDistance |= 0b00000001; Serial.write(sendDistance); } sending = !sending; } void test() { readBallInterpolation(); Serial.print(S0); Serial.print(" | "); Serial.print(S1); Serial.print(" | "); Serial.print(S2); Serial.print(" | "); Serial.print(S3); Serial.print(" | "); Serial.print(S4); Serial.print(" | "); Serial.print(S5); Serial.print(" | "); Serial.print(S6); Serial.print(" | "); Serial.print(S7); Serial.print(" | "); Serial.print(S8); Serial.print(" | "); Serial.print(S9); Serial.print(" | "); Serial.print(S10); Serial.print(" | "); Serial.print(S11); Serial.print(" | "); Serial.print(S12); Serial.print(" | "); Serial.print(S13); Serial.print(" | "); Serial.print(S14); Serial.print(" | "); Serial.print(S15); Serial.print(" () "); Serial.println(sensor); } void printCounter() { for (int i = 0; i < 16; i++) { Serial.print(counter[i]); Serial.print(" | "); } Serial.println(); } <file_sep>/include/chat.h void whereAreYou(); void teamZone(); bool com(int); void Ao(); void friendo(int); <file_sep>/utility/MultiThreading/doubleled.cpp #include <Arduino.h> #include "TeensyThreads.h" #define LED 13 //pin dei led (ma va?) #define LED2 14 volatile int b1 = 0; //numero dei blink, volatile perché la modifichiamo fuori loop volatile int b2 = 0; //altrimenti la wiki lo definisce come "buggy code" int id1, id2; //numero ID dei thread int co, cc; //inizializzo contatori void blinkthread() { //funzione primo thread while(1) { //loop ;) if (b1) { //controllo for (int i=0; i<b1; i++) { //for per blinkare digitalWrite(LED, HIGH); threads.delay(150); //DELAY CHE NON ROMPE IL CAZZO digitalWrite(LED, LOW); threads.delay(150); } b1 = 0; //resetti per uscire } threads.yield(); //devo ancora capire a che serve } } void blinkthread2() { //uguale while(1) { if (b2) { for (int i=0; i<b2; i++) { digitalWrite(LED2, HIGH); threads.delay(500); //con un delay diverso ;) digitalWrite(LED2, LOW); threads.delay(500); } b2 = 0; } threads.yield(); } } void setup() { pinMode(LED, OUTPUT); pinMode(LED2, OUTPUT); id1 = threads.addThread(blinkthread); //assegno un id al thread per fare funzioni id2 = threads.addThread(blinkthread2); //nel loop, es. sospensione, restart, kill, ecc } void loop() { co++; cc++; b1 = co; b2 = cc; //sospendo per un secondo il thread del secondo led threads.suspend(id2); delay(500); threads.restart(id2); delay(500); } <file_sep>/utility/kirkhammett/cam_pp.ino void x_porta() { while (Serial1.available()) { // get the new byte: char inChar = (char)Serial1.read(); // if the incoming character is a 'Y', set the start packet flag if (inChar == 'Y') { startpY = 1; } // if the incoming character is a 'Y', set the start packet flag if (inChar == 'B') { startpB = 1; } // if the incoming character is a '.', set the end packet flag if (inChar == 'y') { endpY = 1; } // if the incoming character is a '.', set the end packet flag if (inChar == 'b') { endpB = 1; } if ( (startpY == 1) && (endpY == 0) ) { if (isDigit(inChar)) { // convert the incoming byte to a char and add it to the string: valStringY += inChar; } } if ( (startpB == 1) && (endpB == 0) ) { if (isDigit(inChar)) { // convert the incoming byte to a char and add it to the string: valStringB += inChar; } } if ( (startpY == 1) && (endpY == 1) ) { valY = valStringY.toInt(); // valid data valStringY = ""; startpY = 0; endpY = 0; datavalid = 1; } if ( (startpB == 1) && (endpB == 1) ) { valB = valStringB.toInt(); // valid data valStringB = ""; startpB = 0; endpB = 0; datavalid = 1; } } // end of while if (datavalid==1) { if(p=1){ //leggi porta blu x=valB; } else { //leggi porta gialla x=valY; } datavalid = 0; } update_location_complete(); if(x>160) XP_SX=true; //porta a sinistra del robot else XP_SX=false; if(x<35) XP_DX=true; //porta a destra del robot else XP_DX=false; if(x==999) { if(status_x==EST) XP_SX==true; if(status_x==OVEST) XP_DX==true; } } //c 125 //s >140 //d <35 <file_sep>/utility/kirkhammett/libraries/pcint.cpp #include "pcint.h" #ifdef PCINT_NO_MAPS HANDLER_TYPE PCintFunc[NUM_DIGITAL_PINS]; template<int N> void PCint() {PCintFunc[N]();} //static voidFuncPtr PCints[NUM_DIGITAL_PINS]; //PCints[0]=PCint<0>; //PCints[1]=PCint<1>; #else static int PCintMode[3][8]; static HANDLER_TYPE PCintFunc[3][8]; static bool PCintLast[3][8];//?we can use only 3 bytes... but will use more processing power calculating masks void PCattachInterrupt(uint8_t pin,HANDLER_TYPE userFunc, uint8_t mode) { volatile uint8_t *pcmask=digitalPinToPCMSK(pin); if (!pcmask) return;//runtime checking if pin has PCINT, i would prefer a compile time check uint8_t bit = digitalPinToPCMSKbit(pin); uint8_t mask = 1<<bit; uint8_t pcicrBit=digitalPinToPCICRbit(pin); PCintMode[pcicrBit][bit] = mode; PCintFunc[pcicrBit][bit] = userFunc; //initialize last status flags PCintLast[pcicrBit][bit]=(*portInputRegister(digitalPinToPort(pin)))&digitalPinToBitMask(pin); // set the mask *pcmask |= mask; // enable the interrupt PCICR |= (1<<pcicrBit); } void PCdetachInterrupt(uint8_t pin) { volatile uint8_t *pcmask=digitalPinToPCMSK(pin); if (!pcmask) return;//runtime checking if pin has PCINT, i would prefer a compile time check // disable the mask. *pcmask &= ~(1<<digitalPinToPCMSKbit(pin)); // if that's the last one, disable the interrupt. if (*pcmask == 0) PCICR &= ~(1<<digitalPinToPCICRbit(pin)); } // common code for isr handler. "port" is the PCINT number. // there isn't really a good way to back-map ports and masks to pins. // here we consider only the first change found ignoring subsequent, assuming no interrupt cascade static void PCint(uint8_t port) { const uint8_t* map=pcintPinMapBank(port);//get 8 bits pin change map for(int i=0;i<8;i++) { uint8_t p=digitalPinFromPCINTBank(map,i); if (p==-1) continue;//its not assigned //uint8_t bit = digitalPinToPCMSKbit(p); //uint8_t mask = (1<<bit); if (PCintFunc[port][i]!=NULL) {//only check active pins bool stat=(*portInputRegister(digitalPinToPort(p)))&digitalPinToBitMask(p); if (PCintLast[port][i]^stat) {//pin changed! PCintLast[port][i]=stat;//register change if ( (PCintMode[port][i]==CHANGE) || ((stat)&&(PCintMode[port][i]==RISING)) || ((!stat)&&(PCintMode[port][i]==FALLING)) ) { PCintFunc[port][i](); break;//if using concurrent interrupts remove this } } } } } //AVR handle pin change... later figure out the pin SIGNAL(PCINT0_vect) { PCint(0); } SIGNAL(PCINT1_vect) { PCint(1); } SIGNAL(PCINT2_vect) { PCint(2); } #endif <file_sep>/include/vars.h #include <Arduino.h> #ifndef MAIN #define extr extern #else #define extr #endif #define R 20 #define Y 17 #define G 13 // IR shield pin #define BUZZER 30 #define SWITCH_SX 28 #define SWITCH_DX 29 // ZONE DEL CAMPO // codici utilizzabili per una matice 3x3 #define EST 2 #define OVEST 0 #define CENTRO 1 #define NORD 0 #define SUD 2 #define NORD_OVEST 1 #define NORD_CENTRO 2 #define NORD_EST 3 #define CENTRO_OVEST 4 #define CENTRO_CENTRO 5 // codici zona nuovi #define CENTRO_EST 6 #define SUD_OVEST 7 #define SUD_CENTRO 8 #define SUD_EST 9 // VARIABILI E COSTANTI DEL PID #define KP 1.2 //2 // K proporzionale #define KI 0 //0.1 // K integrativo #define KD 0.7 //1.7 // K derivativo // Linesensors e interrupt #define S1I A14 #define S1O A15 #define S2I A16 #define S2O A17 #define S3I A20 #define S3O A0 #define S4I A1 #define S4O A2 #define LINE_THRESH 90 #define UNLOCK_THRESH 2000 #define EXTIME 100 #define BNO055_SAMPLERATE_DELAY_MS (60) #define BT Serial3 #define DEBUG_PRINT Serial #define CAMERA Serial2 #define NANO_BALL Serial4 // IMU extr int imu_current_euler; //Read ball extr int ball_degrees, ball_distance; extr bool ball_seen; // PID extr float errorePre; extr float integral; extr int st; extr int prevPidDir; extr int prevPidSpeed; // test new angle extr int globalDir; extr int globalSpeed; // Motors extr float x, y, vx, vy, speed1, speed2, speed3, speed4, pidfactor, sins[360], cosin[360]; //LINES extr byte lineSensByteBak; extr byte lineReading; //flags for semi-axis block extr bool vxp, vxn, vyp, vyn; extr bool bounds; extr bool slow; extr elapsedMillis exitTimer; extr unsigned long unlockTime; extr bool canUnblock; extr int LN1I; extr int LN2I; extr int LN3I; extr int LN4I; extr int LN1O; extr int LN2O; extr int LN3O; extr int LN4O; // US extr int reading; extr long us_t0; // US measure start extr long us_t1; // time value during measure extr bool us_flag; // is it measuring or not? extr int us_values[4]; // US values array extr int us_sx, us_dx, us_px, us_fr; // copies with other names in the array // POSITION extr int old_status_x; // posizione precedente nel campo vale EST, OVEST o CENTRO o 255 >USI FUTURI< extr int old_status_y; // posizione precedente nel campo vale SUD, NORD o CENTRO o 255 >USI FUTURI< extr bool good_field_x; // vedo tutta la larghezza del campo si/no extr bool good_field_y; // vedo tutta la lunghezza del campo si/no extr int status_x; // posizione nel campo vale EST, OVEST o CENTRO o 255 extr int status_y; // posizione nel campo vale SUD, NORD o CENTRO o 255 extr int guessed_x, guessed_y; extr int zoneIndex; extr bool calcPhyZoneCam; extr int DxF; // con misura y OK e robot a EST o A OVEST con us_fx o us_px < DyF sto a NORD o a SUD era - 10 extr bool goal_zone; // BLUETOOTH extr int a; // puzzi tanto extr unsigned long old_timer; // Comunicazione compagno extr int iAmHere; extr int friendZone; // ;( extr int fpos; extr int role; extr bool comrade; extr int topolino; // attack extr int atk_direction; extr int atk_speed; // defense extr bool defGoRight; extr bool defGoLeft; extr bool defGoBehind; extr bool stop_menamoli; extr elapsedMillis keeperAttackTimer; extr bool keeper_tookTimer; extr bool keeper_backToGoalPost; extr int pAtk; // variabile dello switch che decide dove bisogna attaccare extr int pDef; // variabile dello switch che decide dove bisogna difendere extr bool XP_SX; extr bool XP_DX; extr int portx; extr int goal_orientation; extr int cameraReady; extr float stincr; extr float cstorc; // test vars extr char test; // test select extr bool flagtest; void initVars();<file_sep>/include/motors.h #include <Arduino.h> void initMotorsGPIO(); void turnMotor(byte, byte, byte, byte); void brake(); void brakeI(); float torad(float); void initSinCos(); void mot(byte, int); void testMotors(); void inchioda();
498c3ca74ae4c5d0418445849c0b7f3a02453905
[ "Markdown", "C", "Python", "C++" ]
69
C++
spqr-team/SPQR-Team-2019
6303321415552c83131cb230b1727b18ac46de02
c5bc74f69f4876e55e171c93e21140f2e70c5bdb
refs/heads/master
<file_sep>Ahah ==== just a funny recorder to analyze the sound in several secends. show the score of your record voice. <file_sep>package com.echoandd.ahah; import android.app.Activity; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ToggleButton; public class LightActivity extends Activity { public ToggleButton lightButton; public Camera camera; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_light); lightButton = (ToggleButton)findViewById(R.id.toggleLightButton); lightButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub Log.i("", isChecked+"------"); if(isChecked && camera == null){ camera = Camera.open(); Camera.Parameters parameters = camera.getParameters(); parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(parameters); }else if(!isChecked){ camera.release(); camera = null; }else{ camera = null; } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_light, menu); return true; } } <file_sep>package com.echoandd.ahah; import foo.AlAudioRecord; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.View.OnLongClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; public class SingleHaActivity extends Activity implements ViewSwitcher.ViewFactory,View.OnClickListener, OnLongClickListener { private int seconds=5000; private int recBufSize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); private AudioRecord audioRecord; private AlAudioRecord alAudioRecord; private TextSwitcher voiceScore; private TextView textViewInfo; @Override public void onClick(View arg0) { voiceScore.setText(String.valueOf(alAudioRecord.getVoice())); } @Override public boolean onLongClick(View arg0) { // TODO Auto-generated method stub Log.i("mmmm", "点击了"); //初始化 this.changetext(0); audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, recBufSize); alAudioRecord = new AlAudioRecord( audioRecord, seconds, recBufSize); if(alAudioRecord.getRunStatus()){ Toast.makeText(this,"已经点击,请等待~", Toast.LENGTH_SHORT).show(); return false; } alAudioRecord.goRecord(); int time = 5000; while (true) { try { Thread.sleep(200); time -= 500; if(time<0){ alAudioRecord.setRun(false); break; } this.changetext(alAudioRecord.getVoice()); } catch (Exception e) { e.printStackTrace(); } } this.changetext(alAudioRecord.getVoice()); Toast.makeText(this, "可以松开手指啦~\n^_^", Toast.LENGTH_LONG).show(); return true; } @Override public View makeView() { TextView t = new TextView(this); t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); t.setTextSize(36); return t; } private void changetext(Object obj) { voiceScore.setText(String.valueOf(obj)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_ha); voiceScore = (TextSwitcher)findViewById(R.id.textSwitcher1); voiceScore.setFactory(this); Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); voiceScore.setInAnimation(in); voiceScore.setOutAnimation(out); this.changetext(0); Button button = (Button) findViewById(R.id.goSButton); button.setOnLongClickListener(this); textViewInfo = (TextView) findViewById(R.id.textViewInfo); textViewInfo.setText("0"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return false; } } <file_sep><java> just test </java>
762b61507e4aec9b1f8695e2ff6bf460888cff8d
[ "Markdown", "Java", "Ant Build System" ]
4
Markdown
yangl326-Dylan/Ahah
fd756d82c644add7f30b8f5e814fb75ccc26615d
4b5bf9b1fedd8b95758d885e43a7156190e6fbeb
refs/heads/main
<file_sep>python-crontab python-redmine pyyaml requests urllib2<file_sep>#!/usr/bin/python3 from redminelib import Redmine from typing import List from html_eltex_loc import eltex_get_employee_status, Status import yaml import datetime ymlconf = "config.yml" config = yaml.safe_load(open(ymlconf)) defconfig = config['defconfig'] userconf = config['userconf'] timetracker = config['timetracker'] redmine = Redmine( defconfig['red'], key=userconf['key'], raise_attr_exception=('Project', 'Issue', 'WikiPage') ) def get_current_tasks() -> List: tasks = [] this_user = redmine.user.get('current') in_progress = filter(lambda task: task.status.id == 2, this_user.issues) for item in in_progress: tasks.append(item.id) return tasks def commit_changes(): try: summ = sum(timetracker['current_tasks'].values()) for key, value in timetracker['current_tasks'].items(): time_entry = redmine.time_entry.create( issue_id=key, spent_on=datetime.date.today(), hours=timetracker['online'] * value / summ, activity_id=9, # Code ) time_entry.save() except Exception: return if __name__ == "__main__": # complete config info if config['userconf']['redname'] is None: this_user = redmine.user.get('current') userconf['redname'] = this_user.login with open(ymlconf, 'w') as file: yaml.dump(config, file) # commit existed changes if user goes offline if eltex_get_employee_status(userconf['redname']) != Status.work: # commit changes here commit_changes() # reset commited values timetracker['current_tasks'] = {} timetracker['online'] = None with open(ymlconf, 'w') as file: yaml.dump(config, file) exit() # find in_progress tasks = get_current_tasks() # update values in yaml file tracker = timetracker['current_tasks'] for item in tasks: try: if tracker[item] is None: tracker[item] = 0 else: tracker[item] = tracker[item] + 1 except KeyError: # value doesnt exist tracker[item] = 0 if timetracker['online'] is None: timetracker['online'] = 0 else: timetracker['online'] = timetracker['online'] + 1 with open(ymlconf, 'w') as file: yaml.dump(config, file) <file_sep># redmine_timechecker Collect information about user activity from Redmine to yaml file, commit labor costs to the server. ### Usage Set up yours checker enviroment by editing [config.yml](https://gitlab.eltex.loc/irina.emelyanova/redmine_timechecker/blob/master/README.md). ```sh userconf: key: <%your access key%> name: null redname: null ``` Then install requirements and start the [main.py](https://gitlab.eltex.loc/irina.emelyanova/redmine_timechecker/blob/master/main.py) ```sh pip3 install -r requirements.txt chmod +x main.py cronjob.py ./main.py ``` To watch created cron task do ```sh crontab -e ```<file_sep>#!/usr/bin/python3 from crontab import CronTab from os import getcwd as pwd # use crontab -e to edit commands in eour's user cronfile if needed # use crontab -l to show all cronjobs with CronTab(user=True) as cron: location = pwd() job = cron.new(command=f'{location}/cronjop.py') job.hour.every(1) job.set_comment("Timechecker for redmine") cron.write() <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- from re import search as grep import requests from html.parser import HTMLParser from yaml import safe_load from enum import Enum class Status(Enum): error = 0 work = 1 no_work = 2 holiday = 3 regName = r"^'[A-z]+\.[A-z]+.[A-z]+'$" regStatus = r'^[A-z-]*-icon' parser = HTMLParser() config = safe_load(open("config.yml")) def eltex_get_employee_status(find_name): names, status = __eltex_get_people_list() if find_name in names: idx = names.index(find_name) return status[idx] else: return Status.error def __eltex_get_people_list(url = config['defconfig']['eltex_host']) -> list: names = [] status = [] page = requests.get(url).text.split() for item in page: guess = parser.unescape(item) if (grep(regName, guess) is not None): names.append(guess[1:-1]) if (grep(regStatus, guess) is not None): st = guess[0:-len('-icon')] if 'no-job' in st: status.append(Status.no_work) elif 'job' in st: status.append(Status.work) elif 'holiday' in st: status.append(Status.holiday) return names, status
41834fba3120d071b5cefc55db53f587407eb4df
[ "Markdown", "Python", "Text" ]
5
Text
LieutenantRed/redmine_timecheck
7ec67979037b684a23c52f68024a24ad8cc54fba
9c458025434eb900ecf468640e5663d73e614a7b
refs/heads/master
<repo_name>DianaNeumann/arp_spoofer<file_sep>/arp_spoofer.py #!usr/bin/etc/env python # -*- coding: utf-8 -*- import scapy.all as scapy import sys def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst = "ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast / arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] return answered_list[0][1].hwdst def spoof(target_ip,spoof_ip): target_mac = get_mac(target_ip) packet = scapy.ARP(op = 2,pdst = target_ip,hwdst = target_mac, psrc = spoof_ip) scapy.send(packet,verbose = False) def restore(dest_ip,src_ip): dest_mac = get_mac(dest_ip) src_mac = get_mac(src_ip) packet = scapy.ARP(op=2, pdst = dest_ip, hwdst = dest_mac, psrc = src_ip, hwsrc = src_mac) scapy.send(packet, count = 10, verbose = False) sent_packets_counter = 0 try: while True: spoof('**.**.**.**','**.**.**.**') spoof('**.**.**.**','**.**.**.**') sent_packets_counter += 2 print('\r[+] Packets sent: ' + str(sent_packets_counter)), sys.stdout.flush() except KeyboardInterrupt: print('\r[=] Resetting ARP-table.Good Luck C:') restore('**.**.**.**','**.**.**.**') restore('**.**.**.**','**.**.**.**')
80901f2d648af437470bb70b1f2c92b834a3e644
[ "Python" ]
1
Python
DianaNeumann/arp_spoofer
ff007af43eb42e1a46eddc4151224caf31c5a9be
21e257ed53fee84e3fc299d2c07ef981761ce68d
refs/heads/master
<file_sep># S8-AIOB ## AIOB Calculators ### Prerequisites - JDK8 - [SBT](https://www.scala-sbt.org/download.html) ### Run In [aiob-calculators](aiob-calculators) run the following command: ```shell-session $ sbt run ```<file_sep>import os import random # https://keepass.info/help/base/pwgenerator.html # wIZpjhqGn6cBovKi6loO - default example charset_def = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' charset_upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' charset_lower = 'abcdefghijklmnopqrstuvwxyz' charset_number = '0123456789' charset_special = '!"#$%&()*+,-:;<=>?@^_`' def generate_default(): password = '' for i in range(20): password = password + random.choice(charset_def) return password def generate_comprehensive16(): password = '' password = <PASSWORD> + random.<PASSWORD>(charset_upper) password = <PASSWORD> + random.<PASSWORD>(charset_number) password = <PASSWORD> + random.<PASSWORD>(charset_special) print(len(password)) print(password) for i in range(len(password), 20): password = <PASSWORD> + random.choice(charset_def + charset_special) print(len(password)) print(password) return password def main(): with open('./output.txt', 'a+', encoding='utf-8', errors='ignore') as outfile: for i in range(50000): outfile.write(generate_comprehensive16() + '\n') if __name__ == '__main__': main()<file_sep>import re import string from os import listdir from os.path import isfile, join # '^[!-.0-9?-Z^-z]+$' # at least 1 symbol # latin letters only # numbers # some specials # ASCII codes allowed: <33,46> + <48,57> + <63,90> + <94, 122> input_path = 'G:/BreachCompilation/data' output_path = 'G:/BreachCompilation/real' #output_path = '../../resources/passwords/real' raw_passwords = [[], 0] regular8_passwords = [[], 0] regular16_passwords = [[], 0] #nospecial8_passwords = [[], 0] comprehensive8_passwords = [[], 0] comprehensive16_passwords = [[], 0] passwords_per_file = 500000 def parse_file(input_path): with open(input_path, encoding='utf-8', errors='ignore') as infile: for line in infile: password = parse_line(line) if password is not None: filter_password(password) def parse_line(line): # dump lines are in format 'email:password' i = line.strip().rfind(':') if i == -1: return None line = line[i + 1:] if re.match('^[!-.0-9?-Z^-z]+$', line) is not None: return line else: return None # old method #def filter_password(password): # global raw_passwords # global regular8_passwords # #global nospecial8_passwords # global comprehensive8_passwords # raw_passwords[0].append(password) # if (len(password.strip()) >= 8): # regular8_passwords[0].append(password) # # !@#$%^&*()-_=+[]{};’:”,./<>? # if re.search('[0-9]', password) is None: # return # if re.search('[A-Z]', password) is None: # return # if re.search('[!@#$%^&*\-_=+’”,\/.?]', password) is None: # return # comprehensive8_passwords[0].append(password) # quick shitpatch to get 16s def filter_password(password): global regular16_passwords global comprehensive16_passwords if (len(password.strip()) >= 16): regular16_passwords[0].append(password) # !@#$%^&*()-_=+[]{};’:”,./<>? if re.search('[0-9]', password) is None: return if re.search('[A-Z]', password) is None: return if re.search('[!@#$%^&*\-_=+’”,\/.?]', password) is None: return comprehensive16_passwords[0].append(password) def count_lines_in_file(file): return sum(1 for _ in file) # probably can be pythonized and improved a lot def write_passwords(filename, passwords): print(f'saving {filename}: {len(passwords[0])} (file-{passwords[1]})') if len(passwords[0]) < 1: return outfile = open(f'{output_path}/{filename}/{filename}_{passwords[1]}.txt', 'a+', encoding='utf-8') outfile.seek(0) lines = 0 for line in outfile: lines += 1 if lines >= passwords_per_file: print(f'file full, creating new') passwords[1] += 1 outfile.close() write_passwords(filename, passwords) return for i in range(passwords_per_file - lines): if len(passwords[0]) < 1: return outfile.write(passwords[0].pop()) if len(passwords[0]) > 0: outfile.close() write_passwords(filename, passwords) def parse_directory(dir_path): print(f'working on {dir_path}...') contents = listdir(dir_path) for content in contents: content_path = join(dir_path, content) if isfile(content_path): parse_file(content_path) else: print(f'nested folder {content_path}') parse_directory(content_path) #write_passwords('raw', raw_passwords) write_passwords('regular16', regular16_passwords) write_passwords('comprehensive16', comprehensive16_passwords) def main(): # dumps are split into files named 0-9 and a-z (first letter of email) namerange = string.digits + string.ascii_lowercase namerange2 = string.ascii_lowercase for dirname in namerange: parse_directory(f'{input_path}/{dirname}') # for dirname in namerange2: # for filename in namerange: # print(f'working on {dirname}-{filename}') # if os.path.isfile(f'{input_path}/{dirname}/{filename}'): # parse_file(f'{input_path}/{dirname}/{filename}') # else: # print(f'{dirname}-{filename}: nested directory detected') # for nested_filename in namerange: # parse_file( # f'{input_path}/{dirname}/{filename}/{nested_filename}') # write_passwords('raw', raw_passwords) # write_passwords('regular8', regular8_passwords) # #write_passwords('nospecial8', nospecial8_passwords) # write_passwords('comprehensive8', comprehensive8_passwords) if __name__ == '__main__': main()<file_sep>#!/usr/bin/env python3 # Copyright 2016 Symantec Corporation # # 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 # standard library import argparse import csv import sys import os # internal imports import backoff import model import ngram_chain import pcfg parser = argparse.ArgumentParser() parser.add_argument('training_set', help='password training set') parser.add_argument('password_set', help='password strength test set') parser.add_argument('--min_ngram', type=int, default=2, help='minimum n for n-grams') parser.add_argument('--max_ngram', type=int, default=5, help='maximum n for n-grams') parser.add_argument('--backoff_threshold', type=int, default=10, help='threshold for backoff') parser.add_argument('--samplesize', type=int, default=10000, help='sample size for Monte Carlo model') required = parser.add_argument_group('required arguments') args = parser.parse_args() with open(args.training_set, 'rt') as f: training = [w.strip('\r\n') for w in f] models = { '{}-gram'.format(i): ngram_chain.NGramModel(training, i) for i in range(args.min_ngram, args.max_ngram + 1) } models['Backoff'] = backoff.BackoffModel(training, 10) models['PCFG'] = pcfg.PCFG(training) samples = { name: list(model.sample(args.samplesize)) for name, model in models.items() } estimators = { name: model.PosEstimator(sample) for name, sample in samples.items() } modelnames = sorted(models) outfilename = f'./{os.path.splitext(args.password_set)[0]}_output.csv' outfile = open(outfilename, 'w', encoding='utf-8', newline='') writer = csv.writer(outfile) writer.writerow(['password'] + modelnames) with open(args.password_set, 'r', encoding='utf-8') as infile: for password in infile: password = <PASSWORD>') estimations = [ estimators[name].position(models[name].logprob(password)) for name in modelnames ] writer.writerow([password] + estimations) outfile.close()<file_sep>_default : generator out-of-box keepassa; 20 długość, duże + małe litery, cyfry _comprehensive16_16 : generator dodatkowo używający specjalnych; 16 długość _comprehensive16_20 : generator dodatkowo używający specjalnych; 20 długość <file_sep>import os import json input_path = '../../resources/passwords/fake/test.txt' output_path = '../../resources/weir_prep' lcs_occurence = {} # { 'structure': { 'terminal': occurence } } # example: # { # "LL": { "aa": 3, "bb": 1, "cc": 1, "dd": 1, "ee": 1 }, # "DD": { "11": 3, "22": 1, "33": 1, "55": 1, "66": 1 }, # "LLLLLL": { "aabbcc": 1 }, # "DDDD": { "1122": 1, "6666": 1 }, # "LLLL": { "hhhh": 1 } # } def get_structure_char(char): if char.isalpha(): return 'L' if char.isdigit(): return 'D' return 'S' def get_structure(text): structure = '' for char in text: structure += get_structure_char(char) return structure def get_lcs_list(text): print(f'lcs list for: {text}') previous_structure = get_structure_char(text[0]) lcs = text[0] lcs_list = [] for char in text[1:]: structure_char = get_structure_char(char) if structure_char != previous_structure: lcs_list.append(lcs) lcs = '' lcs += char previous_structure = structure_char lcs_list.append(lcs) return lcs_list # def get_lcs_list(text): # print(f'lcs list for: {text}') # previous_char = get_structure_char(text[0]) # lcs = previous_char # lcs_list = [] # for char in text[1:]: # structure_char = get_structure_char(char) # if structure_char != previous_char: # lcs_list.append(lcs) # lcs = '' # lcs += structure_char # previous_char = structure_char # print(lcs_list) # return lcs_list def write_terminal(terminal, structure): with open(f'{output_path}/{structure}.txt', 'a+', encoding='utf-8') as outfile: outfile.write(f'{terminal}\n') def add_lcs_occurence(lcs_list): global lcs_occurence for lcs in lcs_list: lcs_structure = get_structure(lcs) if lcs_structure not in lcs_occurence: lcs_occurence[lcs_structure] = {lcs: 1} elif lcs not in lcs_occurence[lcs_structure]: lcs_occurence[lcs_structure][lcs] = 1 else: lcs_occurence[lcs_structure][lcs] += 1 def parse_input_file(): with open(input_path, encoding='utf-8', errors='ignore') as infile: for line in infile: terminal = line.strip() lcs_list = get_lcs_list(terminal) structure = get_structure(terminal) write_terminal(terminal, structure) add_lcs_occurence(lcs_list) def write_lcs_occurence(): global lcs_occurence with open(f'{output_path}/lcs.json', 'a+', encoding='utf-8') as outfile: outfile.write(json.dumps(lcs_occurence)) def main(): parse_input_file() write_lcs_occurence() if __name__ == '__main__': main()<file_sep>import argparse import random parser = argparse.ArgumentParser() parser.add_argument('input', help='input path') parser.add_argument('output', help='output path') parser.add_argument('--count', type=int, default=50000) args = parser.parse_args() def main(): lines = [] selected_lines = [] with open(args.input, encoding='utf-8', errors='ignore') as infile: for line in infile: lines.append(line) for i in range(args.count): selected_lines.append(random.choice(lines)) with open(args.output, 'a+', encoding='utf-8') as outfile: for selected_line in selected_lines: outfile.write(selected_line) if __name__ == '__main__': main()
fdcdda62f06a90242c5633bb2099dbbe26187a98
[ "Markdown", "Python", "Text" ]
7
Markdown
JanJPK/S8-AIOB
bafe24a35b7559ec1c56579ea5a2010262a0c863
1a0382d8126700272df4ff0c49484553851b3d5d
refs/heads/master
<file_sep># i know qualllitii coooootteeeeeeeeeeeeeeeeeeee :D f = open("../main.py", "w") f.write('input_number = input("Wpisz liczbe: ")') number = 1 # reppppeatttt 100x while number < 100: if (number % 2) == 0: f.write(f'\nif(input_number == "{number}"):\n') f.write(' print("liczba jest parzysta")\n') else: f.write(f'\nif(input_number == "{number}"):\n') f.write(' print("liczba jest nieparzysta")\n') number += 1 f.close() <file_sep># is_even VERY GUUT CHECKKERRR NUMBER IS EVEEEENNNNNNNN fri suupport -> https://hexmc.space/discord # CODE KUALITI 10000/10 # AND DONT OPEN `dont_read_this_pls.py` FILE PLZZZZZ
794a0c515bf4469e4a9b913626d5ec71559cfe9b
[ "Markdown", "Python" ]
2
Python
Noxerek1337/isEven
27c43ae84e9465aedc2eb74299856012e5c96c86
0689c180903d06719b67376b9cdd5e36de51b614
refs/heads/master
<file_sep># Search-Macro 네이버 연관검색어, 자동 완성 매크로 <file_sep>from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from time import sleep FIRST_KEYWORD = [] SECOND_KEYWORD = [] # 네이버 검색 시 블로그탭에서 찾으려는 text BLOG_KEYWORD = [] # 구글 검색 시 찾고자하는 링크 일부 GOOGLE_KEYWORD = [] # 네이버 블로그 몇 페이지까지 검색할 것인지 NAVER_PAGE = 5 # 구글 블로그 몇 페이지까지 검색할 것인지 GOOGLE_PAGE = 5 def chromeOpen(): options = webdriver.ChromeOptions() # secret 모드 options.add_argument("--incognito") driver = webdriver.Chrome('./chromedriver', options=options) driver.implicitly_wait(3) return driver def moveNaver(driver): driver.get("https://www.naver.com") # 해당 사이트 제목이 NAVER 확인 assert "NAVER" in driver.title def moveGoogle(driver): driver.get("https://www.google.com/") def searchNaver(driver, viewType, keyword): if viewType == 0: # www.naver.com search_elem = driver.find_element_by_xpath("//input[@class='input_text']") # 천천히 검색하도록 for character in keyword: search_elem.send_keys(character) sleep(0.3) search_elem.submit() else: # 상세페이지에서 다시 검색하는 경우 search_elem = driver.find_element_by_xpath("//input[@class='box_window']") # 천천히 검색하도록 search_elem.clear() for character in keyword: search_elem.send_keys(character) sleep(0.3) search_elem.submit() driver.implicitly_wait(3) def searchGoogle(driver, keyword): search_elem = driver.find_element_by_xpath("//input[@title='검색']") search_elem.clear() # 천천히 검색하도록 for character in keyword: search_elem.send_keys(character) sleep(0.3) search_elem.submit() def clickBlog(driver): # 블로그 클릭 blog_elem = driver.find_element_by_xpath("//span[text()='블로그']") blog_elem.click() driver.implicitly_wait(3) def closeTab(driver): # 현재 탭 종료 driver.switch_to.window(driver.window_handles[1]) driver.close() driver.switch_to.window(driver.window_handles[0]) def findKeyword(driver, keyword): page = NAVER_PAGE while(page): # 검색 결과 페이지에서 특정 문자열을 포함하는 링크 텍스트 찾기 try: elem = driver.find_element_by_partial_link_text(keyword) elem.click() # 1분간 쉼 sleep(60) closeTab(driver) return except NoSuchElementException: page -= 1 try: next_elem = driver.find_element_by_xpath("//a[text()='다음페이지']") next_elem.click() driver.implicitly_wait(3) except NoSuchElementException: page = 0 break if page == 0: print("❌ error: 현재 페이지에서", keyword, "를 찾을 수 없습니다.") def findLink(driver, keyword): page = GOOGLE_PAGE while(page): try: path = "//a[contains(@href,'" + keyword + "')]" elem = driver.find_element_by_xpath(path) elem.click() # 1분간 쉼 sleep(60) driver.back() return except NoSuchElementException: page -= 1 try: next_elem = driver.find_element_by_xpath("//span[text()='다음']") next_elem.click() driver.implicitly_wait(3) except NoSuchElementException: page = 0 break if page == 0: print("❌ error: 현재 페이지에서", keyword, "를 찾을 수 없습니다.") def macroNaverBlog(driver): clickBlog(driver) for blogKeyword in BLOG_KEYWORD: findKeyword(driver, blogKeyword) def macroNaver(driver, firstKeyword, secondKeyword): moveNaver(driver) searchNaver(driver, 0, firstKeyword) macroNaverBlog(driver) searchNaver(driver, 1, firstKeyword + ' ' + secondKeyword) macroNaverBlog(driver) driver.close() def macroGoogle(driver, firstKeyword, secondKeyword): moveGoogle(driver) searchGoogle(driver, firstKeyword) for googleKeyword in GOOGLE_KEYWORD: findLink(driver, googleKeyword) searchGoogle(driver, firstKeyword + ' ' + secondKeyword) for googleKeyword in GOOGLE_KEYWORD: findLink(driver, googleKeyword) driver.close() if __name__ == "__main__": while(1): idx = 0 cnt = 2 * len(FIRST_KEYWORD) * len(SECOND_KEYWORD) for firstKeyword in FIRST_KEYWORD: for secondKeyword in SECOND_KEYWORD: driver = chromeOpen() idx += 1 print("Naver - ", firstKeyword, secondKeyword, "검색 시작! 🍀 (", idx, "/", cnt , ")") macroNaver(driver, firstKeyword, secondKeyword) driver = chromeOpen() idx += 1 print("Google - ", firstKeyword, secondKeyword, "검색 시작! 🐳 (", idx, "/", cnt , ")") macroGoogle(driver, firstKeyword, secondKeyword) # 30분마다 반복 sleep(1800)
bac13525f3d2aba46a1287c6aaec613d44daf183
[ "Markdown", "Python" ]
2
Markdown
Sunghee2/Search-Macro
6eaab949b3c851b585b5110d4d3b099ba9fb2b63
2093204a930f85af452dc11cf758ba8dee24495e
refs/heads/master
<file_sep>// // Created by <NAME> on 3/21/20. // #ifndef ALGORITHMS_TEST_HPP #define ALGORITHMS_TEST_HPP //#include <gtest/gtest.h> void testAll(){ //testing::InitGoogleTest(); //RUN_ALL_TESTS(); } #endif //ALGORITHMS_TEST_HPP <file_sep>// // Created by <NAME> on 3/21/20. // #include "tests/test.hpp" #include <set> int main(){ //testAll(); std::set<int> s; return 0; } <file_sep>cmake_minimum_required(VERSION 3.14) project(algorithms) set(CMAKE_CXX_STANDARD 14) add_executable(algorithms src/BinaryTree.hpp src/RedBlackTree.hpp src/SplayTree.hpp src/BPlusTree.hpp src/BPlusTree.tpp tests/catch.cpp tests/bplus_tree_test.cpp src/BinomialHeap.tpp src/BinomialHeap.hpp tests/binomial_heap_test.cpp src/AVLTree.tpp src/AVLTree.hpp tests/avltree_test.cpp) target_link_libraries(algorithms)<file_sep>// // Created by darik on 4/12/2020. // #include "catch.hpp" #include "../src/BinomialHeap.hpp" #include <memory> using std::shared_ptr; using std::make_shared; TEST_CASE("Insertion in Binomil Heap", "[BinomialHeap]") { BinomialHeap<int> heap; heap.insert(5); CHECK(heap._head->_key == 5); heap.insert(7); CHECK(heap._head->_child->_key == 7); heap.insert(3); CHECK(heap._head->_key == 3); for (int i = 0; i < 12; ++i) { heap.insert(rand() % 500); } CHECK(heap._head->_degree == 0); heap.insert(500); CHECK(heap._head->_degree == 4); } TEST_CASE("Searching minimum in Binomial Heap", "[BinomialHeap]") { BinomialHeap<int> heap; int minimum{1500}; for (int i = 0; i < 100; ++i) { int element = rand() % 1500; if (element < minimum) minimum = element; heap.insert(element); } REQUIRE(heap.getMinimum()->_key == minimum); } TEST_CASE("Extracting minimum in Binomial Heap", "[BinomialHeap]") { BinomialHeap<int> heap; for (int i = 0; i < 100; ++i) { heap.insert(i); } CHECK(heap.extractMin()->_key == 0); CHECK(heap.getMinimum()->_key == 1); for (int i = 0; i < 10; ++i) { heap.extractMin(); } CHECK(heap.getMinimum()->_key == 11); } TEST_CASE("Final test Binomial Heap", "[BinomialHeap]") { BinomialHeap<int> heap1, heap2; for(int i=0; i<100; ++i) { int element = rand()%15000; heap1.insert(element); heap2.insert(element); } for(int i=0; i<5; ++i) { int element = heap1.extractMin()->_key; heap1.insert(element); } CHECK(heap1.getMinimum()->_key == heap2.getMinimum()->_key); }<file_sep>// // Created by darik on 4/12/2020. // #ifndef ALGORITHMS_BINOMIALHEAP_HPP #define ALGORITHMS_BINOMIALHEAP_HPP #include <iostream> #include <vector> #include <memory> using std::shared_ptr; using std::make_shared; template<typename T> class BinomialNode { public: BinomialNode() = default; explicit BinomialNode(T value) : _key{value} {} T _key; shared_ptr<BinomialNode<T>> _child; shared_ptr<BinomialNode<T>> _parent; shared_ptr<BinomialNode<T>> _sibling; // for roots in Binomial heap sibling is the next root in the list unsigned _degree = 0; // number of children }; template<typename T> class BinomialHeap { public: BinomialHeap() = default; shared_ptr<BinomialNode<T>> _head; void insert(T value); shared_ptr<BinomialNode<T>> getMinimum(); void decreaseKey(shared_ptr<BinomialNode<T>> node, const T &k); shared_ptr<BinomialNode<T>> extractMin(); // return pointer on the node with min key void remove(shared_ptr<BinomialNode<T>> node); void _merge(); void _sort(); // sort by degrees of roots in increasing order }; #include "BinomialHeap.tpp" #endif //ALGORITHMS_BINOMIALHEAP_HPP <file_sep>// // Created by <NAME> on 3/21/20. // #include <gtest/gtest.h> #include "../src/RedBlackTree.hpp" #include <cmath> #include <set> #include <random> TEST(RBTree, CreationSearcing){ //RedBlackTreeNode<int> * node; RedBlackTree<int> tree; tree.insert(3); EXPECT_TRUE(tree.search(3) != nullptr); EXPECT_EQ(tree.search(3)->value(), 3); tree.insert(5); tree.insert(2); tree.insert(17); EXPECT_TRUE(tree.search(11) == nullptr); EXPECT_EQ(tree.search(2)->value(), 2); EXPECT_EQ(tree.search(17)->value(), 17); } TEST(RBTree, Height){ RedBlackTree<int> tree; for (int i = 0 ; i < 1000; ++i) { tree.insert(i); EXPECT_TRUE(tree.height() <int(2 * (std::log2(i + 1) + 1))); } } TEST(RBTree, Remove){ RedBlackTree<int> tree; for (int i = 0 ; i < 20; ++i) { tree.insert(i); } tree.remove(tree.search(4)); tree.remove(tree.search(5)); tree.remove(tree.search(6)); tree.remove(tree.search(7)); tree.remove(tree.search(8)); tree.remove(tree.search(9)); tree.remove(tree.search(10)); tree.remove(tree.search(11)); tree.remove(tree.search(12)); tree.remove(tree.search(13)); for (int i = 0; i < 4; ++i){ EXPECT_TRUE(tree.search(i) != nullptr); } for (int i = 4; i < 14; ++i) EXPECT_EQ(tree.search(i), nullptr); for (int i = 14; i < 20; ++i){ EXPECT_TRUE(tree.search(i) != nullptr); } } TEST(RBTree, select1){ RedBlackTree<int> tree; for (int i = 0 ; i < 20; ++i) { tree.insert(i); } for (int i = 1 ; i <= 20; ++i) { EXPECT_TRUE(tree.select(i) != nullptr); EXPECT_EQ(tree.select(i)->value(), i - 1); } tree.remove(tree.search(5)); tree.remove(tree.search(6)); tree.remove(tree.search(7)); tree.remove(tree.search(8)); tree.remove(tree.search(9)); tree.remove(tree.search(10)); tree.remove(tree.search(11)); tree.remove(tree.search(12)); tree.remove(tree.search(13)); for (int i = 6 ; i <= 11; ++i) { EXPECT_TRUE(tree.select(i) != nullptr); EXPECT_EQ(tree.select(i)->value(), i + 8); } } TEST(RBTree, select2){ RedBlackTree<int> tree; for (int i = 0 ; i < 20; ++i) tree.insert(i); for (int i = 0; i < 10; ++i) tree.remove(tree.search(i * 2)); for (int i = 0; i < 10; ++i) EXPECT_EQ(tree.select(i + 1)->value(), 2 * i + 1); } TEST(RBTree, order1){ RedBlackTree<int> tree; for (int i = 0 ; i < 20; ++i) { tree.insert(i); } tree.remove(tree.search(5)); tree.remove(tree.search(6)); tree.remove(tree.search(7)); tree.remove(tree.search(8)); tree.remove(tree.search(9)); tree.remove(tree.search(10)); tree.remove(tree.search(11)); tree.remove(tree.search(12)); tree.remove(tree.search(13)); for (int i = 6 ; i <= 11; ++i) { EXPECT_EQ(tree.order(tree.search(i + 8)), i); } } TEST(RBTree, order2){ RedBlackTree<int> tree; for (int i = 0 ; i < 20; ++i) tree.insert(i); for (int i = 0; i < 10; ++i) tree.remove(tree.search(i * 2)); for (int i = 0; i < 10; ++i) EXPECT_EQ(tree.order(tree.search(2 * i + 1)), i + 1); } TEST(RBTree, CompareWithSTL){ srand(time(0)); RedBlackTree<int> tree; std::set <int> s; for (int i = 0; i < 10000; ++i){ int value = rand() % 10000000; if (!s.count(value)) { tree.insert(value); s.insert(value); } } for (auto it = s.begin(); it != s.end(); ++it){ EXPECT_TRUE(tree.search(*it) != nullptr); } } TEST(RBTree, Iterator){ std::vector <int> v; RedBlackTree<int> tree; for (int i = 0; i < 10; ++i) { tree.insert(i); v.push_back(i); } auto p = tree.print(); for (auto i : p) std::cout << i.first << " " << i.second << "\n";/* int k = 0; for (auto it = tree.begin(); it!= tree.end(); ++it, k++) EXPECT_EQ(*it, v[k]);*/ } <file_sep>// // Created by darik on 4/10/2020. // #include "catch.hpp" #include "../src/BPlusTree.hpp" #include <memory> using std::shared_ptr; using std::make_shared; TEST_CASE("Searching in B+-tree", "algorithms") { shared_ptr<BPlusTree<int>> tree = make_shared<BPlusTree<int>>(5); for (int i = 0; i < 100; ++i) { tree->insert(i, make_shared<int>(i)); } for (int i = 0; i < 10; ++i) { int searched{rand() % 100}; CHECK(*tree->search(searched) == searched); } for (int i = 0; i < 5; ++i) { CHECK(tree->search(rand() + 100) == nullptr); } } TEST_CASE("Insertion in B+-tree", "algorithms") { shared_ptr<BPlusTree<int>> tree = make_shared<BPlusTree<int> >(4); for (int i = 0; i < 100; ++i) { tree->insert(i, make_shared<int>(i)); } for (int i = 0; i < 5; ++i) { CHECK(tree->search(rand() % 100) != nullptr); } } TEST_CASE("Removing from B+-tree", "algorithms") { shared_ptr<BPlusTree<int>> tree = make_shared<BPlusTree<int> >(5); for (int i = 0; i < 199; ++i) { tree->insert(i, make_shared<int>(i)); } for (int i = 0; i < 10; ++i) { int removing = rand() % 199; tree->remove(removing); CHECK(tree->search(removing) == nullptr); } } TEST_CASE("Final test in B+-tree", "algorithms") { shared_ptr<BPlusTree<int>> tree = make_shared<BPlusTree<int>>(13); for (int i = 0; i < 1000; ++i) { int element = rand() % 15000; tree->insert(element, make_shared<int>(element)); } for (int i = 0; i < 5; ++i) { int element = rand() % 15000; tree->remove(element); CHECK(tree->search(element) == nullptr); tree->insert(element, make_shared<int>(element)); CHECK(tree->search(element) != nullptr); } } TEST_CASE("Iterators in B+-tree", "algorithms") { BPlusTree<int> tree(13); for (auto i = 0; i < 100; ++i) { tree.insert(i, make_shared<int>(i)); } int counter{0}; auto it = tree.begin(); for(; it != tree.end(); ++it){ CHECK(*it == counter); ++counter; } CHECK(counter == 100); }<file_sep>// // Created by <NAME> on 3/21/20. // #ifndef ALGORITHMS_REDBLACKTREE_HPP #define ALGORITHMS_REDBLACKTREE_HPP #include "BinaryTree.hpp" #include "Tree.hpp" #include <string> #include <vector> enum color { RED, BLACK }; template <typename TreeItem> class RedBlackTree; template <typename TreeItem> class RedBlackTreeNode:Node<TreeItem>{ private: TreeItem _value; RedBlackTreeNode<TreeItem> * _left; RedBlackTreeNode<TreeItem> * _right; RedBlackTreeNode<TreeItem> * _parent; color _color; int _size; public: explicit RedBlackTreeNode<TreeItem> ( TreeItem item, RedBlackTreeNode<TreeItem> * left = nullptr, RedBlackTreeNode<TreeItem> * right = nullptr, RedBlackTreeNode<TreeItem> * parent = nullptr); TreeItem value(); friend class RedBlackTree<TreeItem>; Node<TreeItem> * next(); }; template <typename TreeItem> class RedBlackTree { private: RedBlackTreeNode <TreeItem> * _root; void _leftRotate(RedBlackTreeNode<TreeItem> * node); void _rightRotate(RedBlackTreeNode<TreeItem> * node); void _fixInsertion(RedBlackTreeNode<TreeItem> * node); void _print(RedBlackTreeNode<TreeItem> * node, std::vector<std::pair<TreeItem, TreeItem>> &events); void _fixDeleting(RedBlackTreeNode <TreeItem> * x); int _height(RedBlackTreeNode<TreeItem> * node); RedBlackTreeNode<TreeItem> * _select(RedBlackTreeNode<TreeItem> * node, int k); void _fixSize(RedBlackTreeNode<TreeItem> * node); int _updateSize(RedBlackTreeNode<TreeItem> * node); void _updateNode(RedBlackTreeNode<TreeItem> * node); public: RedBlackTree(); void insert(TreeItem item); RedBlackTreeNode <TreeItem> * search(TreeItem item); std::vector<std::pair<TreeItem, TreeItem>> print(); void remove(RedBlackTreeNode <TreeItem> * z); int height(); RedBlackTreeNode<TreeItem> * select(int k); void updateSize(); int order(RedBlackTreeNode <TreeItem> * node); TreeIterator<TreeItem> begin(){ if (_root == nullptr) return TreeIterator<TreeItem>(nullptr); RedBlackTreeNode<TreeItem> * cur = _root; while (cur->_left != nullptr) cur = cur->_left; return TreeIterator<TreeItem>(cur); } TreeIterator<TreeItem> end(){ return nullptr; } }; template<typename TreeItem> void RedBlackTree<TreeItem>::insert(TreeItem item) { if (_root == nullptr){ _root = new RedBlackTreeNode<TreeItem>(item); _root->_color = BLACK; _root->_size = 1; } else { RedBlackTreeNode<TreeItem> *current_node = _root; RedBlackTreeNode<TreeItem> *previous_node = nullptr; while (current_node != nullptr) { current_node->_size++; if (item < current_node->_value) { previous_node = current_node; current_node = current_node->_left; } else { previous_node = current_node; current_node = current_node->_right; } } current_node = new RedBlackTreeNode<TreeItem>(item); current_node->_parent = previous_node; if (item < previous_node->_value){ previous_node->_left = current_node; } else { previous_node->_right = current_node; } _fixInsertion(current_node); } } template<typename TreeItem> void RedBlackTree<TreeItem>::_fixInsertion(RedBlackTreeNode<TreeItem> *node) { while (node->_parent != nullptr && node->_parent->_color == RED){ if (node->_parent == node->_parent->_parent->_left){ if (node->_parent->_parent->_right != nullptr){ if (node->_parent->_parent->_right->_color == RED){ node->_parent->_color = BLACK; node->_parent->_parent->_right->_color = BLACK; node->_parent->_parent->_color = RED; node = node->_parent->_parent; } else { if (node == node->_parent->_right){ node = node->_parent; _leftRotate(node); } node->_parent->_color = BLACK; node->_parent->_parent->_color = RED; _rightRotate(node->_parent->_parent); } } else { if (node == node->_parent->_right){ node = node->_parent; _leftRotate(node); } node->_parent->_color = BLACK; node->_parent->_parent->_color = RED; _rightRotate(node->_parent->_parent); } } else { if (node->_parent->_parent->_left != nullptr){ if (node->_parent->_parent->_left->_color == RED){ node->_parent->_color = BLACK; node->_parent->_parent->_left->_color = BLACK; node->_parent->_parent->_color = RED; node = node->_parent->_parent; } else { if (node->_parent->_left == node){ node = node->_parent;//tuta ostanovilsia _rightRotate(node); } node->_parent->_color = BLACK; node->_parent->_parent->_color = RED; _leftRotate(node->_parent->_parent); } } else { if (node->_parent->_left == node){ node = node->_parent;//tuta ostanovilsia _rightRotate(node); } node->_parent->_color = BLACK; node->_parent->_parent->_color = RED; _leftRotate(node->_parent->_parent); } } } _root->_color = BLACK; } template<typename TreeItem> RedBlackTreeNode<TreeItem> *RedBlackTree<TreeItem>::search(TreeItem item) { RedBlackTreeNode <TreeItem> * node = _root; while (node != nullptr && node->_value != item){ if (item < node->_value) node = node->_left; else node = node->_right; } return node; } template<typename TreeItem> void RedBlackTree<TreeItem>::_fixDeleting(RedBlackTreeNode<TreeItem> *x) { if (x == nullptr) return; while (x != _root && x->_color == BLACK) { if (x == x->_parent->_left) { RedBlackTreeNode <TreeItem> * w = x->_parent->_right; if (w->_color == RED) { w->_color = BLACK; x->_parent->_color = RED; _leftRotate (x->_parent); w = x->_parent->_right; } if (w->_left->_color == BLACK && w->_right->_color == BLACK) { w->_color = RED; x = x->_parent; } else { if (w->_right->_color == BLACK) { w->_left->_color = BLACK; w->_color = RED; _rightRotate (w); w = x->_parent->_right; } w->_color = x->_parent->_color; x->_parent->_color = BLACK; w->_right->_color = BLACK; _leftRotate (x->_parent); x = _root; } } else { RedBlackTreeNode <TreeItem> * w = x->_parent->_left; if (w->_color == RED) { w->_color = BLACK; x->_parent->_color = RED; _rightRotate(x->_parent); w = x->_parent->_left; } if (w->_right->_color == BLACK && w->_left->_color == BLACK) { w->_color = RED; x = x->_parent; } else { if (w->_left->_color == BLACK) { w->_right->_color = BLACK; w->_color = RED; _leftRotate(w); w = x->_parent->_left; } w->_color = x->_parent->_color; x->_parent->_color = BLACK; w->_left->_color = BLACK; _rightRotate (x->_parent); x = _root; } } } x->_color = BLACK; } template<typename TreeItem> std::vector<std::pair<TreeItem, TreeItem>> RedBlackTree<TreeItem>::print() { std::vector<std::pair<TreeItem, TreeItem>> events; _print(_root, events); return events; } template<typename TreeItem> void RedBlackTree<TreeItem>::_leftRotate(RedBlackTreeNode<TreeItem> *node) { RedBlackTreeNode<TreeItem> * y = node->_right; y->_size = node->_size; RedBlackTreeNode<TreeItem> * x = y->_left; y->_parent = node->_parent; if (node->_parent == nullptr){ _root = y; } else if (node == node->_parent->_left){ node->_parent->_left = y; } else node->_parent->_right = y; node->_parent = y; y->_left = node; node->_right = x; node->_size = 1; if (node->_left) node->_size += node->_left->_size; if (node->_right) node->_size += node->_right->_size; if (x != nullptr) x->_parent = node; } template<typename TreeItem> void RedBlackTree<TreeItem>::_rightRotate(RedBlackTreeNode<TreeItem> *node) { RedBlackTreeNode<TreeItem> * y = node->_left; y->_size = node->_size; RedBlackTreeNode<TreeItem> * x = y->_right; y->_parent = node->_parent; if (node->_parent == nullptr){ _root = y; } else if (node == node->_parent->_left){ node->_parent->_left = y; } else node->_parent->_right = y; node->_parent = y; y->_right = node; node->_left = x; node->_size = 1; if (node->_left) node->_size += node->_left->_size; if (node->_right) node->_size += node->_right->_size; if (x != nullptr) x->_parent = node; } template<typename TreeItem> void RedBlackTree<TreeItem>::_print(RedBlackTreeNode<TreeItem> *node, std::vector<std::pair<TreeItem, TreeItem>> &events) { if (node == nullptr) return; if (node->_left != nullptr){ events.push_back({node->value(),node->_left->value()}); _print(node->_left, events); } if (node->_right != nullptr){ events.push_back({node->value(),node->_right->value()}); _print(node->_right, events); } } template<typename TreeItem> void RedBlackTree<TreeItem>::remove(RedBlackTreeNode<TreeItem> *z) { //_fixSize(z); RedBlackTreeNode <TreeItem> *x, *y; if (z == nullptr) return; if (z->_left == nullptr || z->_right == nullptr) { /* y has a NIL node as a child */ y = z; } else { /* find tree successor with a NIL node as a child */ y = z->_right; while (y->_left != nullptr) y = y->_left; }// y == 6? _fixSize(y); /* x is y's only child */ if (y->_left != nullptr) x = y->_left; else x = y->_right;//x == null /* remove y from the parent chain */ if (x != nullptr) x->_parent = y->_parent; if (y->_parent != nullptr) if (y == y->_parent->_left) y->_parent->_left = x; else y->_parent->_right = x; else _root = x; if (y != z) z->_value = y->value(); if (y->_color == BLACK) _fixDeleting (x); delete y; } template<typename TreeItem> RedBlackTree<TreeItem>::RedBlackTree() { _root = nullptr; } template<typename TreeItem> int RedBlackTree<TreeItem>::_height(RedBlackTreeNode<TreeItem> *node) { if (node == nullptr) return 0; return std::max(_height(node->_left), _height(node->_right)) + 1; } template<typename TreeItem> int RedBlackTree<TreeItem>::height() { return _height(_root); } template<typename TreeItem> RedBlackTreeNode<TreeItem> *RedBlackTree<TreeItem>::select(int k) { if (_root == nullptr || _root->_size < k) return nullptr; return _select(_root, k); } template<typename TreeItem> RedBlackTreeNode<TreeItem> *RedBlackTree<TreeItem>::_select(RedBlackTreeNode<TreeItem> *node, int k) { int r = 1; if (node->_left != nullptr) r = node->_left->_size + 1; if (r == k) return node; if (k < r) return _select(node->_left, k); return _select(node->_right, k - r); } template<typename TreeItem> void RedBlackTree<TreeItem>::updateSize() { _updateSize(_root); } template<typename TreeItem> void RedBlackTree<TreeItem>::_fixSize(RedBlackTreeNode<TreeItem> *node) { if (node == nullptr) return; node->_size--; _fixSize(node->_parent); } template<typename TreeItem> int RedBlackTree<TreeItem>::_updateSize(RedBlackTreeNode<TreeItem> *node) { if (node == nullptr) return 0; return node->_size = _updateSize(node->_left) + _updateSize(node->_right) + 1; } template<typename TreeItem> void RedBlackTree<TreeItem>::_updateNode(RedBlackTreeNode<TreeItem> *node) { if (node == nullptr) return; node->_size = 1; if (node->_left) node->_size += node->_left->_size; if (node->_right) node->_size += node->_right->_size; } template<typename TreeItem> int RedBlackTree<TreeItem>::order(RedBlackTreeNode<TreeItem> *node) { int r = 1; if (node->_left != nullptr) r += node->_left->_size; RedBlackTreeNode <TreeItem> * cur = node; while (cur->_parent != nullptr){ if (cur->_parent->_right == cur){ r += 1; if (cur->_parent->_left) r += cur->_parent->_left->_size; } cur = cur->_parent; } return r; } template<typename TreeItem> RedBlackTreeNode<TreeItem>::RedBlackTreeNode(TreeItem item, RedBlackTreeNode<TreeItem> *left, RedBlackTreeNode<TreeItem> *right, RedBlackTreeNode<TreeItem> *parent) : _value(item), _color(RED), _left(left), _right(right), _parent(parent) { _size = 0; } template<typename TreeItem> TreeItem RedBlackTreeNode<TreeItem>::value() { return _value; } template<typename TreeItem> Node<TreeItem> *RedBlackTreeNode<TreeItem>::next() { if (_right != nullptr) return _right; RedBlackTreeNode<TreeItem> * cur = this; while (cur->_parent != nullptr && cur->_parent->_right == cur) cur = cur->_parent; return cur->_parent; } #endif //ALGORITHMS_REDBLACKTREE_HPP <file_sep>// // Created by darik on 4/10/2020. // #define CATCH_CONFIG_MAIN #include "catch.hpp" <file_sep>#ifndef ALGORITHMS_BINARYTREE_HPP #define ALGORITHMS_BINARYTREE_HPP template <typename T> class BinaryNode { public: T _value; BinaryNode<T>* _left = nullptr; BinaryNode<T>* _right = nullptr; BinaryNode<T>* _parent = nullptr; }; template <typename T> class BinaryTree { public: virtual void insert(T value); virtual void remove(T value); virtual BinaryNode<T>* search(T value); }; #endif //ALGORITHMS_BINARYTREE_HPP <file_sep>// // Created by darik on 4/12/2020. // #include "BinomialHeap.hpp" template<typename T> void BinomialHeap<T>::_sort() // bubble sort { if (this->_head == nullptr) return; auto cur = &(this->_head); while ((*cur)->_sibling != nullptr) { auto cur1 = cur; while ((*cur1)->_sibling != nullptr) { if ((*cur1)->_sibling->_degree < (*cur1)->_degree) { shared_ptr<BinomialNode<T>> tmp = *cur1; (*cur1) = (*cur1)->_sibling; tmp->_sibling = (*cur1)->_sibling; (*cur1)->_sibling = tmp; } cur1 = &((*cur1)->_sibling); } cur = &((*cur)->_sibling); } } template<typename T> void BinomialHeap<T>::_merge() // merging of roots with equal degrees { auto curH = &(this->_head); while ((*curH)->_sibling != nullptr) { if ((*curH)->_degree == (*curH)->_sibling->_degree) { if ((*curH)->_key <= (*curH)->_sibling->_key) { // root with greater key should become a child of root with lesser key auto tmp = (*curH)->_sibling; (*curH)->_sibling = tmp->_sibling; tmp->_sibling = (*curH)->_child; (*curH)->_child = tmp; tmp->_parent = *curH; (*curH)->_degree++; } else { auto tmp = (*curH)->_sibling; (*curH)->_sibling = tmp->_sibling; tmp->_sibling = *curH; *curH = tmp; } } else { curH = &((*curH)->_sibling); } } } template<typename T> shared_ptr <BinomialHeap<T>> merge(BinomialHeap<T>& H1, BinomialHeap<T>& H2) // merging 2 heaps { //and return pointer on new heap which is result of merging // if (H1 == nullptr) return H2; // if (H2 == nullptr) return H1; shared_ptr<BinomialHeap<T>> answer = make_shared<BinomialHeap<T>>(); auto curH = &(answer->_head); auto curH1 = H1._head; auto curH2 = H2._head; while (curH1 != nullptr && curH2 != nullptr) { if (curH1->_degree < curH2->_degree) { (*curH) = curH1; curH = &((*curH)->_sibling); curH1 = curH1->_sibling; } else { (*curH) = curH2; curH = &((*curH)->_sibling); curH2 = curH2->_sibling; } } if (curH1 == nullptr) { while (curH2 != nullptr) { *(curH) = curH2; curH = &((*curH)->_sibling); curH2 = curH2->_sibling; } } else { while (curH1 != nullptr) { *(curH) = curH1; curH = &((*curH)->_sibling); curH1 = curH1->_sibling; } } curH = &(answer->_head); answer->_merge(); answer->_sort(); return answer; } template<typename T> void BinomialHeap<T>::insert(T value) //creating new heap with only root with key=value and merging this heap and new one { shared_ptr<BinomialNode<T>> new_node = make_shared<BinomialNode<T>>(value); if (this->_head == nullptr) this->_head = new_node; else { new_node->_sibling = _head; _head = new_node; this->_merge(); } } template<typename T> shared_ptr<BinomialNode<T>> BinomialHeap<T>::getMinimum() // the minimum key is in the one of root nodes { auto answer = this->_head; auto curH = this->_head; while (curH != nullptr) { if (curH->_key < answer->_key) { answer = curH; } curH = curH->_sibling; } return answer; } template<typename T> shared_ptr <BinomialNode<T>> BinomialHeap<T>::extractMin() { if (this->_head == nullptr) return nullptr; auto answer = this->_head; auto curH = this->_head; auto previous = this->_head; while (curH->_sibling != nullptr) // finding root with min key { if (curH->_sibling->_key < answer->_key) { answer = curH->_sibling; previous = curH; } curH = curH->_sibling; } if (answer == previous) { this->_head = answer->_sibling; } else { previous->_sibling = answer->_sibling; } shared_ptr<BinomialHeap<T>> new_heap = make_shared<BinomialHeap<T>>(); // creating new heap where roots are children // of root with min key auto cur = answer->_child; auto cur_new = &new_heap->_head; while (cur != nullptr) { cur->_parent = nullptr; *cur_new = cur; cur_new = &((*cur_new)->_sibling); cur = cur->_sibling; } auto merged_heap = merge(*this, *new_heap); // merging this heap and new one this->_head = merged_heap->_head; return answer; } template<typename T> void BinomialHeap<T>::decreaseKey(shared_ptr <BinomialNode<T>> node, const T &k) { if (k > *node->key) return; // method can only decrease value *node->key = k; while (node->parent != nullptr && node->parent->key > node->key) { auto tmp = *node; node->key = node->parent->key; node = node->parent; node->key = tmp.key; } } template<typename T> void BinomialHeap<T>::remove(shared_ptr <BinomialNode<T>> node) { this->decreaseKey(node, T()); // set the key of removing node to min possible this->extractMin(); this->_sort(); }
4876291423fda899f5aab29713994a719a57c99e
[ "CMake", "C++" ]
11
C++
IvanRamyk/tree-analytics
1d0dc4baf1a0e6f8c0b02c1c730dc2ee22e51bf4
9525b493c69d1e8c5015394d3f39171cb7c81803
refs/heads/master
<file_sep>package com.example.muhammadshoaib.onboardingexample.SharedPreference; import android.content.Context; import android.content.SharedPreferences; import com.example.muhammadshoaib.onboardingexample.R; public class PrefernceManager { //declaring varriables private Context context; private SharedPreferences sharedPreferences; //constructor takes context as argument and initializing context object public PrefernceManager(Context context){ this.context=context; //this method will give shared preference getSharedPreference(); } private void getSharedPreference(){ sharedPreferences=context.getSharedPreferences(context.getString(R.string.my_preference),Context.MODE_PRIVATE); } //this method will write shared preference public void writePreference(){ SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putString(context.getString(R.string.my_preference_key),"INIT_OK"); editor.commit(); } //this method will check preference and return a status varriable public boolean checkPreference(){ boolean status = false; if (sharedPreferences.getString(context.getString(R.string.my_preference_key),"null").equals("null")){ status = false; } else { status = true; } return status; } } <file_sep>package com.example.muhammadshoaib.onboardingexample.Activities; import android.content.Intent; import android.os.Build; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import com.example.muhammadshoaib.onboardingexample.Adapters.MPagerAdapter; import com.example.muhammadshoaib.onboardingexample.SharedPreference.PrefernceManager; import com.example.muhammadshoaib.onboardingexample.R; public class WelcomeActivity extends AppCompatActivity implements View.OnClickListener { private ViewPager mPager; private int[] layouts = {R.layout.first_slide,R.layout.second_slide,R.layout.third_slide}; private MPagerAdapter mPagerAdapter; private LinearLayout DotsLayout; private ImageView[] dots; private Button bnNext,bnSkip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //to check if the user has opened the app before or not if (new PrefernceManager(this).checkPreference()){ CallHomeActivity(); } //if the api level is 19 or above, this will aply transparent notification bar if (Build.VERSION.SDK_INT >= 19){ getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } setContentView(R.layout.activity_welcome); //initializing mPager=(ViewPager) findViewById(R.id.viewPager); mPagerAdapter=new MPagerAdapter(layouts,this); mPager.setAdapter(mPagerAdapter); DotsLayout=(LinearLayout) findViewById(R.id.dotsLayout); bnNext=findViewById(R.id.btnNext); bnSkip=findViewById(R.id.btnSkip); //setting click listeners on buttons bnSkip.setOnClickListener(this); bnNext.setOnClickListener(this); //this method will create page indicators for view pager createDots(0); //listener for view pager mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { //this method will create page indictor createDots(position); //if the current page in the viewpager is the last one , this code will change the text of "next" to "start" and hide the "skip" button if(position == layouts.length -1 ){ bnNext.setText("Start"); bnSkip.setVisibility(View.INVISIBLE); } else { bnNext.setText("Next"); bnSkip.setVisibility(View.VISIBLE); } } @Override public void onPageScrollStateChanged(int i) { } }); } //this method gets the current position in viewpager and set the indicators private void createDots(int current_position){ if (DotsLayout!=null){ DotsLayout.removeAllViews(); dots=new ImageView[layouts.length]; for (int i=0; i<layouts.length; i++) { dots[i] = new ImageView(this); //this condition will be true varriable i is equal to current position and change the dot icon color into active if(i == current_position){ dots[i].setImageDrawable(ContextCompat.getDrawable(this,R.drawable.active_dots)); } //otherwise it will change the dot color into inactive else { dots[i].setImageDrawable(ContextCompat.getDrawable(this,R.drawable.default_dots)); } //creates an instance of linear layout parameters instance and pass height and width into arguments LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); //sets the margins of linear layout params.setMargins(4,0,4,0); //it will generate dot icons into linear layout DotsLayout.addView(dots[i],params); } } } //onclick listeners for skip and next buttons @Override public void onClick(View view) { //checking which button is clicked switch (view.getId()){ //it will load next page on click case R.id.btnNext: LoadNextSlide(); break; //it will launch main activity and write the preference that next time main activity will launch directly case R.id.btnSkip: CallHomeActivity(); new PrefernceManager(this).writePreference(); break; } } //this method will launch main activity private void CallHomeActivity() { startActivity(new Intent(getApplicationContext(),MainActivity.class)); finish(); } //this method will get current slide in view pager and check if it is the last slide or not private void LoadNextSlide(){ int next_slide= mPager.getCurrentItem() + 1; //if the current slide is not last slide it will add the next slide if(next_slide < layouts.length){ mPager.setCurrentItem(next_slide); } // otherwise if it is the last slide it will call main activity and write the preference else { CallHomeActivity(); new PrefernceManager(this).writePreference(); } } }
4589b8bbf39addd70db55bb763f748c1d1075af5
[ "Java" ]
2
Java
shoaibmushtaq/OnBoardingExample
2481148fe125af9765f648c3b4d80552ae6985fe
f102ba80f85990b65b7a28d56d25557cabaecf2d
refs/heads/master
<repo_name>tnaughts/HorsetrackCommandLine<file_sep>/horse_betting/app/helpers/horses_helper.rb module HorsesHelper end <file_sep>/horse_betting/spec/models/money_spec.rb require 'spec_helper' describe Money do let (:bill_data1) do { :money_id => 1, :denomination => 5, :inventory => 10 } end let (:bill_data2) do { :money_id => 1, :denomination => 10, :inventory => 10 } end let(:money){Money.new(id: 1)} let(:bill1){Bill.new(bill_data1)} let(:bill2){Bill.new(bill_data2)} describe 'associations' do it { should have_many(:bills) } end describe 'attributes' do it "has readable cash" do money.save bill1.save bill2.save expect(money.total_cash).to eq 150 end end end <file_sep>/horse_betting/db/migrate/20161013193510_create_bills.rb class CreateBills < ActiveRecord::Migration def change create_table :bills do |t| t.integer :money_id, {null: false} t.integer :inventory, {null: false} t.integer :denomination, {null: false} t.timestamps null: false end end end <file_sep>/horse_betting/app/controllers/bets_controller.rb class BetsController < ApplicationController def self.check_bet(horse_number, wagered_amount) payout_string = "Payout: " betted_horse = Horse.find_by(number: horse_number) if betted_horse != nil bet = Bet.new(horse_id: betted_horse.id, bet_amount: wagered_amount) if bet.save if betted_horse.winner payout_string << "#{betted_horse.name}, $#{bet.payout} \n" payout_string << MoniesController.dispense(bet.payout) else return "No Payout: #{betted_horse.name}" end else return "Invalid Bet: #{wagered_amount}" end else return "Invalid Horse Number: #{horse_number}" end payout_string end end <file_sep>/horse_betting/app/controllers/bills_controller.rb class BillsController < ApplicationController def self.show bills = Bill.order(:denomination) bill_string = "Inventory: \n" bills.each do |bill| bill_string << "#{bill.display} \n" end bill_string end def self.restock bills = Bill.all bills.each do |bill| bill.restock_bills end end end <file_sep>/horse_betting/spec/models/bill_spec.rb require 'spec_helper' describe Bill do let (:bill_data) do { :money_id => 1, :denomination => 11, :inventory => 10 } end let(:bill){Bill.new(bill_data)} describe 'associations' do it { should belong_to(:money) } end describe 'validations' do it { should validate_presence_of(:money_id)} it { should validate_presence_of(:inventory)} it { should validate_presence_of(:denomination)} it { should validate_numericality_of(:inventory)} end describe 'attributes' do it 'has readable attributes' do expect(bill.denomination).to eq 11 expect(bill.inventory).to eq 10 expect(bill.bill_cash).to eq 110 end it 'restocks inventory' do bill.inventory = 5 expect(bill.inventory).to eq 5 bill.restock_bills expect(bill.inventory).to eq 10 end it 'displays a string of the denomination and inventory' do expect(bill.display).to eq "$11, 10" end end end <file_sep>/README.md # HorsetrackCommandLine A command line application that simulates a horse betting machine ## Ruby built on Ruby version ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin15.0] built on Rails version Rails 4.2.1 In order to run ## Open folder ~ :> cd HorsetrackCommandLine/horse_betting ## Bundle horse_betting :> bundle install ## Create database Migrations and Seed horse_betting :> rake db:create horse_betting :> rake db:migrate horse_betting :> rake db:seed ## Run Program horse_betting :> ruby runner.rb ## Tests -Tests are viewable in the horse_betting/spec folder -Tests have been completed for Models and Controllers ## Run tests horse_betting :> bundle exec rspec ## Design Utilized a postgres database to store horses, bets, horses, bills and money ### Horses Stores number, name, odds, boolean winner, and timestamps *Reasoning: need to strore/update/delete horses easily* ### Bets stores bet amount, and horse_id *Reasoning: may need to access amount of bets for a particular horse to dynamically calculate odds, ensure bet is valid* ### Bills stores bill denomination, and inventory limited to 10 inventory can easily be changed by editing 2 lines of code in application once on validation and once on model method *frequently access bills to dispense money, need to access cash on hand* ### Monies May also be referred to as a machine. Linked to bills *Need to access all bills for a particular machine. Liklihood that we will need multiple machines* <file_sep>/horse_betting/app/controllers/monies_controller.rb class MoniesController < ApplicationController def self.dispense(amount) dispensed_list = "Dispensing: \n" m = Money.first all_bills = m.bills.order(denomination: :desc) #ensure bills are greatest to least for dispesing return "Insufficient funds: $#{amount}" if amount > m.total_cash i = 0 to_be_paid = amount while to_be_paid > 0 && i < all_bills.length to_be_paid = sub_from_inventory(all_bills[i], to_be_paid, dispensed_list) i += 1 end return "Insufficient Funds: $#{amount}" if to_be_paid > 0 dispensed_list end def self.sub_from_inventory(bill, amount, dispensed_list) divisor = amount/bill.denomination num_bills_dispensed = 0 if (divisor > 0) && (bill.inventory > 0) #confirm that divisor is greater than one and there are bills if bill.inventory >= divisor bill.inventory -= divisor amount -= bill.denomination * divisor bill.save num_bills_dispensed = divisor else #catch case if not enough bills amount -= bill.bill_cash num_bills_dispensed = bill.inventory bill.inventory = 0 bill.save end end dispensed_list.insert(13, "$#{bill.denomination}, #{num_bills_dispensed} \n") #inserting strings amount end end <file_sep>/horse_betting/db/migrate/20161013202633_add_winner_to_horses.rb class AddWinnerToHorses < ActiveRecord::Migration def change add_column :horses, :winner, :boolean, default: false end end <file_sep>/horse_betting/spec/controllers/monies_controller_spec.rb require 'spec_helper' describe MoniesController do let (:bill_data1) do { :money_id => 1, :denomination => 1, :inventory => 10 } end let (:bill_data2) do { :money_id => 1, :denomination => 5, :inventory => 10 } end let (:bill_data3) do { :money_id => 1, :denomination => 10, :inventory => 10 } end let (:bill_data4) do { :money_id => 1, :denomination => 20, :inventory => 10 } end let(:money){Money.new(id: 1)} let(:bill1){Bill.new(bill_data1)} let(:bill2){Bill.new(bill_data2)} let(:bill3){Bill.new(bill_data3)} let(:bill3){Bill.new(bill_data4)} # describe 'sub_from_inventory' do # it # end end<file_sep>/horse_betting/app/models/money.rb class Money < ActiveRecord::Base has_many :bills def total_cash all_bills = self.bills total = 0 all_bills.each do |bill| total += bill.bill_cash end total end end <file_sep>/horse_betting/spec/models/horse_spec.rb require 'spec_helper' describe Horse do let (:horse_data) do { :number => 1, :name => 'Secretariat', :odds => 5, } end let(:horse){Horse.new(horse_data)} describe 'attributes' do it "has a readable attributes" do # horse = Horse.new(:horse_data) expect(horse.number).to eq 1 expect(horse.name).to eq 'Secretariat' expect(horse.odds).to eq 5 end it "has writable attributes" do horse.number = 2 horse.name = 'Seabiscuit' horse.winner = true horse.odds = 8 expect(horse.number).to eq 2 expect(horse.name).to eq 'Seabiscuit' expect(horse.winner).to eq true expect(horse.odds).to eq 8 end it "has a id and default winner of false on save" do expect(horse.id).to eq nil horse.save expect(horse.winner).to eq false end it "can be checked if won or lost" do expect(horse.did_win).to eq "Lost" horse.horse_won expect(horse.did_win).to eq "Won" horse.horse_lost expect(horse.did_win).to eq "Lost" end it "can display its attributes in a string" do expect(horse.display).to eq "1, Secretariat, 5, Lost \n" end end describe 'associations' do it { should have_many(:bets) } end end<file_sep>/horse_betting/test/controllers/horses_controller_test.rb require 'test_helper' class HorsesControllerTest < ActionController::TestCase # test "the truth" do # assert true # end # describe HorsesController do # describe '.' end <file_sep>/horse_betting/app/models/bill.rb class Bill < ActiveRecord::Base belongs_to :money validates_presence_of :money_id, :inventory, :denomination validates_uniqueness_of :denomination validates_numericality_of :inventory, less_than_or_equal_to: 10 def display "$#{self.denomination}, #{self.inventory}" end def restock_bills self.inventory = 10 self.save end def bill_cash self.inventory * self.denomination end end <file_sep>/horse_betting/app/models/bet.rb class Bet < ActiveRecord::Base belongs_to :horse validates_presence_of :bet_amount, :horse_id validates_numericality_of :bet_amount, only_integer: true def payout self.horse.odds * self.bet_amount end end <file_sep>/horse_betting/app/models/horse.rb class Horse < ActiveRecord::Base has_many :bets validates_presence_of :odds, :number, :name validates_uniqueness_of :name, :number def did_win if self.winner return "Won" else return "Lost" end end def horse_won self.winner = true self.save end def horse_lost self.winner = false self.save end def display "#{self.number}, #{self.name}, #{self.odds}, #{self.did_win} \n" end end <file_sep>/horse_betting/spec/models/bet_spec.rb require 'spec_helper' describe Bet do let (:horse_data) do { :id => 1, :number => 1, :name => 'Secretariat', :odds => 5 } end let (:bet_data) do { :horse_id => 1, :bet_amount => 5 } end let(:horse){Horse.new(horse_data)} let(:bet){Bet.new(bet_data)} describe "attributes" do it "has readable attributes" do expect(bet.bet_amount).to eq 5 expect(bet.horse_id).to eq 1 end it "calculates payout" do bet.save horse.save expect(bet.payout).to eq 25 end end describe 'associations' do it { should belong_to(:horse) } end describe 'validations' do it { should validate_presence_of(:bet_amount) } it { should validate_presence_of(:horse_id) } it { should validate_numericality_of(:bet_amount) } end end<file_sep>/horse_betting/spec/controllers/horses_controller_spec.rb require 'spec_helper' describe HorsesController do let (:horse_data) do { :number => 1, :name => 'Secretariat', :odds => 5 } end let (:horse_data2) do { :number => 2, :name => 'Nyquist', :odds => 4 } end let(:horse1){Horse.new(horse_data)} let(:horse2){Horse.new(horse_data2)} describe '.show' do it 'returns a string of the horses' do horse1.save horse2.save expect(HorsesController.show).to eq "Horses: \n1, Secretariat, 5, Lost \n2, Nyquist, 4, Lost \n" end end describe '.horse_exists' do it 'returns true if horse exists' do horse1.save expect(HorsesController.horse_exists('1')).to eq true expect(HorsesController.horse_exists('5')).to eq false end end end<file_sep>/horse_betting/app/controllers/horses_controller.rb class HorsesController < ApplicationController def self.show horses = Horse.order(:number) horses_string = "Horses: \n" horses.each do |horse| horses_string << "#{horse.display}" end horses_string end def self.update_winner(number) winning_number = number.to_i horses = Horse.order(:number) return false if !self.horse_exists(number) horses.each do |horse| if horse.number == winning_number horse.horse_won else horse.horse_lost end end true end def self.horse_exists(horse_number) Horse.find_by(number: horse_number) != nil end end <file_sep>/horse_betting/app/views/horses/horse_view.rb module HorseView def self.show(horse) "sup #{horse}" end end<file_sep>/horse_betting/spec/controllers/bills_controller_spec.rb require 'spec_helper' describe BillsController do let (:bill_data1) do { :money_id => 1, :denomination => 5, :inventory => 7 } end let (:bill_data2) do { :money_id => 1, :denomination => 10, :inventory => 4 } end let(:bill1){Bill.create(bill_data1)} let(:bill2){Bill.create(bill_data2)} describe '.show' do it 'returns a string of all of the bills and denominations' do bill1.save bill2.save expect(BillsController.show).to eq "Inventory: \n$5, 7 \n$10, 4 \n" end end end<file_sep>/horse_betting/spec/controllers/bets_controller_spec.rb require 'spec_helper' describe BetsController do let (:horse_data) do { :id => 1, :number => 1, :name => 'Secretariat', :odds => 1 } end let (:bet_data) do { :horse_id => 1, :bet_amount => 5 } end let (:bill_data) do { :money_id => 1, :denomination => 1, :inventory => 7 } end let(:money){Money.new(id: 1)} let(:bill){Bill.new(bill_data)} let(:horse){Horse.new(horse_data)} let(:bet){Bet.new(bet_data)} describe 'check_bet' do it "ensures horse is real" do expect(BetsController.check_bet(2, 1)).to eq "Invalid Horse Number: 2" end it "ensures bet amount is accepted" do horse.save expect(BetsController.check_bet(1, 1.5)).to eq "Invalid Bet: 1.5" end it "does not pay a losing horse" do horse.save expect(BetsController.check_bet(1, 5)).to eq "No Payout: Secretariat" horse.horse_won horse.save bill.save money.save expect(BetsController.check_bet(1, 5)).to eq "Payout: Secretariat, $5 \nDispensing: \n$1, 5 \n" end end end<file_sep>/horse_betting/runner.rb require_relative 'config/environment' puts BillsController.show puts HorsesController.show command = gets.chomp command.downcase! #normailize inputs while command != "q" if command[0] == "w" if !(HorsesController.update_winner(command[2..-1])) puts "Invalid Horse Number: #{command[2..-1]}" end elsif command[0] == "r" && command.length == 1 #restocking BillsController.restock elsif /^\d/ === command #utilized regex so that more accurate error messages can be displayed update_command = command.split(' ') puts BetsController.check_bet(update_command[0], update_command[1]) else puts "Invalid command: #{command}" end puts BillsController.show puts HorsesController.show command = gets.chomp command.downcase! end<file_sep>/horse_betting/db/seeds.rb #seed file, validations set on model, so multiple seeds will not create duplicates a = Horse.create(name: '<NAME>', number: 1, odds: 5, winner: true) Horse.create(name: '<NAME>', number: 2, odds: 10) Horse.create(name: '<NAME>', number: 3, odds: 9) Horse.create(name: '<NAME>', number: 4, odds: 4) Horse.create(name: '<NAME>', number: 5, odds: 3) Horse.create(name: '<NAME>', number: 6, odds: 5) Horse.create(name: '<NAME>', number: 7, odds: 6) if Money.first == nil a = Money.create() Bill.create(money_id: a.id, inventory: 10, denomination: 1) Bill.create(money_id: a.id, inventory: 10, denomination: 5) Bill.create(money_id: a.id, inventory: 10, denomination: 10) Bill.create(money_id: a.id, inventory: 10, denomination: 20) Bill.create(money_id: a.id, inventory: 10, denomination: 100) end
f65d06b8821be8c2580e3a030dadb04d2bb24760
[ "Markdown", "Ruby" ]
24
Ruby
tnaughts/HorsetrackCommandLine
6ae686dbea62dcec3dda70085b307eeb40a63357
aad87860f7a53af426690eb98bc1e29ca70ad8b3
refs/heads/master
<file_sep>// // SwiftUIView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-04. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import MapKit struct SwiftUIView: View{ @ObservedObject var locationManager = LocationManager() @State private var search: String = "" @State private var landmarks: [Landmark] = [Landmark]() @State private var tapped:Bool = false private func getNearByLandmarks(){ let request = MKLocalSearch.Request() request.naturalLanguageQuery = search let search = MKLocalSearch(request: request) search.start { (resp, err) in if let resp = resp{ let mapItems = resp.mapItems self.landmarks = mapItems.map{ Landmark(placemark: $0.placemark) } } } } func calculateOffset() -> CGFloat{ if self.landmarks.count > 0 && !self.tapped{ return UIScreen.main.bounds.size.height-UIScreen.main.bounds.size.height/4 }else if self.tapped{ return 100 }else{ return UIScreen.main.bounds.size.height } } var body: some View { ZStack(alignment: .top){ MapView(landmarks:landmarks) TextField("Search", text:$search, onEditingChanged: {_ in}) { self.getNearByLandmarks() }.textFieldStyle(RoundedBorderTextFieldStyle()) .padding() .offset(y:44) PlaceListView(landmarks: self.landmarks) { self.tapped.toggle() }.animation(.spring()) .offset(y: calculateOffset()) } } } struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { SwiftUIView() } } <file_sep>// // Constants.swift // TravelDiscovery // // Created by <NAME> on 2020-11-29. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit let HEIGHTSPACE = UIScreen.main.bounds.height/30 let WIDTHSPACE = UIScreen.main.bounds.width/10 let NAVBACKGROUNDCOLOR:UIColor = #colorLiteral(red: 0.9710348248, green: 0.5955002904, blue: 0.251747191, alpha: 1) let NAVTEXTCOLOR:UIColor = #colorLiteral(red: 0.9315580726, green: 0.9322516322, blue: 0.9350935221, alpha: 1) <file_sep>// // PopularDestinationBox.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct PopularDestinationBox:View{ let destination: Destination var body: some View{ VStack(alignment: .leading, spacing: 0){ Image(destination.imageName) .resizable() .scaledToFill() .frame(width: HEIGHTSPACE*5, height: HEIGHTSPACE*5) .cornerRadius(4) .padding(.horizontal, 6) .padding(.vertical, 6) Text(destination.name) .font(.system(size: 12, weight: .semibold)) .padding(.horizontal, 12) .foregroundColor(Color(.label)) Text(destination.country) .font(.system(size: 12, weight: .semibold)) .padding(.horizontal, 12) .padding(.bottom, 8) .foregroundColor(.gray) //.asTile() } .asTile() } } <file_sep>// // MapView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-04. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import SwiftUI import MapKit class Coordinator: NSObject, MKMapViewDelegate{ var control: MapView init(_ control:MapView) { self.control = control } func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) { if let annotationView = views.first{ if let annotation = annotationView.annotation{ if annotation is MKUserLocation{ let region = MKCoordinateRegion(center: annotation.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000 ) mapView.setRegion(region, animated: true) } } } } } struct MapView: UIViewRepresentable{ let landmarks:[Landmark] func makeUIView(context: Context) -> MKMapView { let map = MKMapView() map.showsUserLocation = true map.delegate = context.coordinator return map } func makeCoordinator() -> Coordinator { Coordinator(self) } func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) { updateAnnotations(from: uiView) } private func updateAnnotations(from mapView: MKMapView){ mapView.removeAnnotations(mapView.annotations) let annotations = self.landmarks.map(LandmarkAnnotation.init) mapView.addAnnotations(annotations) } } <file_sep>// // ActivityIndeicatorView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct ActivityIndeicatorView:UIViewRepresentable { func makeUIView(context: Context) -> UIActivityIndicatorView { let aiv = UIActivityIndicatorView(style: .large) aiv.startAnimating() aiv.color = .white return aiv } typealias UIViewType = UIActivityIndicatorView func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) { } } <file_sep>// // DiscoverCategoriesView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct DiscoverCategoriesView: View { let categories:[Category] = [ .init(name: "Art", imageName: "paintpalette.fill"), .init(name: "Sports", imageName: "sportscourt.fill"), .init(name: "Live Events", imageName: "music.mic"), .init(name: "Food", imageName: "tray.fill"), .init(name: "History", imageName: "books.vertical.fill"), ] var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(alignment: .top, spacing:14){ ForEach(categories, id: \.self) { category in NavigationLink( destination: NavigationLazyView(CategoryDetailsView(name: category.name)), label: { VStack(spacing:8){ // Spacer() Image(systemName: category.imageName) .font(.system(size: 20)) .foregroundColor(Color(#colorLiteral(red: 0.9709280133, green: 0.5917922854, blue: 0.246740669, alpha: 1))) .frame(width: HEIGHTSPACE*2.5, height: HEIGHTSPACE*2.5) .background(Color.white) .cornerRadius(HEIGHTSPACE*2.5) // .shadow(color: .gray, radius: 4, x: 0.0, y: 2) Text(category.name) .font(.system(size: 12, weight: .semibold)) .multilineTextAlignment(.center) .foregroundColor(.white) } }) } }.padding(.horizontal) } } } struct DiscoverCategoriesView_Previews: PreviewProvider { static var previews: some View { HomeView() } } <file_sep>// // UserDetailsView.swift // TravelDiscoveryLBTA // // Created by <NAME> on 11/10/20. // import SwiftUI import KingfisherSwiftUI struct UserDetailsView: View { // setup dummy vm @ObservedObject var vm: UserDetailsViewModel let user: User init(user: User) { self.user = user self.vm = .init(userId: user.id) } var body: some View { ScrollView { VStack(spacing: 12) { Image(user.imageName) .resizable() .scaledToFit() .frame(width: 60) .clipShape(Circle()) .shadow(radius: 10) .padding(.horizontal) .padding(.top) Text("\(self.vm.userDetails?.firstName ?? "") \(self.vm.userDetails?.lastName ?? "")") .font(.system(size: 14, weight: .semibold)) //OPT + 8 HStack { Text("@\(self.vm.userDetails?.username ?? "") •") Image(systemName: "hand.thumbsup.fill") .font(.system(size: 10, weight: .semibold)) Text("2541") } .font(.system(size: 12, weight: .regular)) Text("YouTuber, Vlogger, Travel Creator") .font(.system(size: 14, weight: .regular)) .foregroundColor(Color(.lightGray)) HStack(spacing: 12) { VStack { Text("\(vm.userDetails?.followers ?? 0)") .font(.system(size: 13, weight: .semibold)) Text("Followers") .font(.system(size: 9, weight: .regular)) } Spacer() .frame(width: 0.5, height: 12) .background(Color(.lightGray)) VStack { Text("\(vm.userDetails?.following ?? 0)") .font(.system(size: 13, weight: .semibold)) Text("Following") .font(.system(size: 9, weight: .regular)) } } HStack(spacing: 12) { Button(action: {}, label: { HStack { Spacer() Text("Follow") .foregroundColor(.white) Spacer() } .padding(.vertical, 8) .background(Color.orange) .cornerRadius(100) }) Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/, label: { HStack { Spacer() Text("Contact") .foregroundColor(.black) Spacer() } .padding(.vertical, 8) .background(Color(white: 0.9)) .cornerRadius(100) }) } .font(.system(size: 11, weight: .semibold)) ForEach(vm.userDetails?.posts ?? [], id: \.self) { post in VStack(alignment: .leading, spacing: 12) { KFImage(URL(string: post.imageUrl)) .resizable() .scaledToFill() .frame(height: 200) .clipped() HStack { Image(user.imageName) .resizable() .scaledToFit() .frame(height: 34) .clipShape(Circle()) VStack(alignment: .leading) { Text(post.title) .font(.system(size: 14, weight: .semibold)) Text("\(post.views) views") .font(.system(size: 12, weight: .regular)) .foregroundColor(.gray) } }.padding(.horizontal, 12) HStack { ForEach(post.hashtags, id: \.self) { hashtag in Text("#\(hashtag)") .foregroundColor(Color(#colorLiteral(red: 0.07797152549, green: 0.513774395, blue: 0.9998757243, alpha: 1))) .font(.system(size: 13, weight: .semibold)) .padding(.horizontal, 12) .padding(.vertical, 4) .background(Color(#colorLiteral(red: 0.9057956338, green: 0.9333867431, blue: 0.9763537049, alpha: 1))) .cornerRadius(20) } }.padding(.bottom) .padding(.horizontal, 12) } // .frame(height: 200) .background(Color(white: 1)) .cornerRadius(12) .shadow(color: .init(white: 0.8), radius: 5, x: 0, y: 4) } }.padding(.horizontal) }.navigationBarTitle(user.name, displayMode: .inline) } } struct UserDetailsView_Previews: PreviewProvider { static var previews: some View { HomeView() NavigationView { UserDetailsView(user: .init(name: "amy", imageName: "<NAME>", id: 0)) } } } <file_sep>// // RestaurantDetailsViewModel.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI class RestaurantDetailsViewModel: ObservableObject{ @Published var isLoading = true @Published var details: RestaurantDetails? init(id:Int){ let urlString = "https://travel.letsbuildthatapp.com/travel_discovery/restaurant?id=\(id)" guard let url = URL(string: urlString) else {return} URLSession.shared.dataTask(with: url) { (data, resp, err) in guard let data = data else {return} DispatchQueue.main.async { self.details = try?JSONDecoder().decode(RestaurantDetails.self, from: data) print("loading restaurant: ", self.details?.name) } }.resume() } } <file_sep>// // TrendingCreatorView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct TrendingCreatorView: View { let users:[User] = [.init(name: "<NAME>", imageName: "amy", id: 0), .init(name: "Billy", imageName: "billy", id: 1), .init(name: "<NAME>", imageName: "sam", id: 2) ] var body: some View{ VStack{ HStack{ Text("Trending Creators") .font(.system(size: 14, weight: .semibold)) Spacer() Text("See All") .font(.system(size: 12, weight: .semibold)) .lineLimit(nil) }.padding(.horizontal) .padding(.top) ScrollView(.horizontal, showsIndicators: false){ HStack(alignment: .top, spacing: 12){ CreatorBox(users: self.users) }.padding(.horizontal) .padding(.bottom) } } } } struct TrendingCreatorView_Previews: PreviewProvider { static var previews: some View { TrendingCreatorView() HomeView() } } // struct CreatorBox: View { let users: [User] var body: some View { ForEach(users, id: \.self) { user in NavigationLink( destination: UserDetailsView(user: user), label: { VStack(spacing:4){ Image(user.imageName) .resizable() .scaledToFill() .frame(width: HEIGHTSPACE*2.5, height: HEIGHTSPACE*2.5) .background(Color(.init(white:0.9, alpha: 1)) ) .cornerRadius(HEIGHTSPACE*2.5) .shadow(color: .gray, radius: 4, x: 0.0, y: 2) Text(user.name) .font(.system(size: 12, weight: .semibold)) .multilineTextAlignment(.center) .foregroundColor(Color(.label)) } .frame(width: HEIGHTSPACE*2.5) }) } } } <file_sep>// // DestinationDetails.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct DestinationDetails: Decodable{ let photos:[String] let description: String } <file_sep>// // PopularRestuarantView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct PopularRestuarantView: View { var body: some View{ VStack{ HStack{ Text("Popular places to eat") .font(.system(size: 14, weight: .semibold)) Spacer() Text("See All") .font(.system(size: 12, weight: .semibold)) .lineLimit(nil) }.padding(.horizontal) .padding(.top) ScrollView(.horizontal, showsIndicators:false){ HStack(spacing: 8.0){ ForEach(resturants, id: \.self) { restaurant in NavigationLink( destination: RestaurantDetailsView(restaurant: restaurant), label: { ResturantBox(restaurant: restaurant) .foregroundColor(Color(.label)) }) // Spacer() } }.padding(.horizontal) .padding(.bottom) } } } } struct PopularRestuarantView_Previews: PreviewProvider { static var previews: some View { // PopularRestuarantView() HomeView() } } <file_sep>// // CustomMapAnnotation.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct CustomMapAnnotation:View{ let attration: Attraction var body: some View{ VStack{ Image(attration.imageName) .resizable() .frame(width:HEIGHTSPACE*3.5, height:HEIGHTSPACE*2.5) .cornerRadius(4) .overlay(RoundedRectangle(cornerRadius: 4) .stroke(Color(.init(white: 0, alpha: 0.5)))) Text(attration.name) .padding(.horizontal, 6) .padding(.vertical, 4) .background(LinearGradient(gradient:Gradient(colors:[Color.red,Color.blue]), startPoint: .leading, endPoint: .trailing)) .foregroundColor(.white) //.border(Color.black) .cornerRadius(4) .overlay(RoundedRectangle(cornerRadius: 4) .stroke(Color(.init(white: 0, alpha: 0.5)))) }.shadow(radius: 5) } } <file_sep>// // UserDetails.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct UserDetails: Decodable { let username, firstName, lastName, profileImage: String let followers, following: Int let posts: [Posted] } struct Posted: Decodable, Hashable { let title, imageUrl, views: String let hashtags: [String] } <file_sep>// // NavigationLazyView.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct NavigationLazyView<T: View>: View { let build: () -> T init(_ build: @autoclosure @escaping () -> T) { self.build = build } var body: T { build() } } <file_sep>// // DestinationDetailsViewModel.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI class DestinationDetailsViewModel: ObservableObject{ @Published var isLoading = true @Published var destiantionDetails: DestinationDetails? init(name:String){ let urlString = "https://travel.letsbuildthatapp.com/travel_discovery/destination?name=\(name.lowercased())" .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" guard let url = URL(string: urlString) else{return} URLSession.shared.dataTask(with: url) { (data, resp, err) in DispatchQueue.main.async { guard let data = data else {return} do{ self.destiantionDetails = try JSONDecoder().decode(DestinationDetails.self, from: data) }catch{ print("Failed to decode JSON,",error.localizedDescription) } } }.resume() } } <file_sep>// // DestionationDetailView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-02. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import MapKit struct PopularDestinationDetailsView: View{ @ObservedObject var vm:DestinationDetailsViewModel let destination: Destination // var region: MKCoordinateRegion @State var region: MKCoordinateRegion @State var isShowingAttrations = true init(destination:Destination) { self.destination = destination self._region = State(initialValue: MKCoordinateRegion(center: .init(latitude:self.destination.latitude, longitude:self.destination.longitude), span: .init(latitudeDelta: 0.2, longitudeDelta: 0.2))) self.vm = .init(name: destination.name) print("Destination city requested:",destination.name) } var body: some View{ ScrollView{ //top pvc if let photos = vm.destiantionDetails?.photos{ DestinationHeaderContainer(imageUrlString: photos) .frame(height:HEIGHTSPACE*10) } VStack(alignment: .leading){ Text(destination.name) .font(.system(size:18,weight:.bold)) Text(destination.country) HStack{ ForEach(0..<5,id:\.self) { num in Image(systemName: "star.fill") .foregroundColor(.orange) } }.padding(.top,2) HStack{ // Text(destination.info) Text(vm.destiantionDetails?.description ?? "") .padding(.top,4) .font(.system(size:14)) Spacer() } } .padding(.horizontal) HStack{ Text("Location") .font(.system(size: 18, weight: .semibold)) Spacer() Button(action:{ isShowingAttrations.toggle() },label:{ Text("\(isShowingAttrations ? "Hide" : "Show") Attrations") .font(.system(size:14, weight:.semibold)) }) Toggle("", isOn: $isShowingAttrations) .labelsHidden() }.padding(.horizontal) //bottom Maps Map(coordinateRegion: $region, annotationItems: isShowingAttrations ? destination.attraction:[]) { attration in MapAnnotation(coordinate: .init(latitude: attration.latitude, longitude: attration.longitude)){ CustomMapAnnotation(attration: attration) } } .frame(height:HEIGHTSPACE*12) }.navigationBarTitle(destination.name,displayMode: .inline) } let attrations: [Attraction] = [ // 50.067827472166265, -122.95894709245864 // 40.709642454744966, -74.05112367258354 .init(name: "<NAME>", imageName: "whistlerMountain", latitude:48.8566, longitude:2.35), .init(name: "<NAME>", imageName: "mt_currie", latitude:35.67988, longitude:139.769584), .init(name: "<NAME>", imageName: "blackcomb", latitude:40.709642454744966, longitude:-74.05112367258354) ] } struct PopularDestinationDetailsView_Previews: PreviewProvider { static var previews: some View { HomeView() //PopularDestinationDetailsView(destination: ) } } <file_sep>// // RestaurantDetails.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct RestaurantDetails: Decodable { let id:Int let description,name,city,country,category,thumbnail: String let popularDishes: [Dish] let reviews: [Review] let photos: [String] } struct Dish: Decodable, Hashable { let name,price,photo:String let numPhotos: Int } struct Review: Decodable, Hashable { let text:String let rating:Int let user : ReviewUser } struct ReviewUser: Decodable, Hashable { let username, firstName,lastName,profileImage:String let followers,following,id:Int let posts: [Post] } struct Post: Decodable, Hashable{ let title,imageUrl,views: String let hashtags: [String] } <file_sep>// // ResturantBox.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI struct ResturantBox: View{ let restaurant: Resturant var body: some View{ HStack{ Image(restaurant.imageName) .resizable() .scaledToFill() .frame(width: HEIGHTSPACE*2.5, height: HEIGHTSPACE*2.5) .cornerRadius(4) .padding(.horizontal, 6) .padding(.vertical, 6) VStack(alignment: .leading, spacing:HEIGHTSPACE/2){ HStack{ Text(restaurant.name) //Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/, label: { Image(systemName: "ellipsis") .foregroundColor(.gray) }) } HStack{ Image(systemName: "star.fill") Text("4.7 • sushi • $$") } Text("tokyo, Japan") }.font(.system(size: 12, weight: .semibold)) } .asTile() } } <file_sep>// // CategoryDetailsView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI //import KingfisherSwiftUI import SDWebImageSwiftUI struct CategoryDetailsView:View { private let name:String @ObservedObject private var vm: CategoryDetailsViewModel init(name:String) { print("newwork requeist for \(name)") self.name = name self.vm = .init(name: name) } //Where do I perform my network activity code? // @ObservedObject var vm = CategoryDetailsViewModel() @available(iOS 14.0, *) var body: some View{ ZStack{ if vm.isLoading{ VStack{ ActivityIndeicatorView() Text("Loading..") .foregroundColor(.white) .font(.system(size:16, weight:.semibold)) }.padding() .background(Color.black) }else{ ZStack{ if !vm.errorMessage.isEmpty{ VStack(spacing: 12){ Image(systemName: "xmark.octagon.fill") .font(.system(size: 64, weight: .semibold) ) .foregroundColor(.red) Text(vm.errorMessage) } }else{ ScrollView{ ForEach(vm.places,id:\.self){ place in VStack(alignment:.leading, spacing:0){ // KFImage(URL(string: place.thumbnail)!) WebImage(url: URL(string: place.thumbnail) ) .resizable() .indicator(.activity) // Activity Indicator .transition(.fade(duration: 0.5)) .scaledToFill() Text(place.name) .font(.system(size:12,weight:.semibold)) .padding() }.asTile() .padding() } } } } } } .navigationBarTitle(name, displayMode: .inline) } } //struct CategoryDetailsView_Previews: PreviewProvider { // static var previews: some View { // NavigationView{ // CategoryDetailsView(name: "") // } // } //} <file_sep>// // PopularDestinationView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import MapKit struct PopularDestinationView: View { var body: some View{ VStack{ HStack{ Text("Popular Destinations") .font(.system(size: 14, weight: .semibold)) Spacer() Text("See All") .font(.system(size: 12, weight: .semibold)) .lineLimit(nil) }.padding(.horizontal) .padding(.top) ScrollView(.horizontal, showsIndicators: false){ HStack(spacing: 8.0){ ForEach(0..<3, id: \.self) { num in NavigationLink( destination: NavigationLazyView(PopularDestinationDetailsView(destination: destinations[num])), label: { PopularDestinationBox(destination: destinations[num]) .padding(.bottom) }) } }.padding(.horizontal) } } } } struct PopularDestinationView_Previews: PreviewProvider { static var previews: some View { NavigationView{ PopularDestinationDetailsView(destination: .init(name: "Parius", country: "France", imageName: "eiffel_tower", info: "", latitude:48.86064473141706, longitude:2.297619224300003, attraction: [Attraction]())) } HomeView() } } <file_sep>// // TileModifier.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI extension View{ func asTile() -> some View{ modifier(TileModifer()) } } struct TileModifer: ViewModifier{ func body(content: Content) -> some View { content .background(Color.white ) .cornerRadius(5) .shadow(color: .init(.sRGB, white: 0.6, opacity: 1), radius: 4, x: 0.0, y: 2) } } extension Color { static let discoverBackground = Color(.init(white:0.95, alpha: 1)) } <file_sep># Travel Discovery <p float = "center"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/1.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/2.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/3.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/4.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/5.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/6.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/7.PNG" width="200" height="400"> <img src="https://github.com/28cmm/TravelDiscovery/blob/master/picture/screenshot/8.PNG" width="200" height="400"> </p> ## Getting Started ## Built With * SwiftUI * CoreLocation * Mapkit * UIViewRepresentable ## Third Party Libary * [KingFisher]() - getting image ## Contributing Contributions are always welcome! Please read the [contribution guidelines](contributing.md) first. ## Authors * **28cm** - *Initial work* - [<NAME>](www.joshuafang.com) ## License This project is licensed under the MIT License - see the [LICENSE.md]() file for details <file_sep>// // User.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct User:Hashable{ let name,imageName:String let id:Int } <file_sep>// // Category.swift // TravelDiscovery // // Created by <NAME> on 2020-11-28. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import SwiftUI struct Category: Hashable { let name, imageName:String } <file_sep>// // UserDetailsViewModel.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI class UserDetailsViewModel: ObservableObject { @Published var userDetails: UserDetails? init(userId: Int) { // network code guard let url = URL(string: "https://travel.letsbuildthatapp.com/travel_discovery/user?id=\(userId)") else { return } URLSession.shared.dataTask(with: url) { (data, resp, err) in DispatchQueue.main.async { guard let data = data else { return } do { self.userDetails = try JSONDecoder().decode(UserDetails.self, from: data) } catch let jsonError { print("Decoding failed for UserDetails:", jsonError) } print(data) } }.resume() } } <file_sep>// // ReviewBottomView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-03. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct ReviewBottomView: View { let reviews: [Review] var body: some View{ HStack(){ Text("Customer Reviews") .font(.system(size: 16, weight:.bold)) Spacer() }.padding(.horizontal) // if let reviews = vm.details?.reviews { ForEach(reviews, id: \.self){ review in VStack(alignment:.leading){ HStack(){ KFImage(URL(string: review.user.profileImage)) .resizable() .scaledToFit() .frame(width:HEIGHTSPACE*2) .clipShape(Circle()) VStack(alignment:.leading, spacing:4){ Text("\(review.user.firstName) \(review.user.lastName)") .font(.system(size: 14, weight:.bold)) HStack(spacing:2){ ForEach(0..<review.rating,id:\.self){ star in Image(systemName: "star.fill") }.foregroundColor(.orange) let time = 5 - review.rating ForEach(0..<time,id:\.self){ star in Image(systemName: "star.fill") }.foregroundColor(.gray) } .font(.system(size:12)) } Spacer() Text("Dec 2020") .font(.system(size: 14, weight:.bold)) } Text(review.text) .font(.system(size: 14, weight:.regular)) } } .padding(.horizontal) } } //struct ReviewBottomView_Previews: PreviewProvider { // static var previews: some View { // ReviewBottomView(reviews: [Review()]) // } //} <file_sep>// // RestInnerPhotosView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-03. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct RestInnerPhotosView: View { var photosUrls:[String] @State var mode = "grid" @State var shouldShowFullScreenModal = false @State var selectedPhotoIndex = 0 init(photoUrls:[String]){ self.photosUrls = photoUrls } var body: some View { GeometryReader{ proxy in ScrollView{ Picker("Test", selection: $mode) { Text("Grid").tag("grid") Text("List").tag("list") }.pickerStyle(SegmentedPickerStyle()) .padding() Spacer() .fullScreenCover(isPresented:$shouldShowFullScreenModal,content:{ ZStack(alignment: .topLeading){ Color.black.ignoresSafeArea() RestaurantCarouselView(imageUrlString: photosUrls, selectedIndex: self.selectedPhotoIndex) Button(action: {shouldShowFullScreenModal.toggle()}, label: { Image(systemName: "xmark") .font(.system(size:32, weight:.bold)) .foregroundColor(.white) .padding() }) } }) .opacity(shouldShowFullScreenModal ? 1 : 0) if mode == "grid"{ LazyVGrid(columns: [ GridItem(.adaptive(minimum: proxy.size.width/3-3, maximum: 600),spacing: 2) ], spacing: HEIGHTSPACE/8, content: { ForEach(photosUrls, id:\.self){ urlString in Button(action: {self.selectedPhotoIndex = photosUrls.firstIndex(of: urlString) ?? 0 shouldShowFullScreenModal.toggle()}, label: { KFImage(URL(string: urlString)) .resizable() .scaledToFill() .frame(width:proxy.size.width/3-3, height: proxy.size.width/3-3) .clipped() }) } }).padding(.horizontal,2) }else{ //list ForEach(photosUrls, id:\.self){ num in VStack{ KFImage(URL(string: num)) .resizable() .scaledToFill() VStack(alignment:.leading){ HStack{ Image(systemName: "heart") Image(systemName: "bubble.right") Image(systemName: "paperplane") Spacer() Image(systemName: "bookmark") }.font(.system(size:22)) Text("Very good Food") .font(.system(size:14)) Text("Posted on 11/4/2020") .font(.system(size:14)) .foregroundColor(.gray) }.padding(.horizontal, 4) }.padding(.bottom) } } } } .navigationBarTitle("All Photos", displayMode: .inline) } } struct RestInnerPhotosView_Previews: PreviewProvider { static var previews: some View { NavigationView{ RestInnerPhotosView(photoUrls: ["https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/e2f3f5d4-5993-4536-9d8d-b505d7986a5c", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/a4d85eff-4c79-4141-a0d6-761cca48eae1", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/20a6783b-3de7-4e58-9e22-bcc6a43b6df6", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/0d1d2e79-2f10-4cfd-82da-a1c2ab3638d2", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/3923d237-3931-44e5-836f-5de40ec04b31", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/254c0418-2b55-4a2b-b530-a31a9799c7d5", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/fa20d064-b6d7-4df9-8f44-0f25f6ee5a19", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/a441d22b-5324-4444-8ddf-22b99128838c", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/6b5d013b-dc3b-4e5e-93d9-ec932f42aead", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/a6de1d65-8fa3-4674-a6ce-a207b8f86b15", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/5c6bc68c-a8a1-42ac-ab3a-947927826807", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/a5e83c0c-c815-4129-bfd4-17e73fa1da78", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/f6ee5fb7-b21b-42c1-b1d8-a455742d0247", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/c22e8d9e-10f2-4559-8c81-375491295e84", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/3a352f87-3dc1-4fa7-affe-fb12fa8691fe", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/8ca76521-1f52-4043-8b86-d2a573342daf", "https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/73f69749-f986-46ac-9b8b-d7b1d42bddc5"]) } // .navigationViewStyle(StackNavigationViewStyle()) // .previewLayout(.fixed(width: 1800, height: 400)) } } <file_sep>// // RestaurantDetailView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-02. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct RestaurantDetailsView: View{ @ObservedObject var vm:RestaurantDetailsViewModel let restaurant: Resturant init(restaurant:Resturant) { self.restaurant = restaurant self.vm = .init(id: self.restaurant.id) } var body: some View{ ScrollView{ //topView RestDetailTopView(restaurant: vm.details!) //middle location view VStack(alignment: .leading, spacing: 8){ Text("Location & Description") .font(.system(size: 16, weight:.bold)) Text("Tokyo, Japan") HStack{ ForEach(0..<5, id:\.self){ num in Image(systemName: "dollarsign.circle.fill") }.foregroundColor(.orange) } HStack{Spacer()} }.padding(.top) .padding(.horizontal) Text(vm.details?.description ?? "") .font(.system(size: 14, weight:.regular)) .padding(.horizontal) .padding(.bottom) // bottom popular dishes HStack(){ Text("Popular Dishes") .font(.system(size: 16, weight:.bold)) Spacer() }.padding(.horizontal) ScrollView(.horizontal, showsIndicators: false){ HStack(spacing:HEIGHTSPACE/2){ ForEach(vm.details?.popularDishes ?? [], id: \.self) { dish in DishCell(dish: dish) } }.padding(.horizontal) } // custoumer reviews if let reviews = vm.details?.reviews { ReviewBottomView(reviews: reviews) .padding(.top) } } .navigationBarTitle(vm.details!.name, displayMode: .inline) } // let sampleDishPhotos = ["tapas","2"] } struct RestaurantDetailsView_Previews: PreviewProvider { static var previews: some View { NavigationView{ RestaurantDetailsView(restaurant: .init(name: "Japan's Finest Tapast", imageName: "tapas", country: "Japan", id: 0)) } } } <file_sep>// // CategoryDetailsViewModel.swift // TravelDiscovery // // Created by <NAME> on 2021-06-24. // Copyright © 2021 <NAME>. All rights reserved. // import SwiftUI class CategoryDetailsViewModel: ObservableObject{ @Published var isLoading = true @Published var places = [Place]() @Published var errorMessage = "" init(name: String) { //net work code let urlString = "https://travel.letsbuildthatapp.com/travel_discovery/category?name=\(name.lowercased())" .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" guard let url = URL(string: urlString) else{ self.isLoading = false return} URLSession.shared.dataTask(with: url) { (data, resp, err) in //you want to check resp statuscode and err DispatchQueue.main.asyncAfter(deadline: .now()+1) { if let statusCode = (resp as? HTTPURLResponse)?.statusCode, statusCode >= 400{ self.isLoading = false self.errorMessage = "Bad status: \(statusCode)" return } guard let data = data else{return} do{ self.places = try JSONDecoder().decode([Place].self, from: data) }catch{ debugPrint("Failed to decode Json: ",error) self.errorMessage = error.localizedDescription } self.isLoading = false } }.resume() // make sure to have resume } } <file_sep>// // ContentView.swift // TravelDiscovery // // Created by <NAME> on 2020-11-28. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct HomeView: View { init(){ UINavigationBar.appearance().largeTitleTextAttributes = [ .foregroundColor:UIColor.white ] } var body: some View { NavigationView{ ZStack{ if #available(iOS 14.0, *) { LinearGradient(gradient: Gradient(colors:[Color(#colorLiteral(red: 0.9736030698, green: 0.7127186656, blue: 0.2694658041, alpha: 1)), Color(#colorLiteral(red: 0.9706799388, green: 0.5768225789, blue: 0.2493174076, alpha: 1))]), startPoint: .top, endPoint: .center) .ignoresSafeArea() } else { // Fallback on earlier versions } Color.discoverBackground .offset(y:HEIGHTSPACE*10) ScrollView{ //search bar HStack{ Image(systemName: "magnifyingglass") Text("Where do you want to go?") Spacer() }.font(.system(size:14, weight: .semibold)) .foregroundColor(.white) .padding() .background(Color(.init(white: 1.0, alpha: 0.3))) .cornerRadius(10) .padding(16) //top category DiscoverCategoriesView() VStack{ PopularDestinationView() PopularRestuarantView() TrendingCreatorView() } // bottmbox setup .background(Color.discoverBackground) .cornerRadius(HEIGHTSPACE/2) .padding(.top,HEIGHTSPACE) } }.navigationBarTitle("Discover") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { HomeView() } } //40.78417894034642, -73.96030985433653 let destinations:[Destination] = [ .init(name: "Paris", country: "France", imageName: "vancouver", info: "Vancouver, BC is a coastal city on the southwest corner of Canada. Read about its geography, weather, international alliances, and role as the Host", latitude:48.86358094601, longitude:2.296246417698961, attraction: [.init(name: "<NAME>", imageName: "paris1", latitude: 48.87532409441599, longitude: 2.2952164494359164),.init(name: "Sacré-Cœur", imageName: "paris2", latitude: 48.890450626390056, longitude: 2.3432816350446615)]), .init(name: "Tokyo", country: "Japan", imageName: "2", info: "Vancouver, BC is a coastal city on the southwest corner of Canada. Read about its geography, weather, international alliances, and role as the Host", latitude: 35.687126701201144, longitude: 139.7690116381597, attraction: [.init(name: "<NAME>", imageName: "tokyo1", latitude: 35.68489585597972, longitude: 139.69691385974653), .init(name: "Tokyo Skytree", imageName: "tokyo2", latitude: 35.71500700234045, longitude: 139.81227030520753) ] ), .init(name: "New York", country: "US", imageName: "3", info: "Located in the spectacular Coast Mountains of British Columbia just two hours north of Vancouver, Whistler is Canada’s favourite year-round destination. There are two majestic mountains with a vibrant base Village, epic skiing and snowboarding, four championship golf courses, unbeatable shopping, restaurants and bars, accommodation to suit every budget, hiking trails, spas and arguably the best mountain bike park in the world. Dive in and discover Whistler for yourself:", latitude: 40.76583209520241, longitude: -73.9852057037487, attraction: [.init(name: "Empire State Building", imageName: "newyork1", latitude: 40.75167734101037, longitude: -73.9864671395415), .init(name: "<NAME>", imageName: "newyork2", latitude: 40.78417894034642, longitude: -73.96030985433653)] ), ] let resturants :[Resturant] = [ .init(name: "Japan's Finest Tapas", imageName: "tapas", country: "", id:0), .init(name: "Bar & Grill", imageName: "bar_grill", country: "", id: 1), ] <file_sep>// // Destination.swift // TravelDiscovery // // Created by <NAME> on 2020-11-29. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit //struct Destination: Hashable{ // var name, country, imageName:String? // var latitude, longitude:Double? // // init(dictionary:[String:Any]) { // self.name = dictionary["name"] as? String // self.country = dictionary["country"] as? String // self.imageName = dictionary["imageName"] as? String // seslf.latitude = dictionary["latitude"] as? Double // self.longitude = dictionary["longitude"] as? Double // } //} // struct Destination{ //var id: ObjectIdentifier var name, country, imageName, info:String var latitude, longitude:Double var attraction: [Attraction] } <file_sep>// // Landmark.swift // TravelDiscovery // // Created by <NAME> on 2020-12-04. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import MapKit struct Landmark { let placemark: MKPlacemark var id: UUID{ return UUID() } var name: String{ self.placemark.name ?? "" } var title: String{ self.placemark.title ?? "" } var coordinate: CLLocationCoordinate2D{ self.placemark.coordinate } } <file_sep>// // DishCell.swift // TravelDiscovery // // Created by <NAME> on 2020-12-03. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct DishCell:View{ let dish: Dish var body: some View{ VStack(alignment: .leading){ ZStack(alignment: .bottomLeading){ KFImage(URL(string: dish.photo)) .resizable() .scaledToFill() .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.gray)) .shadow(radius: 2 ) .padding(.vertical, 2) LinearGradient(gradient: Gradient(colors: [Color.clear, Color.black]), startPoint: .center, endPoint: .bottom) Text(dish.price) .foregroundColor(.white) .font(.system(size:13, weight:.bold)) .padding(.horizontal, 6) .padding(.bottom, 4) } .frame(height:HEIGHTSPACE*4) .cornerRadius(5) Text(dish.name) .font(.system(size: 14, weight:.bold)) Text("\(dish.numPhotos) photos") .foregroundColor(.gray) .font(.system(size: 12, weight:.regular)) } } } <file_sep>// // RestaurantDetailTop.swift // TravelDiscovery // // Created by <NAME> on 2020-12-03. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct RestDetailTopView: View { let restaurant: RestaurantDetails var body: some View { ZStack(alignment: .bottomLeading){ KFImage(URL(string: restaurant.thumbnail)) .resizable() .scaledToFill() LinearGradient(gradient: Gradient(colors: [Color.clear, Color.black]), startPoint: .center, endPoint: .bottom) HStack{ VStack(alignment:.leading, spacing: 4){ Text(restaurant.name) .foregroundColor(.white) .font(.system(size: 18, weight:.bold)) HStack{ ForEach(0..<5, id:\.self){ num in Image(systemName: "star.fill") }.foregroundColor(.orange) } } Spacer() NavigationLink( destination: RestInnerPhotosView(photoUrls: restaurant.photos), label: { Text("See more photos") .foregroundColor(.white) .font(.system(size: 14, weight:.bold)) .frame(width:WIDTHSPACE*3) .multilineTextAlignment(.trailing) }) }.padding() } } } struct RestDetailTopView_Previews: PreviewProvider { static var previews: some View { HomeView() // RestDetailTopView(restaurant: resturants[0]) } } <file_sep>// // Place.swift // TravelDiscovery // // Created by <NAME> on 2020-11-30. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Place:Decodable, Hashable { let name, thumbnail:String } <file_sep>// // DestinationHeaderContainer.swift // TravelDiscovery // // Created by <NAME> on 2020-12-01. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct DestinationHeaderContainer:UIViewControllerRepresentable{ let imageUrlString:[String] func makeUIViewController(context: Context) -> UIViewController { let pvc = CustomPVC(imageNames: imageUrlString) return pvc } typealias UIViewControllerType = UIViewController func updateUIViewController(_ uiViewController: UIViewController, context: Context) { } } extension CustomPVC{ func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = allControllers.firstIndex(of: viewController) else {return nil} if index == 0 {return nil} return allControllers[index - 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = allControllers.firstIndex(of: viewController) else {return nil} if index == allControllers.count - 1 {return nil} return allControllers[index + 1] } func presentationCount(for pageViewController: UIPageViewController) -> Int { allControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { 0 } } class CustomPVC:UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate{ // static let myPVC = CustomPVC(imageNames: ["eiffel_tower","art1","art2"]) var allControllers:[UIViewController] = [] init(imageNames:[String]){ UIPageControl.appearance().pageIndicatorTintColor = UIColor.systemGray5 UIPageControl.appearance().currentPageIndicatorTintColor = UIColor.orange super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) //pages swipe allControllers = imageNames.map({ imageName in let hostingController = UIHostingController(rootView: KFImage(URL(string: imageName)) .resizable() .scaledToFill() ) hostingController.view.clipsToBounds = true return hostingController }) if let first = allControllers.first{ setViewControllers([first], direction: .forward, animated: true, completion: nil) } self.dataSource = self self.delegate = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } struct DestinationHeaderContainer_Previews: PreviewProvider { static let imageUrlString = ["https://letsbuildthatapp-videos.s3.us-west-2.amazonaws.com/7156c3c6-945e-4284-a796-915afdc158b5", "https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/b1642068-5624-41cf-83f1-3f6dff8c1702", "https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/6982cc9d-3104-4a54-98d7-45ee5d117531", "https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/2240d474-2237-4cd3-9919-562cd1bb439e"] static var previews: some View { DestinationHeaderContainer(imageUrlString: imageUrlString) .frame(height:HEIGHTSPACE*10) NavigationView{ PopularDestinationDetailsView(destination: .init(name: "Parius", country: "France", imageName: "eiffel_tower", info: "", latitude:48.86064473141706, longitude:2.297619224300003, attraction: [Attraction]())) } } } <file_sep>// // Attraction.swift // TravelDiscovery // // Created by <NAME> on 2020-12-02. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Attraction:Identifiable{ var id = UUID().uuidString let name,imageName:String let latitude, longitude:Double } <file_sep>// // Place.swift // TravelDiscovery // // Created by <NAME> on 2020-11-29. // Copyright © 2020 <NAME>. All rights reserved. // //import Foundation struct Resturant: Hashable { let name, imageName, country:String let id:Int } <file_sep>// // RestaurantCarouselView.swift // TravelDiscovery // // Created by <NAME> on 2020-12-03. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI import KingfisherSwiftUI struct RestaurantCarouselView:UIViewControllerRepresentable{ let imageUrlString:[String] let selectedIndex:Int func makeUIViewController(context: Context) -> UIViewController { let pvc = RestaurantPVC(imageNames: imageUrlString, selectedIndex: selectedIndex) return pvc } typealias UIViewControllerType = UIViewController func updateUIViewController(_ uiViewController: UIViewController, context: Context) { } } extension RestaurantPVC{ func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = allControllers.firstIndex(of: viewController) else {return nil} if index == 0 {return nil} return allControllers[index - 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = allControllers.firstIndex(of: viewController) else {return nil} if index == allControllers.count - 1 {return nil} return allControllers[index + 1] } func presentationCount(for pageViewController: UIPageViewController) -> Int { allControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { self.selectedIndex } } class RestaurantPVC:UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate{ // static let myPVC = CustomPVC(imageNames: ["eiffel_tower","art1","art2"]) var allControllers:[UIViewController] = [] var selectedIndex: Int = 0 init(imageNames:[String], selectedIndex:Int){ self.selectedIndex = selectedIndex UIPageControl.appearance().pageIndicatorTintColor = UIColor.systemGray5 UIPageControl.appearance().currentPageIndicatorTintColor = UIColor.orange super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) //pages swipe allControllers = imageNames.map({ imageName in let hostingController = UIHostingController(rootView: ZStack{ Color.black KFImage(URL(string: imageName)) .resizable() .scaledToFit() } ) hostingController.view.clipsToBounds = true return hostingController }) if selectedIndex < allControllers.count{ setViewControllers([allControllers[selectedIndex]], direction: .forward, animated: true, completion: nil) } self.dataSource = self self.delegate = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //struct RestaurantCarouselView_Previews: PreviewProvider { // static var previews: some View { // RestaurantCarouselView() // } //}
3fee8fbfafd08b6f89fcebd2f7c4ddae6ff5b619
[ "Swift", "Markdown" ]
39
Swift
JoshFang-Dev/TravelDiscovery
e36b880690c3aa1a54897ccde47590e7a5de69bb
eba060a5cd527061037b8a0384128dd16c9a3928
refs/heads/master
<repo_name>changyi11/ReactExercise<file_sep>/src-basic/App.js import React , { Component } from 'react'; /* import TodoList from './todolist/TodoList' */ /* import Calculator from './calculator/calculator' */ /* import Combination from './combination/combination' */ /* import ContextExample from './context/ContextExample' */ /* import PopFather from './pop-up/father' */ /* import {Brother , Sister } from './bus/Mybus' */ /* import Running from './lifecycle/main' */ /* import HocExanple from './HOC/HOCexample' */ /* import PropTypes from './prop-types/main' */ /* import StyledComponent from './styledComponent' */ import Root from './react-router' class App extends Component { render() { return ( <div className="App"> {/* <TodoList /> */} {/* <Calculator /> */} {/* <Combination /> */} {/* <ContextExample /> */} {/* <PopFather /> */} {/* <Brother /> <Sister /> */} {/* <Running /> */} {/* <HocExanple /> */} {/* <PropTypes /> */} {/* <StyledComponent /> */} <Root/> </div> ); } } export default App; <file_sep>/src-basic/react-router/index.js import React, { Component, Fragment } from 'react' import { BrowserRouter as Router, Route, Link, Switch, Redirect } from 'react-router-dom' const Index = () => <h2>Home</h2>; const About = (props) => ( <div> <h1>About</h1> <Link to = '/about/us'>us</Link> <Link to = '/about/you'>you</Link> <Switch> <Redirect from = '/' exact to='/about/us'/> <Route path = '/about/us' render = {() => <h3>This is Us</h3>} /> <Route path = '/about/you' render = {() => <h3>This is You</h3>} /> </Switch> </div> ) const Users = () => <h2>Users</h2>; const UsersA = () => <h2>Users-a</h2>; const Login = () => <h2>login</h2>; const NotFound = () => <h2>404 page</h2>; class Root extends Component { render () { return ( <div className = 'root'> <h1 className = "text-center">react-router example</h1> <Router> <Fragment> <Link to = '/'>Home</Link> <Link to = '/about'>About</Link> <Link to = '/users'>Users</Link> <Switch> {/* 这里多的可以匹配到少的,比如/home可以匹配到/,/users/a可以匹配到/users */} <Route path = '/' exact render = {() =>{ let isLogin = true return isLogin ? <Redirect to = '/home'/> : <Login /> }}/> <Route path = '/home' exact component = {Index}></Route> <Route path = '/about' component = {About}></Route> <Route path = '/users/a' component = {UsersA}></Route> <Route path = '/users' component = {Users}></Route> <Route path = '/not-found' component = {NotFound}></Route> <Redirect to = {{ pathname: '/not-found' }} /> </Switch> </Fragment> </Router> </div> ) } } export default Root<file_sep>/src-redux/store/counter/actionTypes.js export const COUNT_ADDONE = 'COUNT_ADDONE' export const COUNT_ADDOTHER = 'COUNT_ADDOTHER'<file_sep>/src-redux/examples/counter/view.js import React, { Component } from 'react' import store from '../../store' class CounterView extends Component { state = { count: store.getState().count.count } componentWillMount () { store.subscribe(() => { this.setState({ count: store.getState().count.count }) }) } render () { return ( <div className = 'text-center'> <p>count: {this.state.count }</p> </div> ) } } export default CounterView<file_sep>/src-basic/context/ContextSon.js import React , { Component } from 'react' import { Consumer } from './context' class ContextSon extends Component { constructor ( props ) { super ( props ) this.state = { } } a = ({money, changeMoney}) => { return ( < div> {money} <button onClick = {changeMoney}></button> </div> ) } render () { return ( <Consumer> { value => (this.a(value)) } </Consumer> ) } } export default ContextSon<file_sep>/src-basic/context/ContextExample.js import React , { Component } from 'react' import ContextControl from './ContextControl' import { Provider } from './context' class Contextexample extends Component { constructor ( props ) { super ( props ) this.state = { money: 20 } } changeMoney = () => { this.setState({ money: --this.state.money}) } render () { return ( <Provider value={{money: this.state.money , changeMoney: this.changeMoney}}> <div> <ContextControl /> </div> </Provider> ) } } export default Contextexample<file_sep>/src/store/defaultState.js export const defaultState = { id: 2, todos: [ { id: 1, title: '杀人放火抢银行', isFinished: false }, { id: 2, title: '天黑路滑车子没闸', isFinished: true} ], types: [ { id: 1, title: '未完成', type: false}, { id: 2, title: '已完成', type: true} ] }<file_sep>/src/todolist/TodoList.js import React , { Component, } from 'react' import TodoContent from './TodoContent' import store from '../store' import action from '../store/action' class TodoList extends Component { constructor (props) { //接收属性 super(props) //定义状态 //state就是一个对象 this.state = { // 这里state的id第一次获取之后已经有了,然后每次都会给id+1,其实就已经跟远程id没关系了,每次都在state基础上加 id: store.getState().id, _todos: store.getState().todos, types: store.getState().types } } componentWillMount () { store.subscribe(() => { this.setState({ _todos: store.getState().todos }) }) } render () { return ( <div className="container todo-box"> <h1 className="text-center"> ToDoList—最简单的待办事项列表 </h1> <input onKeyUp = { this.handleInputSync } v-model = "new_title" type="text" className="form-control"/> { this.renderContent() } </div> ) } renderContent () { let { types } = this.state return types.map(item => <TodoContent key = {item.id} todos = { this.correctTodos(item.type) } title = { item.title } /> ) } // 生成已完成或者未完成的数据 correctTodos (type) { return this.state._todos.filter(todo => todo.isFinished === type) } handleInputSync = (e) => { if ( e.keyCode === 13 ) { let title = e.target.value let obj = { id: ++ this.state.id, title, isFinished: false } store.dispatch(action.addtodos(obj)) } } } export default TodoList<file_sep>/src-redux/store/counter/reducer.js import { defaultState } from './default-state' import { COUNT_ADDONE, COUNT_ADDOTHER } from './actionTypes' const reducer = (previousState = defaultState, action) => { let newObj = Object.assign( {}, previousState ) //这里是应该是count的值 switch( action.type ){ case COUNT_ADDONE: newObj.count ++; break; // reducer必须是一个纯函数,也就是说一个action只能生成一个结果,所以我们不能把随机数写在这里 case COUNT_ADDOTHER: newObj.count += action.value; break; default: break; } return newObj //之前state就等于这个newObj,但是现在分模块以后这里返回的就是state的count的值 } export default reducer<file_sep>/src-basic/context/ContextControl.js import React , { Component } from 'react' import ContextSon from './ContextSon' class ContextControl extends Component { constructor ( props ) { super ( props ) this.state = { } } render () { return ( <div> <ContextSon /> </div> ) } } export default ContextControl<file_sep>/src/store/reducer.js import { defaultState } from './defaultState' import { ADDTODOS, CHANGE_FINISHED, REMOVE_TODO, UPDATE_TITLE } from './actionTypes' const reducer = (previousState = defaultState, action) => { let newObj = Object.assign({}, previousState) switch(action.type){ case ADDTODOS: newObj.todos.push(action.value) break; case CHANGE_FINISHED: newObj.todos.forEach(item =>{ if ( item.id === action.value ) item.isFinished = !item.isFinished }) break; case REMOVE_TODO: newObj.todos = newObj.todos.filter( item => item.id !== action.value) break; case UPDATE_TITLE: newObj.todos.forEach(item => { if (item.id === action.value) item.title = action.title }) break; default: break; } return newObj } export default reducer<file_sep>/src-basic/combination/combination.js import React, { Component } from 'react' import Children from './children' class Combination extends Component { constructor (props) { super (props) this.state = { } } render () { return ( <div> 这里相当于Vue的slot,直接将代码插入到组件中 <Children> <span>这一句是被插入的</span> </Children> </div> ) } } export default Combination<file_sep>/src-basic/combination/children.js import React, { Component } from 'react' class Children extends Component { constructor (props) { super (props) this.state = { } } render () { return ( <div> <h1>这里是插入的哦</h1> {this.props.children} <div>哈哈</div> </div> ) } } export default Children<file_sep>/src-basic/calculator/TemperatureInput.js import React, { Component } from 'react' class TemperatureInput extends Component { constructor (props) { super(props) this.state = { c: '摄氏度', f: '华氏度' } } render () { let type = this.props.type return ( <div> <legend>输入{this.state[type]}数值</legend> {/* 其实这里就是先启动了input的onchange事件改变了父组件的temperature然后子组件的value就是父组件传递过来的,所以改变 */} <input value={this.props.temperature} onChange = { (e) => { this.props.onTemperatureChange(e.target.value)}} /> </div> ) } } export default TemperatureInput <file_sep>/src-redux/store/counter/actionCreatros.js import { COUNT_ADDONE, COUNT_ADDOTHER } from './actionTypes' const actionCreators = { addone () { let action = { type: COUNT_ADDONE } return action }, addother ( _count ) { let action = { type: COUNT_ADDOTHER, value : _count} return action }, randomCount () { let action = { type: COUNT_ADDOTHER, value: Math.random()} return action } } export default actionCreators<file_sep>/src-redux/store/reducer.js // 这里就是给stroe分模块了 import { combineReducers } from 'redux' import count from './counter/reducer' import message from './message/reducer' const reducer = combineReducers({ count, message }) export default reducer<file_sep>/src-basic/styledComponent/Adapting-based-on-props.js import React , { Component } from 'react' import styled from 'styled-components' import { Wrapper } from './commen' //可以第一种方法,给函数传一个props然后background判断有没有这个属性 /* ${props => `background: ${props.primary ? 'red': 'white'}`} */ //也可以第二种写法background直接等于这个函数 const Button = styled.button` font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; /* background: ${props => props.primary ? 'red': 'white'} color: ${props => props.outline ? 'red' : 'palevioletred'} */ ${props => `background: ${props.primary ? 'red': 'white'} color: ${props.outline ? 'red' : 'white'} `} ` class Example extends Component { render () { return ( <Wrapper> <Button outline>outline</Button> <Button primary>primary</Button> </Wrapper> ) } } export default Example<file_sep>/src-basic/HOC/HOCexample.js import React, { Component } from 'react' import CommentList from './CommentList' import BlogList from './BlogList' import Datasource from './Datasource' class HocExample extends Component { render () { return ( <div> <button onClick = { Datasource.changeComments }>change</button> <CommentList /> <BlogList /> </div> ) } } export default HocExample<file_sep>/src-basic/bus/Mybus.js import React , { Component } from 'react' import bus from './bus' class Brother extends Component { constructor (props) { super (props) this.state = { money: 20 } //给bus一个事件,当这个事件执行的时候就执行changeMoney这个事件 bus.on('money',() => { this.changeMoney() }) } changeMoney () { this.setState({ money: --this.state.money }) } render () { return ( <div> {this.state.money} </div> ) } } class Sister extends Component { //当点击的时候触发button,button调用bus的money事件 button () { bus.emit('money') } render () { return ( <div> <button onClick = { this.button } ></button> </div> ) } } //这样是将这两个东西分别暴露 export { Brother , Sister } //这样是暴露一个对象 export default { Brother, Sister } <file_sep>/src/store/actionTypes.js export const ADDTODOS = 'ADDTODOS' export const CHANGE_FINISHED = 'CHANGE_FINISHED' export const REMOVE_TODO = 'REMOVE_TODO' export const UPDATE_TITLE = 'UPDATE_TITLE'<file_sep>/src-redux/store/message/reducer.js export default (state = { message: 'Hello Message!'}, action ) => { return state }<file_sep>/src-basic/prop-types/context.js import React , { Component } from 'react' import PropTypes from 'prop-types' class Son extends Component { constructor (props) { super (props) this.state = { } } render () { return ( <div> {this.props.num + 12} </div> ) } } Son.propTypes = { num: PropTypes.number } class Father extends Component { render () { return ( <div> <Son num = {1}/> </div> ) } } export default Father <file_sep>/src-basic/HOC/Datasource.js //专门用来存放数据的 const Datasource = { data: { comments: [ { id: 1, title: '今天是个好日子'}, { id: 2, title: '心想的事儿都能成'} ], blogPost: [ { id: 1, title: '床前明月光'}, { id: 2, title: '疑是地上霜'} ] }, getComments () { return this.data.comments }, getBlogPost () { return this.data.blogPost }, handlers: [], //这里是组件传入需要监听执行的方法,也就是一进组件就要执行然后把handler放入handlers里面 addChangeListener( handler ) { this.handlers.push( handler ) }, //这里要在数组里面移除这个方法 removeChangeListener( handler ) { this.handlers = this.handlers.filter(item => item !== handler) }, //这里就是发布按钮,也就是会改变数据以后执行emit changeComments () { //改变之后会往comments里面添加一条数据,然后调用函数的emit,emit调用数组里面的方法,方法会调用setState this.data.comments.push({ id: 3, title: '今天真高兴'}) this.emit() }, changeBlogPost () { this.data.blogPost.push({ id: 3, title: '举头望明月'}) this.emit() }, //emit的作用就是将组件放入handlers的方法全部执行 emit () { this.handlers.forEach(handler => handler()) } } Datasource.changeComments = Datasource.changeComments.bind(Datasource) Datasource.changeBlogPost = Datasource.changeBlogPost.bind(Datasource) export default Datasource<file_sep>/src-basic/todolist/TodoItem.js import React , { Component } from 'react' class TodoItem extends Component { constructor (props) { super (props) this.state = { isUpdate: false } } // 这里是点击span然后input出现 isChanged = () => { this.setState({ isUpdate: !this.state.isUpdate }) if( !this.state.isUpdate ) { setTimeout( () => { //这里因为setState是异步的, 所以还没有出来input所以无法给他自动获取焦点 this.refs.input.focus() //需要使用setTimeout(0) }) } } //input失去焦点的时候改变title handlerBlur = (e) => { let { id } = this.props.item this.isChanged() let title = e.target.value this.props.updateTitle( title, id ) } render () { let { item, changeFinished, removeTodo } = this.props return ( <li className="list-group-item"> <div className="row"> <input onChange = { changeFinished.bind(null, item.id) } defaultChecked = { item.isFinished } className="col-xs-1" type="checkbox" /> <div className="title col-xs-8"> { this.state.isUpdate ? <input onBlur = {this.handlerBlur} ref = {'input'} type="text" defaultValue = {item.title}/> : <span onClick = {this.isChanged}>{ item.title }</span> } </div> <button onClick = { removeTodo.bind(null, item.id) } type="button" className="close col-xs-1" ><span >&times;</span></button> </div> </li> ) } } export default TodoItem<file_sep>/src-basic/Tag/index.js import React from 'react' import { NavLink, Route, withRouter } from 'react-router-dom' import styled from 'styled-components' const OwnLinkItem = (props) => { // 在props里面取出tag属性,这是将要变成的元素 let Tag = props.tag || 'a' // 拿到传递的class let _class = props.className || '' let _activeClassName = props.activeClassName || 'active' // 判断是否要加active // 这里还是会返回一个布尔值 let isActive = props.exact ? props.location.pathname === props.to : props.location.pathname.startsWith(props.to) // 这里如果有nav就是NavLink 没有就是Link let className = (props.nav && isActive) ? _class + ' ' + _activeClassName : _class return <Tag className = {className} onClick = {() => {props.history.push(props.to)}}>{props.children}</Tag> } // 自己实现的Link组件,因为内部需要调用history的路由相关api,而Link组件又不是一个路由组件(会自动包Route,并能得到context中的路由相关属性) // 所以想要使用这些api,需要利用withRouter的高阶组件来进行处理 export const OwnLink = props => { let Item = withRouter(OwnLinkItem) return ( <Item {...props} /> ) } export const OwnNavLink = props => { //使用这个ownnavlink的时候先给上面的ownlinkitem包一个withrouter let Item = withRouter(OwnLinkItem) return ( //然后这里渲染的时候会把自己写到ownnavlink上面的props传递到item上面,然后就能在ownlinkitem里面使用判断了 <Item {...props} nav /> ) } export const ActiveNavLink = styled(NavLink)` &.active { color: tomato; } &.selected { color: blue; } color: #333; ` export const ActiveOwnNavLink = styled(OwnNavLink)` &.active { color: tomato; } &.selected { color: blue; } color: #333; `<file_sep>/src/store/action.js import { ADDTODOS, CHANGE_FINISHED, REMOVE_TODO, UPDATE_TITLE } from './actionTypes' const action = { addtodos (obj) { let action = {type: ADDTODOS, value: obj} return action }, changeFinished (id) { let action = {type: CHANGE_FINISHED, value: id } return action }, removeTodo (id) { let action = {type: REMOVE_TODO, value: id} return action }, updateTitle (title, id) { let action = {type:UPDATE_TITLE, value: id, title: title } return action } } export default action<file_sep>/src-redux/examples/counter/index.js import React, { Component } from 'react' /* import store from '../../store' */ import store from '../../store' import actionCreators from '../../store/counter/actionCreatros' import CounterControl from './control' import CounterView from './view' class Counter extends Component { constructor () { super() this.state = { count: store.getState().count.count, message: store.getState().message.message } this.addone = this.addone.bind(this) } componentWillMount() { console.log(this.state.message) // subscribe会返回一个函数,返回的函数执行可以注销这个监听器 let unlistener = store.subscribe(() => { this.setState({ count: store.getState().count.count }) }) /* setTimeout( () => { // 这样写可以注销这个监听器 unlistener() }, 500) */ } render () { return ( <div className = 'panel panel-primary'> <div className = 'panel-heading'> 计算器案例-Redux </div> <div className = 'panel-body'> <h1 className = 'text-center'>count: <mark>{ this.state.count }</mark></h1> <CounterView /> <p className = 'text-center'> <button onClick = {this.addone} className = 'btn btn-primary'>+1</button> </p> <CounterControl /> </div> </div> ) } addone = () => { store.dispatch(actionCreators.addone()) console.log(this.state.message) } } export default Counter<file_sep>/src-redux/examples/counter/control.js import React, { Component } from 'react' import store from '../../store' import actionCreators from '../../store/counter/actionCreatros' class CounterControl extends Component { render () { return ( <div className = 'text-center'> <p> <button onClick = {() => { store.dispatch(actionCreators.addother(2)) }} className = 'btn btn-danger'>+2</button> </p> <p> <button onClick = {() => { store.dispatch(actionCreators.addother(-2)) }} className = 'btn btn-warning'>-2</button> </p> <p> <button onClick = {() => { store.dispatch(actionCreators.randomCount()) }} className = 'btn btn-success'>random</button> </p> </div> ) } } export default CounterControl<file_sep>/src-basic/styledComponent/index.js import React , { Component } from 'react' /* import Example from './start' */ /* import Example from './Extending-Styles' */ /* import Example from './Styling-any-components' */ import Example from './Animations' class StyledExample extends Component { render () { return ( <div> <Example /> </div> ) } } export default StyledExample<file_sep>/src-basic/pop-up/father.js import React, { Component } from 'react' class PopFather extends Component { constructor (props) { super (props) this.state = { isshow: true } } fatherclick = () => { this.setState({ isshow: !this.state.isshow }) } render () { return ( <div> <button onClick = {this.fatherclick}>滚出来/滚回去</button> <PopSon isshow = {this.state.isshow}/> </div> ) } } class PopSon extends Component { constructor (props) { super (props) this.state = { show: true } } //改变props的时候执行 componentWillReceiveProps (props) { if ( props.isshow === this.state.show) { console.log(1) this.setState({ show: !props.isshow }) } else { this.setState({ show: props.isshow }) } } click = () => { this.setState({ show: !this.state.show }) } render () { return ( <div> <div style={{width: '200px', height: '200px', border: '1px solid black',display: this.state.show ? 'block' : 'none'}}> <button onClick = {this.click}>X</button> 这是一个弹出框, 当我想让他弹出的时候他就会弹出 </div> </div> ) } } export default PopFather<file_sep>/src-redux/store/counter/default-state.js export const defaultState = { count: 0 }
90285b9a5782bc14a6b295d6905b6b2054e146b4
[ "JavaScript" ]
31
JavaScript
changyi11/ReactExercise
c28d7099d692444604b071150e5196d479414991
60f890efcece8da836c15d3b19be9e9588736318
refs/heads/master
<file_sep>package com.example.administrator.guardian.ui.activity.Login; import android.app.DatePickerDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import com.example.administrator.guardian.R; import com.example.administrator.guardian.utils.ConnectServer; import com.example.administrator.guardian.utils.MakeUTF8Parameter; import com.yarolegovich.lovelydialog.LovelyInfoDialog; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.NumberFormat; public class JoinContentsActivity extends AppCompatActivity { private static final String TAG = "JoinContentsActivity"; private static final int LOAD_GOOGLE_MAP = 1000; public static final int JOIN_PERMITTED = 200; public static final int JOIN_DENIED = 404; private Context mContext; private Button toMap; private String type; // senior?? or volunteer?? private Button seniorJoinButton; private Button birth; private EditText my_id; private EditText my_name; private EditText my_pw; private EditText my_pn1; private EditText my_pn2; private EditText my_pn3; private RadioButton radioButton_man; private RadioButton radioButton_woman; private EditText detailedAddressEditText; private String address; private String latitude; private String longitude; private boolean isMan; private int birth_year; private int birth_monthOfYear; private int birth_dayOfMonth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_joincontents); mContext = this; toMap=(Button)findViewById(R.id.tomap); birth=(Button)findViewById(R.id.birth); seniorJoinButton = (Button) findViewById(R.id.seniorjoinbutton); my_id = (EditText) findViewById(R.id.my_id); my_name = (EditText) findViewById(R.id.my_name); my_pw = (EditText) findViewById(R.id.my_pw); my_pn1 = (EditText) findViewById(R.id.my_pn1); my_pn2 = (EditText) findViewById(R.id.my_pn2); my_pn3 = (EditText)findViewById(R.id.my_pn3); detailedAddressEditText = (EditText) findViewById(R.id.detailedAddressEditText); radioButton_man = (RadioButton) findViewById(R.id.radioButton); radioButton_woman = (RadioButton) findViewById(R.id.radioButton2); birth_year = 1990; birth_monthOfYear = 1; birth_dayOfMonth = 1; my_pn1.setNextFocusDownId(R.id.my_pn2); my_pn2.setNextFocusDownId(R.id.my_pn3); Intent intent = getIntent(); type = intent.getAction(); birth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogDatePicker(); } }); toMap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent Go_Map = new Intent(getApplicationContext(), MapsActivity.class); startActivityForResult(Go_Map,LOAD_GOOGLE_MAP); } }); seniorJoinButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Intent Go_loginActivity = new Intent(getApplicationContext(), LoginActivity.class); //startActivity(Go_loginActivity); //finish(); //Send join data to server if(isAllEntered()) { ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { String login_id; String login_pw; String user_type; String user_name; String user_gender; String user_tel; String user_address; NumberFormat numformat; @Override protected void onPreExecute() { //Collect the input data login_id = my_id.getText().toString(); login_pw = my_pw.getText().toString(); user_type = getIntent().getStringExtra("type"); user_name = my_name.getText().toString(); isMan = radioButton_man.isChecked(); user_gender = isMan ? "남" : "여"; user_tel = my_pn1.getText().toString() + my_pn2.getText().toString() + my_pn3.getText().toString(); numformat = NumberFormat.getIntegerInstance(); numformat.setMinimumIntegerDigits(2); user_address = address +" "+detailedAddressEditText.getText().toString(); } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Sign_Up")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setDoOutput(true); //set Request parameter MakeUTF8Parameter parameterMaker = new MakeUTF8Parameter(); parameterMaker.setParameter("login_id", login_id); parameterMaker.setParameter("login_pw", login_pw); parameterMaker.setParameter("user_type", user_type); parameterMaker.setParameter("user_name", user_name); parameterMaker.setParameter("user_birthdate", "" + birth_year + numformat.format(birth_monthOfYear) + numformat.format(birth_dayOfMonth)); parameterMaker.setParameter("user_gender", user_gender); parameterMaker.setParameter("user_address", user_address); parameterMaker.setParameter("user_tel", user_tel); parameterMaker.setParameter("latitude", latitude); parameterMaker.setParameter("longitude", longitude); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(parameterMaker.getParameter()); wr.flush(); BufferedReader rd = null; if (con.getResponseCode() == JOIN_PERMITTED) { //Sign up Success rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); Log.d(TAG, "Sign up Success: " + rd.readLine()); finish(); } else { //Sign up Fail rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); new LovelyInfoDialog(mContext) .setTopColorRes(R.color.wallet_holo_blue_light) .setIcon(R.mipmap.ic_not_interested_black_24dp) //This will add Don't show again checkbox to the dialog. You can pass any ID as argument .setTitle("경고") .setMessage(rd.readLine()) .show(); rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG, "Sign up Fail: " + rd.readLine()); } } catch (IOException e) { e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } else{ //When All input is not entered new LovelyInfoDialog(mContext) .setTopColorRes(R.color.wallet_holo_blue_light) .setIcon(R.mipmap.ic_not_interested_black_24dp) //This will add Don't show again checkbox to the dialog. You can pass any ID as argument .setTitle("경고") .setMessage("내용들을 모두 입력해주세요.") .show(); } } }); } private boolean isAllEntered() { if(!my_id.getText().toString().equals("") && !my_name.getText().toString().equals("") && !my_pw.getText().toString().equals("") && !my_pn1.getText().toString().equals("") && !my_pn2.getText().toString().equals("") && !my_pn3.getText().toString().equals("") && (radioButton_man.isChecked() || radioButton_woman.isChecked()) && !detailedAddressEditText.getText().toString().equals("")){ return true; } return false; } private void DialogDatePicker(){ DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { // onDateSet method public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { birth_year = year; birth_monthOfYear = monthOfYear+1; birth_dayOfMonth = dayOfMonth; birth.setText(" "+birth_year+" 년"+" "+birth_monthOfYear+" 월"+" "+birth_dayOfMonth+" 일"); } }; DatePickerDialog alert = new DatePickerDialog(this, mDateSetListener, birth_year, birth_monthOfYear-1, birth_dayOfMonth); alert.setTitle("생년월일 입력"); alert.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if(resultCode==RESULT_OK) { if(requestCode==LOAD_GOOGLE_MAP) { toMap.setText(data.getStringExtra("Address")); address = data.getStringExtra("Address"); latitude = data.getStringExtra("latitude"); longitude = data.getStringExtra("longitude"); } } else{ //When resultCode is false } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_registration, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } <file_sep>package com.example.administrator.guardian.ui.activity.Senior; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import com.example.administrator.guardian.R; import com.example.administrator.guardian.datamodel.SeniorScheduleRecyclerItem; import com.example.administrator.guardian.ui.adapter.SeniorScheduleRecyclerViewAdapter; import com.example.administrator.guardian.utils.ConnectServer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SeniorFragmentThreeScheduleActivity extends AppCompatActivity { private static final String TAG = "SeniorThreeSchedule"; RecyclerView recyclerView; List<SeniorScheduleRecyclerItem> items; LinearLayoutManager layoutManager; private Button sfts_back; int responseStatus = 1; String volunteer_id, volunteer_name; int volunteer_age; String volunteer_gender; String startInfo, details; int req_hour, type; private int tmpCode = 0; private SeniorScheduleRecyclerViewAdapter seniorScheduleRecyclerViewAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_senior_fragment_three_schedule); sfts_back = (Button)findViewById(R.id.sfts_back); sfts_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getReqInfo(); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "resume start"); if(tmpCode != 0) getReqInfo(); else tmpCode = 1; } public void getReqInfo(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { items = new ArrayList<SeniorScheduleRecyclerItem>(); } @Override protected void onPostExecute(Boolean params) { if(responseStatus == 1){ Log.d(TAG, "responseStatus start: " + items.size()); seniorScheduleRecyclerViewAdapter = new SeniorScheduleRecyclerViewAdapter(getApplicationContext(), items, R.layout.activity_senior_fragment_three_schedule); seniorScheduleRecyclerViewAdapter.setAdapter(seniorScheduleRecyclerViewAdapter); recyclerView = (RecyclerView)findViewById(R.id.senior_schedule_recyclerView); layoutManager = new LinearLayoutManager(getApplicationContext()); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(seniorScheduleRecyclerViewAdapter); } } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Request_List")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; charset=utf8"); con.setRequestProperty("Accept", "application/json"); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); Log.d(TAG, "doInBackground: "+resultValues); JSONObject object = new JSONObject(resultValues); JSONArray dataArray = object.getJSONArray("data"); Log.d(TAG, "doInBackground: "+dataArray.toString()); for (int i=0; i<dataArray.length(); i++){ try{ volunteer_id = (String)dataArray.getJSONObject(i).get("volunteer_id"); }catch (Exception e){ volunteer_id = ""; } try{ volunteer_name = (String)dataArray.getJSONObject(i).get("user_name"); }catch (Exception e){ volunteer_name= "<NAME>"; } try{ volunteer_age = (20179999 - dataArray.getJSONObject(i).getInt("user_birthdate"))/10000; }catch (Exception e){ volunteer_age= 0; } try{ volunteer_gender = (String)dataArray.getJSONObject(i).get("user_gender"); }catch (Exception e){ volunteer_gender= ""; } startInfo= (String)dataArray.getJSONObject(i).get("date_from"); try{ details = (String)dataArray.getJSONObject(i).get("details"); }catch (Exception e){ details = ""; } req_hour = (Integer)dataArray.getJSONObject(i).getInt("req_hour"); if((dataArray.getJSONObject(i).getInt("current_status")) == 2 ){ type = 4; // 기간만료 }else if( ((Integer)dataArray.getJSONObject(i).getInt("req_type")) == 0 && ((Integer)dataArray.getJSONObject(i).getInt("current_status")) == 0 ){ type = 0; // 요청중 }else if(((Integer)dataArray.getJSONObject(i).getInt("req_type")) == 1 && ((Integer)dataArray.getJSONObject(i).getInt("current_status")) == 0 ){ type = 2; // 수락대기 }else if( dataArray.getJSONObject(i).getInt("current_status") == 1 ){ if(dataArray.getJSONObject(i).getInt("req_type") == 0){ if(dataArray.getJSONObject(i).getString("signature").compareTo("0") != 0){ type = 6; // 완료 }else if(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) > Long.parseLong(startInfo) && Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) < (Long.parseLong(startInfo) + req_hour*100) ){ type = 5; //진행중 }else if(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) > (Long.parseLong(startInfo) + req_hour*100)){ Log.d(TAG, "doInBackground:1 " + Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date()))); Log.d(TAG, "doInBackground:1 " + Long.parseLong(startInfo) + req_hour); type = 7; // 서명필요 }else{ type = 1;// 요청완료 } }else if(dataArray.getJSONObject(i).getInt("req_type") == 1){ if(dataArray.getJSONObject(i).getString("signature").compareTo("0") != 0){ type = 6; // 완료 }else if(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) > Long.parseLong(startInfo) && Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) <(Long.parseLong(startInfo) + req_hour*100) ){ type = 5; // 진행중 }else if(Long.parseLong(new SimpleDateFormat("yyyyMMddHHmm").format(new Date())) > (Long.parseLong(startInfo) + req_hour*100)){ type = 7; // 서명필요 }else{ type = 3;// 수락완료 } } } items.add(new SeniorScheduleRecyclerItem(volunteer_id,volunteer_name, volunteer_age,volunteer_gender, startInfo,details,req_hour,type )); } Log.d(TAG, "success : " + items.size()); } else { responseStatus *= 0; rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"fail : " + rd.readLine()); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.ui.activity.Manager; import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.administrator.guardian.R; import com.example.administrator.guardian.utils.ConnectServer; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; @SuppressLint("ValidFragment") public class ManagerManagePulseActivity extends Fragment { private static final String TAG = "ManagerHR"; Context mContext; String senior_id; EditText editMaxSeriousPulse; EditText editSeriousPulse; EditText editMinSeriousPulse; Button managePulseBtn; boolean responseStatus; int high_zone_2; int high_zone_1; int low_zone_1; public ManagerManagePulseActivity(Context context, String senior_id, int high_zone_2, int high_zone_1, int low_zone_1){ this.mContext=context; this.senior_id = senior_id; this.high_zone_2 = high_zone_2; this.high_zone_1 = high_zone_1; this.low_zone_1 = low_zone_1; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_manager_manage_pulse, null); editMaxSeriousPulse=(EditText)view.findViewById(R.id.editMaxSeriousPulse); editSeriousPulse=(EditText)view.findViewById(R.id.editSeriousPulse); editMinSeriousPulse=(EditText)view.findViewById(R.id.editMinSeriousPulse); managePulseBtn = (Button)view.findViewById(R.id.managePulseButton); managePulseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setHeartrate(); } }); editMaxSeriousPulse.setText(high_zone_2+""); editSeriousPulse.setText(high_zone_1+""); editMinSeriousPulse.setText(low_zone_1+""); managePulseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setHeartrate(); } }); return view; } public void setHeartrate(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { high_zone_2 = Integer.parseInt(editMaxSeriousPulse.getText().toString()); high_zone_1 = Integer.parseInt(editSeriousPulse.getText().toString()); low_zone_1 = Integer.parseInt(editMinSeriousPulse.getText().toString()); } protected void onPostExecute(Boolean params) { if(responseStatus == true){ Toast.makeText(getActivity(), "심박수 변경 성공", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getActivity(), "심박수 변경 실패", Toast.LENGTH_SHORT).show(); } } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Set_HR")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; charset=utf8"); con.setRequestProperty("Accept", "application/json"); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); JSONObject jsonObj = new JSONObject(); jsonObj.put("senior_id", senior_id); jsonObj.put("high_zone_2", high_zone_2); jsonObj.put("high_zone_1", high_zone_1); jsonObj.put("low_zone_1", low_zone_1); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ //Sign up Success responseStatus = true; rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); Log.d(TAG, "success"); } else { //Sign up Fail responseStatus = false; rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"fail : " + rd.readLine()); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.ui.activity.Login; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import com.example.administrator.guardian.R; import com.example.administrator.guardian.ui.activity.Manager.ManagerMainActivity; import com.example.administrator.guardian.ui.activity.Senior.SeniorTabActivity; import com.example.administrator.guardian.ui.activity.Volunteer.VolunteerTabActivity; import com.example.administrator.guardian.utils.ConnectServer; import com.example.administrator.guardian.utils.GlobalVariable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class IntroActivity extends Activity { Handler handler; SharedPreferences pref; SharedPreferences.Editor editor; GlobalVariable globalVariable; int responseStatus=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); handler = new Handler(); handler.postDelayed(rIntent,2000); } Runnable rIntent = new Runnable(){ @Override public void run(){ globalVariable = (GlobalVariable)getApplication(); pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); if( pref.getString("token", "").compareTo("") != 0 ){ tokenTest(); }else{ Log.d("bugfix99", "run: "); Intent Login = new Intent(getApplicationContext(), LoginActivity.class); Login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(Login); finish(); } } }; @Override public void onBackPressed(){ super.onBackPressed(); handler.removeCallbacks(rIntent); } private void getUserInfo() { //Send join data to server ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("User_Info")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); JSONObject jsonObj = new JSONObject(); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ //Sign up Success rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); JSONObject object = new JSONObject(resultValues); JSONArray jArr = object.getJSONArray("data"); JSONObject c = jArr.getJSONObject(0); globalVariable.setUser_name(c.getString("user_name")); }else { //Login Fail rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); String returnMessage = rd.readLine(); Log.d("intro","Login Fail: " + returnMessage); } } catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } public void tokenTest(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } protected void onPostExecute(Boolean params) { if(responseStatus == 1){ String user_type = pref.getString("userType",""); ConnectServer.getInstance().setToken(pref.getString("token","")); getUserInfo(); Log.d("intro-test", pref.getString("token","") + " / "+user_type); if(user_type.equals("senior")){ globalVariable.setLoginType(0); Intent firstMainActivity = new Intent(getApplicationContext(), SeniorTabActivity.class); startActivity(firstMainActivity); finish(); } else if(user_type.equals("volunteer")){ globalVariable.setLoginType(1); Intent firstMainActivity = new Intent(getApplicationContext(), VolunteerTabActivity.class); startActivity(firstMainActivity); finish(); } else if(user_type.equals("manager")){ globalVariable.setLoginType(2); Intent firstMainActivity = new Intent(getApplicationContext(), ManagerMainActivity.class); startActivity(firstMainActivity); finish(); } else { globalVariable.setLoginType(-1); //error case } }else{ Intent Login = new Intent(getApplicationContext(), LoginActivity.class); Login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(Login); finish(); } } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("TokenTest")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; charset=utf8"); con.setRequestProperty("Accept", "application/json"); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); JSONObject jsonObj = new JSONObject(); jsonObj.put("token",pref.getString("token", "")); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ responseStatus = 1; } else { responseStatus = 0; } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.ui.activity.Volunteer; import android.app.Dialog; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.guardian.R; import com.example.administrator.guardian.utils.ConnectServer; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class VolunteerFragmentTwoAcceptDialog extends Dialog { private static final String TAG = "VolunteerAcceptDialog"; int responseStatus = 0; private TextView vftda_Name; private TextView vftda_Age; private TextView vftda_Address; private TextView vftda_Contents; private TextView vftda_Gender; private TextView vftda_vDate; private TextView vftda_vTime; private String senior_id; private String startInfo; private int req_hour; private String senior_name; private int senior_age; private String senior_gender; private String senior_address; private String latitude; private String longitude; private String details; private Button vftda_left; private Button vftda_right; private GoogleMap mMap; MapView mapView; public VolunteerFragmentTwoAcceptDialog(Context context, String senior_id, String startInfo, int req_hour, String senior_name, int senior_age, String senior_gender, String address, String latitude, String longitude, String details) { super(context , android.R.style.Theme_Translucent_NoTitleBar); this.senior_id = senior_id; this.startInfo = startInfo; this.req_hour = req_hour; this.senior_name = senior_name; this.senior_age = senior_age; this.senior_gender = senior_gender; this.senior_address = address; this.latitude = latitude; this.longitude = longitude; this.details = details; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams(); lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; lpWindow.dimAmount = 0.1f; getWindow().setAttributes(lpWindow); setContentView(R.layout.activity_volunteer_fragment_two_accept_dialog); setLayout(); setTitle(senior_name); setContent(); mapView = (MapView)findViewById(R.id.vftda_map); mapView.onCreate(new Bundle()); mapView.onResume(); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng senior_home = new LatLng( Double.parseDouble(latitude), Double.parseDouble(longitude)); CameraPosition cameraPosition = new CameraPosition.Builder().target(senior_home).zoom(16).build(); mMap.moveCamera( CameraUpdateFactory.newLatLng(senior_home) ); MarkerOptions optFirst = new MarkerOptions(); optFirst.position(senior_home);// 위도 • 경도 optFirst.title(senior_name);// 제목 미리보기 optFirst.snippet(senior_address+""); mMap.addMarker(optFirst); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } }); vftda_left = (Button)findViewById(R.id.vftda_left); vftda_left.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { acceptReq(); } }); vftda_right = (Button)findViewById(R.id.vftda_right); vftda_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VolunteerFragmentTwoAcceptDialog.this.dismiss(); } }); } private void setTitle(String Name){ if(senior_gender.compareTo("남") == 0){ Name = Name + " 할아버지"; } else{ Name = Name + " 할머니"; } vftda_Name.setText(Name); } private void setContent(){ vftda_Age.setText("나이 : "+senior_age); vftda_Gender.setText("성별 : "+ senior_gender); vftda_Address.setText("주소 : "+senior_address); vftda_Contents.setText(details); } /* * Layout */ private void setLayout(){ vftda_Name = (TextView) findViewById(R.id.vftda_name); vftda_Age = (TextView)findViewById(R.id.vftda_age); vftda_Gender = (TextView)findViewById(R.id.vftda_gender); vftda_Address = (TextView)findViewById(R.id.vftda_address); vftda_Contents = (TextView)findViewById(R.id.vftda_content); } public void acceptReq(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } @Override protected void onPostExecute(Boolean params){ if(responseStatus == 1){ Toast.makeText(VolunteerFragmentTwoAcceptDialog.this.getContext(), "수락 완료", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(VolunteerFragmentTwoAcceptDialog.this.getContext(), "수락 실패", Toast.LENGTH_SHORT).show(); } VolunteerFragmentTwoAcceptDialog.this.dismiss(); } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Accept_Request")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); //set Request parameter JSONObject jsonObj = new JSONObject(); jsonObj.put("senior_id", senior_id); jsonObj.put("date_from", startInfo); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ //Request Success responseStatus = 1; rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); Log.d(TAG,"Successs"); }else { //Request Fail responseStatus = 0; rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"Fail: " + rd.readLine()); } } catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.ui.activity.Senior; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import com.example.administrator.guardian.R; public class SeniorFragmentTwoDialog extends Dialog { private TextView sName; private TextView sAge; private TextView sAddress; private TextView sGender; private String name; private int age; private String gender; private String address; private String phoneNumber; private Button bt_left; private Button bt_right; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams(); lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; lpWindow.dimAmount = 0.8f; getWindow().setAttributes(lpWindow); setContentView(R.layout.activity_senior_fragment_two_dialog); bt_left = (Button)findViewById(R.id.bt_left); bt_left.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SeniorFragmentTwoDialog.this.dismiss(); } }); bt_right = (Button)findViewById(R.id.bt_right); bt_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String Dial = "tel:"+phoneNumber; Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(Dial)); try { getContext().startActivity(intent); }catch(SecurityException e){ Log.d("SecurityException","try/catch gulrim");} } }); setLayout(); setTitle(name); setContent(age,gender,address); } public SeniorFragmentTwoDialog(Context context , String name , int age, String gender, String address, String phoneNumber) { super(context , android.R.style.Theme_Translucent_NoTitleBar); this.name = name; this.age = age; this.gender = gender; this.address = address; this.phoneNumber = phoneNumber; } private void setTitle(String Name){ if(gender.compareTo(new String("남")) == 0){ Name = Name + " 할아버지"; }else{ Name = Name + " 할머니"; } sName.setText(Name); } private void setContent(int age, String gender, String address){ sAge.setText("나이 : "+age); sGender.setText("성별 : "+ gender); sAddress.setText("주소 : "+address); } /* * Layout */ private void setLayout(){ sName = (TextView) findViewById(R.id.ss_name); sAge = (TextView)findViewById(R.id.ss_age); sGender = (TextView)findViewById(R.id.ss_gender); sAddress = (TextView)findViewById(R.id.ss_address); } }<file_sep>package com.example.administrator.guardian.ui.activity.Volunteer; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import com.example.administrator.guardian.R; public class VolunteerFragmentTwoFinishDialog extends Dialog { private TextView vftdf_Name; private TextView vftdf_Contents; private String name; private String gender; private String contents; private Button vftdf_button; public VolunteerFragmentTwoFinishDialog(Context context, String name, String gender, String contents) { super(context , android.R.style.Theme_Translucent_NoTitleBar); this.name = name; this.gender=gender; this.contents = contents; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams(); lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; lpWindow.dimAmount = 0.6f; getWindow().setAttributes(lpWindow); setContentView(R.layout.activity_volunteer_fragment_two_finish_dialog); setLayout(); setTitle(name); setContent(contents); vftdf_button = (Button)findViewById(R.id.vftdf_button); vftdf_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VolunteerFragmentTwoFinishDialog.this.dismiss(); } }); } private void setTitle(String Name){ if(gender.compareTo("남") == 0){ Name = Name + " 할아버지"; } else{ Name = Name + " 할머니"; } vftdf_Name.setText(Name); } private void setContent(String contents){ vftdf_Contents.setText(contents); } /* * Layout */ private void setLayout(){ vftdf_Name = (TextView) findViewById(R.id.vftdf_name); vftdf_Contents = (TextView)findViewById(R.id.vftdf_content); } } <file_sep>package com.example.administrator.guardian.ui.activity.Senior; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.administrator.guardian.R; @SuppressLint("ValidFragment") public class SeniorFragmentOneActivity extends Fragment { private static final String TAG = "SeniorMainActivity"; private static final int REQUEST_ENABLE_BT = 6666; private static final int REQUEST_CONNECT_DEVICE = 6667; private View view; Context mContext; int high_zone_2, low_zone_1; private Button measure; public SeniorFragmentOneActivity(Context context, int high_zone_2, int low_zone_1) { this.mContext = context; this.high_zone_2 = high_zone_2; this.low_zone_1 = low_zone_1; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.activity_senior_fragment_one, null); measure = (Button)view.findViewById(R.id.measure); measure = (Button)view.findViewById(R.id.measure); measure.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(getContext(), SeniorFragmentOneMeasureActivity.class); intent.putExtra("high_zone_2", high_zone_2); intent.putExtra("low_zone_1", low_zone_1); startActivity(intent); } }); return view; } }<file_sep>package com.example.administrator.guardian.ui.activity.Volunteer; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.guardian.R; import com.example.administrator.guardian.utils.ConnectServer; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout; import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.text.NumberFormat; import java.util.Calendar; public class VolunteerFragmentOneRequestActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener{ private static final String TAG = "VolunteerReqActivity"; int responseStatus = 0; private TextView vfor_Name; private TextView vfor_Age; private TextView vfor_Address; private TextView vfor_Gender; private Button dateTextView; private Button timeTextView; private int v_year; private int v_month; private int v_day_of_month; private int v_hour_of_day; private int v_minute; String info_message; private String id; private String name; private int age; private String gender; private String address; private double latitude, longitude; private Button vfor_left; private Button vfor_right; private GoogleMap mMap; MapView mapView; View view; Context mContext; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_volunteer_fragment_one_request); Intent intent = getIntent(); try{ id = intent.getExtras().getString("id"); }catch(Exception e){ id = ""; } name = intent.getExtras().getString("name"); age = intent.getExtras().getInt("age"); gender = intent.getExtras().getString("gender"); address = intent.getExtras().getString("address"); latitude = intent.getExtras().getDouble("latitude"); longitude = intent.getExtras().getDouble("longitude"); dateTextView = (Button) findViewById(R.id.vfor_DateButton); timeTextView = (Button) findViewById(R.id.vfor_TimeButton); //Set the current date & time v_year = Calendar.getInstance().get(Calendar.YEAR); v_month = Calendar.getInstance().get(Calendar.MONTH); v_month+=1; v_day_of_month = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); v_hour_of_day = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); v_minute = Calendar.getInstance().get(Calendar.MINUTE); dateTextView.setText(v_year + "년 " + v_month + "월 " + v_day_of_month + "일 "); setTime(); //Set the Date & Time ClickListener dateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(getContext(), "a", Toast.LENGTH_SHORT).show(); Calendar now = Calendar.getInstance(); DatePickerDialog dpd = DatePickerDialog.newInstance( VolunteerFragmentOneRequestActivity.this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) ); dpd.show(getFragmentManager(), "Datepickerdialog"); } }); timeTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar now = Calendar.getInstance(); TimePickerDialog dpd = TimePickerDialog.newInstance( VolunteerFragmentOneRequestActivity.this, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), true ); dpd.show(getFragmentManager(), "Timepickerdialog"); } }); vfor_left = (Button) findViewById(R.id.vfor_left); vfor_left.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); vfor_right = (Button) findViewById(R.id.vfor_right); vfor_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { request(); finish(); } }); setLayout(); setTitle(name); setContent(age,gender,address); mapView = (MapView)findViewById(R.id.vfor_map); mapView.onCreate(new Bundle()); mapView.onResume(); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng senior_home = new LatLng( latitude, longitude); CameraPosition cameraPosition = new CameraPosition.Builder().target(senior_home).zoom(16).build(); mMap.moveCamera( CameraUpdateFactory.newLatLng(senior_home) ); MarkerOptions optFirst = new MarkerOptions(); optFirst.position(senior_home);// 위도 • 경도 optFirst.title(name);// 제목 미리보기 optFirst.snippet(address+""); mMap.addMarker(optFirst); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } }); } @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { this.v_year = year; this.v_month = monthOfYear; this.v_day_of_month = dayOfMonth; dateTextView.setText(v_year+"년 " + v_month +"월 " + v_day_of_month + "일 "); } @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) { this.v_hour_of_day = hourOfDay; this.v_minute = minute; setTime(); } private void setTime() { if(v_hour_of_day > 12) { timeTextView.setText("오후 " + (v_hour_of_day-12) + "시 " + v_minute + "분 "); } else { timeTextView.setText("오전 " + v_hour_of_day + "시 " + v_minute + "분 "); } } private void setTitle(String Name){ if(gender.compareTo("남") == 0){ Name = Name + " 할아버지"; } else{ Name = Name + " 할머니"; } vfor_Name.setText(Name); } private void setContent(int age, String gender, String address){ vfor_Age.setText("나이 : "+age); vfor_Gender.setText("성별 : "+ gender); vfor_Address.setText("주소 : "+address); } /* * Layout */ private void setLayout(){ vfor_Name = (TextView) findViewById(R.id.vfor_name); vfor_Age = (TextView)findViewById(R.id.vfor_age); vfor_Gender = (TextView)findViewById(R.id.vfor_gender); vfor_Address = (TextView)findViewById(R.id.vfor_address); } void request(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { String date_from; NumberFormat numformat; @Override protected void onPreExecute() { //Collect the input data if (v_hour_of_day > 12) { info_message = new String("일시 : " + v_year + "년 " + v_month + "월 " + v_day_of_month + "일 " + "오후" + (v_hour_of_day - 12) + "시 " + v_minute + "분 "); } else { info_message = new String ("일시 : " + v_year + "년 " + v_month + "월 " + v_day_of_month + "일 " + "오전" + v_hour_of_day + "시 " + v_minute + "분 "); } numformat = NumberFormat.getIntegerInstance(); numformat.setMinimumIntegerDigits(2); date_from = ""+ v_year + numformat.format(v_month) + numformat.format(v_day_of_month) + numformat.format(v_hour_of_day) + numformat.format(v_minute); } @Override protected void onPostExecute(Boolean params){ if(responseStatus == 1){ Toast.makeText(VolunteerFragmentOneRequestActivity.this.getApplicationContext(), "신청 완료", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(VolunteerFragmentOneRequestActivity.this.getApplicationContext(), "신청 실패", Toast.LENGTH_SHORT).show(); } } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Request")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); //set Request parameter JSONObject jsonObj = new JSONObject(); jsonObj.put("date_from", date_from); jsonObj.put("req_hour", 1); jsonObj.put("senior_id", id); jsonObj.put("details", info_message); Log.d(TAG, "doInBackground: "+id); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ //Request Success responseStatus = 1; rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); Log.d(TAG,"Connect Success: " + resultValues); }else { //Request Fail responseStatus = 0; rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"Connect Fail: " + rd.readLine()); } } catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.datamodel; /** * Created by Administrator on 2016-04-28. */ public class SeniorRecyclerItem { String login_id; String user_name; String user_birthdate; int user_age; String user_gender; String user_address; String user_tel; Double distance; String latitude; String longitude; public String getId(){return this.login_id;} public String getName(){return this.user_name;} public String getBirthDate(){return this.user_birthdate;} public int getAge(){return this.user_age;} public String getGender(){return this.user_gender;} public String getAddress(){return this.user_address;} public String getTel(){return this.user_tel;} public Double getDistance(){return this.distance;} public Double getLatitude(){ return Double.parseDouble(this.latitude); } public Double getLongitude(){ return Double.parseDouble(this.longitude); } public SeniorRecyclerItem(String id, String name, String birthdate, int age, String gender, String address, String tel, Double distance){ this.login_id=id; this.user_name=name; this.user_birthdate=birthdate; this.user_age=age; this.user_gender=gender; this.user_address=address; this.user_tel=tel; this.distance = distance; this.latitude = "37.5041470000"; this.longitude = "126.956954000"; } public SeniorRecyclerItem(String id, String name, String birthdate, int age, String gender, String address, String tel, Double distance, String latitude, String longitude){ this.login_id=id; this.user_name=name; this.user_birthdate=birthdate; this.user_age=age; this.user_gender=gender; this.user_address=address; this.user_tel=tel; this.distance = distance; this.latitude = latitude; this.longitude = longitude; } } <file_sep>package com.example.administrator.guardian.ui.activity.Manager; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.administrator.guardian.R; import com.example.administrator.guardian.ui.activity.Login.LoginActivity; import com.example.administrator.guardian.utils.ConnectServer; import com.example.administrator.guardian.utils.MakeUTF8Parameter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class ManagerMainActivity extends AppCompatActivity{ private static final String TAG = "ManagerMainActivity"; ListView lv; final ArrayList<Senior> list = new ArrayList<>(); @Override protected void onCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_manager_main); Toolbar toolbar = (Toolbar) findViewById(R.id.mtoolbar); setSupportActionBar(toolbar); lv = (ListView)findViewById(R.id.senior_list_view); getInfoFromServer(); /* list.add(new Senior("1","이원세","19941222","남","서울시","01088888888")); SeniorAdapter adpt = new SeniorAdapter(ManagerMainActivity.this, R.layout.unit_senior_to_manage, list); lv.setAdapter(adpt); */ } @Override public void onBackPressed() { AlertDialog.Builder alert_confirm = new AlertDialog.Builder(this); alert_confirm.setMessage("프로그램을 종료 하시겠습니까?").setCancelable(false).setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 'No' return; } }); AlertDialog alert = alert_confirm.create(); alert.show(); } @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuItem item = menu.add(0, 1, 0, "logout"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: signOut(); return true; } return false; } public void getInfoFromServer(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } protected void onPostExecute(Boolean params) { super.onPostExecute(null); SeniorAdapter adpt = new SeniorAdapter(ManagerMainActivity.this, R.layout.unit_senior_to_manage, list); lv.setAdapter(adpt); } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Senior_List")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); //set Request parameter MakeUTF8Parameter parameterMaker = new MakeUTF8Parameter(); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(parameterMaker.getParameter()); wr.flush(); wr.close(); BufferedReader rd =null; if(con.getResponseCode() == 200){ //Sign up Success rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); JSONObject object = new JSONObject(resultValues); JSONArray dataArray = object.getJSONArray("data"); for (int i=0; i<dataArray.length(); i++){ String login_id = (String)dataArray.getJSONObject(i).get("login_id"); String user_name= (String)dataArray.getJSONObject(i).get("user_name"); String user_birthdate= (String)dataArray.getJSONObject(i).get("user_birthdate"); String user_gender= (String)dataArray.getJSONObject(i).get("user_gender"); String user_tel= (String)dataArray.getJSONObject(i).get("user_tel"); Senior senior = new Senior(login_id, user_name, user_birthdate, user_gender, user_tel); list.add(senior); } } else { //Sign up Fail rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"fail"); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } // Senior Object Def class Senior{ String login_id; String user_name; String user_birthdate; String user_gender; String user_tel; Senior(String id, String name, String birthdate, String gender, String tel){ this.login_id = id; this.user_name = name; this.user_birthdate=birthdate; this.user_gender=gender; this.user_tel=tel; } } // Adapter for Senior ListView class SeniorAdapter extends BaseAdapter{ Context context; LayoutInflater inflater; ArrayList<Senior> seniorList; int layout; public SeniorAdapter(Context context, int layout, ArrayList<Senior> seniorList){ this.context = context; this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.seniorList = seniorList; this.layout = layout; } @Override public int getCount(){ return seniorList.size(); } @Override public Object getItem(int position){ return seniorList.get(position); } @Override public long getItemId(int position){ return position; } @Override public View getView(final int position, View convertView, ViewGroup parent){ if(convertView == null){ convertView = inflater.inflate(layout, parent, false); } RelativeLayout show_senior_info_button = (RelativeLayout)convertView.findViewById(R.id.show_senior_info_button); ImageButton manage_senior_button = (ImageButton)convertView.findViewById(R.id.manage_senior_button); //show_senior_info_button.setText(seniorList.get(position).name); TextView tv_name = (TextView)convertView.findViewById(R.id.ustm_name); TextView tv_birthdate = (TextView)convertView.findViewById(R.id.ustm_inputbirthdate); TextView tv_gender = (TextView)convertView.findViewById(R.id.ustm_inputgender); tv_name.setText(seniorList.get(position).user_name); tv_birthdate.setText(seniorList.get(position).user_birthdate); tv_gender.setText(seniorList.get(position).user_gender); //-----------------test----------------- show_senior_info_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent manageinfo = new Intent(getApplicationContext(),ManagerSeniorInfoTabActivity.class); manageinfo.putExtra("senior_id",seniorList.get(position).login_id); manageinfo.putExtra("senior_name",seniorList.get(position).user_name); manageinfo.putExtra("senior_birthdate",seniorList.get(position).user_birthdate); manageinfo.putExtra("senior_gender",seniorList.get(position).user_gender); startActivity(manageinfo); } }); manage_senior_button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ String Dial = "tel:"+seniorList.get(position).user_tel;//"tel:"+phoneNumber; Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(Dial)); try { startActivity(intent); }catch(SecurityException e){ Log.d("SecurityException","manage_senior_call");} } }); //-----------------test----------------- return convertView; } } public void signOut(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } @Override protected void onPostExecute(Boolean params) { Intent logout = new Intent(getApplicationContext(), LoginActivity.class); startActivity(logout); finish(); } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Sign_Out")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; charset=utf8"); con.setRequestProperty("Accept", "application/json"); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); JSONObject jsonObj = new JSONObject(); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } else { rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"fail : " + rd.readLine()); } } catch (IOException e) { e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.ui.adapter; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.administrator.guardian.R; import com.example.administrator.guardian.datamodel.SeniorRecyclerItem; import com.example.administrator.guardian.ui.activity.Senior.SeniorFragmentTwoDialog; import com.example.administrator.guardian.ui.activity.Volunteer.VolunteerFragmentOneRequestActivity; import java.util.List; /** * Created by Administrator on 2016-04-28. */ public class SeniorRecyclerViewAdapter extends RecyclerView.Adapter<SeniorRecyclerViewAdapter.ViewHolder> { Context context; List<SeniorRecyclerItem> items; int globalVariable; int item_layout; private SeniorFragmentTwoDialog mCustomDialog; public SeniorRecyclerViewAdapter(Context context, List<SeniorRecyclerItem> items, int item_layout, int globalVariable) { this.context=context; this.items=items; this.item_layout=item_layout; this.globalVariable = globalVariable; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.senior_cardview, null); return new ViewHolder(v); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onBindViewHolder(ViewHolder holder, int position) { final SeniorRecyclerItem item=items.get(position); holder.name.setText(item.getName()); holder.age.setText(item.getAge()+""); holder.gender.setText(item.getGender()); holder.distance.setText(item.getDistance().toString()); holder.cardview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(globalVariable == 0){ mCustomDialog = new SeniorFragmentTwoDialog(context, item.getName(), item.getAge(), item.getGender(), item.getAddress(), item.getTel()); mCustomDialog.show(); }else if(globalVariable == 1){ Intent volunteerRequest = new Intent(context, VolunteerFragmentOneRequestActivity.class); volunteerRequest.putExtra("id", item.getId()); volunteerRequest.putExtra("name",item.getName()); volunteerRequest.putExtra("age",item.getAge()); volunteerRequest.putExtra("gender",item.getGender()); volunteerRequest.putExtra("address",item.getAddress()); volunteerRequest.putExtra("latitude",item.getLatitude()); volunteerRequest.putExtra("longitude",item.getLongitude()); context.startActivity(volunteerRequest); } } }); } @Override public int getItemCount() { return this.items.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView name; TextView age; TextView gender; TextView distance; CardView cardview; public ViewHolder(View itemView) { super(itemView); name=(TextView)itemView.findViewById(R.id.s_inputsname); age=(TextView)itemView.findViewById(R.id.s_inputsage); gender=(TextView)itemView.findViewById(R.id.s_inputsgender); distance=(TextView)itemView.findViewById(R.id.s_inputsdistance); cardview=(CardView)itemView.findViewById(R.id.senior_cardview); } } }<file_sep>package com.example.administrator.guardian.ui.activity.Senior; import android.app.Dialog; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.guardian.R; import com.example.administrator.guardian.utils.ConnectServer; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class SeniorFragmentThreeScheduleAcceptDialog extends Dialog { private static final String TAG = "SeniorThreeAccept"; private TextView sftsa_Content; private TextView sftsa_Name; private TextView sftsa_Age; private TextView sftsa_Gender; private TextView sftsa_vDate; private TextView sftsa_vTime; int responseStatus = 0; private int year; private int month; private int day; private int startHour; private int startMinute; private int finishHour; private int finishMinute; private String startInfo; private String details; private int reqHour; private String name; private int age; private String gender; private Button sftsa_left; private Button sftsa_right; public SeniorFragmentThreeScheduleAcceptDialog(Context context, String startInfo, String details, int reqHour, String name, int age, String gender) { super(context , android.R.style.Theme_Translucent_NoTitleBar); this.startInfo = startInfo; this.details = details; this.reqHour = reqHour; this.name = name; this.age = age; this.gender = gender; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams(); lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; lpWindow.dimAmount = 0.6f; getWindow().setAttributes(lpWindow); setContentView(R.layout.activity_senior_fragment_three_schedule_accept_dialog); setLayout(); setTitle(name); setContent(startInfo,reqHour, age,gender); sftsa_left = (Button)findViewById(R.id.sftsa_left); sftsa_left.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { acceptReq(); } }); sftsa_right = (Button)findViewById(R.id.sftsa_right); sftsa_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SeniorFragmentThreeScheduleAcceptDialog.this.dismiss(); } }); } private void setTitle(String Name){ sftsa_Name.setText(Name); } private void setContent(String startInfo, int reqHour, int age, String gender){ sftsa_vDate.setText(startInfo); sftsa_vTime.setText(reqHour+""); sftsa_Age.setText("나이 : "+age); sftsa_Gender.setText("성별 : "+ gender); } /* * Layout */ private void setLayout(){ sftsa_Name = (TextView) findViewById(R.id.sftsa_name); sftsa_Age = (TextView)findViewById(R.id.sftsa_age); sftsa_Gender = (TextView)findViewById(R.id.sftsa_gender); sftsa_vDate = (TextView)findViewById(R.id.sftsa_vDate); sftsa_vTime = (TextView)findViewById(R.id.sftsa_vTime); } public void acceptReq(){ ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } @Override protected void onPostExecute(Boolean params){ if(responseStatus == 1){ Toast.makeText(SeniorFragmentThreeScheduleAcceptDialog.this.getContext(), "수락 완료", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(SeniorFragmentThreeScheduleAcceptDialog.this.getContext(), "수락 실패", Toast.LENGTH_SHORT).show(); } dismiss(); } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Accept_Request")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); //set Request parameter JSONObject jsonObj = new JSONObject(); jsonObj.put("date_from", startInfo); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == 200){ //Request Success responseStatus = 1; rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); Log.d(TAG,"Successs"); }else { //Request Fail responseStatus = 0; rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); Log.d(TAG,"Fail: " + rd.readLine()); } } catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } } <file_sep>package com.example.administrator.guardian.ui.activity.Login; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.administrator.guardian.R; import com.example.administrator.guardian.ui.activity.Manager.ManagerMainActivity; import com.example.administrator.guardian.ui.activity.Senior.SeniorTabActivity; import com.example.administrator.guardian.ui.activity.Volunteer.VolunteerTabActivity; import com.example.administrator.guardian.utils.ConnectServer; import com.example.administrator.guardian.utils.GlobalVariable; import com.example.administrator.guardian.utils.RegistrationIntentService; import com.yarolegovich.lovelydialog.LovelyInfoDialog; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class LoginActivity extends AppCompatActivity { private static final String TAG = "LoginActivity"; private Context mContext; private Button loginbutton; private Button joinbutton; public EditText idEditText; public EditText pwEditText; private GlobalVariable globalVariable; private Handler messageHandler; SharedPreferences pref; SharedPreferences.Editor editor; int responseStatus = 0; String user_type; String user_name; private final int LOGIN_PERMITTED = 200; public void onStop(){ super.onStop(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); globalVariable = (GlobalVariable)getApplication(); Intent serviceIntent = new Intent(getApplicationContext(), RegistrationIntentService.class); startService(serviceIntent); Log.d("bugfix0", "doInBackground: "+globalVariable.getToken()); Log.d("bugfix0", "doInBackground: "+globalVariable.getToken()); pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); Log.d("bugfix00", "doInBackground: "+pref.getString("token", "")); Log.d("bugfix00", "doInBackground: "+pref.getString("token", "")); mContext = this; messageHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { if(msg.what == 0){ new LovelyInfoDialog(mContext) .setTopColorRes(R.color.wallet_holo_blue_light) .setIcon(R.mipmap.ic_not_interested_black_24dp) //This will add Don't show again checkbox to the dialog. You can pass any ID as argument .setTitle("서버와의 통신 문제") .setMessage((String)msg.obj) .show(); } }}; idEditText = (EditText) findViewById(R.id.idEditText); idEditText.setText(pref.getString("idEditText", "")); pwEditText = (EditText) findViewById(R.id.pwEditText); pwEditText.setText(pref.getString("pwEditText", "")); loginbutton = (Button)findViewById(R.id.loginbutton); loginbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Intent firstMainActivity = new Intent(getApplicationContext(), SeniorMainActivity.class); if(idEditText.getText().toString().equals("") || pwEditText.getText().toString().equals("")){ new LovelyInfoDialog(v.getContext()) .setTopColorRes(R.color.wallet_holo_blue_light) .setIcon(R.mipmap.ic_not_interested_black_24dp) .setTitle("경고") .setMessage("아이디와 비밀번호를 입력해주세요.") .show(); } else{ sendLoginInfoToServer(); } } }); joinbutton = (Button)findViewById(R.id.joinbutton); joinbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent Go_joinActivity = new Intent(getApplicationContext(), JoinActivity.class); startActivity(Go_joinActivity); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void sendLoginInfoToServer() { //Send join data to server ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { String login_id; String login_pw; @Override protected void onPreExecute() { //Collect the input data login_id = idEditText.getText().toString(); login_pw = pwEditText.getText().toString(); } @Override protected void onPostExecute(Boolean params) { if(responseStatus == 1){ getUserInfo(); } } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("Sign_In")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestProperty("Accept-Language", "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3"); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); JSONObject jsonObj = new JSONObject(); jsonObj.put("login_id", login_id); jsonObj.put("login_pw", login_pw); String token; if(pref.getString("token","").compareTo("")!= 0 ){ token = new String(pref.getString("token","")); Log.d("bugfix1", "doInBackground: "+token); }else { token = globalVariable.getToken(); Log.d("bugfix2", "doInBackground: "+token); } jsonObj.put("token", token); Log.d(TAG, "doInBackground: "+pref.getString("token","")); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == LOGIN_PERMITTED){ responseStatus = 1; //Sign up Success rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); Log.d(TAG,"Login Success: " + resultValues); JSONObject object = new JSONObject(resultValues); Boolean login_status = (Boolean) object.get("login_status"); //String token = (String) object.get("token"); user_type = (String) object.get("user_type"); Log.d(TAG,"Received Data: " + login_status + "//" + user_type); Log.d("bugfix3", "doInBackground: "+globalVariable.getToken()); ConnectServer.getInstance().setToken(globalVariable.getToken()); ConnectServer.getInstance().setType(user_type); if(user_type.equals("senior")){ globalVariable.setLoginType(0); Intent firstMainActivity = new Intent(getApplicationContext(), SeniorTabActivity.class); startActivity(firstMainActivity); finish(); } else if(user_type.equals("volunteer")){ globalVariable.setLoginType(1); Intent firstMainActivity = new Intent(getApplicationContext(), VolunteerTabActivity.class); startActivity(firstMainActivity); finish(); } else if(user_type.equals("manager")){ globalVariable.setLoginType(2); Intent firstMainActivity = new Intent(getApplicationContext(), ManagerMainActivity.class); startActivity(firstMainActivity); finish(); } else { globalVariable.setLoginType(-1); //error case Log.d(TAG, "UNEXPECTED PATH!!!"); } }else { responseStatus = 0; //Login Fail rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); String returnMessage = rd.readLine(); Log.d(TAG,"Login Fail: " + returnMessage); Message message = messageHandler.obtainMessage(0, returnMessage); message.sendToTarget(); } } catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } private void getUserInfo() { //Send join data to server ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() { @Override protected void onPreExecute() { } @Override protected void onPostExecute(Boolean params) { pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); editor = pref.edit(); editor.putString("idEditText", idEditText.getText().toString()); editor.putString("pwEditText", pwEditText.getText().toString()); editor.putString("token", globalVariable.getToken()); editor.putString("userType",user_type); editor.putString("userName", user_name); Log.d(TAG, "onPostExecute: "+editor.toString()); editor.commit(); } @Override protected Boolean doInBackground(String... params) { URL obj = null; try { obj = new URL(ConnectServer.getInstance().getURL("User_Info")); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con = ConnectServer.getInstance().setHeader(con); con.setDoOutput(true); JSONObject jsonObj = new JSONObject(); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(jsonObj.toString()); wr.flush(); BufferedReader rd =null; if(con.getResponseCode() == LOGIN_PERMITTED){ responseStatus = 1; //Sign up Success rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String resultValues = rd.readLine(); JSONObject object = new JSONObject(resultValues); JSONArray jArr = object.getJSONArray("data"); JSONObject c = jArr.getJSONObject(0); globalVariable.setUser_name(c.getString("user_name")); }else { responseStatus = 0; //Login Fail rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); String returnMessage = rd.readLine(); Log.d(TAG,"Login Fail: " + returnMessage); } } catch(IOException | JSONException e){ e.printStackTrace(); } return null; } }); ConnectServer.getInstance().execute(); } }
efffaddcf9c7fc99a9b5bf500fcde3dcac8e45c8
[ "Java" ]
14
Java
kyoungjunpark/GuardianProject
f52df090ea51d94917eba1e2db45856cc4d1651e
2825f4d008aab05304a2f417a338d4a36baa7be3
refs/heads/main
<file_sep>Rails.application.routes.draw do resources :ratings resources :users resources :movies do resources :ratings, only: [:show, :index] end post "/users", to: "users#create" post "/login", to: "sessions#create" get "/me", to: "users#show" delete "/logout", to: "sessions#destroy" end <file_sep>class Movie < ApplicationRecord has_many :ratings, through: :users end <file_sep>class MoviesController < ApplicationController rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response def index movies = Movie.all render json: movies, include: :rating end def show movie = find_movie render json: movie, include: :rating end #POST /movies def create movie = Movie.create(movie_params) render json: movie, status: :created end #UPDATE /movies/:id def update movie = find_movie movie.update(movie_params) render json: movie end #DELETE /movies/:id def destroy movie = find_movie movie.destroy head :no_content end private def find_movie Movie.find(params[:id]) end def movie_params params.permit(:title, :poster, :plot, :genre, :director) end def render_not_found_response render json: {error: "Movie not found"}, status: :not_found end end <file_sep>class UsersController < ApplicationController def index users = User.all render json: users end def show user = User.find_by(id: session[:user_id]) if user render json: user else render json: { error: "Not authorized" }, status: :unauthorized end end #POST /users def create user = User.create(user_params) render json: user, status: :created end #UPDATE /users/:id def update user = User.find_by(id: params[:id]) if user user.update(user_params) render json: user else render json: { error: "User not found" }, status: :not_found end end #DELETE /users/:id def destroy user = User.find_by(id: params[:id]) if user user.destroy head :no_content else render json: { error: "User not found" }, status: :not_found end end private def user_params params.permit(:username, :password) end end <file_sep>class RatingsController < ApplicationController def index ratings = Rating.all render json: ratings end def show rating = Rating.find_by(id: params[:id]) if rating render json: rating else render json: { error: "Rating not found" }, status: :not_found end end #POST /ratings def create rating = Rating.create(rating_params) render json: rating, status: :created end #UPDATE /ratings/:id def update rating = Rating.find_by(id: params[:id]) if rating rating.update(rating_params) render json: rating else render json: { error: "Rating not found" }, status: :not_found end end #DELETE /ratings/:id def destroy rating = Rating.find_by(id: params[:id]) if rating rating.destroy head :no_content else render json: { error: "Rating not found" }, status: :not_found end end private def rating_params params.permit(:rating, :review,) end end <file_sep> # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Movie.destroy_all User.destroy_all Rating.destroy_all puts '🌱 Seeding...' m1=Movie.create!( title:'The Avenging Conscience: or Thou Shalt Not Kill', poster: 'https://www.moviemeter.nl/images/cover/77000/77347.jpg?cb=1537986044', plot:'Prevented from dating his sweetheart by his uncle, a young man turns his thoughts to murder.', genre:'Crime, Drama, Horror', director:'<NAME>') m2=Movie.create!( title:'Cleopatra', poster: 'https://fanart.tv/fanart/movies/8095/movieposter/cleopatra-5276e0b55b992.jpg', plot:'The story of Cleopatra, the fabulous queen of Egypt, and the epic romances between her and the greatest men of Rome, Julius Caesar and Antony.', genre:'Biography, Drama, History', director:'<NAME>') m3=Movie.create!( title:'Along Came the Devil 2', poster: 'https://www.dvdsreleasedates.com/posters/800/A/Along-Came-the-Devil-2-2019-movie-poster.jpg', plot:'After receiving an unsettling voicemail, Jordan (Wiggins) returns home, looking for answers, only to find her estranged father and even more questions. A demonic force has attached itself ...', genre:'Horror, Thriller', director:'<NAME>') m4=Movie.create!( title:'I Am Vengeance: Retaliation', poster: 'https://www.newdvdreleasedates.com/images/posters/large/i-am-vengeance-retaliation-2020-01.jpg', plot:'Former special-forces soldier <NAME> is given the opportunity to bring Sean Teague - the man who betrayed his team on their final mission in Eastern Europe several years ago - to justice...', genre:'Action', director:'<NAME>') m5=Movie.create!( title:'Centigrade', poster: 'https://image.tmdb.org/t/p/original/rDhvtF2VyTmd3wWhNcN9buo4MMr.jpg', plot:'A married couple find themselves trapped in their frozen vehicle after a blizzard and struggle to survive amid plunging temperatures and unforeseen obstacles.', genre:'Drama, Thriller', director:'<NAME>') m6=Movie.create!( title:'Spenser Confidential', poster: 'https://www.sfcrowsnest.info/wp-content/uploads/2020/01/spenserforhire.jpg', plot:'When two Boston police officers are murdered, ex-cop Spenser teams up with his no-nonsense roommate, Hawk, to take down criminals.', genre:'Action, Comedy, Crime', director:'<NAME>') m7=Movie.create!( title:'Bad Therapy', poster: 'https://www.dvdsreleasedates.com/posters/800/B/Bad-Therapy-2020-movie-poster.jpg', plot:'A couple seeks out Judy Small, a marriage counselor; but the counselor is more than what meets the eye.', genre:'Comedy, Drama, Romance', director:'<NAME>') m8=Movie.create!( title:'The French Dispatch', poster: 'https://posterspy.com/wp-content/uploads/2020/02/frenchdispatch_small.png', plot:'A love letter to journalists set in an outpost of an American newspaper in a fictional twentieth century French city that brings to life a collection of stories published in \"The French Dispatch Magazine.', genre:'Comedy, Drama, Romance', director:'<NAME>') m9=Movie.create!( title:'Inception', poster: 'https://movieswithaplottwist.com/wp-content/uploads/2016/03/Inception-movie-poster.jpg', plot:'A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a C.E.O.', genre:'Action, Adventure, Sci-Fi', director:'<NAME>') m10=Movie.create!( title:'Fight Club', poster: 'https://image.tmdb.org/t/p/original/iqR0M1ln7Kobjp9liUj2Q7mtQZG.jpg', plot:'An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.', genre:'Drama', director:'<NAME>') m11=Movie.create!( title:'Matrix', poster: 'https://image.tmdb.org/t/p/original/aOIuZAjPaRIE6CMzbazvcHuHXDc.jpg', plot:'A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.', genre:'Action, Sci-Fi', director:'<NAME>, <NAME>') m12=Movie.create!( title:'Harakiri', poster: 'https://1.bp.blogspot.com/-tCGgYxMZMm0/V0b3bUCJ8LI/AAAAAAAAK3I/LBABsKf2TsAuPgoFZk7AG41v5zz4XMJCQCLcB/s1600/201181-samurai-movies-harakiri-french-poster.jpg', plot:'When a ronin requesting seppuku at a feudal lords palace is told of the brutal suicide of another ronin who previously visited, he reveals how their pasts are intertwined - and in doing so challenges the clans integrity.', genre:'Action, Drama, Mystery', director:'<NAME>') m13=Movie.create!( title:'Parasite', poster: 'https://image.tmdb.org/t/p/original/5uz9Se5HBxxPdJY38rPfyWUyjDZ.jpg', plot:'Greed and discrimination threaten the newly formed symbiotic relationship between the wealthy Park family and the destitute Kim clan.', genre:'Comedy, Drama, Thriller', director:'<NAME>') m14=Movie.create!( title:'Joker', poster: 'https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/c58b4681277211.5cfa6e54a6d3d.jpg', plot:'In Gotham City, mentally troubled comedian <NAME> is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime. This path brings him face-to-face with his alter-ego: the Joker.', genre:'Crime, Drama, Thriller', director:'<NAME>') m15=Movie.create!( title:'Whiplash', poster: 'https://fanart.tv/fanart/movies/244786/movieposter/whiplash-54e7bc30bd5bd.jpg', plot:'A promising young drummer enrolls at a cut-throat music conservatory where his dreams of greatness are mentored by an instructor who will stop at nothing to realize a students potential.', genre:'Drama, Music', director:'<NAME>') m16=Movie.create!( title:'Taxi Driver', poster: 'https://fanart.tv/fanart/movies/103/movieposter/taxi-driver-5a31986069a79.jpg', plot:'A mentally unstable veteran works as a nighttime taxi driver in New York City, where the perceived decadence and sleaze fuels his urge for violent action by attempting to liberate a presidential campaign worker and an underage prostitute.', genre:'Crime, Drama', director:'<NAME>') m17=Movie.create!( title:'Stalker', poster: 'https://i.pinimg.com/originals/37/85/6d/37856de8c07418491b1a55904878a672.jpg', plot:'A guide leads two men through an area known as the Zone to find a room that grants wishes.', genre:'Drama, Sci-Fi', director:'<NAME>') m18=Movie.create!( title:'Gone Girl', poster: 'https://www.literarytraveler.com/wp-content/uploads/2015/01/Gone-Girl1.jpg', plot:'With his wifes disappearance having become the focus of an intense media circus, a man sees the spotlight turned on him when its suspected that he may not be innocent.', genre:'Drama, Mystery, Thriller', director:'<NAME>') m19=Movie.create!( title:'Grand Budapest Hotel', poster: 'https://fanart.tv/fanart/movies/120467/movieposter/the-grand-budapest-hotel-539b3738d498b.jpg', plot:'A writer encounters the owner of an aging high-class hotel, who tells him of his early years serving as a lobby boy in the hotels glorious years under an exceptional concierge.', genre:'Adventure, Comedy, Crime', director:'<NAME>') m20=Movie.create!( title:'Spotlight', poster: 'https://www.cinemixtape.com/wp-content/uploads/2015/11/spotlight_movie_poster.jpg', plot:'The true story of how the Boston Globe uncovered the massive scandal of child molestation and cover-up within the local Catholic Archdiocese, shaking the entire Catholic Church to its core.', genre:'Biography, Crime, Drama', director:'<NAME>') m21=Movie.create!( title:'Million Dollar Baby', poster: 'https://www.dvdsreleasedates.com/posters/800/M/Million-Dollar-Baby-movie-poster.jpg', plot:'A determined woman works with a hardened boxing trainer to become a professional.', genre:'Drama, Sport', director:'<NAME>') m22=Movie.create!( title:'Hotel Rwanda', poster: 'https://image.tmdb.org/t/p/original/cbEQFyOsdKSVfmthVZUfUc8VQ80.jpg', plot:'<NAME>, a hotel manager, houses over a thousand Tutsi refugees during their struggle against the Hutu militia in Rwanda, Africa.', genre:'Biography, Drama, History', director:'<NAME>') m23=Movie.create!( title:'Fargo', poster: 'https://cstpdx.com/sites/clinton/files/images/fargo%20movie%20poster.jpg', plot:'<NAME> inept crime falls apart due to his and his henchmens bungling and the persistent police work of the quite pregnant Marge Gunderson.', genre:'Crime, Drama, Thriller', director:'<NAME>, <NAME>') m24=Movie.create!( title:'Pink Floyd: The Wall', poster: 'https://thewallcomplete.com/wp-content/uploads/2016/07/pink-floyd-the-wall-movie-poster-med.jpg', plot:'A confined but troubled rock star descends into madness in the midst of his physical and social isolation from everyone.', genre:'Drama, Fantasy, Music', director:'<NAME>') m25=Movie.create!( title:'Blade Runner', poster: 'https://wallpapercave.com/wp/wp6239959.jpg', plot:'A blade runner must pursue and terminate four replicants who stole a ship in space, and have returned to Earth to find their creator.', genre:'Action, Sci-Fi, Thriller', director:'<NAME>') m26=Movie.create!( title:'The Imitation Game', poster: 'https://www.newdvdreleasedates.com/images/posters/large/the-imitation-game-2014-04.jpg', plot:'During World War II, the English mathematical genius Alan Turing invents a machine that decodes the Nazis morse code comms and changes the course of the war.', genre:'Biography, Drama, Thriller', director:'<NAME>') m27=Movie.create!( title:'Bohemian Rhapsody', poster: 'https://www.laughingplace.com/w/wp-content/uploads/2018/10/Bohemian-Rhapsody.jpg', plot:'The story of the legendary British rock band', genre:'Biography, Drama, Music', director:'<NAME>') m28=Movie.create!( title:'Deadpool', poster: 'https://static.miraheze.org/greatestmovieswiki/thumb/8/83/F9E431D4-C385-494F-AF1D-4A61517F1FB6.jpeg/1200px-F9E431D4-C385-494F-AF1D-4A61517F1FB6.jpeg', plot:'A wisecracking mercenary gets experimented on and becomes immortal but ugly, and sets out to track down the man who ruined his looks.', genre:'Action, Adventure, Comedy', director:'<NAME>') m29=Movie.create!( title:'Dallas Buyers Club', poster: 'https://fanart.tv/fanart/movies/152532/movieposter/dallas-buyers-club-54040152e617d.jpg', plot:'In 1985 Dallas, electrician and hustler Ron Woodroof works around the system to help AIDS patients get the medication they need after he is diagnosed with the disease.', genre:'Biography, Drama', director:'<NAME>') m30=Movie.create!( title:'Blood Diamond', poster: 'https://fanart.tv/fanart/movies/1372/movieposter/blood-diamond-52dec3a11edd8.jpg', plot:'A fisherman, a smuggler, and a syndicate of businessmen match wits over the possession of a priceless diamond.', genre:'Adventure, Drama, Thriller', director:'<NAME>') m31=Movie.create!( title:'Kill Bill - Volume 2', poster: 'https://image.tmdb.org/t/p/original/2yhg0mZQMhDyvUQ4rG1IZ4oIA8L.jpg', plot:'The Bride continues her quest of vengeance against her former boss and lover Bill, the reclusive bouncer Budd, and the treacherous, one-eyed Elle.', genre:'Action, Crime, Thriller', director:'<NAME>') m32=Movie.create!( title:'Casino Royale', poster: 'https://image.tmdb.org/t/p/original/aHxjMxchRe7aZaBz2cFmzpxyHbf.jpg', plot:'After earning 00 status and a licence to kill, Secret Agent <NAME> sets out on his first mission as 007. Bond must defeat a private banker funding terrorists in a high-stakes game of poker at Casino Royale, Montenegro.', genre:'Action, Adventure, Thriller', director:'<NAME>') m33=Movie.create!( title:'Butch Cassidy', poster: 'https://fanart.tv/fanart/movies/642/movieposter/butch-cassidy-and-the-sundance-kid-536166760fb57.jpg', plot:'Wyoming, early 1900s. Butch Cassidy and The Sundance Kid are the leaders of a band of outlaws. After a train robbery goes wrong they find themselves on the run with a posse hard on their heels. Their solution - escape to Bolivia.', genre:'Biography, Crime, Drama', director:'<NAME>') m34=Movie.create!( title:'Nothing But a Man', poster: 'https://cdn.shopify.com/s/files/1/1057/4964/products/nothing-but-a-man-vintage-movie-poster-original-1-sheet-27x41_1800x.progressive.jpg?v=1613163858', plot:'A black man and his school-teacher wife face discriminatory challenges in 1960s America.', genre:'Drama, Romance', director:'<NAME>') m35=Movie.create!( title:'Tenet', poster: 'https://image.tmdb.org/t/p/original/6bBseBvhfnQwWVZUNdyKzDJ2ND7.jpg', plot:'Armed with only one word, Tenet, and fighting for the survival of the entire world, a Protagonist journeys through a twilight world of international espionage on a mission that will unfold in something beyond real time.', genre:'Action, Sci-Fi', director:'<NAME>') m36=Movie.create!( title:'Dunkirk', poster: 'https://image.tmdb.org/t/p/original/zx87sFGLXZdrSF4B9WPhwjaKuQP.jpg', plot:'Allied soldiers from Belgium, the British Empire, and France are surrounded by the German Army and evacuated during a fierce battle in World War II.', genre:'Action, Drama, History', director:'<NAME>') m37=Movie.create!( title:'Star Wars - II', poster: 'https://image.tmdb.org/t/p/original/d4rSvWozgxCq2f1xdVq9rU1Avpv.jpg', plot:'As a new threat to the galaxy rises, Rey, a desert scavenger, and Finn, an ex-stormtrooper, must join Han Solo and Chewbacca to search for the one hope of restoring peace.', genre:'Action, Adventure, Sci-Fi', director:'<NAME>') m38=Movie.create!( title:'District 9', poster: 'https://image.tmdb.org/t/p/original/fr0lbNPybUz7xYwVU7wB5HKI0p0.jpg', plot:'Violence ensues after an extraterrestrial race forced to live in slum-like conditions on Earth finds a kindred spirit in a government agent exposed to their biotechnology.', genre:'Action, Sci-Fi, Thriller', director:'<NAME>') m39=Movie.create!( title:'The Wrestler', poster: 'https://www.themoviedb.org/t/p/original/n7kYxe4UPF1IZ1jp8o4Qtn06Cj6.jpg', plot:'A faded professional wrestler must retire, but finds his quest for a new life outside the ring a dispiriting struggle.', genre:'Drama, Sport', director:'<NAME>') m40=Movie.create!( title:'Boyhood', poster: 'https://image.tmdb.org/t/p/original/vDE3JR3B4Q1VrrdpNzPjsWDowB8.jpg', plot:'The life of Mason, from early childhood to his arrival at college.', genre:'Drama', director:'<NAME>') m41=Movie.create!( title:'Breakfast Club', poster: 'https://image.tmdb.org/t/p/original/nDM2kMAe41IrNT5ZP8LSqmYH4ol.jpg', plot:'Five high school students meet in Saturday detention and discover how they have a lot more in common than they thought.', genre:'Comedy, Drama', director:'<NAME>') m42=Movie.create!( title: 'The Kings Man', poster: 'https://cdn.traileraddict.com/content/20th-century-fox/the-kings-man-poster-2.jpg', plot: 'In the early years of the 20th century, the Kingsman agency is formed to stand against a cabal plotting a war to wipe out millions', genre: 'Action, Adventure, Comedy', director: '<NAME>') #Users u1=User.create!(username:'pumpkins', password_digest: '<PASSWORD>') u2=User.create!(username:'rosecocoa', password_digest: '<PASSWORD>') u3=User.create!(username:'heatham', password_digest: '<PASSWORD>') u4=User.create!(username:'golfbeach', password_digest: '<PASSWORD>') u5=User.create!(username:'grapeswan', password_digest: '<PASSWORD>') u6=User.create!(username:'sodarocky', password_digest: '<PASSWORD>') u7=User.create!(username:'sheeprat', password_digest: '<PASSWORD>') u8=User.create!(username:'cheetah', password_digest: '<PASSWORD>') u9=User.create!(username:'lizardcat', password_digest: '<PASSWORD>') u10=User.create!(username:'relishcat', password_digest: '<PASSWORD>') u11=User.create!(username:'', password_digest: '') u12=User.create!(username:'', password_digest: '') u13=User.create!(username:'', password_digest: '') u14=User.create!(username:'', password_digest: '') u15=User.create!(username:'', password_digest: '') u16=User.create!(username:'', password_digest: '') u17=User.create!(username:'', password_digest: '') u18=User.create!(username:'', password_digest: '') u19=User.create!(username:'', password_digest: '') u20=User.create!(username:'', password_digest: '') u21=User.create!(username:'', password_digest: '') u22=User.create!(username:'', password_digest: '') u23=User.create!(username:'', password_digest: '') u24=User.create!(username:'', password_digest: '') u25=User.create!(username:'', password_digest: '') u26=User.create!(username:'', password_digest: '') u27=User.create!(username:'', password_digest: '') u28=User.create!(username:'', password_digest: '') u29=User.create!(username:'', password_digest: '') u30=User.create!(username:'', password_digest: '') u31=User.create!(username:'', password_digest: '') u32=User.create!(username:'', password_digest: '') u33=User.create!(username:'', password_digest: '') u34=User.create!(username:'', password_digest: '') u35=User.create!(username:'', password_digest: '') u36=User.create!(username:'', password_digest: '') u37=User.create!(username:'', password_digest: '') u38=User.create!(username:'', password_digest: '') u39=User.create!(username:'', password_digest: '') u40=User.create!(username:'', password_digest: '') u41=User.create!(username:'', password_digest: '') u42=User.create!(username:'', password_digest: '') r1=Rating.create!(rating:6 , review:'This D. W. Grifith movie was interesting for the many suspenseful moments', movie_id: m1.id, user_id: u1.id ) r2=Rating.create!(rating:7 , review:'The Greatest Love Affair Of All Time', movie_id: m2.id, user_id: u2.id ) r3=Rating.create!(rating:4.4 , review:'Dont make a 3rd Sequel', movie_id: m3.id, user_id: u3.id ) r4=Rating.create!(rating:3.4 , review:'A team can be a liability', movie_id: m4.id, user_id: u4.id ) r5=Rating.create!(rating:4.4 , review:'Could have been more intense', movie_id: m5.id, user_id: u5.id ) r6=Rating.create!(rating:6.2 , review:'Unlikely Buddies', movie_id: m6.id, user_id: u6.id ) r7=Rating.create!(rating:4.3 , review:'Harmless but Boring', movie_id: m7.id, user_id: u7.id ) r8=Rating.create!(rating:8.8 , review:'Amazingly original...but also a bit overwhelming', movie_id: m8.id, user_id: u8.id ) r9=Rating.create!(rating:8.8 , review:'You love it or you hate it, personally I loved it', movie_id: m9.id, user_id: u9.id ) r10=Rating.create!(rating:8.7 , review:'A sci-fi action thriller milestone', movie_id: m10.id, user_id: u10.id ) r11=Rating.create!(rating:8.7 , review:'', movie_id: m11.id, user_id: u11.id ) r12=Rating.create!(rating:8.7 , review:'', movie_id: m12.id, user_id: u12.id ) r13=Rating.create!(rating:8.7 , review:'', movie_id: m13.id, user_id: u13.id ) r14=Rating.create!(rating:8.7 , review:'', movie_id: m14.id, user_id: u14.id ) r15=Rating.create!(rating:8.7 , review:'', movie_id: m15.id, user_id: u15.id ) r16=Rating.create!(rating:8.7 , review:'', movie_id: m16.id, user_id: u16.id ) r17=Rating.create!(rating:8.7 , review:'', movie_id: m17.id, user_id: u17.id ) r18=Rating.create!(rating:8.7 , review:'', movie_id: m18.id, user_id: u18.id ) r19=Rating.create!(rating:8.7 , review:'', movie_id: m19.id, user_id: u19.id ) r20=Rating.create!(rating:8.7 , review:'', movie_id: m20.id, user_id: u20.id ) r21=Rating.create!(rating:8.7 , review:'', movie_id: m21.id, user_id: u21.id ) r22=Rating.create!(rating:8.7 , review:'', movie_id: m22.id, user_id: u22.id ) r23=Rating.create!(rating:8.7 , review:'', movie_id: m23.id, user_id: u23.id ) r24=Rating.create!(rating:8.7 , review:'', movie_id: m24.id, user_id: u24.id ) r25=Rating.create!(rating:8.7 , review:'', movie_id: m25.id, user_id: u25.id ) r26=Rating.create!(rating:8.7 , review:'', movie_id: m26.id, user_id: u26.id ) r27=Rating.create!(rating:8.7 , review:'', movie_id: m27.id, user_id: u27.id ) r28=Rating.create!(rating:8.7 , review:'', movie_id: m28.id, user_id: u28.id ) r29=Rating.create!(rating:8.7 , review:'', movie_id: m29.id, user_id: u29.id ) r30=Rating.create!(rating:8.7 , review:'', movie_id: m30.id, user_id: u30.id ) r31=Rating.create!(rating:8.7 , review:'', movie_id: m31.id, user_id: u31.id ) r32=Rating.create!(rating:8.7 , review:'', movie_id: m32.id, user_id: u32.id ) r33=Rating.create!(rating:8.7 , review:'', movie_id: m33.id, user_id: u33.id ) r34=Rating.create!(rating:8.7 , review:'', movie_id: m34.id, user_id: u34.id ) r35=Rating.create!(rating:8.7 , review:'', movie_id: m35.id, user_id: u35.id ) r36=Rating.create!(rating:8.7 , review:'', movie_id: m36.id, user_id: u36.id ) r37=Rating.create!(rating:8.7 , review:'', movie_id: m37.id, user_id: u37.id ) r38=Rating.create!(rating:8.7 , review:'', movie_id: m38.id, user_id: u38.id ) r39=Rating.create!(rating:8.7 , review:'', movie_id: m39.id, user_id: u39.id ) r40=Rating.create!(rating:8.7 , review:'', movie_id: m40.id, user_id: u40.id ) r41=Rating.create!(rating:8.7 , review:'', movie_id: m41.id, user_id: u41.id ) r42=Rating.create!(rating:8.7 , review:'', movie_id: m42.id, user_id: u42.id ) puts '✅ Done seeding!' <file_sep>class RatingSerializer < ActiveModel::Serializer attributes :rating, :review end <file_sep>class MovieSerializer < ActiveModel::Serializer attributes :title, :poster, :plot, :genre, :director end
2163a66a089443fda75be661a2b6ada36f203240
[ "Ruby" ]
8
Ruby
er1cn/film-buff-movie-db-app-backend
3bdf1a530cfaf59e6d67be1560e2b42d0175b75a
898b7b6ed5f2077685e97d572142d38190b229e2
refs/heads/master
<repo_name>omarnasir/xml_parsers<file_sep>/src/mappingClasses/JAXBMapper.java package mappingClasses; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import dataObjects.ShortCV; import dataObjects.userprofile.*; public class JAXBMapper { private ShortCV shortCVObj; public ShortCV mapperMethod(File shortCVXML) { try { JAXBContext jaxbContext = JAXBContext.newInstance(ShortCV.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); shortCVObj = (ShortCV) jaxbUnmarshaller.unmarshal(shortCVXML); } catch (JAXBException e) { e.printStackTrace(); } return shortCVObj; } public boolean marshallerMethod(Userprofile userProfileObj, File outputXML) { try { JAXBContext jaxbContext = JAXBContext.newInstance(userProfileObj.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(userProfileObj, outputXML); return true; } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }<file_sep>/src/dataObjects/EmploymentRecord.java package dataObjects; import java.util.ArrayList; import java.util.List; public class EmploymentRecord{ private String name; private ArrayList<EmploymentRecordDetail> records; public EmploymentRecord() { this.records = new ArrayList<EmploymentRecordDetail>(); } public ArrayList<EmploymentRecordDetail> getAllRecords() { return this.records; } public EmploymentRecordDetail getRecord(int num) { return records.get(num); } public int getRecordSize() { return records.size();} public List<String> getCompanyNames () { List<String> companyNames = new ArrayList<String>(); for(int i=0; i < getRecordSize(); i++) { companyNames.add(getRecord(i).getCompany_Name()); } return companyNames; } public void addRecord(EmploymentRecordDetail record) { records.add(record); } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/src/mappingClasses/XSLTMapper.java package mappingClasses; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.stream.StreamResult; public class XSLTMapper { public static void convertXMLToHTML(Source xml, Source xslt, String xmloutputPath) { StringWriter sw = new StringWriter(); try { FileWriter fw = new FileWriter(xmloutputPath); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer trasform = tFactory.newTransformer(xslt); trasform.transform(xml, new StreamResult(sw)); fw.write(sw.toString()); fw.close(); } catch (IOException | TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }<file_sep>/README.md ## XML Processing Application This repository contains implementations of DOM, JAXB, SAX and XSLT parsers, all written in JAVA. An employement service company has been simulated, which has multiple sources of input XMLs. Each contains some specific information that has to be parsed and then mapped into an output.xml. The output xml is serialized using JAXB Marshaller methods, through Java BEAN classes. <file_sep>/src/dataObjects/package-info.java /** * */ /** * @author omar * */ @XmlSchema( namespace = "http://www.employmentservicecompany.org/shortcv.xsd", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package dataObjects; import javax.xml.bind.annotation.XmlSchema;
f7408bf7a374b63ef2eb405bc2bcb3734a43e793
[ "Markdown", "Java" ]
5
Java
omarnasir/xml_parsers
799f6d63f50c2f9275b965df0b7b09144eea24fb
a711f74de23f2a416afe8be57b6a722175c9a44f
refs/heads/master
<file_sep>import React from 'react'; import { TouchableOpacity, Text } from 'react-native'; const Render = (props) => { return ( <TouchableOpacity style={props.buttomStyle} onPress={props.onPress}> <Text style={props.textStyle}> {props.text} </Text> </TouchableOpacity> ); }; export default Render; <file_sep># learn-react-native-albums Project to learn react naive <file_sep>rootProject.name = 'Albums RN' include ':app' <file_sep>import React, { Component } from 'react'; import { ScrollView } from 'react-native'; import axios from 'axios'; import Details from './details'; import Spinner from '../spinner'; // Class component, used for dynamic sources of data. // Handles any data that might change (fetching data, user event ...) // Knows when it gets rendered to the device (useful for data fetching) // More code to write class AlbumList extends Component { constructor(props) { super(props); this.state = { albums: [], loading: true }; } componentWillMount() { axios.get('https://rallycoding.herokuapp.com/api/music_albums') .then(res => { this.setState({ albums: res.data, loading: false }); }); } renderAlbums() { return this.state.albums.map((album, index) => { return <Details key={`album-${album.title}`} album={album} />; }); } render() { if (this.state.loading) return <Spinner size="large" />; return ( <ScrollView> {this.renderAlbums()} </ScrollView> ); } } export default AlbumList;<file_sep>import React from 'react'; import { View, Image, Text, Linking, StyleSheet } from 'react-native'; import Card from '../card'; import Section from '../section'; import Button from '../button'; const Datails = ({ album }) => { const { title, artist, thumbnail_image, image, url } = album; const handerButtonBuy = (url) => { return Linking.openURL(url); }; return ( <View> <Card> <Section> <View style={styles.thumbnailContainer}> <Image style={styles.thumbnail} source={{ uri: thumbnail_image }} /> </View> <View style={styles.contentContainer}> <Text style={styles.contentHighlight}>{title}</Text> <Text>{artist}</Text> </View> </Section> <Section> <View style={styles.imageContainer}> <Image style={styles.image} source={{ uri: image }} /> </View> </Section> <Section> <Button text="Buy" onPress={handerButtonBuy.bind(this, url)} /> </Section> </Card> </View> ); }; Datails.propTypes = { album: React.PropTypes.object.isRequired }; const styles = StyleSheet.create({ thumbnailContainer: { marginLeft: 10, marginRight: 10, justifyContent: 'center', alignItems: 'center' }, thumbnail: { height: 50, width: 50 }, contentContainer: { flexDirection: 'column', justifyContent: 'space-around' }, contentHighlight: { fontSize: 18 }, imageContainer: { flex: 1 }, image: { height: 300 } }); export default Datails;
c99e51f251e795f81e9159fea35fda1e4fe9153e
[ "JavaScript", "Markdown", "Gradle" ]
5
JavaScript
jonatassaraiva/learn-react-native-albums
c8e998220cdf9cd438dfb5e3beaf8901b81fe28d
c9bbb9fd1b86a710be4e436809f6ec10ae06a207
refs/heads/master
<file_sep>// // // package controllers import ( "bytes" "io" "mime/multipart" "net/http" "strings" "github.com/astaxie/beego" "github.com/wangch/glog" ) type MainController struct { beego.Controller } func (c *MainController) Get() { c.TplNames = "index.html" } func (c *MainController) Deposit() { r := c.Ctx.Request u := *r.URL u.Scheme = "http" u.Host = Gconf.Host u.Path = "/api" + u.Path glog.Infoln(u) var resp *http.Response var err error if r.Method == "GET" { resp, err = http.Get(u.String()) } else { contentType := r.Header.Get("Content-Type") var nr *http.Request if strings.Contains(contentType, "multipart/form-data") { buf := &bytes.Buffer{} writer := multipart.NewWriter(buf) i := strings.Index(contentType, "--") boundary := contentType[i:] err = writer.SetBoundary(boundary) if err != nil { glog.Infoln(err) return } for k, v := range r.MultipartForm.Value { writer.WriteField(k, v[0]) } for k, v := range r.MultipartForm.File { w, err := writer.CreateFormFile(k, v[0].Filename) if err != nil { glog.Errorln(err) return } f, err := v[0].Open() if err != nil { glog.Errorln(err) return } io.Copy(w, f) f.Close() } writer.Close() nr, err = http.NewRequest(r.Method, u.String(), buf) } else { nr, err = http.NewRequest(r.Method, u.String(), strings.NewReader(r.Form.Encode())) } if err != nil { glog.Errorln(err) return } nr.Header.Set("Content-Type", contentType) resp, err = http.DefaultClient.Do(nr) } if err != nil { glog.Errorln(err) c.Redirect("/", 302) return } io.Copy(c.Ctx.ResponseWriter, resp.Body) } <file_sep>// // // package controllers import ( "encoding/json" "io/ioutil" "os" "github.com/wangch/glog" ) // type GateBankAccount struct { // Name string // 开户人姓名 // BankName string // 银行名字 // BankId string // 银行账号 // Currencies []string // 支持的货币种类 // Fees Fees // 交易费 // } // type Fees struct { // FeeMap map[string][2]float64 // 最低, 最高费率, 每笔转账小于最低按照最低计算, 高于最高按照最高计算 // Rate float64 // 费率比率 // } type Config struct { // GBAs []GateBankAccount // 收款人信息 Currencies []string // 支持的货币种类 ColdWallet string // 网关钱包地址 用于发行 Host string // Server 地址 // UsdRate float64 // 当前 1 icc == ? usd 默认为1 Domain string } var configFile = "./conf.json" func loadConf() (*Config, error) { data, err := ioutil.ReadFile(configFile) if err != nil { return nil, err } var conf Config err = json.Unmarshal(data, &conf) if err != nil { return nil, err } return &conf, nil } // var defaultFees = Fees{ // FeeMap: map[string][2]float64{ // "CNY": {5, 50}, // "HKD": {6, 60}, // "USD": {1, 10}, // "EUR": {1, 10}, // "ICC": {1, 10}, // "BTC": {0.0005, 0.01}, // }, // Rate: 0.01, // } var defaultConf = &Config{ Domain: "isuncoin.com", Currencies: []string{"USD", "CNY", "HKD", "EUR", "JPY"}, ColdWallet: "iN8sGowQCg1qptWcJG1WyTmymKX7y9cpmr", // ss1TCkz333t3t2J5eobcEMkMY3bXk // w01 Host: "localhost:8080", } func initConf() { conf, err := loadConf() if err != nil { conf = defaultConf b, err := json.MarshalIndent(conf, "", " ") if err != nil { glog.Fatal(err) } err = ioutil.WriteFile(configFile, b, os.ModePerm) if err != nil { glog.Fatal(err) } } Gconf = conf } var Gconf *Config func init() { initConf() } <file_sep>// // // package main import ( "io" "net/http" "os" "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/astaxie/beego/plugins/cors" "github.com/wangch/glog" "github.com/wangch/icloudfund/controllers" _ "github.com/wangch/icloudfund/routers" ) func init() { beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{ AllowOrigins: []string{"*"}, AllowMethods: []string{"GET", "PUT", "PATCH"}, AllowHeaders: []string{"Origin"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, })) beego.EnableHttpListen = false beego.EnableHttpTLS = true beego.HttpsPort = 443 beego.HttpCertFile = "cert.pem" beego.HttpKeyFile = "key.pem" beego.SessionOn = true beego.SetStaticPath("/css", "static/css") beego.SetStaticPath("/js", "static/js") beego.SetStaticPath("/img", "static/img") beego.SetStaticPath("/fonts", "static/fonts") beego.SetStaticPath("/favicon.png", "./favicon.png") } func main() { glog.SetLogDirs(".") glog.SetLogToStderr(true) conf := controllers.Gconf beego.Get("/federation", func(ctx *context.Context) { federation(ctx, conf) }) beego.Get("/ripple.txt", func(ctx *context.Context) { f, err := os.Open("ripple.txt") if err != nil { glog.Fatal(err) } io.Copy(ctx.ResponseWriter, f) f.Close() }) beego.Get("/quote", func(ctx *context.Context) { u := "http://" + conf.Host + "/api/quote?" + ctx.Request.URL.RawQuery glog.Infoln(u) r, err := http.Get(u) if err != nil { glog.Errorln(err) return } io.Copy(ctx.ResponseWriter, r.Body) r.Body.Close() }) beego.Run() } <file_sep>package routers import ( "github.com/astaxie/beego" "github.com/wangch/icloudfund/controllers" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/deposit", &controllers.MainController{}, "get:Deposit") beego.Router("/deposit/*", &controllers.MainController{}, "post:Deposit") beego.Router("/buyicc", &controllers.MainController{}, "get:Deposit") beego.Router("/buyicc/*", &controllers.MainController{}, "post:Deposit") } <file_sep>// // // package main import ( "encoding/json" "github.com/astaxie/beego/context" "github.com/wangch/icloudfund/controllers" ) type FederationResp struct { Result string `json:"result"` Error string `json:"error,omitempty"` ErrorMessage string `json:"error_message,omitempty"` FederationJson *Federation `json:"federation_json,omitempty"` } type Currency struct { Currency string `json:"currency"` Issuer string `json:"issuer,omitempty"` } type ExtraField struct { Required bool `json:"required"` Hint string `json:"hint"` Type string `json:"type"` Name string `json:"name"` Lable string `json:"lable"` } type Federation struct { Domain string `json:"domain"` Currencies []Currency `json:"currencies,omitempty"` ExtraFields []ExtraField `json:"extra_fields,omitempty"` Destination string `json:"destination"` Type string `json:"type"` QuoteUrl string `json:"quote_url"` } func federationErrorResp(msg string) *FederationResp { return &FederationResp{ Result: "error", Error: "-1", ErrorMessage: msg, } } func federationSucessResp(conf *controllers.Config, destination string) *FederationResp { currencies := []Currency{} for _, c := range conf.Currencies { currencies = append(currencies, Currency{c, conf.ColdWallet}) } contactField := ExtraField{ Required: true, Hint: "请留邮箱或者 QQ, 如果提现过程出现问题,客服将通过这个信息联系你", Type: "text", Name: "contact_info", Lable: "联系方式", } fields := []ExtraField{} if destination == "z" { fields = []ExtraField{ ExtraField{ Required: true, Hint: "大额提现请走银行卡,如欲走银行卡请输入 <EMAIL>", Type: "text", Name: "alipay_account", Lable: "支付宝提现,请输入支付宝账户", }, ExtraField{ Required: true, Hint: "请输入支付宝账户对应的真实姓名", Type: "text", Name: "full_name", Lable: "姓名", }, contactField, } } else if destination == "y" { fields = []ExtraField{ ExtraField{ Required: true, Hint: "请填入银行的名称", Type: "text", Name: "bank_name", Lable: "银行卡提现,请填入银行名称", }, ExtraField{ Required: true, Hint: "请填入银行卡卡号", Type: "text", Name: "card_number", Lable: "银行卡号", }, ExtraField{ Required: true, Hint: "待提现的银行账户的姓名", Type: "text", Name: "full_name", Lable: "姓名", }, ExtraField{ Required: true, Hint: "大于等于五万的提现请填写开户行名称", Type: "text", Name: "opening_branch", Lable: "开户行", }, contactField, } } return &FederationResp{ Result: "success", FederationJson: &Federation{ Domain: conf.Domain, Destination: destination, Type: "federation_record", QuoteUrl: "https://" + conf.Domain + "/quote", Currencies: currencies, ExtraFields: fields, }, } } func federation(ctx *context.Context, conf *controllers.Config) { typ := ctx.Request.URL.Query().Get("type") if typ != "federation" { resp := federationErrorResp("the query type must be federation") sendResp(resp, ctx) return } destination := ctx.Request.URL.Query().Get("destination") if destination != "z" && destination != "y" { resp := federationErrorResp("the query destination must be z or y") sendResp(resp, ctx) return } domain := ctx.Request.URL.Query().Get("domain") if domain != conf.Domain { resp := federationErrorResp("the query domain must be " + conf.Domain) sendResp(resp, ctx) return } resp := federationSucessResp(conf, destination) sendResp(resp, ctx) } func sendResp(resp interface{}, ctx *context.Context) error { b, err := json.Marshal(resp) if err != nil { return err } ctx.ResponseWriter.Write(b) return nil }
4776223a68d2e4e1d267cd133dd8eeba287d24ed
[ "Go" ]
5
Go
aryaya/ifundgate
1e0ea73bc48bd75bc7001c4c66f3af0ed7578d8c
4fde362296130f9f9588bde02ec56d9c4508118e
refs/heads/master
<file_sep>--- title: Bio --- Born in Miami, FL as a first generation immigrant. I was taught from a young age to always excel and live my life to set the world on fire. I am currently a senior at Allegheny College pursuing my Bachelors Degree in Computer Science while also getting a minor in Economics. After college I have accepted a position to work with LSP Cargo Incorporated to work with international business who wish to have their cargo delivered or stored for inventory at a warehouse location. I plan to work here until I have saved enough money to go to grad school for either cloud computing, Artificial Intelligence, or Data Analytics. <!-- end --> ```javascript $(document).ready(function() { console.log('Welcome!'); }) ``` Curabitur non blandit dui. Maecenas in ipsum nec leo pellentesque sodales et nec quam. Ut ut facilisis metus, sit amet aliquam nibh. Quisque blandit dui quis augue dictum vehicula. <file_sep>--- title: Senior Comprehensive Project! date: "2018-12-06" --- I will be releasing updates on my Senior Comprehensive project heading into 2019. My project is a logarithmic approach to shipping, calculating quotes, and estimating container sizes. This is a project that I am particularly passionate about and cannot wait to complete. <file_sep>--- title: Blog Post date: "2018-07-01" featuredImage: './featured.jpg' --- This top portion is the beginning of the post and will show up as the excerpt on the homepage. <!-- end --> <file_sep>module.exports = { title: 'Karol Vargas', // Required author: '<NAME>', // Required tagline: 'Miami, FL Full-Stack Developer', primaryColor: '#3498db', // Required showHeaderImage: true, showShareButtons: true, postsPerPage: 5, // Required social: { github: 'https://github.com/karolvargas', twitter: 'https://twitter.com/karolavargas', linkedin: 'https://www.linkedin.com/in/karolalbertovargas/' } };
640ef161566d09a0b2c4b2d4b38062161ca54c93
[ "Markdown", "JavaScript" ]
4
Markdown
karolvargas/devblog
9e4f3611b3f953b2c7d9c9a7efaa3d5fcac8a28a
d02b089673f93bddb7c0dd71dd422d8b74f03f44
refs/heads/master
<repo_name>huazhenjiang/linux_auto_transfer<file_sep>/Makefile PROJ_ROOT := $(shell pwd) INC = -I $(PROJ_ROOT)/include LIB = -L $(PROJ_ROOT)/lib CFLAGS += -Wall -Wextra BUILD_DIR = $(PROJ_ROOT)/output FINAL_TARGET=$(BUILD_DIR)/auto_transfer #i=0 #FUN_file= file export PROJ_ROOT INC LIB CFLAGS BUILD_DIR FINAL_TARGET objects := $(patsubst %.c, %.o,$(wildcard *.c)) #objects := $(patsubst $(SOURCE_C)/%.c, $(SOURCE_C)/%.o,$(wildcard $(SOURCE_C)/*.c)) HTML_folder = $(PROJ_ROOT)/html CSS_folder = $(PROJ_ROOT)/css JS_folder = $(PROJ_ROOT)/js target_html := $(wildcard $(HTML_folder)/*.html) target_css := $(wildcard $(CSS_folder)/*.css) target_js := $(wildcard $(JS_folder)/*.js) c_file_name ?= $(wildcard $(PROJ_ROOT)/output/out/*.c) filter_path_name ?= $(notdir $(c_file_name)) filter_suffix_name ?= $(basename $(filter_path_name)) AUTO_trans: $(FINAL_TARGET) trans_html trans_css trans_js produce_stringweb_h produce_stringweb_h: @echo "$(c_file_name)\n" @echo "$(filter_path_name)\n" @echo "$(filter_suffix_name)\n" for number in $(filter_suffix_name) ; do \ echo "extern char *$$number;" >> $(PROJ_ROOT)/output/out/stringweb.h ; \ done trans_html: for number in $(target_html) ; do \ cd $(BUILD_DIR) && pwd && ./auto_transfer $$number ; \ done trans_css: for number in $(target_css) ; do \ cd $(BUILD_DIR) && pwd && ./auto_transfer $$number ; \ done trans_js: for number in $(target_js) ; do \ cd $(BUILD_DIR) && pwd && ./auto_transfer $$number ; \ done $(FINAL_TARGET): init $(objects) cc $(CFLAGS) $(INC) -o $(FINAL_TARGET) $(objects) init: mkdir -p $(BUILD_DIR) mkdir -p $(HTML_folder) mkdir -p $(CSS_folder) mkdir -p $(JS_folder) .PHONY: clean clean: rm -rf *.o $(BUILD_DIR)/ <file_sep>/auto_transfer.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> void _splitpath(const char *path, char *drive, char *dir, char *fname, char *ext); static void _split_whole_name(const char *whole_name, char *fname, char *ext); char *str_replace (char *source, char *find, char *rep); // str_replace :input char *source , find specific string , replace by *rep char *str_replace (char *source, char *find, char *rep){ // int find_L=strlen(find); // int rep_L=strlen(rep); // int length=strlen(source)+1; // int gap=0; // char *result = (char*)malloc(sizeof(char) * length); strcpy(result, source); // char *former=source; // char *location= strstr(former, find); // while(location!=NULL){ // gap+=(location - former); // result[gap]='\0'; // length+=(rep_L-find_L); // result = (char*)realloc(result, length * sizeof(char)); // strcat(result, rep); // gap+=rep_L; // former=location+find_L; // strcat(result, former); // location= strstr(former, find); } return result; } //splitpath with dir, file's name and extension name void _splitpath(const char *path, char *drive, char *dir, char *fname, char *ext) { char *p_whole_name; drive[0] = '\0'; if (NULL == path) { dir[0] = '\0'; fname[0] = '\0'; ext[0] = '\0'; return; } if ('/' == path[strlen(path)]) { strcpy(dir, path); fname[0] = '\0'; ext[0] = '\0'; return; } p_whole_name = rindex(path, '/'); if (NULL != p_whole_name) { p_whole_name++; _split_whole_name(p_whole_name, fname, ext); snprintf(dir, p_whole_name - path, "%s", path); } else { _split_whole_name(path, fname, ext); dir[0] = '\0'; } } static void _split_whole_name(const char *whole_name, char *fname, char *ext) { char *p_ext; p_ext = rindex(whole_name, '.'); if (NULL != p_ext) { strcpy(ext, p_ext); snprintf(fname, p_ext - whole_name + 1, "%s", whole_name); } else { ext[0] = '\0'; strcpy(fname, whole_name); } } //example E:\code\auto_transfer$ auto_transfer E:\\code\\DevC\\auto_transfer\\css\\switch.css int main (int argc, char *argv[]){ char ch=0,ch2=0; unsigned long i=0,length,j; unsigned long index=0,count=0; unsigned char ten=0, one=0, sum=0; char filename[128]={0}, *head, *ptr; char arrayname[128]={0}; const char cmp = '.'; char drive[16]; char dir[128]; char fname[128]; char ext[16]; //char pwd_path[128]={0}, output_folder[128]={0}; //size_t size; FILE *fp_in, *fp_out, *fp_trans; memset(filename,0,sizeof(filename)); memset(arrayname,0,sizeof(arrayname)); if(argc >2){ printf("\r\n%s, %s",argv[0],argv[1]); return -2; } //get filename and trans '.' , '-' to '_' , add '.c' at final _splitpath( argv[1], drive, dir, fname, ext ); printf("\r\nDrive:%s\n file name: %s\n file type: %s\n",drive,fname,ext); strcat(fname,ext); printf("File name with extension :%s\n",fname); head=str_replace(fname,".","_"); head=str_replace(head,"-","_"); //strncpy(filename, argv[1], strlen(argv[1])); strncpy(filename,head,strlen(head)); strcat(filename,".c"); printf("\r\nOutput_filename: %s",filename); //get arrayname strncpy(arrayname, head , strlen(head)); printf("\r\nArrayname:%s",arrayname); //get pwd //getcwd(pwd_path, sizeof(pwd_path)); //printf("\r\nPWD_path=%s\n", pwd_path); //make out folder //strncpy(output_folder, pwd_path, strlen(pwd_path)); //strcat(output_folder,"\\out"); //printf("\r\nOutput_folder=%s\n", output_folder); if((access( "./out", 0 )) ==0){ printf( "\r\n%s exists ", "./out"); } else{ printf( "\r\ncan not find %s , create it", "./out"); if (mkdir("./out",S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0){ printf("\r\ncan not create out folder, Error:%d\n", __LINE__); //return -1; } } //if( (access( ACCESS.C, 2 )) == 0 ){ // printf( "File ACCESS.C has write permission " ); //} fp_in=fopen(argv[1],"r"); if( NULL == fp_in ){ printf( "\r\n%s open failure",argv[1] ); return -1; } if(chdir("./out") ==0) printf("\r\ncurrent working directory: %s\n", getcwd(NULL, NULL)); else printf("\r\ncan not enter /out"); fp_out=fopen(filename,"w"); if( NULL == fp_out ){ printf( "\r\n%s open failure",filename ); return -1; } //char *index.html.c="3c6874..."; fprintf(fp_out,"char *%s=\"", arrayname); while( (ch=fgetc(fp_in)) != EOF){ fprintf(fp_out,"%02x",ch); } fprintf(fp_out,"\";"); fclose(fp_in); fclose(fp_out); return 0; }
5a961eb26f878a9b57ad942b1989fc62e2a060e5
[ "C", "Makefile" ]
2
Makefile
huazhenjiang/linux_auto_transfer
77a00572353154e85c8f46b672e62ad000647355
dc7e77074b03c54f739c7e7d77603b82f966e027
refs/heads/master
<repo_name>gorthiananth/Das<file_sep>/HelloWorld/src/main/java/com/javacodegeeks/example/DasPojo.java package com.javacodegeeks.example; public class DasPojo { public DasPojo() { super(); } public DasPojo(String tableName, String startDate, String endDate, String column, String serviceType, String cpcode, String groupBy, int limit, String dasServer, String order, String orderBy) { super(); this.tableName = tableName; this.startDate = startDate; this.endDate = endDate; this.column = column; this.serviceType = serviceType; this.cpcode = cpcode; this.groupBy = groupBy; this.limit = limit; this.dasServer = dasServer; this.order = order; this.orderBy = orderBy; } String tableName = null; String startDate; String endDate; String column = null; String serviceType = null; String cpcode = null; String groupBy = null; int limit = 0; String dasServer=null; String order=null; public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public String getOrderBy() { return orderBy; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } public void setCpcode(String cpcode) { this.cpcode = cpcode; } String orderBy=null; public String getDasServer() { return dasServer; } public void setDasServer(String dasServer) { this.dasServer = dasServer; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public String getCpcode() { return cpcode; } public void setCpccode(String cpccode) { this.cpcode = cpccode; } public String getGroupBy() { return groupBy; } public void setGroupBy(String groupBy) { this.groupBy = groupBy; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } @Override public String toString() { return "DasPojo [tableName=" + tableName + ", startDate=" + startDate + ", endDate=" + endDate + ", column=" + column + ", serviceType=" + serviceType + ", cpcode=" + cpcode + ", groupBy=" + groupBy + ", limit=" + limit + ", dasServer=" + dasServer + ", order=" + order + ", orderBy=" + orderBy + "]"; } } <file_sep>/HelloWorld/ncscript.sh echo " table="$1" FDW=1 start="$2" end="$3" column="$4" service="$5" objtype=cpcode object="$6" groupby="$7" orderby="${10}" "${11}" limit="$8" END" | nc "$9" 8457
ae35b396f2496d564893d166597839bf6a6e1739
[ "Java", "Shell" ]
2
Java
gorthiananth/Das
8da2bc0fe771eb777bbebc5d79149eb064b0a486
67f11daa0c5f8c361c7c36b3d18616a48233dca4
refs/heads/master
<file_sep> const axios = require('axios'); const clima = require('../clima/clima'); const getLugar = async ( dir ) => { const encodeUrl = encodeURI(dir); var instance = axios.create({ baseURL: `https://devru-latitude-longitude-find-v1.p.rapidapi.com/latlon.php?location=${encodeUrl}`, headers: {'X-RapidAPI-Key': '<KEY>'} }); const resp = await instance.get(); if(resp.data.Results.length === 0){ throw new Error(`No hay resultados para la ubicación ingresada: ${dir}`) } const data = resp.data.Results[0]; const direccion = data.name; const lat = data.lat; const long = data.lon; return { direccion, lat, long } } module.exports = { getLugar }<file_sep>## Aplicacion del Clima Instalar el ``npm install`` ## Ejemplo ``node app.js -d "Ciudad del Este"``
e6f5dba35ac5d4a0c99df445fba286d21f86a378
[ "JavaScript", "Markdown" ]
2
JavaScript
mafretes/clima-node
b166c01dedd998d7ee9366be5c871ac2efea09c4
1c008111e8436c485e2dcdacba21eafeb2771e80
refs/heads/master
<file_sep># write your code here def who_is_bigger(a, b, c) # !existe = pas existe = nil if !a || !b || !c return "nil detected" elsif a > b && a > c p "a is bigger" elsif b > a && b > c p "b is bigger" else p "c is bigger" end end puts who_is_bigger(82,42,21) <file_sep>#write your code here def echo(str) p str end def shout(str) p str.upcase end def repeat(str, n = 2) str2 = (str + " ") * (n-1) + str p str2 end def start_of_word(str, n) tmp = "" i = 0 while i < n do tmp = tmp + str[i] i += 1 end p tmp end def first_word(str) string = str.split() p string[0] end def titleize(str) string = str.split() string.each { |mot| if mot == string[0] mot.capitalize! elsif mot == "and" || mot == "the" mot = mot else mot.capitalize! end } str2 = string.join(" ") p str2 end<file_sep>class Board def initialize (taille_grille= 5) @taille = taille_grille @lettre= ('a'..'z').to_a @ligne=('a'.. @lettre[@taille-1]).to_a @colonne =(1..@taille).to_a.map(&:to_s) # creation du tableau cellules =[] @colonne.each do |colonne| @ligne.each do |ligne| cellules.push([colonne.to_s, ligne].join("")) end end #creation d'un hash pour mettre les element du tableau hash1=cellules.map { |cell| [cell,nil] } @board = Hash[hash1] end def position_vide? position !@board[position].nil? end def move! (player, position) if position_vide? position @board[position] = player position else nil end end def tentative1 #v_wins v=[] @colonne.each do |colonne| @ligne.each do |ligne| v.push([ligne, colonne].join("")) end end v.each_slice(@size).to_a end def tentative2 h=[] @colonne.each do |colonne| @ligne.each do |ligne| h.push([ligne, colonne].join("")) end end h.each_slice(@taille).to_a end #la methode pour initisaliser le gagnant def tentative3 diag1, diag2 = [], [] 0.upto(@taille-1).each do |i| diag1.push(@ligne[i]+ @colonne[i]) diag2.push(@ligne[@taille-1-i] + @colonne [i]) end [diag1, diag2] end hash2 ={ "a1"=>'x', "b1"=>nil, "1c"=>nil, "a2"=>nil, "b2"=>"x", "2c"=>nil, "a3"=>'y', "b3"=>nil, "3c"=>'x' } def le_gagnant? player # si joueur est un caratère, X gagner.each do |gagnant| occupant=gagnant.map {|position| @board[position]} le_match=occupant.map { |x| x.eaqual? player } if le_match.all? return true end end false end def go_gagnant? player tentative3.map { |gagnant| gagnant.map {|p| @board[p].equal? player}.all? }.any? end def a_gagner? player gagnant = tentative1 + tentative2 + tentative3 gagnant.map { |gagnant| gagnant.map { |p| @board[p].equal? player }.all? }.any? end end b = Board.new puts b.tentative3 <file_sep>#write your code here def ftoc(faren) (faren-32)*5/9 end def ctof(celc) (celc*9.0/5) +32 end
ab48d92b5f92ce633f1dc4b2399b8db2f93bdca7
[ "Ruby" ]
4
Ruby
Hugu90/devoir-du-09-juillet
b62be707f593bfdf3ac5dc43b771e2ddb0a437ca
4caa5214878c1b0cb323af1c8a6aa21093924ad1
refs/heads/master
<repo_name>blessanm86/reddit-assignment<file_sep>/src/App.jsx import React from "react"; import Layout from "./components/Layout"; import Post from "./components/Post"; function App() { //Idealy url should contain the id of the post //which is url to query the api return ( <Layout> <Post id="dfqxf8" /> </Layout> ); } export default App; <file_sep>/src/components/Layout.jsx import React from "react"; import styled from "@emotion/styled"; import { Global, css } from "@emotion/core"; import emotionReset from "emotion-reset"; import { px2rem } from "../utils/styles"; import { COLORS } from "../config/styles"; const globalStyles = css` ${emotionReset} * { box-sizing: border-box; } body { background: ${COLORS.GRAY_100}; font-family: arial; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } h3 { font-size: ${px2rem(22)}; } button { background: none; border: none; cursor: pointer; padding: 0; margin: 0; outline: none; } `; const Layout = styled.section` @media (min-width: 1024px) { margin: ${px2rem([32, 68])}; } `; export default function ({ children }) { return ( <> <Global styles={globalStyles}></Global> <Layout>{children}</Layout> </> ); } <file_sep>/src/config/styles.js export const COLORS = { GRAY_100: "#f9f9f9", GRAY_200: "#f1f1f1", GRAY_300: "#787c7e", GRAY_400: "#2c2c2c", GRAY_500: "#606060", WHITE: "#ffffff", BLUE_100: "#60a9eb", }; <file_sep>/src/components/Error.jsx import React from "react"; export default function ({ error }) { return ( <p data-testid="error-element"> {`An error has occurred: ${error.message}`} </p> ); } <file_sep>/src/utils/styles.js export function px2rem(px, base = 16) { if (typeof px === "number") { const size = px / base; const sizeRounded = Math.round(size); if (size === sizeRounded) { return `${size}rem`; } return `${size.toFixed(2)}rem`; } return px.map((value) => px2rem(value, base)).join(" "); } <file_sep>/src/components/Post/Body/Body.jsx import React, { useState } from "react"; import { Container, Text, CommentsCount, StyledCommentIcon, } from "./Body.styles"; import { convertStringToHtml } from "../../../utils/ui"; export default function ({ body, commentsCount, children }) { const [shouldShowComments, setShouldShowComments] = useState(true); return ( <Container> <Text> <p dangerouslySetInnerHTML={{ __html: convertStringToHtml(body), }} ></p> <button aria-label="Toggle Comments" onClick={() => setShouldShowComments(!shouldShowComments)} > <CommentsCount> <StyledCommentIcon /> <span>{commentsCount} Comments</span> </CommentsCount> </button> </Text> {shouldShowComments && children} </Container> ); } <file_sep>/src/assets/icons/Comment.jsx import React from "react"; export default function CommentIcon({ className }) { return ( <svg className={className} xmlns="http://www.w3.org/2000/svg" x="0" y="0" enableBackground="new 0 0 60 60" version="1.1" viewBox="0 0 60 60" xmlSpace="preserve" > <path d="M6 2h48c3.252 0 6 2.748 6 6v33c0 3.252-2.748 6-6 6H25.442L15.74 57.673a1.003 1.003 0 01-1.101.26A1 1 0 0114 57V47H6c-3.252 0-6-2.748-6-6V8c0-3.252 2.748-6 6-6z"></path> </svg> ); } <file_sep>/src/config/api.js export const POST_API_URL = "https://api.github.com/gists"; <file_sep>/src/__fixtures__/post.js export default { subreddit: "unpopularopinion", selftext: "I almost always shower with my socks on. It just feels more relaxing, I don’t really like the feeling of water below my feet. Having socks on, even light ones, feels like a nice towel to put around my feet when I’m showering. It’s just better this way. I’ve done this since I was like, 8, and I don’t ever plan on changing it. When I told my friends about it they all said it was really weird. I just think it is more comfortable, relaxing, and overall a better experience.\n\nEdit: jeez I really didn’t think that this was a big deal.\n\nEdit 2: To address some things:Yes, I actually do this, I personally like it, and it really isn’t problematic so I do it. My feet aren’t always super clean but I rub lotion on them occasionally.\n\nEdit 3: well I went to sleep, and now I have 953 notifications.", title: "Taking showers with your socks on is so much better than not", subreddit_name_prefixed: "r/unpopularopinion", name: "t3_dfqxf8", score: 20700, thumbnail: "self", selftext_html: '&lt;!-- SC_OFF --&gt;&lt;div class="md"&gt;&lt;p&gt;I almost always shower with my socks on. It just feels more relaxing, I don’t really like the feeling of water below my feet. Having socks on, even light ones, feels like a nice towel to put around my feet when I’m showering. It’s just better this way. I’ve done this since I was like, 8, and I don’t ever plan on changing it. When I told my friends about it they all said it was really weird. I just think it is more comfortable, relaxing, and overall a better experience.&lt;/p&gt;\n\n&lt;p&gt;Edit: jeez I really didn’t think that this was a big deal.&lt;/p&gt;\n\n&lt;p&gt;Edit 2: To address some things:Yes, I actually do this, I personally like it, and it really isn’t problematic so I do it. My feet aren’t always super clean but I rub lotion on them occasionally.&lt;/p&gt;\n\n&lt;p&gt;Edit 3: well I went to sleep, and now I have 953 notifications.&lt;/p&gt;\n&lt;/div&gt;&lt;!-- SC_ON --&gt;', id: "dfqxf8", permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/", url: "https://www.reddit.com/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/", subreddit_subscribers: 775462, created_utc: 1570671373, is_video: false, author: "cynicallogic", ups: 20700, comments: [ { created_utc: 1570693670, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 0, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35vz2f/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Bruh&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Bruh", author: "RandomName01", id: "t1_f35vz2f", ups: 1, }, { created_utc: 1570683149, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 0, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35nn9e/", body_html: '&lt;div class="md"&gt;&lt;p&gt;97% Disagree it&amp;#39;s the most unpopular opinion I&amp;#39;ve seen here after that guy who wanted to be pregnant&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "97% Disagree it's the most unpopular opinion I've seen here after that guy who wanted to be pregnant", author: "shantanu011", id: "t1_f35nn9e", ups: 2233, }, { created_utc: 1570680701, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 0, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35kuhk/", body_html: '&lt;div class="md"&gt;&lt;p&gt;I&amp;#39;m gonna try this tonight op, and if it&amp;#39;s shit I will come for you.&lt;/p&gt;\n\n&lt;p&gt;Edit: just got home. Getting in shower now.&lt;/p&gt;\n\n&lt;p&gt;Edit 2 electric boogaloo: risky click of the day. \n&lt;a href="https://imgur.com/a/u1C215L"&gt;No bamboozle&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;Edit 3: you!!! I declare shenanigans.&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "I'm gonna try this tonight op, and if it's shit I will come for you.\n\nEdit: just got home. Getting in shower now.\n\nEdit 2 electric boogaloo: risky click of the day. \n[No bamboozle](https://imgur.com/a/u1C215L)\n\nEdit 3: you!!! I declare shenanigans.", author: "OceLawless", id: "t1_f35kuhk", ups: 263, }, { created_utc: 1570697457, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 1, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35y9gp/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Or the guy who likes sleeping in jeans&lt;/p&gt;\n\n&lt;p&gt;Edit: to everyone commenting, I meant the dude liked to get into bed at night with the duvet on with jeans, not just taking a nap&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Or the guy who likes sleeping in jeans\n\nEdit: to everyone commenting, I meant the dude liked to get into bed at night with the duvet on with jeans, not just taking a nap", author: "ShitOnMyArsehole", id: "t1_f35y9gp", ups: 638, parent_id: "t1_f35nn9e", }, { created_utc: 1570703350, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 1, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f361yrc/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Am I pregegnant or am I ok?&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Am I pregegnant or am I ok?", author: "HansenTakeASeat", id: "t1_f361yrc", ups: 56, parent_id: "t1_f35nn9e", }, { created_utc: 1570709099, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 2, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f369ye5/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Or the guy who eats his cereal with water&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Or the guy who eats his cereal with water", author: "nikithb", id: "t1_f369ye5", ups: 551, parent_id: "t1_f35y9gp", }, { created_utc: 1570710788, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 2, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f36drup/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Sleeping in jeans is fine on a couch or something, but not good in a bed under sheets.&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Sleeping in jeans is fine on a couch or something, but not good in a bed under sheets.", author: "bellowingbullfinches", id: "t1_f36drup", ups: 32, parent_id: "t1_f35y9gp", }, { created_utc: 1570711829, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 3, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f36ge9a/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Good lord, I wanted to down vote this but realised you&amp;#39;re the messenger, we don&amp;#39;t shoot the messenger&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Good lord, I wanted to down vote this but realised you're the messenger, we don't shoot the messenger", author: "Sazzybee", id: "t1_f36ge9a", ups: 286, parent_id: "t1_f369ye5", }, { created_utc: 1570711069, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 3, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f36efud/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Yeah but you don&amp;#39;t purposely go to bed in jeans like the poster did&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Yeah but you don't purposely go to bed in jeans like the poster did", author: "ShitOnMyArsehole", id: "t1_f36efud", ups: 16, parent_id: "t1_f36drup", }, { created_utc: 1570710595, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 2, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f36daww/", body_html: '&lt;div class="md"&gt;&lt;p&gt;Can you get.....PREGANTE&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "Can you get.....PREGANTE", author: "_Noot_Noot", id: "t1_f36daww", ups: 32, parent_id: "t1_f361yrc", }, { created_utc: 1570711616, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 3, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f36fubr/", body_html: '&lt;div class="md"&gt;&lt;h1&gt;AM I GREGNANT?!&lt;/h1&gt;\n&lt;/div&gt;', downs: 0, body: "#AM I GREGNANT?!", author: "Macho_Mans_Ghost", id: "t1_f36fubr", ups: 29, parent_id: "t1_f36daww", }, { created_utc: 1570681556, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 1, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35ltpb/", body_html: '&lt;div class="md"&gt;&lt;p&gt;[deleted]&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "[deleted]", author: "[deleted]", id: "t1_f35ltpb", ups: 136, parent_id: "t1_f35kuhk", }, { created_utc: 1570690006, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 1, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35tfxh/", body_html: '&lt;div class="md"&gt;&lt;p&gt;So?&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "So?", author: "DaSwagCow", id: "t1_f35tfxh", ups: 33, parent_id: "t1_f35kuhk", }, { created_utc: 1570725030, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 2, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f37esup/", body_html: '&lt;div class="md"&gt;&lt;p&gt;You, sonofabitch.&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "You, sonofabitch.", author: "OceLawless", id: "t1_f37esup", ups: 10, parent_id: "t1_f35ltpb", }, { created_utc: 1570691417, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 2, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35uh0q/", body_html: '&lt;div class="md"&gt;&lt;p&gt;It&amp;#39;s shit.&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "It's shit.", author: "Killahcamcam", id: "t1_f35uh0q", ups: 75, parent_id: "t1_f35tfxh", }, { created_utc: 1570694504, subreddit_name_prefixed: "r/unpopularopinion", subreddit: "unpopularopinion", depth: 2, permalink: "/r/unpopularopinion/comments/dfqxf8/taking_showers_with_your_socks_on_is_so_much/f35wht6/", body_html: '&lt;div class="md"&gt;&lt;p&gt;It&amp;#39;s 3pm where I am. So still at work&lt;/p&gt;\n\n&lt;p&gt;Edit:sorry lads I&amp;#39;m still at a bar. I will update ASAP no bamboozle.&lt;/p&gt;\n&lt;/div&gt;', downs: 0, body: "It's 3pm where I am. So still at work\n\n\nEdit:sorry lads I'm still at a bar. I will update ASAP no bamboozle.", author: "OceLawless", id: "t1_f35wht6", ups: 23, parent_id: "t1_f35tfxh", }, ], }; <file_sep>/src/components/Post/Title/Title.styles.js import styled from "@emotion/styled"; import { px2rem } from "../../../utils/styles"; import { COLORS } from "../../../config/styles"; export const Container = styled.div` padding: ${px2rem([0, 20])}; `; export const SubRedditTitle = styled.span` color: ${COLORS.GRAY_300}; font-size: ${px2rem(12)}; `; export const Grid = styled.div` display: grid; grid-template-columns: max-content 1fr; align-items: baseline; margin: ${px2rem([15, 0])}; `; export const Score = styled.span` color: ${COLORS.GRAY_400}; `; export const Title = styled.h3` color: ${COLORS.GRAY_400}; margin-left: ${px2rem(15)}; `; <file_sep>/src/utils/__test__/styles.test.js import { px2rem } from "../styles"; describe("px2rem", () => { it("Should give rem value with base font size as 16", () => { expect(px2rem(20)).toBe("1.25rem"); expect(px2rem([20])).toBe("1.25rem"); expect(px2rem([20, 20])).toBe("1.25rem 1.25rem"); }); it("Should give rem value based on passed in base font size", () => { expect(px2rem(20, 12)).toBe("1.67rem"); expect(px2rem([20], 12)).toBe("1.67rem"); expect(px2rem([20, 20], 12)).toBe("1.67rem 1.67rem"); }); }); <file_sep>/src/components/Post/Body/Body.styles.js import styled from "@emotion/styled"; import { css } from "@emotion/core"; import { px2rem } from "../../../utils/styles"; import { COLORS } from "../../../config/styles"; import CommentIcon from "../../../assets/icons/Comment"; export const spacingStyles = css` padding: ${px2rem([20, 40])}; @media (max-width: 768px) { padding: ${px2rem([10, 0, 10, 20])}; } `; export const textStyles = css` font-size: ${px2rem(14)}; line-height: 1.4; color: ${COLORS.GRAY_500}; `; export const Container = styled.div` background: ${COLORS.WHITE}; padding: ${px2rem([20])}; border-radius: ${px2rem([8])}; `; export const Text = styled.div` ${spacingStyles}; ${textStyles}; background: ${COLORS.GRAY_200}; border-radius: ${px2rem([8])}; .md { display: grid; row-gap: ${px2rem(16)}; } `; export const CommentsCount = styled.div` display: grid; grid-template-columns: max-content 1fr; align-items: center; padding-top: ${px2rem(20)}; column-gap: ${px2rem(8)}; font-size: ${px2rem(12)}; color: ${COLORS.GRAY_400}; `; export const StyledCommentIcon = styled(CommentIcon)` width: ${px2rem(12)}; height: ${px2rem(12)}; fill: ${COLORS.GRAY_400}; `; <file_sep>/src/__fixtures__/comments.js export default [ { created_utc: 1570693670, body: "Bruh", author: "RandomName01", id: "t1_f35vz2f", }, { created_utc: 1570683149, body: "97% Disagree it's the most unpopular opinion I've seen here after that guy who wanted to be pregnant", author: "shantanu011", id: "t1_f35nn9e", }, { created_utc: 1570680701, body: "I'm gonna try this tonight op, and if it's shit I will come for you.\n\nEdit: just got home. Getting in shower now.\n\nEdit 2 electric boogaloo: risky click of the day. \n[No bamboozle](https://imgur.com/a/u1C215L)\n\nEdit 3: you!!! I declare shenanigans.", author: "OceLawless", id: "t1_f35kuhk", }, { created_utc: 1570697457, body: "Or the guy who likes sleeping in jeans\n\nEdit: to everyone commenting, I meant the dude liked to get into bed at night with the duvet on with jeans, not just taking a nap", author: "ShitOnMyArsehole", id: "t1_f35y9gp", parent_id: "t1_f35nn9e", }, { created_utc: 1570703350, body: "Am I pregegnant or am I ok?", author: "HansenTakeASeat", id: "t1_f361yrc", parent_id: "t1_f35nn9e", }, ]; export const tree = [ { created_utc: 1570693670, body: "Bruh", author: "RandomName01", id: "t1_f35vz2f", children: [], }, { created_utc: 1570683149, body: "97% Disagree it's the most unpopular opinion I've seen here after that guy who wanted to be pregnant", author: "shantanu011", id: "t1_f35nn9e", children: [ { created_utc: 1570697457, body: "Or the guy who likes sleeping in jeans\n\nEdit: to everyone commenting, I meant the dude liked to get into bed at night with the duvet on with jeans, not just taking a nap", author: "ShitOnMyArsehole", id: "t1_f35y9gp", parent_id: "t1_f35nn9e", children: [], }, { created_utc: 1570703350, body: "Am I pregegnant or am I ok?", author: "HansenTakeASeat", id: "t1_f361yrc", parent_id: "t1_f35nn9e", children: [], }, ], }, { created_utc: 1570680701, body: "I'm gonna try this tonight op, and if it's shit I will come for you.\n\nEdit: just got home. Getting in shower now.\n\nEdit 2 electric boogaloo: risky click of the day. \n[No bamboozle](https://imgur.com/a/u1C215L)\n\nEdit 3: you!!! I declare shenanigans.", author: "OceLawless", id: "t1_f35kuhk", children: [], }, ]; export const treeWithDeletedChildren = [ { created_utc: 1570693670, body: "Bruh", author: "RandomName01", id: "t1_f35vz2f", children: [], }, { created_utc: 1570680701, body: "I'm gonna try this tonight op, and if it's shit I will come for you.\n\nEdit: just got home. Getting in shower now.\n\nEdit 2 electric boogaloo: risky click of the day. \n[No bamboozle](https://imgur.com/a/u1C215L)\n\nEdit 3: you!!! I declare shenanigans.", author: "OceLawless", id: "t1_f35kuhk", children: [], }, ]; export const treeWithSortedChildren = [ { created_utc: 1570683149, body: "97% Disagree it's the most unpopular opinion I've seen here after that guy who wanted to be pregnant", author: "shantanu011", id: "t1_f35nn9e", children: [ { created_utc: 1570703350, body: "Am I pregegnant or am I ok?", author: "HansenTakeASeat", id: "t1_f361yrc", parent_id: "t1_f35nn9e", children: [], }, { created_utc: 1570697457, body: "Or the guy who likes sleeping in jeans\n\nEdit: to everyone commenting, I meant the dude liked to get into bed at night with the duvet on with jeans, not just taking a nap", author: "ShitOnMyArsehole", id: "t1_f35y9gp", parent_id: "t1_f35nn9e", children: [], }, ], }, { created_utc: 1570693670, body: "Bruh", author: "RandomName01", id: "t1_f35vz2f", children: [], }, { created_utc: 1570680701, body: "I'm gonna try this tonight op, and if it's shit I will come for you.\n\nEdit: just got home. Getting in shower now.\n\nEdit 2 electric boogaloo: risky click of the day. \n[No bamboozle](https://imgur.com/a/u1C215L)\n\nEdit 3: you!!! I declare shenanigans.", author: "OceLawless", id: "t1_f35kuhk", children: [], }, ]; <file_sep>/src/components/Post/Post.jsx import React, { useState, useEffect, useCallback } from "react"; import Loader from "../Loader"; import Error from "../Error"; import Title from "./Title"; import Body from "./Body"; import Comments from "./Comments"; import usePost from "../../hooks/usePost"; import { convertCommentsToTree } from "../../utils/ui"; export default function Post({ id }) { const { isLoading, error, data: post } = usePost(id); const [commentsFiltered, setCommentsFiltered] = useState([]); useEffect(() => { if (post) { setCommentsFiltered(post.comments); } }, [post]); const onDelete = useCallback( function (id) { const remainingComments = commentsFiltered.filter( (comment) => comment.id !== id ); setCommentsFiltered(remainingComments); }, [commentsFiltered] ); if (isLoading) { return <Loader />; } if (error) { return <Error error={error} />; } const { subreddit_name_prefixed, score, title, selftext_html } = post; const { tree: commentsTree, nodeCount: commentsCount, } = convertCommentsToTree(commentsFiltered); return ( <article data-testid="post-element"> <Title subRedditTitle={subreddit_name_prefixed} score={score} title={title} /> <Body body={selftext_html} commentsCount={commentsCount}> <Comments comments={commentsTree} onDelete={onDelete} /> </Body> </article> ); } <file_sep>/src/utils/api.js export async function fetchAndParse(url) { const response = await fetch(url); if (!response.ok) { throw Error(response.statusText); } return await response.json(); } <file_sep>/README.md # reddit-assignment An assignment that clones the reddit post and comments page. [Click here to view the demo](https://adb-reddit-assignment.netlify.app/) This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. ### `yarn test` Launches the test runner in the interactive watch mode.<br /> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ## Notes 1. Uses [EmotionCSS](https://emotion.sh/docs/introduction) for styling. 2. The post id is hard coded. In the real world it would ideally come from the url. 3. The app is responsive but the UX is not fully optimized for mobile. 4. Uses [react-query](https://react-query.tanstack.com/) as a server state management library. 5. Uses [date-fns](https://date-fns.org/) to calculate the comment time difference. 6. Uses Github public api which is rate limited to 60 calls/hr. 7. Comments will be refetched on window focus. This is the default behaviour of `react-query`.
8e934b1345351fe9bd79332c4a19a381c20e7402
[ "JavaScript", "Markdown" ]
16
JavaScript
blessanm86/reddit-assignment
fcafd2978db4f930f7ae3856495c986d90b0613a
fef5e1e0b8413e15ba4a3478bd40c8c988d99b06
refs/heads/master
<repo_name>dorzim/eliot<file_sep>/pkg/discovery/client.go package discovery import ( "context" "time" node "github.com/ernoaapa/eliot/pkg/api/services/node/v1" "github.com/grandcat/zeroconf" "github.com/pkg/errors" ) // Nodes return list of NodeInfos synchronously with given timeout func Nodes(timeout time.Duration) (nodes []*node.Info, err error) { results := make(chan *node.Info) defer close(results) go func() { for node := range results { nodes = append(nodes, node) } }() err = NodesAsync(results, timeout) if err != nil { return nil, err } return nodes, nil } // NodesAsync search for nodes in network asynchronously for given timeout func NodesAsync(results chan<- *node.Info, timeout time.Duration) error { resolver, err := zeroconf.NewResolver(nil) if err != nil { return errors.Wrapf(err, "Failed to initialize new zeroconf resolver") } entries := make(chan *zeroconf.ServiceEntry) go func(entries <-chan *zeroconf.ServiceEntry) { for entry := range entries { results <- MapToAPIModel(entry) } }(entries) ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() err = resolver.Browse(ctx, ZeroConfServiceName, "", entries) if err != nil { return errors.Wrapf(err, "Failed to browse zeroconf nodes") } <-ctx.Done() return nil } <file_sep>/pkg/resolve/image_test.go package resolve import ( "fmt" "path/filepath" "testing" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) var targetArchitectures = []string{"amd64", "arm64"} func TestImageResolveNode(t *testing.T) { projectDir := getExampleDirectory("node") testResolving(t, projectDir, "nodejs", map[string]string{ "amd64": "docker.io/library/node:latest", "arm64": "docker.io/arm64v8/node:latest", }) } func TestImageResolveGolang(t *testing.T) { projectDir := getExampleDirectory("golang") testResolving(t, projectDir, "golang", map[string]string{ "amd64": "docker.io/library/golang:latest", "arm64": "docker.io/arm64v8/golang:latest", }) } func TestImageResolvePython(t *testing.T) { projectDir := getExampleDirectory("python") testResolving(t, projectDir, "python", map[string]string{ "amd64": "docker.io/library/python:latest", "arm64": "docker.io/arm64v8/python:latest", }) } func getExampleDirectory(name string) string { dir, err := filepath.Abs(filepath.Join(".", "examples", name)) if err != nil { log.Fatal(err) } return dir } func testResolving(t *testing.T, projectDir, expectedProjectType string, images map[string]string) { for _, arch := range targetArchitectures { expectedImage, ok := images[arch] if !ok { assert.FailNow(t, fmt.Sprintf("Test case is missing expected image for projectType %s and architecture %s", expectedProjectType, arch)) } projectType, image, err := Image(arch, projectDir) assert.NoError(t, err) assert.Equal(t, expectedProjectType, projectType) assert.Equal(t, expectedImage, image) } }
74d16df841e6babf4b4b54bd5dae68a8b2196bdd
[ "Go" ]
2
Go
dorzim/eliot
8ace81573faef7fe11aeb64520c8c2043ae4dc0b
20da0bf2732afb2b07be496afd7e822c656e55cd
refs/heads/master
<repo_name>bowlerbear/ptarmiganUpscaling<file_sep>/06_model_summaries.R library(raster) library(sp) library(sf) library(maptools) library(rgeos) library(tmap) library(ggplot2) library(ggmcmc) library(tidyverse) library(ggthemes) #tmaptools::palette_explorer() ### check siteInfo ####################################################### siteInfo_Occ <- readRDS("data/siteInfo_ArtsDaten.rds") ### common grid ########################################################### #using a m grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" #get Norway data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) NorwayOrigProj <- spTransform(NorwayOrig,crs(equalM)) #create grid newres = 5000#5 km grid mygrid<-raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid myGridDF <- as.data.frame(mygrid,xy=T) ### OCCU models ############################################## out1 <- readRDS("model-outputs/SLURM/occModel/outSummary_occModel_upscaling_1.rds") out1 <- readRDS("model-outputs/SLURM/occModel/outSummary_occModel_upscaling_2.rds") out1 <- readRDS("model-outputs/SLURM/occModel/outSummary_occModel_upscaling_3.rds") out1 <- readRDS("model-outputs/SLURM/occModel/outSummary_occModel_upscaling_4.rds") out1 <- readRDS("model-outputs/SLURM/occModel/outSummary_occModel_upscaling_5.rds") out1 <- readRDS("model-outputs/SLURM/occModel/outSummary_occModel_upscaling_6.rds") ### plot map ################################################# out1 <- data.frame(out1) out1$Param <- row.names(out1) table(out1$Rhat<1.1) #Z preds <- z_preds <- subset(out1,grepl("grid.z",out1$Param)) siteInfo_Occ$preds <- preds$mean mygrid[] <- NA mygrid[siteInfo_Occ$grid] <- siteInfo_Occ$preds plot(mygrid) # using tmap package crs(mygrid) <- equalM occ_tmap <- tm_shape(mygrid)+ tm_raster(title="Occupancy",palette="YlGnBu", style="cont") occ_tmap #and sd siteInfo_Occ$preds <- preds$sd mygrid[] <- NA mygrid[siteInfo_Occ$grid] <- siteInfo_Occ$preds plot(mygrid) # using tmap package crs(mygrid) <- equalM occ_tmap_sd <- tm_shape(mygrid)+ tm_raster(title="SD",palette="YlGnBu", style="cont") occ_tmap_sd tmap_arrange(occ_tmap,occ_tmap_sd,nrow=1) #psi preds <- subset(out1,grepl("grid.psi",out1$Param)) siteInfo_Occ$preds <- preds$mean mygrid[] <- NA mygrid[siteInfo_Occ$grid] <- siteInfo_Occ$preds plot(mygrid) # using tmap package crs(mygrid) <- equalM occ_tmap <- tm_shape(mygrid)+ tm_raster(title="a) Occupancy prob",palette="YlGnBu", style="cont") occ_tmap siteInfo_Occ$preds <- preds$sd mygrid[] <- NA mygrid[siteInfo_Occ$grid] <- siteInfo_Occ$preds plot(mygrid) # using tmap package crs(mygrid) <- equalM occ_tmap_sd <- tm_shape(mygrid)+ tm_raster(title="b) Occupancy SD",palette="YlGnBu", style="cont") occ_tmap_sd temp <- tmap_arrange(occ_tmap,occ_tmap_sd,nrow=1) temp tmap_save(temp, "plots/Fig_2.png",width = 6, height = 4) ### summary stats ########################################### subset(out1,grepl("average",out1$Param)) subset(out1,grepl("propOcc",out1$Param)) subset(out1,grepl("beta.",out1$Param)) ### model selection ########################################## #model 1 - a priori selection betas <- subset(out1,grepl("beta",out1$Param)) betas <- subset(betas,!grepl("beta.det",betas$Param)) betas <- subset(betas,!grepl("beta.effort",betas$Param)) betas$variables <- c("tree_line_position","tree_line_position_2","y","bio6", "Bog","Mire","Meadows","ODF","ODF2", "OSF","OSF2","MountainBirchForest") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("effect size on occupancy")+ geom_hline(yintercept=0,color="red", linetype="dashed") #model 2 = lasso betas <- subset(out1,grepl("beta",out1$Param)) betas <- subset(betas,Param!="beta.det.open") betas <- subset(betas,Param!="beta.effort") betas$variables <- c("bio6","bio5","tree_line_position","MountainBirchForest","Bog","ODF","Meadows", "OSF","Mire","SnowBeds","y","distCoast", "bio6_2","bio5_2","tree_line_position_2", "MountainBirchForest_2","Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2", "SnowBeds_2","y_2","distCoast_2") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("effect size on occupancy")+ geom_hline(yintercept=0,color="red", linetype="dashed") #model 3 = variable indicator betas <- subset(out1,grepl("beta",out1$Param)) betas <- subset(betas,!grepl("effort",betas$Param)) betas <- subset(betas,!grepl("det",betas$Param)) betas$variables <- c("bio6","bio5","tree_line_position","MountainBirchForest","Bog","ODF","Meadows", "OSF","Mire","SnowBeds","y","distCoast", "bio6_2","bio5_2","tree_line_position_2", "MountainBirchForest_2","Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2", "SnowBeds_2","y_2","distCoast_2") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("effect size on occupancy")+ geom_hline(yintercept=0,color="red", linetype="dashed")+ theme_few() #inclusion betas <- subset(out1,grepl("g",out1$Param)) betas <- subset(betas,!grepl("grid",betas$Param)) betas <- subset(betas,!grepl("average",betas$Param)) betas$variables <- c("bio6","bio5","tree_line_position","MountainBirchForest","Bog","ODF","Meadows", "OSF","Mire","SnowBeds","y","distCoast", "bio6_2","bio5_2","tree_line_position_2", "MountainBirchForest_2","Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2", "SnowBeds_2","y_2","distCoast_2") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("Model inclusion")+ geom_hline(yintercept=0,color="red", linetype="dashed") subset(betas,mean>0.25) ### BPV ##################################################### subset(out1,grepl("bpv",out1$Param)) ### AUC ############################################## list.files("model-outputs/SLURM/occModel", full.names=TRUE) %>% str_subset("AUC_") %>% set_names() %>% map_dfr(readRDS, .id = "File") ### cross validation ####################################### myfolds <- list.files("model-outputs/SLURM/occModel/CV") %>% str_subset("BUGS_occuModel_upscaling_CV.txt")#model 1 myfolds <- list.files("model-outputs/SLURM/occModel/CV") %>% str_subset("BUGS_occuModel_upscaling_ModelSelection_CV")#model 3 temp <- plyr::ldply(1:5,function(x){ temp <- readRDS(paste0("model-outputs/SLURM/occModel/CV/",myfolds[x])) temp$fold.id <- x return(temp) }) model_3 <- temp %>% group_by(fold.id) %>% summarise(across(everything(),mean)) # A tibble: 5 x 5 #fold.id AUC_psi_test AUC_psi_train AUC_py_test AUC_py_train AUC_pypred_test AUC_pypred_train #<int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #1 1 0.860 0.859 0.740 0.967 0.914 0.922 #2 2 0.829 0.865 0.661 0.970 0.879 0.927 #3 3 0.870 0.866 0.719 0.969 0.883 0.925 #4 4 0.865 0.846 0.734 0.966 0.942 0.913 #5 5 0.877 0.850 0.737 0.965 0.930 0.917 #satisfactory.... temp %>% group_by(fold.id) %>% summarise(across(everything(),mean)) %>% colMeans() # #plot all # model_1$model <- "Gaussian priors" # model_2$model <- "LASSO priors" # model_3$model <- "Variable indicator" # allCV <- rbind(model_1, # model_2, # model_3) # # allCV <- allCV %>% # pivot_longer(!c("fold.id","model"), # names_to = "variable", values_to="value") # allCV$dataset <- sapply(allCV$variable,function(x) # strsplit(x,"_")[[1]][3]) # allCV$parameter <- sapply(allCV$variable,function(x) # strsplit(x,"_")[[1]][2]) # allCV$Parameter <- ifelse(allCV$parameter=="psi","Occupancy","Detection") # # allCV$model <- factor(allCV$model, levels = c("LASSO priors", "Variable indicator","Gaussian priors")) # # ggplot(allCV) + # geom_point(aes(x=fold.id,y=value, colour=model))+ # facet_grid(Parameter~dataset)+ # theme_bw()+ # ylab("AUC") + xlab("Fold") ### DISTANCE models ########################################## bufferData <- readRDS("data/varDF_allEnvironData_buffers_idiv.rds") bufferData <- subset(bufferData, ! LinjeID %in% c(935,874,876,882,884,936,2317,2328,2338,878,886,1250,1569,2331,2339,1925)) out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_1.rds") out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_2.rds") out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_3.rds") out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_4.rds") out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_5.rds") out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_6.rds") #make into a df out1 <- data.frame(out1) out1$Param <- row.names(out1) table(out1$Rhat<1.1) ### plot map ############################################## #density over range of line transects preds <- subset(out1,grepl("meanDensity",out1$Param)) bufferData$preds <- preds$mean bufferData$predsSD <- preds$sd summary(bufferData$preds) #final - model 3 # Min. 1st Qu. Median Mean 3rd Qu. Max. #2.186 8.755 11.731 12.836 16.028 32.253 #tmap bufferData_st <- st_as_sf(bufferData,coords=c("x","y"),crs=equalM) #mean preds density_tmap <- tm_shape(NorwayOrigProj)+ tm_borders()+ tm_shape(bufferData_st)+ tm_dots("preds",title="Est. Density", palette="YlGnBu",size=0.05, style="cont")+ tm_layout(legend.position=c("left","top")) #sd of preds density_tmap_sd <- tm_shape(NorwayOrigProj)+ tm_borders()+ tm_shape(bufferData_st)+ tm_dots("predsSD",title="SD", palette="YlGnBu",size=0.05, style="cont")+ tm_layout(legend.position=c("left","top")) #saving temp <- tmap_arrange(density_tmap,density_tmap_sd,nrow=1) temp tmap_save(temp, "plots/Fig_3.png",width = 6, height = 4) ### coefficients ################ #average strip width summary(subset(out1,grepl("meanESW",out1$Param))[,"mean"]) #group size effect subset(out1,grepl("b.group.size",out1$Param)) #mean density per km summary(subset(out1,grepl("meanDensity",out1$Param))[,"mean"]) #overdispersion? summary(subset(out1,grepl("r",out1$Param))[,"mean"]) ### correlations ################# #mean across all years preds <- subset(out1,grepl("exp.j",out1$Param)) preds$data <- apply(bugs.data$NuIndivs,1,mean,na.rm=T) summary(preds$data) summary(preds$mean) summary(abs(preds$data-preds$mean)) #main plot qplot(data,mean,data=preds)+ geom_abline(intercept=0,slope=1)+ theme_bw()+ xlab("Observed data")+ylab("Model prediction") #on log-scale qplot(data,mean,data=preds)+ geom_abline(intercept=0,slope=1)+ scale_x_log10()+scale_y_log10()+ theme_bw()+ xlab("Observed data")+ylab("Model prediction") cor.test(preds$data,preds$mean)#0.87 cor.test(log(preds$data),log(preds$mean)) #model 3 - 0.85 ### BPV ################################################### subset(out1,grepl("bpv",out1$Param)) ### MAD ################################################### subset(out1,grepl("MAD",out1$Param)) #MAD list.files("model-outputs/SLURM/distanceModel", full.names=TRUE) %>% str_subset("MAD") %>% map(~ readRDS(.x)) %>% reduce(rbind) #RMSE list.files("model-outputs/SLURM/distanceModel", full.names=TRUE) %>% str_subset("RMSE") %>% map(~ readRDS(.x)) %>% reduce(rbind) ### model selection ####################################### #model 1 out1 <- data.frame(out1) out1$Param <- row.names(out1) betas <- subset(out1,grepl("beta",out1$Param)) betas$variables <- c("y",'bio6',"bio6_2","distCoast","distCoast_2", "bio5","bio5_2","tree_line","tree_line_2","OSF","SnowBeds") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("effect size on abundance")+ geom_hline(yintercept=0,color="red", linetype="dashed") #model 2 = lasso out1 <- data.frame(out1) out1$Param <- row.names(out1) betas <- subset(out1,grepl("beta",out1$Param)) betas$variables <- c("bio6","bio5","y","distCoast","tree_line","MountainBirchForest", "Bog","ODF","Meadows","OSF","Mire","SnowBeds", "bio6_2","bio5_2","y_2","distCoast_2","tree_line_2","MountainBirchForest_2", "Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2","SnowBeds_2") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("effect size on abundance")+ geom_hline(yintercept=0,color="red", linetype="dashed") #model 3 = variable indicator out1 <- data.frame(out1) out1$Param <- row.names(out1) betas <- subset(out1,grepl("beta",out1$Param)) betas$variables <- c("bio6","bio5","y","distCoast","tree_line","MountainBirchForest", "Bog","ODF","Meadows","OSF","Mire","SnowBeds", "bio6_2","bio5_2","y_2","distCoast_2","tree_line_2","MountainBirchForest_2", "Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2","SnowBeds_2") ggplot(betas)+ geom_crossbar(aes(x=variables,y=mean, ymin=X2.5.,ymax=X97.5.))+ coord_flip()+ theme_bw()+ ylab("effect size on abundance")+ geom_hline(yintercept=0,color="red", linetype="dashed") #or plot gs gs <- subset(out1,grepl("g",out1$Param)) gs <- subset(gs,!grepl("b.group.size",gs$Param)) gs$variables <- c("bio6","bio5","y","distCoast","tree_line","MountainBirchForest", "Bog","ODF","Meadows","OSF","Mire","SnowBeds", "bio6_2","bio5_2","y_2","distCoast_2","tree_line_2","MountainBirchForest_2", "Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2","SnowBeds_2") ggplot(gs)+ geom_col(aes(x=variables,y=mean))+ coord_flip()+ theme_bw()+ ylab("Proportion of model inclusion")+ geom_hline(yintercept=0,color="red", linetype="dashed")+ xlab("Predictor") #ones included in more than 25% of models: #tree line - additive and squared #bio5 #bio6 #tree line position not important for density ### cross validation ################################### modelTaskID <- read.delim(paste("data","modelTaskID_occuModel_CV.txt",sep="/"),as.is=T) #MAD madFiles <- list.files("model-outputs/SLURM/distanceModel/CV", full.names=TRUE) %>% str_subset("MAD") #read in and combine madData <- madFiles %>% map(~ readRDS(.x)) %>% reduce(rbind) %>% as_tibble()%>% add_column(file = madFiles) %>% dplyr::mutate(tmp = map_chr(file, ~strsplit(.x, "_")[[1]][5])) %>% dplyr::mutate(TaskID = parse_number(tmp)) %>% dplyr::mutate(Type = map_chr(file, ~strsplit(.x, "_")[[1]][2])) %>% left_join(.,modelTaskID) #get mean and range for each Model madData %>% dplyr::group_by(Model, Type) %>% dplyr::summarise(median = median(Mean),min=min(Mean),max=max(Mean)) # Groups: Model [3] #<chr> <chr> <dbl> <dbl> <dbl> # 1 BUGS_occuModel_upscaling_CV.txt test 5.20 3.39 6.65 #2 BUGS_occuModel_upscaling_CV.txt train 5.01 3.81 6.24 #3 BUGS_occuModel_upscaling_LASSO_CV.txt test 6.08 3.67 11.6 #4 BUGS_occuModel_upscaling_LASSO_CV.txt train 4.83 3.73 6.18 #5 BUGS_occuModel_upscaling_ModelSelection_CV.txt test 5.21 3.53 7.12 #6 BUGS_occuModel_upscaling_ModelSelection_CV.txt train 4.93 3.84 6.22 #RMSE rmseFiles <- list.files("model-outputs/SLURM/distanceModel/CV", full.names=TRUE) %>% str_subset("RMSE") #read in and combine rmseData <- rmseFiles %>% map(~ readRDS(.x)) %>% reduce(rbind) %>% as_tibble()%>% add_column(file = madFiles) %>% dplyr::mutate(tmp = map_chr(file, ~strsplit(.x, "_")[[1]][5])) %>% dplyr::mutate(TaskID = parse_number(tmp)) %>% dplyr::mutate(Type = map_chr(file, ~strsplit(.x, "_")[[1]][2])) %>% left_join(.,modelTaskID) #get mean and range for each Model rmseData %>% dplyr::group_by(Model, Type) %>% dplyr::summarise(median = median(Mean),min=min(Mean),max(max(Mean))) ### COMBINED model ##################################### modelFolder <- "model-outputs/SLURM/combinedModel/" #choose model models = c(" _1 ") models = c(" _2 ") models = c(" _3 ") siteInfo_Occ <- readRDS("data/siteInfo_ArtsDaten.rds") siteInfo_Abund <- readRDS("data/siteInfo_AbundanceModels.rds") #plot occupancy preds predsOcc_summary <- readRDS(paste0(modelFolder,"predsOcc_summary", models,".rds")) siteInfo_Occ$preds <- predsOcc_summary$myMean mygrid[] <- NA mygrid[siteInfo_Occ$grid] <-siteInfo_Occ$preds plot(mygrid) #plot density preds predsDensity_summary <- readRDS(paste0(modelFolder,"predsDensity_summary", models,".rds")) siteInfo_Abund$preds <- predsDensity_summary$myMean mygrid[] <- NA mygrid[siteInfo_Abund$grid] <-siteInfo_Abund$preds plot(mygrid) #simple combination (just to check) siteInfo_Occ$abund <- siteInfo_Abund$preds[match(siteInfo_Occ$grid, siteInfo_Abund$grid)] siteInfo_Occ$preds <- siteInfo_Occ$preds * siteInfo_Occ$abund mygrid[] <- NA mygrid[siteInfo_Occ$grid] <- siteInfo_Occ$preds plot(mygrid) #look at annual preds (populationAnnual <- readRDS(paste0(modelFolder,"population_Annual", models,".rds"))) g1 <- populationAnnual %>% mutate(Year = as.numeric(Year)+2007) %>% ggplot()+ geom_pointrange(aes(x=Year, y=medianPop, ymin=lowerPop, ymax=upperPop))+ ylab("Predicted national population size")+ scale_x_continuous(breaks=c(2008,2012,2016), labels=c(2008,2012,2016))+ theme_few() #look at mean preds totalSummary <- readRDS(paste0(modelFolder,"totalSummary", models,".rds")) g2 <- ggplot(totalSummary, aes(totalPop))+ geom_density(fill="red",colour="black",alpha=0.2)+ geom_density(colour="black", size=2)+ theme_few()+ ylab("Probability density") + xlab("Total population size estimate") cowplot::plot_grid(g2,g1,labels=c("a","b"),nrow=1,ncol=2) ggsave("plots/Fig.5.png",width=9.5,height=4) summary(totalSummary$totalPop) quantile(totalSummary$totalPop,c(0.025,0.5,0.975)) #short cut sum(predsOcc_summary$myMean) mean(predsDensity_summary$myMean) sum(predsOcc_summary$myMean)*mean(predsDensity_summary$myMean) #with model 3 - 1207997 #plot grid predictions (populationGrid <- readRDS(paste0(modelFolder,"population_grid", models,".rds"))) mygrid[] <- NA mygrid[populationGrid$grid] <- populationGrid$medianPop crs(mygrid) <- equalM occ_tmap <- tm_shape(mygrid)+ tm_raster(title="a) Abundance",palette="YlGnBu", breaks=c(0,50,100,200,400,800)) occ_tmap mygrid[] <- NA mygrid[populationGrid$grid] <- populationGrid$sdPop plot(mygrid) crs(mygrid) <- equalM occ_tmap_sd <- tm_shape(mygrid)+ tm_raster(title="b) SD ",palette="YlGnBu", breaks=c(0,50,100,200,400)) occ_tmap_sd temp <- tmap_arrange(occ_tmap,occ_tmap_sd,nrow=1) temp tmap_save(temp, "plots/Fig_4.png",width = 6, height = 4) #compare priors library(ggridges) all_ggd <- list.files(paste(modelFolder,"12198176",sep="/"), full.names=TRUE) %>% str_subset("totalSummary") %>% set_names() %>% map_dfr(readRDS, .id="source") %>% as_tibble() all_ggd$Model <- NA all_ggd$Model[grepl("_1", all_ggd$source)] <- "Only important vars" all_ggd$Model[grepl("_2", all_ggd$source)] <- "LASSO priors" all_ggd$Model[grepl("_3", all_ggd$source)] <- "Variable indicator" ggplot(all_ggd, aes(x = totalPop, y = Model)) + geom_density_ridges2()+ theme_minimal()+xlab("Total population size")+ xlim(900000,1800000) ggplot(all_ggd, aes(totalPop))+ geom_density(fill="red",colour="black",alpha=0.2)+ geom_density(colour="black", size=2)+ theme_few()+ facet_wrap(~Model,scales="free")+ ylab("Probability density") + xlab("Total population size estimate") ### make model predictions #### #for use in the uncertainity analysis varDF <- readRDS("data/varDF_allEnvironData_5km_idiv.rds") #run sections above to get z_preds out_occ <- z_preds out_occ$grid <- siteInfo_Occ$grid out_occ <- arrange(out_occ,grid) all(varDF$grid==out_occ$grid) #abundance predictions out1 <- readRDS("model-outputs/SLURM/distanceModel/outSummary_linetransectModel_variables_3.rds") out1 <- data.frame(out1) out1$Param <- row.names(out1) out1 <- subset(out1,grepl("Density.p",out1$Param)) out1$grid <- siteInfo_Abund$grid out_dens <- arrange(out1, grid) #check align all(out_occ$grid, out_dens$grid) #make modelPredictions modelPredictions <- data.frame(density_mean=out_dens$mean, density_sd = out_dens$sd, occ_mean=out_occ$mean, occ_sd = out_occ$sd) #add x and y modelPredictions$x <- varDF$x modelPredictions$y <- varDF$y saveRDS(modelPredictions, file="data/modelPredictions.rds") ### end ##### <file_sep>/05_cross_validation_folds.R ### occupancy models ############################################ #see Broms et al. 2006 #we want 3000 posterior samples for each parameter ### goodness of fit ############################################# #Bayesian p-values #Pearson's residuals - Tobler et al. 2015 #plot them against the residuals too #aggregate detections per site #se also MacKenzie and Bailey (2004). #compare them across sites ### model selection ############################################ #If the goal is prediction, then one could avoid model #selection by including all the covariates in the model and #using regularization to restrict the parameter space #through strong priors #In a similar vein, we used weakly informative #priors as a regularization on the model. The weakly #informative priors helped with collinearity between #covariates and separation related to indicator variables. #WAIC?? #indicator variable #selection #Rushing ### out-of-sample ############################################## #k-fold cross validation - use 5... #Withholding one of the k∗ subsets, one fits the models to #the rest of the data, and calculates a scoring rule to measure #how close the models’ predictions are to the hold-out #data. This process is repeated for each subset of data, #then the scoring function is summed or averaged over #the k∗ folds #After the final model is chosen, it is refit using the entire #data set so that inference is based on all the data #https://besjournals.onlinelibrary.wiley.com/doi/full/10.1111/2041-210X.13107 #https://cran.r-project.org/web/packages/blockCV/vignettes/BlockCV_for_SDM.html library(blockCV) #spatially or environmentally separated folds # loading raster library library(raster) library(sf) library(plyr) library(ggthemes) library(ggplot2) #create grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" library(raster) library(maptools) library(rgeos) data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) plot(Norway) #create grid newres = 5000#5 km grid mygrid <- raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid plot(Norway,add=T) myGridDF <- as.data.frame(mygrid,xy=T) #### for occu model ######### siteInfo <- readRDS("data/siteInfo_ArtsDaten.rds") # import raster data #make each variable column a grid myVars <- names(siteInfo)[c(14:26,32:34,40:42)] myRasters <- list() for(i in 1:length(myVars)){ temp <- mygrid temp[] <- NA temp[siteInfo$grid] <- siteInfo[,myVars[i]] myRasters[i] <- temp } myRasters <- stack(myRasters) awt<- raster::brick(myRasters) projection(awt) <- equalM plot(awt) # make a SpatialPointsDataFrame object from data.frame PA <- siteInfo[,c("x","y","species")] PA$species[is.na(PA$species)] <- 0 pa_data <- st_as_sf(PA, coords = c("x", "y"), crs = st_crs(awt,asText=TRUE)) # see the first few rows pa_data st_crs(pa_data)==st_crs(awt) # plot species data on the map plot(awt[[1]]) # plot raster data plot(pa_data[which(pa_data$species==1), ], pch = 16, col="red", add=TRUE) plot(pa_data[which(pa_data$species==0), ], pch = 16, col="blue", add=TRUE) plot(pa_data) # spatial blocking sb <- spatialBlock(speciesData = pa_data, species = "species", rasterLayer = awt, theRange = 75000, # 150 km works k = 5, selection = "random") sb <- spatialBlock(speciesData = pa_data, species = "species", rasterLayer = awt, rows = 25, cols = 1, k = 5, selection = "systematic") # buffering with presence-absence data #sb <- buffering(speciesData= pa_data, # species= "species", # theRange= 70000, # spDataType = "PA", # progress = TRUE) # # environmental clustering # # eb <- envBlock(rasterLayer = awt, # speciesData = pa_data, # species = "species", # k = 5, # standardization = "standard", # rescale variables between 0 and 1 # rasterBlock = TRUE, # numLimit = 50) sac <- spatialAutoRange(rasterLayer = awt, sampleNumber = 5000, doParallel = TRUE, showPlots = TRUE) #interactive # explore generated folds foldExplorer(blocks = sb, rasterLayer = awt, speciesData = pa_data) # explore the block size rangeExplorer(rasterLayer = awt) # the only mandatory input # add species data to add them on the map rangeExplorer(rasterLayer = awt, speciesData = pa_data, species = "species", rangeTable = NULL, minRange = 30000, # limit the search domain maxRange = 100000) ### retrieve each fold in the data mydata <- raster::extract(awt, pa_data,df=TRUE) nrow(mydata) #sites with NA species data are excluded nrow(siteInfo) folds <- sb$foldID length(folds) #plot the folds siteInfo$folds <- factor(sb$foldID) g1 <- qplot(x, y, data=siteInfo, colour=folds) + theme_void()+ theme(legend.position = "top") g1 #random saveRDS(siteInfo[,c("grid","siteIndex","folds")], file="data/folds_occModel.rds") #systematic bands saveRDS(siteInfo[,c("grid","siteIndex","folds")], file="data/folds_occModel_bands.rds") #how many are in each fold #### for distance model #### library(blockCV) siteInfo <- readRDS("data/siteInfo_ArtsDaten.rds") # import raster data for whole country myVars <- names(siteInfo)[c(14:26,32:34,40:42)] myRasters <- list() for(i in 1:length(myVars)){ temp <- mygrid temp[] <- NA temp[siteInfo$grid] <- siteInfo[,myVars[i]] myRasters[i] <- temp } myRasters <- stack(myRasters) awt<- raster::brick(myRasters) projection(awt) <- equalM plot(awt) # get transect data siteInfo <- readRDS("data/lines_to_grids.rds") # import presence-absence species data pa_data <- siteInfo pa_data$species <- 1 coordinates(pa_data) <- c("x","y") proj4string(pa_data) <- CRS(equalM) # plot species data on the map plot(awt[[1]]) # plot raster data plot(pa_data,add=TRUE) # spatial blocking sb <- spatialBlock(speciesData = pa_data, species = "species", rasterLayer = awt, theRange = 100000, #theRange = 150000, # size of the blocks k = 5, selection = "random") sb <- spatialBlock(speciesData = pa_data, species = "species", rasterLayer = awt, rows = 25, cols = 1, k = 5, selection = "systematic") sac <- spatialAutoRange(rasterLayer = awt, sampleNumber = 5000, doParallel = TRUE, showPlots = TRUE) ### retrieve each fold in the data mydata <- raster::extract(awt, pa_data,df=TRUE) nrow(mydata) #sites with NA species data are excluded nrow(siteInfo) folds <- sb$foldID length(folds) #plot the folds siteInfo$folds <- sb$foldID ggplot2::qplot(x, y, data=siteInfo, colour=factor(folds)) #random saveRDS(siteInfo[,c("grid","siteIndex","LinjeID","folds")], file="data/folds_distanceModel.rds") #bands saveRDS(siteInfo[,c("LinjeID","grid","folds")], file="data/folds_distanceModel_bands.rds") ### AUC ################################################## #choice for binary data models is AUC, area under #the receiver operator characteristic curve #AUC, Brier, Logarithmic, and 0–1 scoring rules #https://www.r-bloggers.com/2013/07/occupancy-model-fit-auc/ #Now that we have our posteriors for $\psi$ at each site in the final #year, we can fit a single-year model to the final year’s data to #estimate $Z$. #To set up the data for AUC calculations, produce site by #iteration arrays for $\psi$ and $Z$ #Now generate the posterior for AUC and store data on the true and false #positive rates to produce ROC curves #https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/11-1936.1 #https://rviews.rstudio.com/2019/03/01/some-r-packages-for-roc-curves/ #AUC is equal to the probability that a true positive is scored greater than a true negative #In a ROC plot the true positive rate (sensitivity) is plotted against the false positive rate (1.0-specificity) as the threshold varies from 0 to 1. library(ROCR) #using point estimate siteInfo_obsSites <- subset(siteInfo,!is.na(species)) auc.tmp <- performance(pred,"auc"); auc <- as.numeric(auc.tmp@y.values) library(data.table) library(mltools) preds <- siteInfo_obsSites$preds actuals <- siteInfo_obsSites$species auc_roc(preds, actuals) df <- auc_roc(preds, actuals, returnDT=TRUE) qplot(CumulativeFPR,CumulativeTPR,data=df) pred <- prediction(preds, actuals) perf <- performance(pred,"tpr","fpr") plot(perf,colorize=TRUE) #using full posterior #Rather than use average values to determine a single point estimate, we used the full posterior distribution (3000 draws) and the R package ROCR #make data frame into a matrix - site by iterations matrix #calculate auc for each iteration - need both z and psi for this bit library(ggmcmc) ggd2 <- ggs(out2) nstore <- niter / nthin psi.pred <- array(dim=c(nsite, nstore*nchain)) Z.est <- array(dim=c(nsite, nstore*nchain)) for (j in 1:nsite){ indx <- which(ggd$Parameter == paste("psi[", j, ",", nyear, "]", sep="")) psi.pred[j, ] <- ggd$value[indx] indx <- which(ggd2$Parameter == paste("z[", j, "]", sep="")) Z.est[j,] <- ggd2$value[indx] } require(ROCR) AUC1 <- rep(NA, nstore * nchain) fpr <- array(dim=c(nstore * nchain, nsite + 1)) tpr <- array(dim=c(nstore * nchain, nsite + 1)) for (i in 1:(nstore * nchain)){ psi.vals <- psi.pred[, i] Z.vals <- Z.est[, i] pred <- prediction(psi.vals, factor(Z.vals, levels=c("0", "1"))) perf <- performance(pred, "auc") AUC1[i] <- perf@y.values[[1]] perf <- performance(pred, "tpr","fpr") fpr[i, ] <- perf@x.values[[1]] tpr[i, ] <- perf@y.values[[1]] } require(reshape2) fprm <- melt(fpr, varnames=c("iter", "site")) tprm <- melt(tpr, varnames = c("iter", "site")) ROC1 <- data.frame(fpr = fprm$value, tpr = tprm$value, iter = rep(fprm$iter, 2)) #actually compares z and psi... #https://rdrr.io/github/jdyen/occupancy/man/validate.html library(occupancy) occupancy#object just Jags objects calculate_metrics r2_calc validate https://rdrr.io/github/jdyen/occupancy/src/R/validate.R #fitted is p_obs??? <file_sep>/00_generalFunctions.R #general functions: #get function to extract raster into for these grids: getEnvironData<-function(myraster,mygridTemp){ require(maptools) require(plyr) #crop raster to Norway extent rasterCRS<-crs(myraster) NorwayB<-spTransform(Norway,rasterCRS) myraster<-crop(myraster,extent(NorwayB)) #convert raster into points and convert myrasterDF<-as.data.frame(myraster,xy=T) names(myrasterDF)[3]<-"myraster" coordinates(myrasterDF)<-c("x","y") proj4string(myrasterDF)<-rasterCRS myrasterDF<-spTransform(myrasterDF,crs(equalM)) #get general grid mygrid<-gridTemp projection(mygrid)<- equalM #get mean myraster values per grid cell mygrid[]<-1:ncell(mygrid) variable<-extract(mygrid,myrasterDF) myrasterDF<-data.frame(myrasterDF@data) myrasterDF$grid<-variable myrasterDF<-ddply(myrasterDF,.(grid),summarise,myraster=mean(myraster,na.rm=T)) return(myrasterDF) } getBufferData<-function(myraster,mybuffer){ require(maptools) require(plyr) #crop raster to Norway extent and project all to raster crs rasterCRS <- crs(myraster) NorwayB <- spTransform(Norway,rasterCRS) myraster <- crop(myraster,extent(NorwayB)) mybuffer <- spTransform(mybuffer,rasterCRS) #get mean myraster values per buffer rasterDF <- raster::extract(myraster,mybuffer,fun=mean,na.rm=T,df=T) rasterDF$LinjeID <- mybuffer@data$LinjeID return(rasterDF[,c(3,2)]) } mergeCounties <- function(x,further=FALSE){ x <- as.character(x) x[x %in% c("Ãstfold","Akershus","Buskerud","Oslo")] <- "Viken" x[x %in% c("Hedmark","Oppland")] <- "Innlandet" x[x %in% c("Hordaland","Sogn og Fjordane")] <- "Vestland" x[x %in% c("Telemark","Vestfold")] <- "Vestfold og Telemark" x[x %in% c("Nord-Trøndelag","Sør-Trøndelag")] <- "Trøndelag" x[x %in% c("Vest-Agder","Aust-Agder")] <- "Adger" x[x %in% c("Finnmark","Troms")] <- "Troms og Finnmark" if(further==TRUE){ x[x %in% c("Adger","Rogaland","Vestland")] <- "Adger/Rogaland/Vestfold/Telemark/Viken" x[x %in% c("Vestfold og Telemark","Viken")] <- "Adger/Rogaland/Vestfold/Telemark/Viken" x[x %in% c("Møre og Romsdal","Vestland")] <- "Innlandet" } return(x) } plotBUGSData<-function(myvar){ temp<-listlengthDF temp<-subset(temp,siteIndex %in% bugs.data$site) temp$variable<-as.numeric(bugs.data[myvar][[1]])[match(temp$siteIndex,bugs.data$site)] temp$variablePA<-sapply(temp$variable,function(x)ifelse(is.na(x),0,1)) temp<-subset(temp,!duplicated(siteIndex)) mygrid<-gridTemp par(mfrow=c(1,2)) mygrid[]<-0 mygrid[temp$grid]<-temp$variable plot(mygrid) mygrid[]<-0 mygrid[temp$grid]<-temp$variablePA plot(mygrid) } plotZ<-function(model,param="z"){ zSummary<-data.frame(model$summary[grepl(param,row.names(model$summary)),]) zSummary$ParamNu <- as.character(sub(".*\\[([^][]+)].*", "\\1", row.names(zSummary))) zSummary$Site<-sapply(zSummary$ParamNu,function(x)strsplit(x,",")[[1]][1]) zSummary$Year<-sapply(zSummary$ParamNu,function(x)strsplit(x,",")[[1]][2]) zSummary$grid<-listlengthDF$grid[match(zSummary$Site,listlengthDF$siteIndex)] #zSummary_year<-subset(zSummary,Year==11) #predicted occupancy across all years zSummary_year<-ddply(zSummary,.(grid),summarise,prop=mean(mean)) #plot mean prop occupancy par(mfrow=c(1,1)) mygrid[]<-0 mygrid[zSummary_year$grid]<-zSummary_year$prop plot(mygrid) plot(Norway,add=T) } plotZerror<-function(model){ zSummary<-data.frame(model$summary[grepl("z",row.names(model$summary)),]) zSummary$ParamNu <- as.character(sub(".*\\[([^][]+)].*", "\\1", row.names(zSummary))) zSummary$Site<-sapply(zSummary$ParamNu,function(x)strsplit(x,",")[[1]][1]) zSummary$Year<-sapply(zSummary$ParamNu,function(x)strsplit(x,",")[[1]][2]) zSummary$grid<-listlengthDF$grid[match(zSummary$Site,listlengthDF$siteIndex)] #predicted occupancy across all years zSummary_year<-ddply(zSummary,.(grid),summarise,prop=mean(mean),prop_sd=mean(sd),prop_cov=prop_sd/prop) #plot sd par(mfrow=c(2,1)) mygrid[]<-0 mygrid[zSummary_year$grid]<-zSummary_year$prop_sd plot(mygrid) plot(Norway,add=T) mygrid[]<-0 #plot cov mygrid[zSummary_year$grid]<-zSummary_year$prop_cov plot(mygrid) plot(Norway,add=T) } getParam<-function(model,param="z"){ zSummary<-data.frame(model$summary[grepl(param,row.names(model$summary)),]) zSummary$ParamNu <- as.character(sub(".*\\[([^][]+)].*", "\\1", row.names(zSummary))) zSummary$Site<-sapply(zSummary$ParamNu,function(x)strsplit(x,",")[[1]][1]) zSummary$Year<-sapply(zSummary$ParamNu,function(x)strsplit(x,",")[[1]][2]) return(zSummary) } logit<-function(x) log(x/(1-x)) invlogit<- function(x) exp(x)/(1+exp(x)) getDecimalPlaces<-function(x){ nchar(gsub("(.*\\.)|([0]*$)", "", as.character(x))) } #get the mode Name for each mtbq Mode <- function(x) { ux <- unique(x) x <- x[!is.na(x)] if(length(x)>0){ return(ux[which.max(tabulate(match(x, ux)))]) } else{ return(NA) } } <file_sep>/05_HPC_occurrence_cross_validation.R library(sp) library(raster) library(maptools) library(ggplot2) library(rgeos) library(plyr) #HPC myfolder <- "/data/idiv_ess/ptarmiganUpscaling" #local #myfolder <- "data" ### get norway############################################################## #using a m grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) NorwayOrigProj <- spTransform(NorwayOrig,crs(equalM)) ### ref grid ######################################################## #create grid newres=5000#5 km grid mygrid<-raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid myGridDF <- as.data.frame(mygrid,xy=T) ### listlength ##################################################### #read in list length object (made on the Rstudio server - see 01 script) listlengthDF <- readRDS(paste(myfolder,"listlength_iDiv.rds",sep="/")) names(listlengthDF)[which(names(listlengthDF)=="y")] <- "species" #subset to May to September listlengthDF <- subset(listlengthDF,is.na(month)|(month > 4 & month <10)) #2008 to 2017.... listlengthDF$Year <- listlengthDF$year listlengthDF <- subset(listlengthDF, Year>2007 & Year <=2017) ### subset ########################################################## #subset to focal grids and those with environ covariate data focusGrids <- readRDS(paste(myfolder,"focusGrids.rds",sep="/")) varDF <- readRDS(paste(myfolder,"varDF_allEnvironData_5km_idiv.rds",sep="/")) listlengthDF <- subset(listlengthDF,grid %in% focusGrids) listlengthDF <- subset(listlengthDF,grid %in% varDF$grid) #merge with environ data listlengthDF <- merge(listlengthDF,varDF,by="grid",all.x=T) #adm indices listlengthDF$admN <- as.numeric(factor(listlengthDF$adm)) listlengthDF$admN2 <- as.numeric(factor(listlengthDF$adm2)) ### effort ###################################################################### #we will treat it as a categorical variable table(listlengthDF$L) listlengthDF$singleton <- ifelse(listlengthDF$L==1,1,0) listlengthDF$short <- ifelse(listlengthDF$L %in% c(2:4),1,0) ### Absences ################################################################### #remove missing observations listlengthDF <- subset(listlengthDF,!is.na(species)) siteInfo <- subset(listlengthDF,!duplicated(grid)) siteInfo <- arrange(siteInfo,grid) ### choose model ############################################## modelTaskID <- read.delim(paste(myfolder,"modelTaskID_occuModel_CV.txt",sep="/"),as.is=T) #get task id task.id = as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID", "1")) #get model for this task mymodel <- modelTaskID$Model[which(modelTaskID$TaskID==task.id)] ### folds ############################################################# folds <- readRDS(paste(myfolder,"folds_occModel_bands.rds",sep="/")) listlengthDF$fold <- folds$fold[match(listlengthDF$grid,folds$grid)] table(listlengthDF$fold) #select fold of this task fold.id = modelTaskID$Fold[which(modelTaskID$TaskID==task.id)] #fold.id = 1 #split intp test and train listlengthDF_test <- subset(listlengthDF,fold == fold.id) listlengthDF_train<- subset(listlengthDF,fold != fold.id) ### indices ##################################################################### #order data by site and year: listlengthDF_test$siteIndex <- as.numeric(factor(listlengthDF_test$grid)) listlengthDF_test$yearIndex <- as.numeric(factor(listlengthDF_test$year)) listlengthDF_test <- arrange(listlengthDF_test,siteIndex,yearIndex) listlengthDF_train$siteIndex <- as.numeric(factor(listlengthDF_train$grid)) listlengthDF_train$yearIndex <- as.numeric(factor(listlengthDF_train$year)) listlengthDF_train <- arrange(listlengthDF_train,siteIndex,yearIndex) ### site info ################################################################# siteInfo_test <- subset(listlengthDF_test,!duplicated(grid)) siteInfo_train <- subset(listlengthDF_train,!duplicated(grid)) ### BUGS object ################################################################ #for BUGS bugs.data <- list(nsite = length(unique(listlengthDF$siteIndex)), nsite_test = length(unique(listlengthDF_test$siteIndex)), nsite_train = length(unique(listlengthDF_train$siteIndex)), nyear_test = length(unique(listlengthDF_test$yearIndex)), nyear_train = length(unique(listlengthDF_train$yearIndex)), nvisit_test = nrow(listlengthDF_test), nvisit_train = nrow(listlengthDF_train), site_test = listlengthDF_test$siteIndex, site_train = listlengthDF_train$siteIndex, year_test = listlengthDF_test$yearIndex, year_train = listlengthDF_train$yearIndex, y_test = listlengthDF_test$species, y_train = listlengthDF_train$species, #detection covariates Effort_test = listlengthDF_test$singleton, Effort_train = listlengthDF_train$singleton, Effort2_test = listlengthDF_test$short, Effort2_train = listlengthDF_train$short, det.tlp_test = listlengthDF_test$tree_line_position/1000, det.tlp_train = listlengthDF_train$tree_line_position/1000, det.tlp2_test = listlengthDF_test$tree_line^2/100000, det.tlp2_train = listlengthDF_train$tree_line^2/100000, det.open_test = listlengthDF_test$Open, det.open_train = listlengthDF_train$Open, det.bio5_test = listlengthDF_test$bio5/100, det.bio5_train = listlengthDF_train$bio5/100, det.bio6_test = listlengthDF_test$bio6/100, det.bio6_train = listlengthDF_train$bio6/100, #add an adm effect adm_train = siteInfo_train$admN, det.adm_train = listlengthDF_train$admN, n.adm_train = length(unique(siteInfo_train$admN)), adm2 = siteInfo$admN2, det.adm2_train = listlengthDF_train$admN2, n.adm2 = length(unique(siteInfo$admN2))) #bugs.data_ArtsDaten <- bugs.data ### initials #################################################################### #get JAGS libraries library(rjags) library(jagsUI) #need to specify initial values zst <- reshape2::acast(listlengthDF_train, siteIndex~yearIndex, value.var="species",fun=max,na.rm=T) zst [is.infinite(zst)] <- 0 inits <- function(){list(z = zst)} ### scale vars ################################################################# siteInfo$admGrouped <- as.numeric(as.factor(siteInfo$admGrouped)) siteInfo[,-c(1:11)] <- plyr::numcolwise(scale)(siteInfo[,-c(1:11)]) siteInfo_test <- subset(siteInfo,grid %in% siteInfo_test$grid) siteInfo_train <- subset(siteInfo,grid %in% siteInfo_train$grid) #check everything aligns siteInfo_test$siteIndex <- listlengthDF_test$siteIndex[match(siteInfo_test$grid, listlengthDF_test$grid)] siteInfo_train$siteIndex <- listlengthDF_train$siteIndex[match(siteInfo_train$grid, listlengthDF_train$grid)] ### choose covariates ########################################################## #standard model if(mymodel == "BUGS_occuModel_upscaling_CV.txt"){ #specify model structure - a priori picking variables bugs.data$occDM_train <- model.matrix(~ siteInfo_train$tree_line_position + I(siteInfo_train$tree_line_position^2) + siteInfo_train$y + siteInfo_train$bio6 + siteInfo_train$Bog + siteInfo_train$Mire + siteInfo_train$Meadows + siteInfo_train$ODF + I(siteInfo_train$ODF^2) + siteInfo_train$OSF + I(siteInfo_train$OSF^2) + siteInfo_train$MountainBirchForest)[,-1] bugs.data$occDM_test <- model.matrix(~ siteInfo_test$tree_line_position + I(siteInfo_test$tree_line_position^2) + siteInfo_test$y + siteInfo_test$bio6 + siteInfo_test$Bog + siteInfo_test$Mire + siteInfo_test$Meadows + siteInfo_test$ODF + I(siteInfo_test$ODF^2) + siteInfo_test$OSF + I(siteInfo_test$OSF^2) + siteInfo_test$MountainBirchForest)[,-1] #lasso model or model selection model }else{ bugs.data$occDM_train <- model.matrix(~ siteInfo_train$bio6 + siteInfo_train$bio5 + siteInfo_train$tree_line_position + siteInfo_train$MountainBirchForest + siteInfo_train$Bog + siteInfo_train$ODF + siteInfo_train$Meadows + siteInfo_train$OSF + siteInfo_train$Mire + siteInfo_train$SnowBeds + siteInfo_train$y + siteInfo_train$distCoast + I(siteInfo_train$bio6^2) + I(siteInfo_train$bio5^2) + I(siteInfo_train$tree_line_position^2) + I(siteInfo_train$MountainBirchForest^2) + I(siteInfo_train$Bog^2) + I(siteInfo_train$ODF^2) + I(siteInfo_train$Meadows^2) + I(siteInfo_train$OSF^2) + I(siteInfo_train$Mire^2) + I(siteInfo_train$SnowBeds^2) + I(siteInfo_train$y^2) + I(siteInfo_train$distCoast^2))[,-1] bugs.data$occDM_test <- model.matrix(~ siteInfo_test$bio6 + siteInfo_test$bio5 + siteInfo_test$tree_line_position + siteInfo_test$MountainBirchForest + siteInfo_test$Bog + siteInfo_test$ODF + siteInfo_test$Meadows + siteInfo_test$OSF + siteInfo_test$Mire + siteInfo_test$SnowBeds + siteInfo_test$y + siteInfo_test$distCoast + I(siteInfo_test$bio6^2) + I(siteInfo_test$bio5^2) + I(siteInfo_test$tree_line_position^2) + I(siteInfo_test$MountainBirchForest^2) + I(siteInfo_test$Bog^2) + I(siteInfo_test$ODF^2) + I(siteInfo_test$Meadows^2) + I(siteInfo_test$OSF^2) + I(siteInfo_test$Mire^2) + I(siteInfo_test$SnowBeds^2) + I(siteInfo_test$y^2) + I(siteInfo_test$distCoast^2))[,-1] } bugs.data$n.covs <- ncol(bugs.data$occDM_test) ### fit model ####################################################### params <- c("mean.p","mean.psi","beta") modelfile <- paste(myfolder,mymodel,sep="/") #n.cores = as.integer(Sys.getenv("NSLOTS", "1")) #n.cores = 3 n.cores = as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1")) n.iterations = 20000 out1 <- jags(bugs.data, inits = inits, params, modelfile, n.thin = 20, n.chains = n.cores, n.burnin = round(n.iterations/2), n.iter = n.iterations, parallel = T) summary(out1$Rhat$beta) #once converged update to get z, py and psi out2 <- update(out1, parameters.to.save = c("mid.z_train","mid.psi_train", "Py_train","Py.pred_train", "mid.z_test","mid.psi_test", "Py_test","Py.pred_test"), n.iter = 2000) ### AUC check ############################################################ library(ggmcmc) ggd2 <- ggs(out2$samples) #Y against Py #test Py_preds <- subset(ggd2,grepl("Py_test",ggd2$Parameter)) Py_preds$Iteration <- as.numeric(interaction(Py_preds$Iteration,Py_preds$Chain)) nu_Iteractions <- max(Py_preds$Iteration) head(Py_preds) #look through all iterations AUC_py_test <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ py.vals <- Py_preds$value[Py_preds$Iteration==i] #select data useData <- bugs.data$year_test==6 pred <- ROCR::prediction(py.vals[useData], bugs.data$y_test[useData]) #get AUC perf <- ROCR::performance(pred, "auc") AUC_py_test[i] <- perf@y.values[[1]] } summary(AUC_py_test) #train Py_preds <- subset(ggd2,grepl("Py_train",ggd2$Parameter)) Py_preds$Iteration <- as.numeric(factor(paste(Py_preds$Iteration,Py_preds$Chain))) nu_Iteractions <- max(Py_preds$Iteration) head(Py_preds) #look through all iterations AUC_py_train <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ py.vals <- Py_preds$value[Py_preds$Iteration==i] #select data useData <- bugs.data$year_train==6 pred <- ROCR::prediction(py.vals[useData], bugs.data$y_train[useData]) #get AUC perf <- ROCR::performance(pred, "auc") AUC_py_train[i] <- perf@y.values[[1]] } summary(AUC_py_train) #Y against pypred #test Py_preds <- subset(ggd2,grepl("Py.pred_test",ggd2$Parameter)) Py_preds$Iteration <- as.numeric(interaction(Py_preds$Iteration,Py_preds$Chain)) nu_Iteractions <- max(Py_preds$Iteration) head(Py_preds) #look through all iterations AUC_pypred_test <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ py.vals <- Py_preds$value[Py_preds$Iteration==i] #select data useData <- bugs.data$year_test==6 pred <- ROCR::prediction(py.vals[useData], bugs.data$y_test[useData]) #get AUC perf <- ROCR::performance(pred, "auc") AUC_pypred_test[i] <- perf@<EMAIL>[[1]] } summary(AUC_pypred_test) #train Py_preds <- subset(ggd2,grepl("Py.pred_train",ggd2$Parameter)) Py_preds$Iteration <- as.numeric(factor(paste(Py_preds$Iteration,Py_preds$Chain))) nu_Iteractions <- max(Py_preds$Iteration) head(Py_preds) #look through all iterations AUC_pypred_train <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ py.vals <- Py_preds$value[Py_preds$Iteration==i] #select data useData <- bugs.data$year_train==6 pred <- ROCR::prediction(py.vals[useData], bugs.data$y_train[useData]) #get AUC perf <- ROCR::performance(pred, "auc") AUC_pypred_train[i] <- perf@y.values[[1]] } summary(AUC_pypred_train) #Z against psi #test Preds <- subset(ggd2,grepl("mid.psi_test",ggd2$Parameter)) Z_Preds <- subset(ggd2,grepl("mid.z_test",ggd2$Parameter)) Preds$Iteration <- as.numeric(factor(paste(Preds$Iteration,Preds$Chain))) Z_Preds$Iteration <- as.numeric(interaction(Z_Preds$Iteration,Z_Preds$Chain)) nu_Iteractions <- max(Preds$Iteration) head(Preds) #look through all iterations AUC_psi_test <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ psi.vals <- Preds$value[Preds$Iteration==i] z.vals <- Z_Preds$value[Z_Preds$Iteration==i] pred <- ROCR::prediction(psi.vals, z.vals) #get AUC perf <- ROCR::performance(pred, "auc") AUC_psi_test[i] <- perf@y.values[[1]] } summary(AUC_psi_test) #train Preds <- subset(ggd2,grepl("mid.psi_train",ggd2$Parameter)) Z_Preds <- subset(ggd2,grepl("mid.z_train",ggd2$Parameter)) Preds$Iteration <- as.numeric(factor(paste(Preds$Iteration,Preds$Chain))) Z_Preds$Iteration <- as.numeric(interaction(Z_Preds$Iteration,Z_Preds$Chain)) nu_Iteractions <- max(Preds$Iteration) head(Preds) #look through all iterations AUC_psi_train <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ psi.vals <- Preds$value[Preds$Iteration==i] z.vals <- Z_Preds$value[Z_Preds$Iteration==i] pred <- ROCR::prediction(psi.vals, z.vals) #get AUC perf <- ROCR::performance(pred, "auc") AUC_psi_train[i] <- perf@y.values[[1]] } summary(AUC_psi_train) #combine all together and save all_AUCs <- data.frame(AUC_psi_test,AUC_psi_train, AUC_py_test,AUC_py_train, AUC_pypred_test,AUC_pypred_train) saveRDS(all_AUCs,file=paste0("all_AUCs_fold.id_",fold.id,"_",mymodel,".rds")) ### end ################################################################## <file_sep>/07_HPC_simple_combined_analysis.R library(tidyverse) library(sp) library(sf) library(raster) library(rgeos) library(maptools) library(ggthemes) #local #myfolder <- "data" #on HPC myfolder <- "/data/idiv_ess/ptarmiganUpscaling" #models #modelfolderOccu <- "/work/bowler/=ptarmigan_occuModel/11670197" modelfolderOccu <- "/work/bowler/=ptarmigan_occuModel/12072779" modelfolderAbund <- "/work/bowler/=ptarmigan_distanceModel/12041062" list.files(modelfolderOccu) list.files(modelfolderAbund) ### check siteInfo ####################################################### siteInfo_Occ <- readRDS(paste(myfolder,"siteInfo_ArtsDaten.rds",sep="/")) siteInfo_Abund <- readRDS(paste(myfolder,"siteInfo_AbundanceModels.rds",sep="/")) ### model choice ######################################## modelList <- c("_1","_2","_3") task.id = as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID", "1")) mymodel <- modelList[task.id] ### get data ############################################# # get occupancy model predictions predsOcc <- readRDS(paste0(modelfolderOccu,"/", "Z_occModel_upscaling",mymodel,".rds")) names(predsOcc) head(predsOcc) # get abundance predictions predsDensity <- readRDS(paste0(modelfolderAbund, "/", "Density.pt_linetransectModel_variables",mymodel,".rds")) names(predsDensity) head(predsDensity) ### sort indices ####################################### #predsDensity <- as.data.frame(predsDensity) #predsDensity$Parameter <- row.names(predsDensity) predsDensity$ParamNu <- as.character(sub(".*\\[([^][]+)].*", "\\1", predsDensity$Parameter)) predsDensity <- subset(predsDensity,Parameter!="deviance") predsDensity <- predsDensity %>% separate(ParamNu, c("Site", "Year")) head(predsDensity) #predsOcc <- as.data.frame(predsOcc) #predsOcc$Parameter <- row.names(predsOcc) predsOcc$ParamNu <- as.character(sub(".*\\[([^][]+)].*", "\\1", predsOcc$Parameter)) predsOcc <- subset(predsOcc,Parameter!="deviance") predsOcc <- predsOcc %>% separate(ParamNu, c("Site", "Year")) head(predsOcc) ### mean occ ############################################ #occupancy predsOcc_summary <- predsOcc %>% group_by(Site) %>% summarise(myMean = mean(value), mySD = sd(value)) %>% mutate(Site = as.numeric(Site)) %>% arrange(Site) saveRDS(predsOcc_summary, file=paste("predsOcc_summary",mymodel,".rds")) ### mean density ########################################## #density - average across all years predsDensity_summary <- predsDensity %>% group_by(Site) %>% summarise(myMean = mean(value), mySD = sd(value)) %>% mutate(Site = as.numeric(Site)) %>% arrange(Site) saveRDS(predsDensity_summary, file=paste("predsDensity_summary",mymodel,".rds")) ### cap density ######################################## #cap high values #get maximum elevation at which one is seen at #1658 m - but few above 1500 m predsDensity_summary$myMean[siteInfo_Abund$elevation>1660] <- 0 #what is the maximum observed density? cap by this #high mean density was 34 per km2 34*25#850 summary(predsDensity_summary$myMean) mean(predsDensity_summary$myMean>850)#only 0.1% of grids predsDensity_summary$myMean[predsDensity_summary$myMean>850] <- 850 siteInfo_Abund$preds <- predsDensity_summary$myMean #save again saveRDS(predsDensity_summary, file=paste("predsDensity_summary",mymodel,".rds")) ### mean multiplication #################################### siteInfo_Abund$meanDensity <- predsDensity_summary$myMean summary(siteInfo_Abund$meanDensity) siteInfo_Occ$meanOcc <- predsOcc_summary$myMean summary(siteInfo_Occ$meanOcc) siteInfo <- inner_join(siteInfo_Abund, siteInfo_Occ, by="grid") siteInfo$realAbund <- siteInfo$meanDensity * siteInfo$meanOcc sum(siteInfo$realAbund) #still around 1 million!!! ### iteration multiplication ############################### head(predsOcc) head(predsDensity) #add grid info predsOcc$grid <- siteInfo_Occ$grid[match(predsOcc$Site, siteInfo_Occ$siteIndex)] #add grid info siteInfo_Abund$siteIndex <- 1:nrow(siteInfo_Abund) predsDensity$grid <- siteInfo_Abund$grid[match(predsDensity$Site,siteInfo_Abund$siteIndex)] predsDensity$Density <- predsDensity$value #merge predsOcc <- predsDensity %>% as_tibble() %>% dplyr::select(Iteration,Chain,Year,grid,Density) %>% inner_join(.,predsOcc) head(predsOcc) #cal real density predsOcc$realDensity <- predsOcc$value * predsOcc$Density ### annual total population size ####################### population_Annual <- predsOcc %>% group_by(Iteration,Chain,Year) %>% summarise(totalPop = sum(realDensity)) %>% group_by(Year) %>% summarise(medianPop = median(totalPop), lowerPop = quantile(totalPop, 0.025), upperPop = quantile(totalPop, 0.975)) saveRDS(population_Annual, file=paste("population_Annual",mymodel,".rds")) ### grid level abundances ############################### nuYears <- n_distinct(predsOcc$Year) population_grid <- predsOcc %>% group_by(Iteration,Chain,grid) %>% summarise(totalPop = sum(realDensity)/nuYears) %>% group_by(grid) %>% summarise(medianPop = median(totalPop), sdPop = sd(totalPop), lowerPop = quantile(totalPop, 0.025), upperPop = quantile(totalPop, 0.975)) saveRDS(population_grid, file=paste("population_grid",mymodel,".rds")) ### mean total abundance ################################# nuYears <- n_distinct(predsOcc$Year) totalSummary <- predsOcc %>% group_by(Iteration,Chain) %>% summarise(totalPop = sum(realDensity)/nuYears) saveRDS(totalSummary, file=paste("totalSummary",mymodel,".rds")) #### end ################################### <file_sep>/prelim_analysis_abundance_data.R #script to analysis line transect data on the HPC library(tidyverse) library(sp) library(rgeos) library(raster) library(maptools) library(tmap) source('generalFunctions.R', encoding = 'UTF-8') #specify top level folder myfolder <- "Data" #on local PC #myfolder <- "/data/idiv_ess/ptarmiganUpscaling" #HPC ### get norway ############################################## equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" library(raster) library(maptools) library(rgeos) data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) NorwayOrig <- spTransform(NorwayOrig,crs(equalM)) plot(Norway) ### ptarmigan data ############################################################### #read in data frame allData <- readRDS(paste(myfolder,"allData.rds",sep="/")) #subset to years of interest allData <- subset(allData,Year>2006 & Year<2018) #remove hyphens for help with subsetting allData$Fylkesnavn <- gsub("-"," ",allData$Fylkesnavn) allData$Fylkesnavn[which(allData$Rapporteringsniva=="Indre Troms")] <- "Troms" #mistake with 1405 - transect length allData$LengdeTaksert[which(allData$LinjeID==1405&allData$LengdeTaksert==1100)] <- 11000 ### aggregate data to the lines ###################################### #Get statistics per year and line tlDF <- allData %>% dplyr::group_by(LinjeID,Year) %>% dplyr::summarise(nuGroups=length(totalIndiv[!is.na(totalIndiv)]), totalsInfo=sum(totalIndiv,na.rm=T), groupSize=mean(totalIndiv,na.rm=T), length = mean(LengdeTaksert,na.rm=T)) sum(tlDF$totalsInfo,na.rm=T) #67946 #insert NA when there is no transect but evidence of a survey tlDF$length[is.na(tlDF$length)] <- 0 tlDF$nuGroups[tlDF$length==0 ] <- NA tlDF$totalsInfo[tlDF$length==0] <- NA tlDF$groupSize[tlDF$length==0] <- NA summary(tlDF) sum(tlDF$length==0)#1302 ### get environ data ############################################## #get mean across all years siteMeans <- tlDF %>% mutate(density = totalsInfo/(length/1000 * 106/1000 * 2)) %>% group_by(LinjeID) %>% summarise(meanNu = mean(totalsInfo,na.rm=T), meanTL = mean(length[length!=0]), meanDensity = mean(density,na.rm=T)) %>% filter(!is.na(meanNu)) %>% filter(!is.infinite(meanNu)) summary(siteMeans) bufferData <- readRDS("data/varDF_allEnvironData_buffers_idiv.rds") siteMeans <- merge(siteMeans,bufferData,by="LinjeID") siteMeans <- subset(siteMeans,!is.na(tree_line)) siteMeans$adm <- mergeCounties(siteMeans$adm,further=TRUE) table(siteMeans$adm) ### get spatial polygons ########################################### Polys_spatial <- readRDS("data/Polys_spatial.rds") Polys_spatial <- merge(Polys_spatial,siteMeans,by="LinjeID") Polys_spatial <- subset(Polys_spatial,!is.na(meanDensity)) Polys_spatial$meanDensity[Polys_spatial$meanDensity > 25] <- 25 head(Polys_spatial) summary(Polys_spatial) tm_shape(NorwayOrig) + tm_borders()+ tm_shape(Polys_spatial)+ tm_fill(col="adm") tm_shape(NorwayOrig) + tm_fill("grey")+ tm_shape(Polys_spatial)+ tm_fill(col="meanDensity",style="pretty",n=7)+ tm_legend(legend.position=c("left","top")) ### glm model ###################################################### hist(siteMeans$meanDensity) summary(siteMeans$meanDensity) hist(log(siteMeans$meanDensity+1)) glm1 <- lm(log(meanDensity+1) ~ scale(bio5) + scale(bio6) + Forest + Bog + ODF + OSF + Mire + SnowBeds + Human + scale(y) + scale(distCoast) + scale(tree_line) + scale(elevation), data=siteMeans) summary(glm1)#21% #bio5 has negative effect #bio6 has positive effect #distCoast has negative effect library(MuMIn) options(na.action = "na.fail") dd <- dredge(glm1) subset(dd, delta < 2) #bog, forest, mire, ODF, OSF,bio5, bio6, distCoast,treeline, y, snowbeds #check variance inflation glm1 <- lm(log(meanDensity+0.01) ~ scale(bio5) + scale(bio6) + Forest + Bog + SnowBeds + Meadows + scale(y) + scale(distCoast) + scale(tree_line) + scale(elevation), data=siteMeans) summary(glm1)#only 20% car::vif(glm1) #tree line, elevation and y pairs(siteMeans[,c("y","distCoast","tree_line","elevation","tree_line_position")]) #tree line and elevation are highly correlated #y and elevation are also correlated ggplot(siteMeans,aes(y=log(meanDensity+1), x=y))+ geom_point()+stat_smooth() #quadratic should be fine ggplot(siteMeans,aes(y=log(meanDensity+1), x=distCoast))+ geom_point()+stat_smooth() #nothing obvious ggplot(siteMeans,aes(y=log(meanDensity+1), x=tree_line))+ geom_point()+stat_smooth() #increase, but humped ggplot(siteMeans,aes(y=log(meanDensity+1), x=tree_line_position))+ geom_point()+stat_smooth() #nothing obvious ggplot(siteMeans,aes(y=log(meanDensity+1), x=elevation))+ geom_point()+stat_smooth() #general increase - humped #look at partial plots glm1 <- lm(log(meanDensity+0.01) ~ scale(bio5) + scale(bio6) + Forest + Bog + SnowBeds + Meadows + scale(y) + scale(distCoast) + scale(tree_line), data=siteMeans) car::avPlots(glm1) ### brt ######################################################################### #Boosted regression tree library(dismo) library(gbm) siteMeans$log.Density <- log(siteMeans$meanDensity+0.01) brt1 <- gbm.step(data=siteMeans, gbm.x = c(5:17,20,26:28), gbm.y = 29, family = 'gaussian') summary(brt1) # var rel.inf # bio6 bio6 22.3458169 # bio5 bio5 14.2431986 # y y 11.7659117 # x x 9.9893607 # distCoast distCoast 9.9046832#non linear effect maybe # tree_line tree_line 6.8581819 # Open Open 3.8421042 # bio1 bio1 2.8542700 # MountainBirchForest MountainBirchForest 2.7410876 # Mire Mire 2.6665185 # OSF OSF 2.6246154 # Forest Forest 2.4941139 # Meadows Meadows 2.1145808 # SnowBeds SnowBeds 1.9913050 # Bog Bog 1.8380248 #plot main effects gbm.plot(brt1, n.plots=12, write.title = TRUE) #interactions? find.int <- gbm.interactions(brt1) find.int$interactions#none! find.int$rank.list #check similar glm glm1 <- lm(log(meanDensity+0.01) ~ bio6 + y + bio5 + distCoast + tree_line+ Open+bio1 + Mire + Forest + MountainBirchForest + Meadows + OSF + SnowBeds + Bog,data=siteMeans) summary(glm1)#21%... #### gam model ######################################################### library(mgcv) gam1 <- gam(log(meanDensity+0.01) ~ s(bio6,k=3) + s(y,k=3) + s(bio5,k=3) + s(distCoast,k=3) + s(tree_line,k=3),data=siteMeans) summary(gam1)#25% plot(gam1) #### quadratic model ################################################## glm1 <- lm(log(meanDensity+0.01) ~ bio6 + I(bio6^2)+ distCoast + I(distCoast^2)+ bio5 + I(bio5^2)+ tree_line + I(tree_line^2)+ SnowBeds + y + OSF,data=siteMeans) summary(glm1)#26% ### end ################################################################ <file_sep>/03_mapping_linetransects_to_grids.R siteInfo_ArtsDaten <- readRDS("data/siteInfo_ArtsDaten.rds") head(siteInfo_ArtsDaten) #connect lines and grids - based on line centroids lines_to_grids <- readRDS("data/lines_to_grids.rds") subset(lines_to_grids,LinjeID %in% c("92","93"))#in the same grid #do we have the grid data for all the lines in this analysis siteInfo$LinjeID[!siteInfo$LinjeID %in% lines_to_grids$LinjeID]#yes!!! siteInfo$grid <- lines_to_grids$grid[match(siteInfo$LinjeID,lines_to_grids$LinjeID)] siteInfo$grid #all present #and are all these grids in the siteInfo_Arts_daten siteInfo$grid %in% siteInfo_ArtsDaten$grid siteInfo$grid[!siteInfo$grid %in% siteInfo_ArtsDaten$grid] #there are NAs... #probably lines at the edge #find an alternative grid that overlaps for those missing siteInfo_ArtsDaten$siteIndex <- as.numeric(as.factor(siteInfo_ArtsDaten$grid)) siteInfo$siteIndex_All <- siteInfo_ArtsDaten$siteIndex[match(siteInfo$grid,siteInfo_ArtsDaten$grid)] missing <- siteInfo$LinjeID[is.na(siteInfo$siteIndex_All)] length(missing)#23 #get other overlapping grids within 5km lineBuffers_to_grids <- readRDS("data/lineBuffers_to_grids_5km.rds") lineBuffers_to_grids <- subset(lineBuffers_to_grids, LinjeID %in% missing) lineBuffers_to_grids <- subset(lineBuffers_to_grids, grid %in% siteInfo_ArtsDaten$grid) lineBuffers_to_grids5km <- subset(lineBuffers_to_grids,!duplicated(LinjeID)) nrow(lineBuffers_to_grids5km)#13 siteInfo$grid_5km <- lineBuffers_to_grids5km$grid[match(siteInfo$LinjeID,lineBuffers_to_grids5km$LinjeID)] #other overlapping grids within 15km _these are in islands in the north and in Sweden missing <- missing[!missing %in% lineBuffers_to_grids5km$LinjeID] lineBuffers_to_grids <- readRDS("data/lineBuffers_to_grids_15km.rds") lineBuffers_to_grids <- subset(lineBuffers_to_grids, LinjeID %in% missing) lineBuffers_to_grids <- subset(lineBuffers_to_grids, grid %in% siteInfo_ArtsDaten$grid) lineBuffers_to_grids15km <- subset(lineBuffers_to_grids,!duplicated(LinjeID)) nrow(lineBuffers_to_grids15km)#10 siteInfo$grid_15km <- lineBuffers_to_grids15km$grid[match(siteInfo$LinjeID,lineBuffers_to_grids15km$LinjeID)] #add to siteInfo object #switch original grid to those with data #first at 5km siteInfo$grid[!is.na(siteInfo$grid_5km)] <- siteInfo$grid_5km[!is.na(siteInfo$grid_5km)] #then at 15km siteInfo$grid[!is.na(siteInfo$grid_15km)] <- siteInfo$grid_15km[!is.na(siteInfo$grid_15km)] #now check we have data for all siteInfo$grid[!siteInfo$grid %in% siteInfo_ArtsDaten$grid] siteInfo$siteIndex_All <- siteInfo_ArtsDaten$siteIndex[match(siteInfo$grid,siteInfo_ArtsDaten$grid)] siteInfo$LinjeID[is.na(siteInfo$siteIndex_All)] saveRDS(siteInfo[,c("LinjeID","grid","siteIndex_All")], file="data/siteIndex_linetransects.rds") <file_sep>/01_formatting_occurrence_data.R ######################################################################## setwd("/data/dbowler/ptarmiganUpscaling") #load in general functions source('generalFunctions.R') library(sp) library(raster) library(maptools) library(ggplot2) library(rgeos) library(plyr) #get norway############################################################## #using a m grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) NorwayOrigProj <- spTransform(NorwayOrig,crs(equalM)) ######################################################################### #create grid newres=5000#5 km grid mygrid<-raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid myGridDF <- as.data.frame(mygrid,xy=T) ######################################################################### #within this grid, define cells of interest: # plot(mygrid) # plot(NorwayOrigProj,add=T) # # #get cells at least 50% covering Norway # myGridMask <- data.frame(extract(mygrid,NorwayOrigProj,weights=T,normalizeWeights=F)[[1]]) # myGridMask <- myGridMask$value[myGridMask$weight>0.5] # myGrid2 <- mygrid # myGrid2[!getValues(mygrid) %in% myGridMask]<-NA # plot(myGrid2) # plot(NorwayOrigProj,add=T) # #looks good! # # #get these grid numbers # focusGrids <- getValues(myGrid2)[!is.na(getValues(myGrid2))] # focusGridsDF <- as.data.frame(myGrid2,xy=T) focusGrids <- readRDS("focusGrids.rds") ######################################################################### #get willow ptarmigan data - occurrence data #get GBIF data #tdir <- "C:/Users/db40fysa/Dropbox/Alpine/GBIF" #lirype <- read.delim(paste(tdir,"willow_ptarmigan_GBIF.txt",sep="/"),as.is=T,row.names=NULL) tdir <- "GBIF" lirype <- read.delim(paste(tdir,"willow_ptarmigan_GBIF.txt",sep="/"),as.is=T,row.names=NULL,fileEncoding="latin1",quote = "") names(lirype) <- gsub("X.","",names(lirype)) names(lirype) <- gsub("\\.","",names(lirype)) #clean lirype$decimalLatitude<-as.numeric(lirype$decimalLatitude) lirype$decimalLongitude<-as.numeric(lirype$decimalLongitude) lirype<-subset(lirype,!is.na(lirype$decimalLatitude)|!is.na(lirype$decimalLongitude)) #which column has the dataset information temp <- subset(lirype,samplingProtocol=="\"Distance sampling based on line transects\"") unique(temp$datasetName) unique(temp$ownerInstitutionCode) table(temp$ownerInstitutionCode) #see also datasetName #Statskog and FeFo are both in the line transect surveys #might need to remove these....??? lirype<-lirype[,c("decimalLatitude","decimalLongitude","coordinateUncertaintyInMeters", "name","year","month","day","recordedBy")] #get artsdatenbanken data #tdir<-"C:/Users/db40fysa/Dropbox/Alpine/SpeciesMapServices/Ptarmigan" tdir<-"SpeciesMapServices/Ptarmigan" lirype2 <- read.delim(paste(tdir,"DataExportFraArtskart.txt",sep="/"),skipNul=T,dec=",") lirype2$Species<-apply(lirype2,1,function(x)paste(x["Genus"],x["Species"],sep=" ")) #check dataset names unique(lirype2$InstitutionName) lirype2<-lirype2[,c("Latitude","Longitude","CoordinatePrecision", "Species","YearCollected","MonthCollected","DayCollected","Collector")] names(lirype2)<-names(lirype) #combine them lirype<-rbind(lirype,lirype2) lirypeD<-lirype #remove duplicates lirype$year <- as.numeric(lirype$year) lirype$date<-paste(lirype$year,lirype$month,lirype$day,sep="-") lirype$id<-paste(lirype$date,round(lirype$decimalLatitude,digits=4),round(lirype$decimalLongitude,digits=4),sep="_") lirype<-subset(lirype,!duplicated(id)) #remove dodgy records summary(lirype$coordinateUncertaintyInMeters) lirype$coordinateUncertaintyInMeters <- as.numeric(lirype$coordinateUncertaintyInMeters) lirype <- subset(lirype, coordinateUncertaintyInMeters<5000|is.na(coordinateUncertaintyInMeters)) #remove those without 2 decimal places lirype$latDP<-getDecimalPlaces(lirype$decimalLatitude) lirype$lonDP<-getDecimalPlaces(lirype$decimalLongitude) lirype<-subset(lirype,latDP>2 & lonDP>2) #examine recorders - choose those with a name?? ut some are just numbers.... #mean(is.na(lirype$recordedBy))#0.3178803 #lirype <- subset(lirype,!is.na(recordedBy)) #out <- ddply(lirype,.(recordedBy),summarise,nuObs=length(name)) #subsetting lirype<-subset(lirype,year>2006&year<2018) #exclude Nov to March - rock and willow both have white coats# lirype<-subset(lirype,month >4 & month <10) table(lirype$year) #make spatial and convert CRS coordinates(lirype)<-c("decimalLongitude","decimalLatitude") proj4string(lirype) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0") #overlay to the grid plot(NorwayOrig) plot(lirype,add=T,pch=16,cex=0.1,col= alpha("red",0.1)) #all points look pretty good!! #pull out the grid cells lirype <- sp::spTransform(lirype, crs(equalM)) plot(mygrid) plot(lirype,add=T,pch=16,cex=0.5,col= alpha("red",0.1)) lirype$grid <- raster::extract(mygrid,lirype) #subset to focal grids lirype@data <- subset(lirype@data,grid %in% focusGrids) #get number of points per grid cell gridSummary<-ddply(lirype@data,.(grid),summarise,nuRecs=length(name)) mygrid[]<-0 mygrid[gridSummary$grid] <- gridSummary$nuRecs length(gridSummary$grid)==length(gridSummary$nuRecs) plot(mygrid) #how many records per site are there hist(gridSummary$nuRecs) gridSummary$RepeatedVisits<-sapply(gridSummary$nuRecs,function(x)ifelse(x>1,1,0)) table(gridSummary$RepeatedVisits) #grid cell per year gridSummary<-ddply(lirype@data,.(grid,year),summarise,nuRecs=length(name)) gridSummary$RepeatedVisits<-sapply(gridSummary$nuRecs,function(x)ifelse(x>1,1,0)) table(gridSummary$RepeatedVisits) lirype <- lirype@data nrow(lirype) #12135 ########################################################################## #get data for all birds - as an effort layer #for first time: # #get GBIF data #tdir<-"C:/Users/diana.bowler/OneDrive - NINA/Alpine/GBIF" tdir<-"GBIF" speciesFiles<-list.files(tdir)[grepl("all_birds",list.files(tdir))] library(plyr) allbirds<-ldply(speciesFiles,function(x){ read.delim(paste(tdir,x,sep="/"),as.is=T,fileEncoding="latin1",quote = "") }) #clean names names(allbirds) <- gsub("X.","",names(allbirds)) names(allbirds) <- gsub("\\.","",names(allbirds)) #filter allbirds<-allbirds[,c("decimalLatitude","decimalLongitude","coordinateUncertaintyInMeters", "name","year","month","day","recordedBy")] allbirds$decimalLatitude<-as.numeric(allbirds$decimalLatitude) allbirds$decimalLongitude<-as.numeric(allbirds$decimalLongitude) allbirds$year<-as.numeric(allbirds$year) allbirds$month<-as.numeric(allbirds$month) allbirds$day<-as.numeric(allbirds$day) allbirds <- subset(allbirds,!is.na(year)) allbirds <- subset(allbirds,!is.na(month)) allbirds<-subset(allbirds,!is.na(allbirds$decimalLatitude)) allbirds<-subset(allbirds,!is.na(allbirds$decimalLongitude)) #get artsdatenbanken data #tdir<-"C:/Users/diana.bowler/OneDrive - NINA/Alpine/SpeciesMapServices/Birds" tdir<-"SpeciesMapServices/Birds" allbirds2 <- read.delim(paste(tdir,"DataExportFraArtskart.txt",sep="/"),skipNul=T,dec=",",as.is=T) allbirds2$Species<-apply(allbirds2,1,function(x)paste(x["Genus"],x["Species"],sep=" ")) allbirds2<-allbirds2[,c("Latitude","Longitude","CoordinatePrecision", "Species","YearCollected","MonthCollected","DayCollected","Collector")] names(allbirds2)<-names(allbirds) allbirds2 <- subset(allbirds2,!is.na(day)) #combine them allbirds<-rbind(allbirds,allbirds2) #also with ptarmigan data allbirds<-rbind(allbirds,lirypeD) allbirds$year <- as.numeric(allbirds$year) #tidy species names allbirds$name <- gsub('[\"]','',allbirds$name) sort(unique(allbirds$name)) #remove records that arent species level allbirds <- subset(allbirds, grepl(" ",allbirds$name)) #remove duplicates allbirds$date<-paste(allbirds$year,allbirds$month,allbirds$day,sep="-") allbirds$id<-paste(allbirds$name,allbirds$date,round(allbirds$decimalLatitude,digits=4), round(allbirds$decimalLongitude,digits=4),sep="_") allbirds<-subset(allbirds,!duplicated(id)) #remove dodgy records allbirds$coordinateUncertaintyInMeters <- as.numeric(allbirds$coordinateUncertaintyInMeters) summary(allbirds$coordinateUncertaintyInMeters) allbirds <- subset(allbirds, coordinateUncertaintyInMeters<5000|is.na(coordinateUncertaintyInMeters)) allbirds<-subset(allbirds,!is.na(allbirds$decimalLatitude)|!is.na(allbirds$decimalLongitude)) #remove those without more than 2 decimal places allbirds$latDP<-getDecimalPlaces(allbirds$decimalLatitude) allbirds$lonDP<-getDecimalPlaces(allbirds$decimalLongitude) allbirds<-subset(allbirds,latDP>2 & lonDP>2) #extract survyed grids within time period of interest allbirds<-subset(allbirds,month >4 & month <10) allbirds<-subset(allbirds,year>2006&year<2018) table(allbirds$year) #rename names(allbirds)[which(names(allbirds)=="name")]<-"Species" nrow(allbirds)#7068029 saveRDS(allbirds,file="allbirds_uniqueRecords.rds") ##################################################################### #subsequent times: load("C:/Users/db40fysa/Dropbox/ptarmigan Upscaling/data/allbirds_uniqueRecords.RData") ##################################################################################### #make spatial and get grid info coordinates(allbirds)<-c("decimalLongitude","decimalLatitude") proj4string(allbirds)<-CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0") #plotting original #plot(NorwayOrig) #plot(allbirds[sample(1:nrow(allbirds),591174),],add=T,pch=16,cex=0.5,col= alpha("red",0.1))#10% #plotting allbirds <- spTransform(allbirds, CRS(equalM)) mygrid[]<-1:ncell(mygrid) plot(mygrid) plot(Norway,add=T) plot(allbirds[1:1000,],add=T) #all points look pretty good!! #exclude points beyond the mask #out <- over(allbirds,Norway) #allbirds <- allbirds[!is.na(out),] #overlay to the grid allbirds$grid <- extract(mygrid,allbirds) #subset to focus grids allbirds <- subset(allbirds, grid %in% focusGrids) #reorganise allbirds <-subset(allbirds,!is.na(Species)) allbirds <- subset(allbirds,!is.na(grid)) all_data <- data.frame(allbirds@data) all_data <- all_data[,c("year","month","day","grid","Species","recordedBy")] table(all_data$year,all_data$month) ######################################################################## #downsample the dataset nrow(all_data)#4276862 dataSummary <- ddply(all_data,.(grid,year,month),summarise,nuObs=length(unique(day))) summary(dataSummary$nuObs) all_data #cap at 25? all_dataS <- ddply(all_data,.(grid,year,month),function(x){ #get number of observations uniq = unique(x$day) nuObs = length(uniq) if(nuObs > 4){ mySample = sample(uniq,4) subset(x, day %in% mySample) }else{ x }}) nrow(all_dataS)#1883262 #reduces the dataset by over a half ######################################################################### #are all grid cells in focus grids included here? length(focusGrids)#11846 length(unique(all_dataS$grid))#9209 obsGrids <- sort(unique(all_dataS$grid)) #data from 78% of grids #where are we missing data? missingGrids <- focusGrids[!focusGrids %in% obsGrids] mygrid[] <- 0 mygrid[missingGrids] <- 1 plot(mygrid) #where we have data? mygrid[] <- 0 mygrid[obsGrids] <- 1 plot(mygrid) ################################################################################################## #get list length info #add list length of all birds on each sampling visit listlengthDF <- ddply(all_dataS,.(year,month,day,grid),summarise, L = length(unique(Species)), #number of species L2 = length(Species)) nrow(listlengthDF)#322363 #get total number of species ever seen per grid # gridRichness <- ddply(all_dataS,.(grid),summarise,nuSpecies=length(unique(Species))) # mygrid[] <- 0 # mygrid[gridRichness$grid] <- gridRichness$nuSpecies # plot(mygrid) # # #add species richness to the listlength df # listlengthDF$nuSpecies <- gridRichness$nuSpecies[match(listlengthDF$grid,gridRichness$grid)] # summary(listlengthDF$nuSpecies) ################################################################################## #add on ptarmigan obs listlengthDF$visit <- paste(listlengthDF$year,listlengthDF$month, listlengthDF$day,listlengthDF$grid,sep="-") lirype$visit <- paste(lirype$year,lirype$month, lirype$day,lirype$grid,sep="-") listlengthDF$y <- sapply(listlengthDF$visit,function(x)ifelse(x%in%lirype$visit,1,0)) table(listlengthDF$y) #0 1 #314459 7904 #################################################################################################### #add NAs for all years and grids newgrid <- expand.grid(year=unique(listlengthDF$year), grid=focusGrids) listlengthDF <- merge(listlengthDF,newgrid,by=c("year","grid"),all.y=T) summary(listlengthDF) #table(listlengthDF$grid,listlengthDF$year) ###################################################################################################### #adding non-detections?? #listlengthDF$L[is.na(listlengthDF$L)] <- 0 #listlengthDF$y[listlengthDF$L==0] <- 0 ######################################### ####################################################################### #order data by site and year listlengthDF<-arrange(listlengthDF,year,grid) #add indices listlengthDF$siteIndex<-as.numeric(as.factor(listlengthDF$grid)) listlengthDF$yearIndex<-as.numeric(as.factor(listlengthDF$year)) saveRDS(listlengthDF,file="listlength_iDiv.rds") ###################################################################################################### <file_sep>/prelim_analysis_occurrence_data.R setwd("C:/Users/db40fysa/Dropbox/ptarmigan Upscaling") library(sp) library(raster) library(maptools) library(ggplot2) library(rgeos) library(plyr) ### get norway############################################################## #using a m grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) NorwayOrigProj <- spTransform(NorwayOrig,crs(equalM)) ### ref grid ######################################################## #create grid newres=5000#5 km grid mygrid<-raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid myGridDF <- as.data.frame(mygrid,xy=T) ### listlength ##################################################### #source('formattingArtDatenBank_missing_data.R') #read in list length object (made on the Rstudio server) listlengthDF <- readRDS("data/listlength_iDiv.rds") #subset to May to September listlengthDF <- subset(listlengthDF,is.na(month)|(month > 4 & month <10)) ### subset ########################################################## #subset to focal grids and those with environ covariate data focusGrids <- readRDS("data/focusGrids.rds") varDF <- readRDS("data/varDF_allEnvironData_5km_idiv.rds") listlengthDF <- subset(listlengthDF,grid %in% focusGrids) listlengthDF <- subset(listlengthDF,grid %in% varDF$grid) ### effort ###################################################################### #we will treat it as a categorical variable table(listlengthDF$L) listlengthDF$singleton <- ifelse(listlengthDF$L==1,1,0) ### Absences ################################################################### listlengthDF$L[is.na(listlengthDF$L)] <- 1 #set to nominal effort #listlengthDF$y[listlengthDF$L==0] <- 0 ### GLM - binary ############################################################### #fit as glm with explanatory variables - binary response #get y per grid occupancyGrid <- plyr::ddply(listlengthDF,.(grid),summarise,species=max(y,na.rm=T)) occupancyGrid <- subset(occupancyGrid,!is.infinite(species)) mean(occupancyGrid$species) #get environ data tempDF <- merge(varDF,occupancyGrid,by="grid",all.y=T) #simple glms #temp vars summary(glm(species~scale(bio1),data=tempDF,family="binomial"))#large summary(glm(species~scale(bio5),data=tempDF,family="binomial")) summary(glm(species~scale(bio6),data=tempDF,family="binomial"))#large #tree line or elevation summary(glm(species~scale(elevation),data=tempDF,family="binomial"))#large summary(glm(species~scale(tree_line),data=tempDF,family="binomial")) summary(glm(species~scale(tree_line_position),data=tempDF,family="binomial"))#best qplot(elevation,tree_line_position,data=tempDF) #habitat summary(glm(species~MountainBirchForest,data=tempDF,family="binomial"))#small positive summary(glm(species~Bog,data=tempDF,family="binomial"))#large positive summary(glm(species~Forest,data=tempDF,family="binomial"))#negative large summary(glm(species~ODF,data=tempDF,family="binomial"))#large positive summary(glm(species~Meadows,data=tempDF,family="binomial"))#large positive summary(glm(species~OSF,data=tempDF,family="binomial"))#large positive summary(glm(species~SnowBeds,data=tempDF,family="binomial"))#no effect summary(glm(species~Mire,data=tempDF,family="binomial"))#small positive summary(glm(species~Human,data=tempDF,family="binomial"))#large negative #all together glm1 <- glm(species~bio1 + MountainBirchForest+ Bog + Forest + ODF + Meadows + OSF + Mire + Human + SnowBeds + tree_line_position + I(tree_line_position^2), data=tempDF,family="binomial") #meadows, bog and mountainbirch forest and ODF DescTools::PseudoR2(glm1) #large range of variables to test library(MuMIn) options(na.action = "na.fail") glm1<-glm(species ~ scale(bio1) + scale(bio5) + #mostly scale(bio6) + #always scale(y) + #always scale(distCoast) + #mostly scale(MountainBirchForest) + #always scale(Bog) + #always scale(Forest) + scale(Mire) + scale(Human) + scale(ODF) + #always scale(Meadows) + #always scale(OSF) + scale(SnowBeds) + scale(tree_line_position) + scale(I(tree_line_position^2))+ #always scale(elevation)+ #mostly scale(elevation^2), family="binomial",data=tempDF) summary(glm1) DescTools::PseudoR2(glm1) dd <- dredge(glm1) subset(dd, delta < 2) ### plot predictions ############################################# tempDF$x <- myGridDF$x[match(tempDF$grid,myGridDF$layer)] tempDF$y <- myGridDF$y[match(tempDF$grid,myGridDF$layer)] tempDF$fits<-predict(glm1,type="response",newdata=tempDF) ggplot(tempDF)+ geom_point(aes(x,y,colour=fits),shape=15,size=rel(1))+ scale_colour_viridis_c() tempDF$fits.se<-predict(glm1,type="response",newdata=tempDF,se.fit=TRUE)$se.fit ggplot(tempDF)+ geom_point(aes(x,y,colour=fits.se),shape=15,size=rel(1))+ scale_colour_gradient(low="steelblue",high="red") ### brt ######################################################################### #Boosted regression tree library(dismo) library(gbm) brt1 <- gbm.step(data=tempDF, gbm.x = c(2:14,20:21,29:30), gbm.y = 33, family = "bernoulli") summary(brt1) # var rel.inf # tree_line_position tree_line_position 31.1882397#complex # Bog Bog 21.1275937 # ODF ODF 13.8494494 # y y 6.2408870 # tree_line tree_line 5.0624717 # bio1 bio1 3.7947544 # Meadows Meadows 3.5494534 # bio6 bio6 3.0857581 # MountainBirchForest MountainBirchForest 2.7713510 # elevation elevation 1.9931910 # OSF OSF 1.8197470 # distCoast distCoast 1.3255056 # SnowBeds SnowBeds 1.0535460 #plot main effects gbm.plot(brt1, n.plots=12, write.title = TRUE) gbm.plot.fits(brt1) #non-linear plot for tree line position and bio1 #### quadratic effects ######################################################### glm1<-glm(species ~ tree_line_position + I(tree_line_position^2)+ Bog + ODF + OSF + y + bio1 + I(bio1^2)+ Meadows + MountainBirchForest + OSF, family="binomial",data=tempDF) summary(glm1) DescTools::PseudoR2(glm1) ### ignore from here on ######################################################## ### indices ##################################################################### #order data by site and year: listlengthDF$siteIndex <- as.numeric(factor(listlengthDF$grid)) listlengthDF$yearIndex <- as.numeric(factor(listlengthDF$year)) listlengthDF <- arrange(listlengthDF,siteIndex,yearIndex) #merge with environ data listlengthDF <- merge(listlengthDF,varDF,by="grid",all.x=T) #have missing singletons as 1 listlengthDF$singleton[is.na(listlengthDF$singleton)] <- 1 ### adm inidices ############################################################# listlengthDF$admN <- as.numeric(factor(listlengthDF$adm)) listlengthDF$admN2 <- as.numeric(factor(listlengthDF$adm2)) #extract site data siteInfo <- subset(listlengthDF,!duplicated(grid)) #add on observations occupancyGrid <- ddply(listlengthDF,.(grid),summarise, species = max(y,na.rm=T)) occupancyGrid$species[is.infinite(occupancyGrid$species)] <- NA table(occupancyGrid$species) siteInfo$species <- occupancyGrid$species[match(siteInfo$grid,occupancyGrid$grid)] siteInfo$x <- myGridDF$x[match(siteInfo$grid,myGridDF$layer)] siteInfo$y <- myGridDF$y[match(siteInfo$grid,myGridDF$layer)] ### BUGS object ################################################################ #for BUGS bugs.data <- list(nsite = length(unique(listlengthDF$siteIndex)), nyear = length(unique(listlengthDF$yearIndex)), nvisit = nrow(listlengthDF), site = listlengthDF$siteIndex, year = listlengthDF$yearIndex, Effort = listlengthDF$singleton, y = listlengthDF$y, #add an adm effect adm = siteInfo$admN, det.adm = listlengthDF$admN, n.adm = length(unique(siteInfo$admN)), adm2 = siteInfo$admN2, det.adm2 = listlengthDF$admN2, n.adm2 = length(unique(siteInfo$admN2)), #environcovs bio1 = scale(siteInfo$bio1), bio1_2 = scale(siteInfo$bio1^2), bio6 = scale(siteInfo$bio6), bio5 = scale(siteInfo$bio5), forest = scale(siteInfo$Forest), open = scale(siteInfo$Open), prefopen = scale(log(siteInfo$PrefOpen+1)), prefclosed = scale(log(siteInfo$PrefClosed+1)), top = scale(log(siteInfo$Top+1)), alpine_habitat1 = siteInfo$alpine_habitat1, alpine_habitat2 = log(siteInfo$alpine_habitat2+1), alpine_habitat3 = log(siteInfo$alpine_habitat3+1), alpine_habitat4 = log(siteInfo$alpine_habitat4+1), tree_line_position = scale(siteInfo$tree_line_position), tree_line_position2 = scale(siteInfo$tree_line_position^2)) #bugs.data_ArtsDaten <- bugs.data #alpine_habitat: #1= Open lowland, #2 = Low alpine zone, #3 = intermediate alpine zone, #4 = high alpine zone ### initials #################################################################### #get JAGS libraries library(rjags) library(jagsUI) #need to specify initial values zst <- reshape2::acast(listlengthDF, siteIndex~yearIndex, value.var="y",fun=max,na.rm=T) zst [is.infinite(zst)] <- 0 inits <- function(){list(z = zst)} ### constant p ##################################################### #costant detection proability params <- c("mean.p","mean.psi") #specify model structure out1 <- jags(bugs.data, inits=inits, params, "models/BUGS_sparta_constant.txt", n.thin=10, n.chains=3, n.burnin=300,n.iter=1000,parallel=T) print(out1,2) save(out1,file="model-outputs/out1_OM_random_missing_5km_basic0.RData") #test sample of 5000 mean sd 2.5% 50% 97.5% overlap0 f Rhat n.eff mean.p 0.15 0.0 0.15 0.15 0.16 FALSE 1 1.00 210 mean.psi 0.17 0.0 0.16 0.17 0.18 FALSE 1 1.01 175 deviance 10716.33 62.6 10600.99 10716.29 10840.94 FALSE 1 1.02 119 ### RE############################################################### #run model with random effects on adm #specify parameters to monitor params <- c("mean.p","mean.psi","random.adm.sd","random.adm2.sd") #specify model structure out1 <- jags(bugs.data, inits=inits, params, "models/BUGS_sparta_random_missing.txt", n.thin=5, n.chains=3, n.burnin=1000,n.iter=2500,parallel=T) print(out1,2) #test sample of 1000 mean sd 2.5% 50% 97.5% overlap0 f Rhat n.eff mean.p 0.09 0.01 0.08 0.09 0.10 FALSE 1 1.07 35 mean.psi 0.04 0.03 0.01 0.03 0.12 FALSE 1 1.57 7 random.adm.sd 3.71 1.16 1.93 3.55 6.56 FALSE 1 1.40 9 random.adm2.sd 3.93 0.53 3.04 3.88 5.11 FALSE 1 1.73 6 deviance 290193.98 31.06 290132.65 290193.92 290254.42 FALSE 1 1.14 19 ### EXP VARS ######################################################## #run model including explanatory variables on observation #specify model structure bugs.data$occDM <- model.matrix(~ bugs.data$tree_line_position + bugs.data$tree_line_position2+ bugs.data$bio1 + bugs.data$open)[,-1] bugs.data$n.covs <- ncol(bugs.data$occDM) params <- c("mean.p","mean.psi","beta") out1 <- jags(bugs.data, inits=inits, params, "models/BUGS_sparta_variables_missing.txt", n.thin=10, n.chains=3, n.burnin=1000,n.iter=3000,parallel=T) print(out1,2) colnames(bugs.data$occDM) #test sample of 1000 mean sd 2.5% 50% 97.5% overlap0 f Rhat n.eff mean.p 0.08 0.01 0.07 0.08 0.09 FALSE 1.00 1.01 163 mean.psi 0.36 0.08 0.22 0.35 0.52 FALSE 1.00 1.24 13 beta[1] 0.87 0.61 -0.33 0.90 2.00 TRUE 0.92 1.24 13 beta[2] -3.17 0.64 -4.18 -3.27 -1.88 FALSE 1.00 1.90 5 beta[3] -1.40 0.22 -1.85 -1.40 -1.00 FALSE 1.00 1.04 64 beta[4] 1.51 0.32 0.88 1.49 2.17 FALSE 1.00 1.02 278 deviance 290302.36 29.10 290249.40 290301.02 290360.29 FALSE 1.00 1.03 79 ### EFFORT ########################################################## #run model including explanatory variable on observation and detection #on detection also put - number of sampling days and records per date #specify model structure bugs.data$occDM <- model.matrix(~ bugs.data$tree_line_position + bugs.data$tree_line_position2+ bugs.data$bio1 + bugs.data$open)[,-1] bugs.data$n.covs <- ncol(bugs.data$occDM) params <- c("mean.p","mean.psi","beta","beta.det","beta.sd","beta.e") out1 <- jags(bugs.data, inits=inits, params, "models/BUGS_sparta_variables_missing.txt", n.thin=3, n.chains=3, n.burnin=2500,n.iter=5000,parallel=T) save(out1,file="model-outputs/out1_OM_random_missing_5km.RData") print(out1,2) mean sd 2.5% 50% 97.5% overlap0 f Rhat n.eff mean.p 0.06 0.00 0.06 0.06 0.07 FALSE 1.00 1.05 47 mean.psi 0.12 0.00 0.12 0.12 0.13 FALSE 1.00 1.11 26 beta[1] 0.68 0.06 0.56 0.68 0.78 FALSE 1.00 1.00 480 beta[2] -1.96 0.07 -2.12 -1.96 -1.83 FALSE 1.00 1.20 17 beta[3] -0.58 0.02 -0.63 -0.58 -0.54 FALSE 1.00 1.02 104 beta[4] 0.39 0.03 0.33 0.39 0.45 FALSE 1.00 1.01 158 beta.det[1] 0.08 0.05 -0.02 0.08 0.19 TRUE 0.94 1.01 284 beta.det[2] -0.49 0.08 -0.64 -0.49 -0.34 FALSE 1.00 1.09 29 beta.det[3] -0.11 0.02 -0.16 -0.11 -0.07 FALSE 1.00 1.01 153 beta.det[4] 0.20 0.02 0.15 0.20 0.25 FALSE 1.00 1.01 351 beta.sd -0.67 0.04 -0.74 -0.67 -0.60 FALSE 1.00 1.01 329 ## negative effect!! beta.e 0.66 0.02 0.62 0.66 0.69 FALSE 1.00 1.00 2502 deviance 8384730.56 250.63 8384259.12 8384725.70 8385231.56 FALSE 1.00 1.01 371 ### PLOT ########################################################### #plot occupancy model out2<-update(out1,parameters.to.save=c("muZ","z"),n.iter=100) plotZ(out2,param="z") plotZ(out2,param="muZ") plotZerror(out2) ### JAGAM ########################################################### #also using jagam #fit as gam library(mgcv) gam1 <- gam(species~ 1 + s(x, y,k=10), data=varDF, family="binomial") #plot it varDF$fits<-gam1$fitted.values library(ggplot2) ggplot(varDF)+ geom_point(aes(x,y,colour=fits),shape=15,size=rel(4))+ scale_colour_gradient(low="blue",high="red")+ geom_point(data=subset(varDF,species==1),aes(x,y)) #Use the JAGAM function to get the BUGS code for the spline #in the BUGS model jags.ready <- jagam(species ~ 1 + s(x, y,k=10), data = varDF, family="binomial", sp.prior="log.uniform", file="jagam.txt") #get the data bits we need from jags data bugs.data$X = jags.ready$jags.data$X bugs.data$S1 = jags.ready$jags.data$S1 bugs.data$zero = jags.ready$jags.data$zero #specify parameters to monitor params <- c("dtype.p","mu.lp","rho") #run model out1 <- jags(bugs.data, inits=inits, params, "models/BUGS_sparta_JAGAM.txt", n.thin=nt, n.chains=3, n.burnin=10000,n.iter=50000) traceplot(out1) print(out1,2) ### DETECTION PROB ###################################################################################### #explore detection prob by hand #per year - for each line, what fraction of surveys had a ptarmigan in it #get rid of NAs listlengthDF_NAfree<-subset(listlengthDF,!is.na(visit)) propSuccess<-ddply(listlengthDF_NAfree,.(grid,adm,adm2,YearCollected), summarise, propY=ifelse(length(y)>1,mean(y),NA),#want to calculate it only when there are repeat visits meanL=mean(L), meanL2=mean(L2), meanL3=mean(L3)) propSuccess<-subset(propSuccess,!is.na(propY)) hist(propSuccess$propY)#very all or nothing mean(propSuccess$propY[propSuccess$propY>0])#0.86 #look at relationship library(ggplot2) library(cowplot) q1<-qplot(meanL,propY,data=propSuccess)#negative relationship q2<-qplot(meanL2,propY,data=propSuccess)#negative relationship q3<-qplot(meanL3,propY,data=propSuccess)#more positive plot_grid(q1,q2,q3) #plot in relation to site covariates propSuccess<-merge(propSuccess,listlengthDF_SiteCovs,by=c("grid","adm","adm2","site")) q1<-qplot(tree_line_position,propY,data=propSuccess)#quadratic relationship q2<-qplot(access,propY,data=propSuccess)#positive?? q3<-qplot(bio1,propY,data=propSuccess)#negative relationship plot_grid(q1,q2,q3) <file_sep>/README.md # ptarmiganUpscaling Combining different data types to produce a national population estimate for the ptarmigan in Norway. The repository contains the following files: 00_general functions.R - bunch of small functions used later, mainly formatting, processing stuff 01_formatting_occurrence_data.R - script to process and format the GBIF data for analysis 01_GBIF_data_retreival.R - script to retreive the GBIF data 02_environmental_data_grid.R - script to process all the environmental covariates for the 5 x 5 km grid 02_environmental_data_transect_buffers.R - scripts to process the covariates around each line-transect 03_mapping_linetransects_to_grids.R - script to align the occurrence data grid to the line-transect surveys 04_HPC_abundance_analysis.R - main script for analysis of the line-transect surveys 04_HPC_occurrence analysis.R - main script fot analysis of the occurrence data 05_crossvalidation_folds.R - script to define the spatial region for each fold 06_model_summaries.R - script to analysis the model outputs of both the line-transect abundance and occurrence data 07_HPC_simple_combined_analysis.R - script to combine the predictions from both models and predict total population size 08_uncertainity_analysis.R - script to examine the links between grid-level and national level uncertainty Folders: model: JAGS model code for both the abundance and occurrence models model-outputs: model outputs (after running on the HPC) for both datasets (not pushed to GitHub) ms: development of the paper (not pushed to GitHub) plots: plots for the paper (not pushed to Github) data: all kinds of data files - raw data as well as spatial environmental information (not pushed to Github) old: a bunch of old files that can be ignored (not pushed to Github) <file_sep>/02_environmental_data_grid.R #using a m grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" #get helper file source('generalFunctions.R') #get focal grids focusGrids <- readRDS("data/focusGrids.rds") ### get norway ############################################################## library(raster) library(maptools) library(rgeos) data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) plot(Norway) ### grid ################################################################### #create grid newres = 5000#5 km grid mygrid <- raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid plot(Norway,add=T) ### adm ##################################################################### #get info on administrative names for the grid library(rgdal) library(plyr) #make both spatial objects in the same crs NorwayADM <- readOGR(dsn="C:/Users/db40fysa/Dropbox/Alpine/NOR_adm",layer="NOR_adm2") #get multiple points per grid NorwayADM <- spTransform(NorwayADM,crs(equalM)) mygridPoints <- mygrid mygridPoints <- disaggregate(mygridPoints,fact=10) mygridPoints <- as.data.frame(mygridPoints,xy=T) coordinates(mygridPoints) <- c("x","y") proj4string(mygridPoints) <- crs(NorwayADM) #check they overlap plot(mygridPoints) plot(NorwayADM,add=T,col="red") #extract the data myAdm <- over(mygridPoints,NorwayADM) myAdm$grid <- mygridPoints$layer #get mode of adm and adm2 per grid myAdm <- ddply(myAdm,.(grid),summarise, adm = Mode(NAME_1), adm2 = Mode(NAME_2)) myAdm$adm[is.na(myAdm$adm)] <- "outside" myAdm$adm2[is.na(myAdm$adm2)] <- "outside" myAdm <- subset(myAdm,!is.na(grid)) saveRDS(myAdm,file="C:/Users/db40fysa/Dropbox/ptarmigan Upscaling/data/grid_Adm.rds") #check the results mygrid[] <- 0 mygrid[myAdm$grid] <- as.numeric(as.factor(myAdm$adm)) plot(mygrid)#looks good! #how many outside do we have? table(getValues(mygrid)) ### accessibility ########################################################### #Code to get environmental data: library(raster) #get accessibility map #https://www.nature.com/articles/nature25181 #setwd("C:/Users/diana.bowler/OneDrive - NINA/maps/accessibility/accessibility_to_cities_2015_v1.0") access <- raster("C:/Users/db40fysa/Nextcloud/sMon/Gis-DataData/Accessibility/2015_accessibility_to_cities_v1.0/2015_accessibility_to_cities_v1.0.tif") out <- getEnvironData(access,mygrid) #check data hist(out$myraster) summary(out$myraster) outAccess <- out names(outAccess)[2] <- "Accessibility" outAccess$Accessibility[is.nan(outAccess$Accessibility)] <- NA summary(outAccess$Accessibility) outAccess <- subset(outAccess,!is.na(Accessibility)) outAccess <- subset(outAccess,!is.na(grid)) saveRDS(outAccess,file="data/grid_Access.rds") #check the results mygrid[] <- 0 mygrid[outAccess$grid] <- outAccess$Accessibility plot(mygrid)#looks good! rm(access) rm(out) ### human pop density ####################################################### humanpop <- raster("C:/Users/db40fysa/Dropbox/Alpine/PopDensity/SEDAC_pop_data/gpw-v4-population-density-adjusted-to-2015-unwpp-country-totals-rev10_2000_30_sec_tif/gpw_v4_population_density_adjusted_to_2015_unwpp_country_totals_rev10_2000_30_sec.tif") out <- getEnvironData(humanpop,mygrid) #check data hist(out$myraster) summary(out$myraster) outHP<- out names(outHP)[2] <- "HumanPop" outHP$HumanPop[is.nan(outHP$HumanPop)] <- NA summary(outHP$HumanPop) outHP <- subset(outHP,!is.na(HumanPop)) outHP <- subset(outHP,!is.na(grid)) saveRDS(outHP,file="data/grid_HumanDensity.rds") #check the results mygrid[] <- 0 mygrid[outHP$grid] <- outHP$HumanPop plot(mygrid)#looks good! # ## habitats ################################################################ setwd("C:/Users/db40fysa/Dropbox/Alpine/Habitat/Satveg_deling_nd_partnere_09_12_2009/Satveg_deling_nd_partnere_09_12_2009/tiff") library(raster) #project other rasters onto this habitatRasterTop <- raster("NNred25-30-t1.tif")#30 x 30 m habitatRasterTop <- aggregate(habitatRasterTop,fact=5,fun=modal,na.rm=T) habitatRasterBot <- raster("sn25_geocorr.tif") habitatRasterBot <- aggregate(habitatRasterBot,fact=5,fun=modal,na.rm=T) extent(habitatRasterTop) extent(habitatRasterBot) #merge each dataset totalExtent <- c(246285,1342485,6414184,8014594) habitatRasterTop <- extend(habitatRasterTop,extent(totalExtent)) habitatRasterBot <- extend(habitatRasterBot,extent(totalExtent)) origin(habitatRasterBot) <- origin(habitatRasterTop) habitatRaster <- merge(habitatRasterTop,habitatRasterBot) plot(habitatRaster) #yeah!!! #Set NAs for irrelevant habitats habitatRaster[habitatRaster==22] <- NA habitatRaster[habitatRaster>24] <- NA habitatRaster[habitatRaster==0] <- NA plot(habitatRaster) #plot each grid, extract what???? #crop raster to Norway extent myraster <- habitatRaster rasterCRS <- crs(myraster) #convert raster into points and convert myrasterDF <- as.data.frame(myraster,xy=T) names(myrasterDF)[3] <- "myraster" myrasterDF<-subset(myrasterDF,!is.na(myraster)) coordinates(myrasterDF) <-c("x","y") proj4string(myrasterDF) <- rasterCRS myrasterDF <- spTransform(myrasterDF,crs(equalM)) #get general grid mygrid<-gridTemp projection(mygrid) <- CRS(equalM) #get myraster values per grid cell mygrid[] <- 1:ncell(mygrid) variable <- raster::extract(mygrid,myrasterDF) mygrid[] <- 0 mygrid[variable] <- 1 myrasterDF <- data.frame(myrasterDF@data) myrasterDF$grid <- variable library(reshape2) myrasterDF <- melt(table(myrasterDF$grid,myrasterDF$myraster)) names(myrasterDF)<-c("grid","raster","count") #add on total count per grid library(plyr) gridTotals <- ddply(myrasterDF,.(grid),summarise,total=sum(count)) myrasterDF$total <- gridTotals$total[match(myrasterDF$grid,gridTotals$grid)] #simplify habitat counts #predict positive effect myrasterDF$MountainBirchForest<-0 myrasterDF$MountainBirchForest[myrasterDF$raster%in%c(6,7,8)]<-myrasterDF$count[myrasterDF$raster%in%c(6,7,8)] #predict positive effect myrasterDF$Bog<-0 myrasterDF$Bog[myrasterDF$raster%in%c(9,10)]<-myrasterDF$count[myrasterDF$raster%in%c(9,10)] #predict negative effect myrasterDF$Forest<-0 myrasterDF$Forest[myrasterDF$raster%in%c(1:5)]<-myrasterDF$count[myrasterDF$raster%in%c(1:5)] #predict positive effect myrasterDF$ODF<-0 myrasterDF$ODF[myrasterDF$raster%in%c(16,17)]<-myrasterDF$count[myrasterDF$raster%in%c(16,17)] #predict positive effect myrasterDF$Meadows<-0 myrasterDF$Meadows[myrasterDF$raster%in%c(18)]<-myrasterDF$count[myrasterDF$raster%in%c(18)] #predict negative effect myrasterDF$OSF<-0 myrasterDF$OSF[myrasterDF$raster%in%c(12,13,14,15)]<-myrasterDF$count[myrasterDF$raster%in%c(12,13,14,15)] #? myrasterDF$Mire<-0 myrasterDF$Mire[myrasterDF$raster%in%c(11)]<-myrasterDF$count[myrasterDF$raster%in%c(11)] #expect negative effect myrasterDF$SnowBeds<-0 myrasterDF$SnowBeds[myrasterDF$raster%in%c(19,20)]<-myrasterDF$count[myrasterDF$raster%in%c(19,20)] #open habitat myrasterDF$Open<-0 myrasterDF$Open[myrasterDF$raster%in%c(11:20)]<-myrasterDF$count[myrasterDF$raster%in%c(11:20)] #human habitat - agriculture and urban myrasterDF$Human<-0 myrasterDF$Human[myrasterDF$raster%in%c(23,24)]<-myrasterDF$count[myrasterDF$raster%in%c(23,24)] #aggregate myrasterDF<-ddply(myrasterDF,.(grid),summarise, MountainBirchForest = sum(MountainBirchForest)/unique(total), Bog = sum(Bog)/unique(total), Mire = sum(Mire)/unique(total), Open = sum(Open)/unique(total), Human = sum(Human)/unique(total), Forest = sum(Forest)/unique(total), ODF = sum(ODF)/unique(total), Meadows = sum(Meadows)/unique(total), OSF = sum(OSF)/unique(total), SnowBeds = sum(SnowBeds)/unique(total), total = unique(total)) saveRDS(myrasterDF,"data/grid_Habitats.rds") ### climate ################################################################################ #average climatic conditions #try the EuroLST dataset setwd("C:/Users/db40fysa/Dropbox/Alpine/Bioclim_LST") #-BIO1: Annual mean temperature (°C*10): eurolst_clim.bio01.zip (MD5) 72MB #-BIO2: Mean diurnal range (Mean monthly (max - min tem)): eurolst_clim.bio02.zip (MD5) 72MB #-BIO3: Isothermality ((bio2/bio7)*100): eurolst_clim.bio03.zip (MD5) 72MB #-BIO4: Temperature seasonality (standard deviation * 100): eurolst_clim.bio04.zip (MD5) 160MB #-BIO5: Maximum temperature of the warmest month (°C*10): eurolst_clim.bio05.zip (MD5) 106MB #-BIO6: Minimum temperature of the coldest month (°C*10): eurolst_clim.bio06.zip (MD5) 104MB #-BIO7: Temperature annual range (bio5 - bio6) (°C*10): eurolst_clim.bio07.zip (MD5) 132MB #-BIO10: Mean temperature of the warmest quarter (°C*10): eurolst_clim.bio10.zip (MD5) 77MB #-BIO11: Mean temperature of the coldest quarter (°C*10): eurolst_clim.bio11.zip (MD5) 78MB #bio1# temp_bio1 <- raster("eurolst_clim.bio01/eurolst_clim.bio01.tif")#res 250 m temp_bio1 <- aggregate(temp_bio1,fact=4,fun=mean,na.rm=T) #extract the data out <- getEnvironData(temp_bio1,mygrid) out_Bio1 <- out rm(temp_bio1) rm(out) #maximum temp# temp_bio5 <- raster("eurolst_clim.bio05/eurolst_clim.bio05.tif") temp_bio5 <- aggregate(temp_bio5,fact=4,fun=mean,na.rm=T) out <- getEnvironData(temp_bio5,mygrid) out_Bio5 <- out rm(temp_bio5) rm(out) #minimum temp temp_bio6 <- raster("eurolst_clim.bio06/eurolst_clim.bio06.tif") temp_bio6 <- aggregate(temp_bio6,fact=4,fun=mean,na.rm=T) out <- getEnvironData(temp_bio6,mygrid) out_Bio6 <- out rm(temp_bio6) rm(out) ### merge ################################################################ #temp data names(out_Bio1)[2]<-"bio1" names(out_Bio5)[2]<-"bio5" names(out_Bio6)[2]<-"bio6" out_Bio<-cbind(out_Bio1,bio5=out_Bio5[,2],bio6=out_Bio6[,2]) saveRDS(out_Bio,"data/grid_Climate.rds") #combine others varDF <- merge(out_Bio,myrasterDF,by="grid",all=T) varDF <- merge(varDF,myAdm,by="grid",all=T) varDF <- merge(varDF,outHP,all=T) varDF <- merge(varDF,outAccess,all=T) varDF <- subset(varDF,!is.na(grid)) saveRDS(varDF,file="data/varDF_missing_5km_idiv.rds") ### correlations ############################################################################ #Examine correlations among bugs variables library(GGally) ggpairs(varDF[,2:11]) #bio1 and bio6 strongly related (0.808) #top and open are strongly related (0.726) #pref open and top (0.901) #Agriculture and bottom are strongly related (0.907) # #plot in space # gridDF<-as.data.frame(gridTemp,xy=T) # varDF$grid<-bugs.data$grid # varDF<-merge(varDF,gridDF,by.x="grid",by.y="layer",all.x=T) # # qplot(x,y,data=varDF,color=habitat) # qplot(x,y,data=varDF,color=Forest) # qplot(x,y,data=varDF,color=Open) # qplot(x,y,data=varDF,color=Top) # qplot(x,y,data=varDF,color=Agriculture) # qplot(x,y,data=varDF,color=bio1) # qplot(x,y,data=varDF,color=bio5) # qplot(x,y,data=varDF,color=bio6) ### coverage ################################################################################ #subset to focal grids varDF <- subset(varDF,grid %in% focusGrids) # missing habitat data for 57 grids apply(varDF,2,function(x)sum(is.na(x))) #check plots mygrid[] <- NA mygrid[varDF$grid] <- varDF$bio1 plot(mygrid) #looks good mygrid[] <- NA mygrid[varDF$grid] <- varDF$Forest plot(mygrid) #ok mygrid[] <- NA mygrid[varDF$grid]<-varDF$bio6 plot(mygrid) #good! #where are these 57 grids with missing habitat data mygrid[]<-0 mygrid[varDF$grid[is.na(varDF$Forest)]]<-1 plot(mygrid) plot(Norway,add=T) #these are on the edge of Norway ### alpine data ############################################################################# #also get alpine data load("data/alpineData_5kmGrid.RData") alpineData <- subset(alpineData,site %in% focusGrids) #plot it library(ggplot2) qplot(x,y,data=alpineData,color=elevation) qplot(x,y,data=alpineData,color=alpine_habitat) #look ok #summarise it summary(alpineData$tree_line) summary(alpineData$elevation) apply(alpineData,2,function(x)sum(is.na(x))) #tree line position alpineData$tree_line_position <- alpineData$tree_line-alpineData$elevation alpineData$alpine_habitat1 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==1,1,0)) alpineData$alpine_habitat2 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==2,1,0)) alpineData$alpine_habitat3 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==3,1,0)) alpineData$alpine_habitat4 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==4,1,0)) #aggregate to site level library(plyr) alpineData <- ddply(alpineData,.(site),summarise, tree_line_position = median(tree_line_position,na.rm=T), tree_line = median(tree_line,na.rm=T), elevation = median(elevation,na.rm=T), alpine_habitat1 = mean(alpine_habitat1,na.rm=T), alpine_habitat2 = mean(alpine_habitat2,na.rm=T), alpine_habitat3 = mean(alpine_habitat3,na.rm=T), alpine_habitat4 = mean(alpine_habitat4,na.rm=T)) names(alpineData)[which(names(alpineData)=="site")]<-"grid" #plot data mygrid[] <- NA mygrid[alpineData$grid] <- alpineData$tree_line plot(mygrid) mygrid[] <- NA mygrid[alpineData$grid] <- alpineData$elevation plot(mygrid) #plot missing data mygrid[] <- NA mygrid[alpineData$grid[is.na(alpineData$tree_line)]] <- 1 plot(mygrid) mygrid[] <- NA mygrid[alpineData$grid[is.na(alpineData$elevation)]] <- 1 plot(mygrid) #any more NAs?? apply(alpineData,2,function(x)sum(is.na(x))) #56 are missing except elevation #are these in addition of different to the missing data in varDF missingVarDF <- varDF$grid[is.na(varDF$Forest)] missingAlpine <- alpineData$grid[is.na(alpineData$tree_line)] length(unique(missingVarDF,missingAlpine))#57 in total!! #merge all varDF <- merge(varDF,alpineData,by="grid",all=T) varDF <- subset(varDF,!is.na(Forest)) varDF <- subset(varDF,!is.na(tree_line)) ### check missing data again ######################################################### apply(varDF,2,function(x)sum(is.na(x))) varDF$adm <- iconv(varDF$adm,"UTF-8","latin1") varDF$adm2 <- iconv(varDF$adm2,"UTF-8","latin1") #5 grids are outside - can we figure out there admin??? table(varDF$adm) table(varDF$adm2) subset(varDF,adm=="outside")$grid #22415 25249 25253 25721 74673 #for each one, see what is the adm before and after the grid subset(varDF,grid %in% c(22412,22413,22414,22415,22416,22417,22418))#none #see about cells below mygrid[] <- 1:ncell(mygrid) rowColFromCell(mygrid,22415) getValues(mygrid,row=95)[137] getValues(mygrid,row=94)[137] getValues(mygrid,row=96)[137] subset(varDF,grid %in% c(22178,22652)) varDF$adm[varDF$grid==22415] <- "Troms" varDF$adm2[varDF$grid==22415] <- "Bardu" subset(varDF,grid %in% c(25247,25248,25250,25251)) varDF$adm[varDF$grid==25249] <- "Nordland" varDF$adm2[varDF$grid==25249] <- "Tysfjord" subset(varDF,grid %in% c(25251,25252,25253,25254,25255)) varDF$adm[varDF$grid==25253] <- "Nordland" varDF$adm2[varDF$grid==25253] <- "Narvik" subset(varDF,grid %in% c(25719,25720,25721,25722,25723)) varDF$adm[varDF$grid==25721] <- "Nordland" varDF$adm2[varDF$grid==25721] <- "Tysfjord" subset(varDF,grid %in% c(74671,74672,74673,74674,74675)) varDF$adm[varDF$grid==74673] <- "Rogaland" varDF$adm2[varDF$grid==74673] <- "Klepp" #also: #11587, 12063, 25485 subset(varDF,grid %in% c(11585,11586,11588,11589)) varDF$adm[varDF$grid==11587] <- "Finnmark" varDF$adm2[varDF$grid==11587] <- "Sør-Varanger" subset(varDF,grid %in% c(12061,12062,12064,12065)) varDF$adm[varDF$grid==12063] <- "Finnmark" varDF$adm2[varDF$grid==12063] <- "Sør-Varanger" subset(varDF,grid %in% c(25483,25484,25486,25487)) varDF$adm[varDF$grid==25485] <- "Nordland" varDF$adm2[varDF$grid==25485] <- "Tysfjord" table(varDF$adm) ### save ############################################################################# saveRDS(varDF,file="data/varDF_allEnvironData_5km_idiv.rds") ### group admins #################################################################### source('generalFunctions.R', encoding = 'UTF-8'f) varDF$admGrouped <- mergeCounties(varDF$adm,further=TRUE) table(varDF$adm) table(varDF$admGrouped) sum(is.na(varDF$admGrouped)) saveRDS(varDF,file="data/varDF_allEnvironData_5km_idiv.rds") ### latitude and distance to the coast ############################################### #coordinates mygridDF <- as.data.frame(mygrid,xy=T) names(mygridDF)[3] <- "grid" varDF <- merge(varDF, mygridDF, by="grid",all.x=T) #distance to coast sldf_coast <- rnaturalearth::ne_coastline() plot(sldf_coast) coast <- sf::st_as_sf(sldf_coast) #get points mygridPoints <- sf::st_as_sf(varDF[,c("grid","x","y")], coords = c("x", "y"), crs = proj4string(NorwayADM)) mygridPoints <- sf::st_transform(mygridPoints,sf::st_crs(coast)) ggplot()+ geom_sf(data=coast)+ geom_sf(data=mygridPoints,color="red") #get distance between them mygridPoints1 <- sf::st_coordinates(mygridPoints) dist <- geosphere::dist2Line(p = as.matrix(mygridPoints1), line = sldf_coast) #pack into data frame dist <- as.data.frame(dist) dist$grid <- mygridPoints$grid names(dist)[1] <- "distCoast" #merge with varDF varDF <- merge(varDF, dist[,c(1:3,5)], by="grid", all.x=T) saveRDS(varDF,file="data/varDF_allEnvironData_5km_idiv.rds") ### correlations ############################################ library(GGally) ggpairs(varDF[,c(2:13,20:22,28:30)]) cor(varDF[,c(2:13,20:22,28:30)]) #cors >0.7 #bio1 and bio6 #bio1 and tree line position #forest and open #osf and open #open and tree line position #y and tree line (0.76) #y and x ### end ##################################################### <file_sep>/04_HPC_occurrence_analysis.R library(tidyverse) library(sp) library(rgeos) library(raster) library(maptools) #local #myfolder <- "data" #HPC myfolder <- "/data/idiv_ess/ptarmiganUpscaling" ### get norway############################################################## #using a m grid equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) NorwayOrigProj <- spTransform(NorwayOrig,crs(equalM)) ### ref grid ######################################################## #create grid newres = 5000#5 km grid mygrid <- raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid myGridDF <- as.data.frame(mygrid,xy=T) ### listlength ##################################################### #source('formattingArtDatenBank_missing_data_iDiv.R') #read in list length object (made on the Rstudio server) listlengthDF <- readRDS(paste(myfolder,"listlength_iDiv.rds",sep="/")) #subset to May to September listlengthDF <- subset(listlengthDF,is.na(month)|(month > 4 & month <10)) #2008 to 2017.... listlengthDF$Year <- listlengthDF$year listlengthDF <- subset(listlengthDF, Year>2007 & Year <=2017) ### subset ########################################################## #subset to focal grids and those with environ covariate data focusGrids <- readRDS(paste(myfolder,"focusGrids.rds",sep="/")) varDF <- readRDS(paste(myfolder,"varDF_allEnvironData_5km_idiv.rds",sep="/")) listlengthDF <- subset(listlengthDF,grid %in% focusGrids) listlengthDF <- subset(listlengthDF,grid %in% varDF$grid) ### plot data ####################################################### # #presences # # listlengthDF_Positive <- subset(listlengthDF, y==1) # listlengthDF_Positive <- subset(listlengthDF_Positive, !duplicated(grid)) # # mygrid[] <- NA # mygrid[listlengthDF_Positive $grid] <- listlengthDF_Positive$y # crs(mygrid) <- equalM # occ_tmap <- tm_shape(NorwayOrigProj) + # tm_borders() + # tm_shape(mygrid)+ # tm_raster(title="Occupancy", legend.show = FALSE) # saveRDS(occ_tmap,"plots/occupancy_raw_presences.RDS") # # #absences # listlengthDF_Abs<- subset(listlengthDF, y==0) # listlengthDF_Abs <- subset(listlengthDF_Abs, !duplicated(grid)) # # mygrid[] <- NA # mygrid[listlengthDF_Abs$grid] <- listlengthDF_Abs$y # crs(mygrid) <- equalM # occ_tmap <- tm_shape(NorwayOrigProj) + # tm_borders() + # tm_shape(mygrid)+ # tm_raster(title="Occupancy", palette="YlGnBu", legend.show = FALSE) # saveRDS(occ_tmap,"plots/occupancy_raw_absences.RDS") ### Absences ################################################################### #the dataset contains missing values listlengthDF$L[is.na(listlengthDF$L)] <- 1 #set to nominal effort #listlengthDF$y[listlengthDF$L==0] <- 0 table(is.na(listlengthDF$y)) ### effort ###################################################################### #we will treat it as a categorical variable table(listlengthDF$L) listlengthDF$singleton <- ifelse(listlengthDF$L==1,1,0) listlengthDF$short <- ifelse(listlengthDF$L %in% c(2:4),1,0) ### indices ##################################################################### #order data by site and year: listlengthDF$siteIndex <- as.numeric(factor(listlengthDF$grid)) listlengthDF$yearIndex <- as.numeric(factor(listlengthDF$year)) listlengthDF <- arrange(listlengthDF,siteIndex,yearIndex) #merge with environ data names(listlengthDF)[which(names(listlengthDF)=="y")] <- "species" listlengthDF <- merge(listlengthDF,varDF,by="grid",all.x=T) ### adm inidices ############################################################# listlengthDF$admN <- as.numeric(factor(listlengthDF$adm)) listlengthDF$admN2 <- as.numeric(factor(listlengthDF$adm2)) #extract site data siteInfo <- subset(listlengthDF,!duplicated(grid)) siteInfo_ArtsDaten <- siteInfo #saveRDS(siteInfo, # file = "data/siteInfo_ArtsDaten.rds") ### data summary ############################################################## length(unique(listlengthDF$grid)) # # listlengthDF_obs <- subset(listlengthDF, !is.na(species)) # length(unique(listlengthDF_obs$grid)) # # listlengthDF_posobs <- subset(listlengthDF, species==1) # length(unique(listlengthDF_posobs$grid)) # # #when a ptarmigan was observed at a grid - how many times was it seen there # ptarmiganGrids <- listlengthDF_posobs %>% # group_by(grid) %>% # summarise(nuVisits = length(unique(visit)), # nuYears = length(unique(year))) # summary(ptarmiganGrids$nuVisits) # summary(ptarmiganGrids$nuYears) # # #how often was a grid surveyed # visitGrids <- listlengthDF_obs %>% # group_by(grid) %>% # summarise(nuVisits = length(unique(visit)), # nuYears = length(unique(year))) # summary(visitGrids$nuVisits) # summary(visitGrids$nuYears) ### BUGS object ################################################################ myScale <- function(x){ as.numeric(scale(x)) } #for BUGS bugs.data <- list(nsite = length(unique(listlengthDF$siteIndex)), nyear = length(unique(listlengthDF$yearIndex)), nvisit = nrow(listlengthDF), site = listlengthDF$siteIndex, year = listlengthDF$yearIndex, y = listlengthDF$species,#includes NAs #detection covariates Effort = listlengthDF$singleton, Effort2 = listlengthDF$short, det.tlp = myScale(listlengthDF$tree_line/100), det.tlp2 = myScale(listlengthDF$tree_line^2/100000), det.open = myScale(listlengthDF$Open), det.bio5 = myScale(listlengthDF$bio5/100), det.bio6 = myScale(listlengthDF$bio6/100), #add an adm effect adm = siteInfo$admN, det.adm = listlengthDF$admN, n.adm = length(unique(siteInfo$admN)),#19 adm2 = siteInfo$admN2, det.adm2 = listlengthDF$admN2, n.adm2 = length(unique(siteInfo$admN2))) #bugs.data_ArtsDaten <- bugs.data #alpine_habitat: #1= Open lowland, #2 = Low alpine zone, #3 = intermediate alpine zone, #4 = high alpine zone ### initials ################################################ #get JAGS libraries library(rjags) library(jagsUI) #need to specify initial values zst <- reshape2::acast(listlengthDF, siteIndex~yearIndex, value.var="species", fun=max,na.rm=T) zst [is.infinite(zst)] <- 0 inits <- function(){list(z = zst)} ### bpv index ############################################## #for each i, sum into t StrIdx <- array(data=0, dim = c(bugs.data$nvisit,bugs.data$nyear)) for(i in 1:bugs.data$nvisit){ StrIdx[i,bugs.data$year[i]] <- 1 } bugs.data$StrIdx <- StrIdx ### scale variables ########################################## #total grids nrow(varDF)#11788 #sampled grid nrow(siteInfo)#11788 names(siteInfo)[1:12] siteInfo[,-c(1:12)] <- plyr::numcolwise(scale)(siteInfo[,-c(1:12)]) ### choose model ############################################## modelTaskID <- read.delim(paste(myfolder,"modelTaskID_occuModel.txt",sep="/"),as.is=T) #get task id task.id = as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID", "1")) #get model for this task mymodel <- modelTaskID$Model[which(modelTaskID$TaskID==task.id)] ### choose covariates ########################################################## #standard model if(mymodel == "BUGS_occuModel_upscaling.txt"){ #specify model structure - a priori picking variables bugs.data$occDM <- model.matrix(~ siteInfo$tree_line_position + I(siteInfo$tree_line_position^2) + siteInfo$y + siteInfo$bio6 + siteInfo$Bog + siteInfo$Mire + siteInfo$Meadows + siteInfo$ODF + I(siteInfo$ODF^2) + siteInfo$OSF + I(siteInfo$OSF^2) + siteInfo$MountainBirchForest)[,-1] #saveRDS(bugs.data,file="data/bugs.data_ArtsDaten.rds") #lasso model or model selection model }else{ bugs.data$occDM <- model.matrix(~ siteInfo$bio6 + siteInfo$bio5 + siteInfo$tree_line_position + siteInfo$MountainBirchForest + siteInfo$Bog + siteInfo$ODF + siteInfo$Meadows + siteInfo$OSF + siteInfo$Mire + siteInfo$SnowBeds + siteInfo$y + siteInfo$distCoast + I(siteInfo$bio6^2) + I(siteInfo$bio5^2) + I(siteInfo$tree_line_position^2) + I(siteInfo$MountainBirchForest^2) + I(siteInfo$Bog^2) + I(siteInfo$ODF^2) + I(siteInfo$Meadows^2) + I(siteInfo$OSF^2) + I(siteInfo$Mire^2) + I(siteInfo$SnowBeds^2) + I(siteInfo$y^2) + I(siteInfo$distCoast^2))[,-1] } bugs.data$n.covs <- ncol(bugs.data$occDM) # myvars <- c("bio6","bio5","tree_line_position","MountainBirchForest","Bog","ODF","Meadows", # "OSF","Mire","SnowBeds","y","distCoast", # "bio6_2","bio5_2","tree_line_position_2", # "MountainBirchForest_2","Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2", # "SnowBeds_2","y_2","distCoast_2") # myvars <- c("tree_line_position","tree_line_position_2","geo_y","bio1","bio1_2","Bog", # "Meadows","ODF","OSF","MountainBirchForest") ### save objects #################################################### # saveRDS(bugs.data, file="data/bugs.data_ArtsDaten.rds") # saveRDS(zst, file="data/zst_ArtsDaten.rds") ### fit model ######################################################## params <- c("beta","g", "average.p","average.psi","propOcc", "beta.effort","beta.effort2", "beta.det.open","beta.det.bio5","beta.det.bio6", "beta.det.tlp","beta.det.tlp2", "bpv","grid.z","grid.psi") #chosen already earlier #modelfile <- "/data/idiv_ess/ptarmiganUpscaling/BUGS_occuModel_upscaling.txt" #modelfile <- "/data/idiv_ess/ptarmiganUpscaling/BUGS_occuModel_upscaling_ModelSelection.txt" #modelfile <- "/data/idiv_ess/ptarmiganUpscaling/BUGS_occuModel_upscaling_LASSO.txt" modelfile <- paste(myfolder,mymodel,sep="/") #n.cores = as.integer(Sys.getenv("NSLOTS", "1")) n.cores = as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1")) #n.cores = 3 n.iterations = 20000 out1 <- jags(bugs.data, inits = inits, params, modelfile, n.thin = 10, n.chains = n.cores, n.burnin = round(n.iterations/2), n.iter = n.iterations, parallel = T) saveRDS(out1$summary,file=paste0("outSummary_occModel_upscaling_",task.id,".rds")) ### get AUC ########################################################## #update by a small number and get full model out2 <- update(out1, parameters.to.save = c("mid.psi","mid.z","Py","Py.pred"),n.iter=2000, n.thin = 10) library(ggmcmc) ggd2 <- ggs(out2$samples) #Z against psi Preds <- subset(ggd2,grepl("mid.psi",ggd2$Parameter)) Preds$Iteration <- as.numeric(interaction(Preds$Iteration,Preds$Chain)) Z_Preds <- subset(ggd2,grepl("mid.z",ggd2$Parameter)) Z_Preds$Iteration <- as.numeric(interaction(Z_Preds$Iteration,Z_Preds$Chain)) nu_Iteractions <- max(Preds$Iteration) head(Preds) #look through all iterations AUC_psi <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ psi.vals <- Preds$value[Preds$Iteration==i] z.vals <- Z_Preds$value[Z_Preds$Iteration==i] pred <- ROCR::prediction(psi.vals, z.vals) #get AUC perf <- ROCR::performance(pred, "auc") AUC_psi[i] <- perf@y.values[[1]] } summary(AUC_psi) saveRDS(summary(AUC_psi),file=paste0("AUC_psi_occModel_upscaling_",task.id,".rds")) #Y against Py - pull out one year Py_preds <- subset(ggd2,grepl("Py",ggd2$Parameter)) Py_preds <- subset(Py_preds,!grepl("Py.pred",Py_preds$Parameter)) Py_preds$Iteration <- as.numeric(interaction(Py_preds$Iteration,Py_preds$Chain)) nu_Iteractions <- max(Py_preds$Iteration) head(Py_preds) #look through all iterations AUC_py <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ py.vals <- Py_preds$value[Py_preds$Iteration==i] #select data useData <- !is.na(bugs.data$y) & bugs.data$year==6 pred <- ROCR::prediction(py.vals[useData],bugs.data$y[useData]) #get AUC perf <- ROCR::performance(pred, "auc") AUC_py[i] <- <EMAIL>[[1]] } summary(AUC_py) saveRDS(summary(AUC_py),file=paste0("AUC_py_occModel_upscaling_",task.id,".rds")) #Y against Py_pred (psi x p) - pull out one year Py_preds <- subset(ggd2,grepl("Py.pred",ggd2$Parameter)) Py_preds$Iteration <- as.numeric(interaction(Py_preds$Iteration,Py_preds$Chain)) nu_Iteractions <- max(Py_preds$Iteration) head(Py_preds) #look through all iterations AUC_py <- rep(NA, nu_Iteractions) for (i in 1:nu_Iteractions){ py.vals <- Py_preds$value[Py_preds$Iteration==i] #select data useData <- !is.na(bugs.data$y) & bugs.data$year==6 pred <- ROCR::prediction(py.vals[useData],bugs.data$y[useData]) #get AUC perf <- ROCR::performance(pred, "auc") AUC_py[i] <- <EMAIL>[[1]] } summary(AUC_py) saveRDS(summary(AUC_py),file=paste0("AUC_pypred_occModel_upscaling_",task.id,".rds")) ### get full z and psi ########################################################## out2 <- update(out1, parameters.to.save = c("z","psi"),n.iter=2000, n.thin = 10) #save summary saveRDS(out2$summary,file=paste0("Z_summary_occModel_upscaling_",task.id,".rds")) #save z and psi samples library(ggmcmc) ggd <- ggs(out2$samples) ggd2 <- subset(ggd,grepl("z",ggd$Parameter)) saveRDS(ggd2,file=paste0("Z_occModel_upscaling_",task.id,".rds")) ggd3 <- subset(ggd,grepl("psi",ggd$Parameter)) saveRDS(ggd3,file=paste0("psi_occModel_upscaling_",task.id,".rds")) <file_sep>/01_GBIF_data_retreival.R #retriving the bird data library(rgbif) #get willow ptarmigan data name_backbone(name='Lagopus lagopus') library(plyr) wp<-ldply(2007:2017,function(x){ out<-occ_data(taxonKey=2473421, country="NO",hasCoordinate=TRUE,year=x,basisOfRecord="HUMAN_OBSERVATION",hasGeospatialIssue=FALSE,limit=200000) out$data }) write.table(wp,file="willow_ptarmigan_GBIF.txt",sep="\t") #get data for all birds name_backbone(name='Aves') library(plyr) myyears<-2010:2017 mymonths<-4:10 #for months 4 to 10 for(y in 1:length(myyears)){ for(m in 1:length(mymonths)){ out<-occ_data(classKey=212, country="NO",hasCoordinate=TRUE,year=myyears[y], month=mymonths[m],hasGeospatialIssue=FALSE,basisOfRecord="HUMAN_OBSERVATION", limit=200000) write.table(out$data,file=paste0("all_birds",myyears[y],"_",mymonths[m],"_GBIF.txt"),sep="\t",row.names=FALSE) } } #get what ebird data is available # eBird <- read.delim("C:/Users/db40fysa/Dropbox/Alpine/eBird/ebd_NO_relNov-2020/ebd_NO_relNov-2020.txt") # head(eBird) # eBird$Date <- as.Date(eBird$OBSERVATION.DATE) # eBird$Year <- lubridate::year(eBird$Date) # table(eBird$Year) # #only data from 2014 onwards... # table(eBird$ALL.SPECIES.REPORTED) # # # #0 1 # #72675 347534 # #use these complete checklists?? # eBird <- subset(eBird,ALL.SPECIES.REPORTED==1) # #subset to 2014 onwards # eBird <- subset(eBird,Year>=2014) # #plot these # qplot(LONGITUDE,LATITUDE,data=subset(eBird,Year==2014)) # qplot(LONGITUDE,LATITUDE,data=subset(eBird,Year==2015)) # qplot(LONGITUDE,LATITUDE,data=subset(eBird,Year==2016)) # qplot(LONGITUDE,LATITUDE,data=subset(eBird,Year==2017)) # qplot(LONGITUDE,LATITUDE,data=subset(eBird,Year==2018)) # #bit sparse???<file_sep>/02_environmental_data_transect_buffers.R library(tidyverse) library(sp) library(rgeos) library(raster) library(maptools) myfolder <- "Data" equalM<-"+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" source('generalFunctions.R') ### get norway ############################################## data(wrld_simpl) Norway <- subset(wrld_simpl,NAME=="Norway") NorwayOrig <- Norway Norway <- gBuffer(Norway,width=1) Norway <- spTransform(Norway,crs(equalM)) plot(Norway) #create grid newres = 5000#5 km grid mygrid <- raster(extent(projectExtent(Norway,equalM))) res(mygrid) <- newres mygrid[] <- 1:ncell(mygrid) plot(mygrid) gridTemp <- mygrid plot(Norway,add=T) ### ptarmigan data ############################################################### #read in data frame allData <- readRDS(paste(myfolder,"allData.rds",sep="/")) #subset to years of interest allData <- subset(allData,Year>2006 & Year<2018) #remove hyphens for help with subsetting allData$Fylkesnavn <- gsub("-"," ",allData$Fylkesnavn) allData$Fylkesnavn[which(allData$Rapporteringsniva=="Indre Troms")] <- "Troms" #mistake with 1405 - transect length allData$LengdeTaksert[which(allData$LinjeID==1405&allData$LengdeTaksert==1100)] <- 11000 ### spatial line transects ####################################################### spatialLines <- readRDS(paste(myfolder,"spatialLineTransects.rds",sep="/")) spatialLines <- subset(spatialLines,LinjeID%in%unique(allData$LinjeID)) LongLat = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") for (i in seq(nrow(spatialLines))) { if (i == 1) { spTemp = readWKT(spatialLines$STAsText[i], spatialLines$LinjeID[i], p4s=LongLat) } else { spTemp = rbind( spTemp, readWKT(spatialLines$STAsText[i], spatialLines$LinjeID[i], p4s=LongLat) ) } } #Make Lines spatial data frame mydata <- spatialLines[,c("LinjeID","Fylkesnavn","Region","Rapporteringsniva","OmradeID", "OmradeNavn")] rownames(mydata) <- paste(mydata$LinjeID) Lines_spatial <- SpatialLinesDataFrame(spTemp, mydata, match.ID=T) #plot(Lines_spatial) saveRDS(Lines_spatial,file="data/Lines_spatial.rds") ### create buffers ############################################################## #convert to utm spTemp <- spTransform(Lines_spatial,crs(equalM)) #get centroids lineCentres <- gCentroid(spTemp,byid=TRUE)@coords #put buffers around each one and make into a polygons makePolygon <- function(x){ myCentre <- data.frame(t(x)) coordinates(myCentre) <- c("x","y") myPoly <- gBuffer(myCentre,width=2821)#sqrt(25/pi) return(myPoly) } p <- apply(lineCentres,1,makePolygon) #make into spatial polygons object library(purrr) allPolys <- list(p, makeUniqueIDs = T) %>% flatten() %>% do.call(rbind, .) plot(allPolys) #make into a spatial object Polys_spatial <- SpatialPolygonsDataFrame(Sr=allPolys, data=mydata, match.ID=FALSE) proj4string(Polys_spatial) <- equalM saveRDS(Polys_spatial,file="data/Polys_spatial.rds") ### plot #################################################### myLines <- Lines_spatial$LinjeID Lines_spatial <- spTransform(Lines_spatial,crs(equalM)) plot(subset(Polys_spatial,LinjeID==122)) plot(subset(Lines_spatial,LinjeID==122),add=T) for(i in 1:length(myLines)){ line <- myLines[i] png(filename=paste0("plots/obs/circles/LinjeID",line,".png")) plot(subset(Polys_spatial,LinjeID==line)) plot(subset(Lines_spatial,LinjeID==line),add=T) dev.off() } ### get main grid of each polygon ########################## centreDF <- data.frame(LinjeID = spTemp$LinjeID, x = lineCentres[,1], y = lineCentres[,2]) coordinates(centreDF) <- c("x","y") proj4string(centreDF) <- CRS(equalM) plot(mygrid) plot(Norway,add=T) plot(centreDF,add=T) centreDF$grid <- extract(mygrid,centreDF) centreDF@data$x <- centreDF@coords[,1] centreDF@data$y <- centreDF@coords[,2] saveRDS(centreDF@data,"data/lines_to_grids.rds") # #### all grids for each line ################################# #why do some lines not overlap with the focal grids?? plot(NorwayOrig) plot(Lines_spatial,add=T,col="red") #for those missing (see 'mapping_lines_to_grids.R') plot(NorwayOrig) plot(subset(Lines_spatial,LinjeID %in% missing),add=T,col="red") #these are in the north - in islands and in Sweden (not in focal grids) #put buffer around each line Lines_spatial <- spTransform(Lines_spatial,crs(equalM)) #Lines_spatial_buffer <- gBuffer(Lines_spatial,width = 5000, byid=TRUE) Lines_spatial_buffer <- gBuffer(Lines_spatial,width = 15000, byid=TRUE) Polys_grids <- extract(mygrid,Lines_spatial_buffer,df=T) head(Polys_grids) #add to data frame Lines_spatial_buffer$ID <- 1:nrow(Lines_spatial_buffer) Polys_grids$LinjeID <- Lines_spatial_buffer$LinjeID[match(Polys_grids$ID,Lines_spatial_buffer$ID)] names(Polys_grids)[2]<- "grid" #saveRDS(Polys_grids,file = "data/lineBuffers_to_grids_5km.rds") saveRDS(Polys_grids,file = "data/lineBuffers_to_grids_15km.rds") ### get environ data for all circles ######################## Polys_spatial <- readRDS("data/Polys_spatial.rds") ### distance to coast ###################################### #get coastline data -very smooth sldf_coast <- rnaturalearth::ne_coastline() plot(sldf_coast) coast <- sf::st_as_sf(sldf_coast) #get better coastline data? too slow # coastNorway <- getData('GADM', country='Norway', level=0) # coastSweden <- getData('GADM', country='Sweden', level=0) # coastFinland <- getData('GADM', country='Finland', level=0) # coastRussia <- getData('GADM', country='Russia', level=0) # coast <- sf::st_union(sf::st_as_sf(coastNorway), sf::st_as_sf(coastSweden)) # coast <- sf::st_union(coast, sf::st_as_sf(coastFinland)) # coast <- sf::st_union(coast, sf::st_as_sf(coastRussia)) #get points lineCentres_xy <- lineCentres lineCentres <- sf::st_as_sf(data.frame(lineCentres), coords = c("x", "y"), crs = equalM) lineCentres <- sf::st_transform(lineCentres,sf::st_crs(coast)) ggplot()+ geom_sf(data=coast)+ geom_sf(data=lineCentres,color="red") #get distance between them lineCentres <- sf::st_coordinates(lineCentres) dist <- geosphere::dist2Line(p = as.matrix(lineCentres), line = sldf_coast) #pack into data frame lineCentres_xy <- as.data.frame(lineCentres_xy) lineCentres_xy$dist <- dist[,1] lineCentres_xy$LinjeID <- Lines_spatial$LinjeID ### admin ################################################## #get info on administrative names for the buffers library(rgdal) library(plyr) #make both spatial objects in the same crs NorwayADM <- readOGR(dsn="C:/Users/db40fysa/Dropbox/Alpine/NOR_adm",layer="NOR_adm2") plot(NorwayADM) NorwayADM$NAME_1 <- iconv(NorwayADM$NAME_1, "UTF-8","latin1") table(NorwayADM$NAME_1) NorwayADM <- spTransform(NorwayADM,crs(Polys_spatial)) NorwayADM$NAME_1 <- mergeCounties(as.character(NorwayADM$NAME_1),further=TRUE) table(NorwayADM$NAME_1) #overlay with the Polygons myAdm <- over(Polys_spatial,NorwayADM) myAdm$LinjeID <- Polys_spatial@data$LinjeID #group?? table(myAdm$NAME_1) myAdm <- myAdm[,c("LinjeID","NAME_1")] names(myAdm)[2] <- "adm" ### habitat ################################################ setwd("C:/Users/db40fysa/Dropbox/Alpine/Habitat/Satveg_deling_nd_partnere_09_12_2009/Satveg_deling_nd_partnere_09_12_2009/tiff") library(raster) #project other rasters onto this habitatRasterTop <- raster("NNred25-30-t1.tif")#30 x 30 m habitatRasterTop <- aggregate(habitatRasterTop,fact=5,fun=modal,na.rm=T) habitatRasterBot <- raster("sn25_geocorr.tif") habitatRasterBot <- aggregate(habitatRasterBot,fact=5,fun=modal,na.rm=T) extent(habitatRasterTop) extent(habitatRasterBot) #merge each dataset totalExtent <- c(246285,1342485,6414184,8014594) habitatRasterTop <- extend(habitatRasterTop,extent(totalExtent)) habitatRasterBot <- extend(habitatRasterBot,extent(totalExtent)) origin(habitatRasterBot) <- origin(habitatRasterTop) habitatRaster <- merge(habitatRasterTop,habitatRasterBot) plot(habitatRaster) #yeah!!! #Set NAs for irrelevant habitats habitatRaster[habitatRaster==22] <- NA habitatRaster[habitatRaster>24] <- NA habitatRaster[habitatRaster==0] <- NA plot(habitatRaster) #plot each grid, extract what???? #crop raster to Norway extent myraster <- habitatRaster rasterCRS <- crs(myraster) #get raster values for each polygon myrasterDF <- raster::extract(myraster,Polys_spatial,weights=TRUE, normalizeWeights=FALSE, df=TRUE) #simplify habitat counts myrasterDF$MountainBirchForest <- ifelse(myrasterDF$layer%in%c(6,7,8),1,0) myrasterDF$Bog <- ifelse(myrasterDF$layer%in%c(9,10),1,0) myrasterDF$Forest <- ifelse(myrasterDF$layer%in%c(1:5),1,0) myrasterDF$ODF <- ifelse(myrasterDF$layer%in%c(16,17),1,0) myrasterDF$Meadows <- ifelse(myrasterDF$layer%in%c(18),1,0) myrasterDF$OSF <- ifelse(myrasterDF$layer%in%c(12:15),1,0) myrasterDF$Mire <- ifelse(myrasterDF$layer%in%c(11),1,0) myrasterDF$SnowBeds <- ifelse(myrasterDF$layer%in%c(19,20),1,0) myrasterDF$Open <- ifelse(myrasterDF$layer%in%c(11:20),1,0) myrasterDF$Human <- ifelse(myrasterDF$layer%in%c(23,24),1,0) #aggregate myrasterDF<-ddply(myrasterDF,.(ID),summarise, MountainBirchForest = sum(weight[MountainBirchForest==1])/sum(weight), Bog = sum(weight[Bog==1])/sum(weight), Forest = sum(weight[Forest=1])/sum(weight), ODF = sum(weight[ODF==1])/sum(weight), Meadows = sum(weight[Meadows==1])/sum(weight), OSF = sum(weight[OSF==1])/sum(weight), Mire = sum(weight[Mire==1])/sum(weight), SnowBeds = sum(weight[SnowBeds==1])/sum(weight), Open = sum(weight[Open==1])/sum(weight), Human = sum(weight[Human==1])/sum(weight)) #add line ID myrasterDF$LinjeID <- Polys_spatial$LinjeID ### climate ################################################################################ #average climatic conditions #try the EuroLST dataset setwd("C:/Users/db40fysa/Dropbox/Alpine/Bioclim_LST") #-BIO1: Annual mean temperature (°C*10): eurolst_clim.bio01.zip (MD5) 72MB #-BIO2: Mean diurnal range (Mean monthly (max - min tem)): eurolst_clim.bio02.zip (MD5) 72MB #-BIO3: Isothermality ((bio2/bio7)*100): eurolst_clim.bio03.zip (MD5) 72MB #-BIO4: Temperature seasonality (standard deviation * 100): eurolst_clim.bio04.zip (MD5) 160MB #-BIO5: Maximum temperature of the warmest month (°C*10): eurolst_clim.bio05.zip (MD5) 106MB #-BIO6: Minimum temperature of the coldest month (°C*10): eurolst_clim.bio06.zip (MD5) 104MB #-BIO7: Temperature annual range (bio5 - bio6) (°C*10): eurolst_clim.bio07.zip (MD5) 132MB #-BIO10: Mean temperature of the warmest quarter (°C*10): eurolst_clim.bio10.zip (MD5) 77MB #-BIO11: Mean temperature of the coldest quarter (°C*10): eurolst_clim.bio11.zip (MD5) 78MB #bio1# temp_bio1 <- raster("eurolst_clim.bio01/eurolst_clim.bio01.tif")#res 250 m temp_bio1 <- aggregate(temp_bio1,fact=4,fun=mean,na.rm=T) #extract the data out <- getBufferData(temp_bio1,Polys_spatial) out_Bio1 <- out rm(temp_bio1) rm(out) #maximum temp# temp_bio5 <- raster("eurolst_clim.bio05/eurolst_clim.bio05.tif") temp_bio5 <- aggregate(temp_bio5,fact=4,fun=mean,na.rm=T) out <- getBufferData(temp_bio5,Polys_spatial) out_Bio5 <- out rm(temp_bio5) rm(out) #minimum temp temp_bio6 <- raster("eurolst_clim.bio06/eurolst_clim.bio06.tif") temp_bio6 <- aggregate(temp_bio6,fact=4,fun=mean,na.rm=T) out <- getBufferData(temp_bio6,Polys_spatial) out_Bio6 <- out rm(temp_bio6) rm(out) ### merge ################################################################ #temp data names(out_Bio1)[2]<-"bio1" names(out_Bio5)[2]<-"bio5" names(out_Bio6)[2]<-"bio6" out_Bio<-cbind(out_Bio1,bio5=out_Bio5[,2],bio6=out_Bio6[,2]) #combine others varDF <- merge(out_Bio,myrasterDF,by="LinjeID",all=T) varDF <- merge(varDF,myAdm,by="LinjeID",all=T) #and with distance to coast data names(lineCentres_xy)[3] <- "distCoast" varDF <- merge(varDF,lineCentres_xy,by="LinjeID",all.x=T) ### alpine data ############################################################################# #also get alpine data load("data/alpineData_5kmGrid.RData") #tree line position alpineData$tree_line_position <- alpineData$tree_line-alpineData$elevation alpineData$alpine_habitat1 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==1,1,0)) alpineData$alpine_habitat2 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==2,1,0)) alpineData$alpine_habitat3 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==3,1,0)) alpineData$alpine_habitat4 <- sapply(alpineData$alpine_habitat,function(x)ifelse(x==4,1,0)) #make spatial coordinates(alpineData) <- c("x","y") proj4string(alpineData) <- CRS("+proj=utm +no_defs +zone=33 +a=6378137 +rf=298.257222101 +towgs84=0,0,0,0,0,0,0 +to_meter=1") alpineData <- spTransform(alpineData,crs(equalM)) #overlay with the spatial polgons alpineData$LinjeID <- over(alpineData, Polys_spatial)$LinjeID alpineData <- subset(alpineData,!is.na(LinjeID)) #aggregate to site level library(plyr) alpineData <- ddply(alpineData@data,.(LinjeID),summarise, tree_line_position = median(tree_line_position,na.rm=T), tree_line = median(tree_line,na.rm=T), elevation = median(elevation,na.rm=T), alpine_habitat1 = mean(alpine_habitat1,na.rm=T), alpine_habitat2 = mean(alpine_habitat2,na.rm=T), alpine_habitat3 = mean(alpine_habitat3,na.rm=T), alpine_habitat4 = mean(alpine_habitat4,na.rm=T)) ### merge all ############################################################################## varDF <- merge(varDF,alpineData,by="LinjeID") varDF <- varDF[,-which(names(varDF)=="ID")] ### correlations ############################################################################ #Examine correlations among bugs variables library(GGally) ggpairs(varDF[,c(2:14,23:25)]) #correlations >0.7 #bio1 vs bio6 #x vs y #choose bio6 for line transects ### save ############################################################################# saveRDS(varDF,file="data/varDF_allEnvironData_buffers_idiv.rds") ### end #####################################################<file_sep>/04_HPC_abundance_analysis.R #script to analysis line transect data on the HPC library(tidyverse) library(sp) library(rgeos) library(raster) library(maptools) #specify top level folder #myfolder <- "Data" #on local PC myfolder <- "/data/idiv_ess/ptarmiganUpscaling" #HPC ### ptarmigan data ############################################################### #read in data frame allData <- readRDS(paste(myfolder,"allData.rds",sep="/")) #subset to years of interest - 2008 onwards since many not visited in 2007 allData <- subset(allData,Year>2007 & Year<2018) #remove hyphens for help with subsetting allData$Fylkesnavn <- gsub("-"," ",allData$Fylkesnavn) allData$Fylkesnavn[which(allData$Rapporteringsniva=="Indre Troms")] <- "Troms" #mistake with 1405 - transect length allData$LengdeTaksert[which(allData$LinjeID==1405&allData$LengdeTaksert==1100)] <- 11000 ### remove outliers (see section below) ############################# #LinjeID 1925 has twice as high counts as all others allData <- subset(allData, LinjeID!=1925) #remove LinjeID 131?? -only 503 m long - smallest transect #drop lines visited in less than 5 years - see below allData <- subset(allData, !LinjeID %in% c(935,874,876,882,884,936,2317,2328,2338,878,886,1250,1569,2331,2339)) ### plot data ####################################################### #get lines as a spatial object # library(sf) # library(tmap) # # Lines_spatial <- readRDS("data/Lines_spatial.rds") # Lines_spatial <- subset(Lines_spatial, LinjeID %in% allData$LinjeID) # Lines_spatial <-st_as_sf(Lines_spatial) # Lines_spatial <- st_transform(Lines_spatial, st_crs(NorwayOrigProj)) # # occ_tmap <- tm_shape(NorwayOrigProj) + # tm_borders() + # tm_shape(Lines_spatial)+ # tm_lines(col="skyblue4",lwd=2) # occ_tmap # # saveRDS(occ_tmap,"plots/transects.RDS") ### aggregate data to the lines ###################################### #Get statistics per year and line tlDF <- allData %>% dplyr::group_by(LinjeID,Year) %>% dplyr::summarise(nuGroups = length(totalIndiv[!is.na(totalIndiv)]), totalsInfo = sum(totalIndiv,na.rm=T), groupSize = mean(totalIndiv,na.rm=T), length = mean(LengdeTaksert,na.rm=T)) sum(tlDF$totalsInfo,na.rm=T) #insert NA when there is no transect but evidence of a survey tlDF$length[is.na(tlDF$length)] <- 0 tlDF$nuGroups[tlDF$length==0 ] <- NA tlDF$totalsInfo[tlDF$length==0] <- NA tlDF$groupSize[tlDF$length==0] <- NA summary(tlDF) sum(tlDF$length==0) #### outlier check ################################################## #row/siteIndex 423 is an outlier/LinejeID 1925 # summaryData <- tlDF %>% # group_by(LinjeID) %>% # summarise(med = median(totalsInfo,na.rm=T), # medDensity = median(totalsInfo/length,na.rm=T), # transectlength=mean(length,na.rm=T), # nuObsYears = length(unique(Year[!totalsInfo==0 & !is.na(totalsInfo)])), # nuYears = length(unique(Year[!is.na(totalsInfo)])), # propObsYears = nuObsYears/nuYears) %>% # arrange(desc(med)) # # qplot(summaryData$transectlength,summaryData$medDensity) # qplot(summaryData$nuYears,summaryData$medDensity) # # subset(summaryData,propObsYears<0.3) # # tlDF %>% # group_by(LinjeID) %>% # summarise(nuYears = sum(!is.na(totalsInfo))) %>% # arrange(nuYears) %>% # filter(nuYears <5) # #15 line ### get environ data ################################################# bufferData <- readRDS(paste(myfolder, "varDF_allEnvironData_buffers_idiv.rds",sep="/")) bufferData <- subset(bufferData, !LinjeID %in% c(935,874,876,882,884,936,2317,2328,2338,878,886,1250,1569,2331,2339,1925)) tlDF <- subset(tlDF, LinjeID %in% bufferData$LinjeID) siteInfo_ArtsDaten <- readRDS(paste(myfolder, "siteInfo_ArtsDaten.rds",sep="/")) ### make siteInfo ###################################### tlDF$siteIndex <- as.numeric(as.factor(tlDF$LinjeID)) siteInfo <- unique(tlDF[,c("LinjeID","siteIndex")]) siteInfo <- arrange(siteInfo,siteIndex) siteInfo$adm <- bufferData$adm[match(siteInfo$LinjeID,bufferData$LinjeID)] siteInfo$admN <- as.numeric(as.factor(siteInfo$adm)) ### make arrays ################################################### #cast into arrays groupInfo <- reshape2::acast(tlDF,siteIndex~Year,value.var="nuGroups") totalsInfo <- reshape2::acast(tlDF,siteIndex~Year,value.var="totalsInfo") groupSizes <- reshape2::acast(tlDF,siteIndex~Year,value.var="groupSize") transectLengths <- reshape2::acast(tlDF,siteIndex~Year,value.var="length") sum(as.numeric(totalsInfo),na.rm=T) ### get observed max density ###################################### #transectArea <- (transectLengths/1000 * 0.1 * 2) #summary(totalsInfo/transectArea) ### transect lengths ############################################## #where there is a NA for transect length - put the mean for the line #just for imputation purposes meanTL = apply(transectLengths,1,function(x)median(x[x!=0])) for(i in 1:nrow(transectLengths)){ for(j in 1:ncol(transectLengths)){ transectLengths[i,j] <- ifelse(transectLengths[i,j]==0, meanTL[i], transectLengths[i,j]) } } #check alignment with other datasets all(row.names(groupInfo)==siteInfo$siteIndex) ### site abundances ############################################## # siteSummary <- tlDF %>% # filter(!is.na(totalsInfo)) %>% # group_by(siteIndex) %>% # summarise(nuZeros = sum(totalsInfo==0),meanCount = mean(totalsInfo)) # table(siteSummary$nuZeros) # summary(siteSummary$meanCount) #all above zero # temp <- allData %>% # filter(!is.na(totalIndiv)) %>% # group_by(LinjeID,Year) %>% # summarise(nuIndiv=sum(totalIndiv)) %>% # group_by(LinjeID) %>% # summarise(med = median(nuIndiv)) # # summary(temp$med) ### detection data ################################################ allDetections <- subset(allData, !is.na(totalIndiv) & totalIndiv!=0 & LinjeID %in% bufferData$LinjeID) allDetections$yearIndex <- as.numeric(factor(allDetections$Year)) allDetections$siteIndex <- siteInfo$siteIndex[match(allDetections$LinjeID, siteInfo$LinjeID)] allDetections$admN <- siteInfo$admN[match(allDetections$LinjeID, siteInfo$LinjeID)] #add on admN index to full data frame as same indices siteInfo_ArtsDaten$admNgrouped <- siteInfo$admN[match(siteInfo_ArtsDaten$admGrouped, siteInfo$adm)] #predict possible ESW for all transects - impute for mean value when it is missing meanGS = apply(groupSizes,1,function(x)median(x[!is.na(x)])) for(i in 1:nrow(groupSizes)){ for(j in 1:ncol(groupSizes)){ groupSizes[i,j] <- ifelse(is.na(groupSizes[i,j]), meanGS[i], groupSizes[i,j]) } } ### line-transect index ######################################## #remember: some lines are given the same siteIndex (when they overlap in the same grid) #get mapping from lines to grids siteIndex_linetransects <- readRDS(paste(myfolder,"siteIndex_linetransects.rds",sep="/")) siteIndex_linetransects <- siteIndex_linetransects %>% ungroup() %>% filter(LinjeID %in% siteInfo$LinjeID) siteIndex_linetransects$siteIndex_All <- as.numeric(as.factor(siteIndex_linetransects$siteIndex_All)) summary(siteIndex_linetransects$siteIndex_All) #302 grids are sampled #map indices to siteInfo for line transects siteInfo$siteIndex_All <- siteIndex_linetransects$siteIndex_All[match(siteInfo$LinjeID, siteIndex_linetransects$LinjeID)] summary(siteInfo$siteIndex_All) #map indices to siteInfo_ArtsDaten for grid data siteInfo_ArtsDaten$siteIndex_All <- siteIndex_linetransects$siteIndex_All[match(siteInfo_ArtsDaten$grid,siteIndex_linetransects$grid)] summary(siteInfo_ArtsDaten$siteIndex_All) siteInfo_ArtsDaten <- plyr::arrange(siteInfo_ArtsDaten,siteIndex_All) #fill in unsampled ones with indices nuMissing <- sum(is.na(siteInfo_ArtsDaten$siteIndex_All)) maxIndex <- max(siteIndex_linetransects$siteIndex_All) siteInfo_ArtsDaten$siteIndex_All[is.na(siteInfo_ArtsDaten$siteIndex_All)] <- (maxIndex+1):(maxIndex + nuMissing) summary(siteInfo_ArtsDaten$siteIndex_All) #arrange siteInfo <- siteInfo %>% arrange(siteIndex) siteInfo_ArtsDaten <- siteInfo_ArtsDaten %>% arrange(siteIndex_All) ### make bugs objects ########################################### bugs.data <- list(#For the state model nsite = length(unique(siteInfo$siteIndex)), nsiteAll = length(unique(siteInfo_ArtsDaten$siteIndex_All)), nyear = length(unique(allData$Year)), nadm = length(unique(siteInfo$admN)), site = siteInfo$siteIndex, siteAll = siteInfo$siteIndex_All, adm = siteInfo$admN, pred.adm = siteInfo_ArtsDaten$admNgrouped, NuIndivs = totalsInfo, TransectLength = transectLengths, #For the distance model W = 200, ndetections = nrow(allDetections), y = allDetections$LinjeAvstand, ln_GroupSize = log(allDetections$totalIndiv+1), GroupSizes = groupSizes, detectionYear = allDetections$yearIndex, detectionSite = allDetections$siteIndex, detectionAdm = allDetections$admN, zeros.dist = rep(0,nrow(allDetections))) names(bugs.data) ### get environ data ######################################### all(bufferData$LinjeID==siteInfo$LinjeID) myVars <- c("bio1", "bio5","y","bio6","MountainBirchForest", "Bog","ODF", "Meadows","OSF","Mire","SnowBeds", "tree_line_position","tree_line","distCoast","elevation") # scale them bufferData <- bufferData[,c("LinjeID",myVars)] bufferMeans <- as.numeric(apply(bufferData,2,mean)) bufferSD <- as.numeric(apply(bufferData,2,sd)) for(i in 2:ncol(bufferData)){ bufferData[,i] <- (bufferData[,i] - bufferMeans[i])/bufferSD[i] } #also for the siteInfo_ArtsDaten with same scaling siteInfo_ArtsDaten <- siteInfo_ArtsDaten[,c("grid",myVars)] for(i in 2:(ncol(siteInfo_ArtsDaten)-1)){#dont scale elevation siteInfo_ArtsDaten[,i] <- (siteInfo_ArtsDaten[,i] - bufferMeans[i])/bufferSD[i] } #saveRDS(siteInfo_ArtsDaten, file="data/siteInfo_AbundanceModels.rds") ### choose model ############################################## modelTaskID <- read.delim(paste(myfolder,"modelTaskID_distanceModel.txt",sep="/"),as.is=T) #get task id task.id = as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID", "1")) #get model for this task mymodel <- modelTaskID$Model[which(modelTaskID$TaskID==task.id)] ### standard model ########################################### #variables selected based on first simple analyses if(mymodel == "linetransectModel_variables.txt"){ #add new variables to the bugs data bugs.data$occDM <- model.matrix(~ bufferData$bio6 + bufferData$bio5 + bufferData$tree_line + I(bufferData$tree_line^2))[,-1] #predictions to full grid bugs.data$predDM <- model.matrix(~ siteInfo_ArtsDaten$bio6 + siteInfo_ArtsDaten$bio5 + siteInfo_ArtsDaten$tree_line + I(siteInfo_ArtsDaten$tree_line^2))[,-1] ### indicator model selection ################################ #all linear and select quadratic } else { bugs.data$occDM <- model.matrix(~ bufferData$bio6 + bufferData$bio5 + bufferData$y + bufferData$distCoast + bufferData$tree_line + bufferData$MountainBirchForest + bufferData$Bog + bufferData$ODF + bufferData$Meadows + bufferData$OSF + bufferData$Mire + bufferData$SnowBeds + I(bufferData$bio6^2) + I(bufferData$bio5^2) + I(bufferData$y^2) + I(bufferData$distCoast^2) + I(bufferData$tree_line^2) + I(bufferData$MountainBirchForest^2) + I(bufferData$Bog^2) + I(bufferData$ODF^2) + I(bufferData$Meadows^2) + I(bufferData$OSF^2) + I(bufferData$Mire^2) + I(bufferData$SnowBeds^2))[,-1] # #predictions to full grid bugs.data$predDM <- model.matrix(~ siteInfo_ArtsDaten$bio6 + siteInfo_ArtsDaten$bio5 + siteInfo_ArtsDaten$y + siteInfo_ArtsDaten$distCoast + siteInfo_ArtsDaten$tree_line + siteInfo_ArtsDaten$MountainBirchForest + siteInfo_ArtsDaten$Bog + siteInfo_ArtsDaten$ODF + siteInfo_ArtsDaten$Meadows + siteInfo_ArtsDaten$OSF + siteInfo_ArtsDaten$Mire + siteInfo_ArtsDaten$SnowBeds + I(siteInfo_ArtsDaten$bio6^2) + I(siteInfo_ArtsDaten$bio5^2) + I(siteInfo_ArtsDaten$y^2) + I(siteInfo_ArtsDaten$distCoast^2) + I(siteInfo_ArtsDaten$tree_line^2) + I(siteInfo_ArtsDaten$MountainBirchForest^2) + I(siteInfo_ArtsDaten$Bog^2) + I(siteInfo_ArtsDaten$ODF^2) + I(siteInfo_ArtsDaten$Meadows^2) + I(siteInfo_ArtsDaten$OSF^2) + I(siteInfo_ArtsDaten$Mire^2) + I(siteInfo_ArtsDaten$SnowBeds^2))[,-1] } # myvars <- c("y",'bio6',"bio6_2","distCoast","distCoast_2", # "bio5","bio5_2","tree_line","tree_line_2","OSF","SnowBeds") # # myvars <- c("bio6","bio5","distCoast","tree_line","MountainBirchForest", # "Bog","ODF","Meadows","OSF","Mire","SnowBeds", # "bio6_2","bio5_2","distCoast_2","tree_line_2","MountainBirchForest_2", # "Bog_2","ODF_2","Meadows_2","OSF_2","Mire_2","SnowBeds_2") bugs.data$n.covs <- ncol(bugs.data$occDM) bugs.data$n.preds <- dim(bugs.data$predDM)[1] #saveRDS(bugs.data, file="data/bugs.data_linetransects.rds") ### fit model ################################################# library(rjags) library(jagsUI) params <- c("int.d","beta","g","r", "b.group.size","meanESW", "meanDensity","Density.p","exp.j", "bpv","MAD","expNuIndivs") #choose model - already done above now #modelfile <- paste(myfolder,"linetransectModel_variables.txt",sep="/") #modelfile <- paste(myfolder,"linetransectModel_variables_LASSO.txt",sep="/") #modelfile <- paste(myfolder,"linetransectModel_variables_ModelSelection.txt",sep="/") modelfile <- paste(myfolder,mymodel,sep="/") #n.cores = as.integer(Sys.getenv("NSLOTS", "1")) n.cores = as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1")) #n.cores = 3 n.iterations = 50000 Sys.time() out1 <- jags(bugs.data, inits=NULL, params, modelfile, n.thin=50, n.chains=n.cores, n.burnin=n.iterations/2, n.iter=n.iterations, parallel=T) saveRDS(out1$summary,file=paste0("outSummary_linetransectModel_variables_",task.id,".rds")) print("Done main model") Sys.time() ### summary ################################################### temp <- data.frame(out1$summary) temp$Param <- row.names(temp) #look at MAD for each year for(i in 1:bugs.data$nyear){ mypattern <- paste0(",",i,"]") temp_train <- subset(temp, grepl("expNuIndivs", temp$Param)) temp_train <- subset(temp_train, grepl(mypattern, temp_train$Param))$mean data_train <- bugs.data$NuIndivs[,i] message(paste("Results in year", i, sep=" ")) print(summary(abs(data_train[!is.na(data_train)] - temp_train[!is.na(data_train)]))) print(cor(data_train[!is.na(data_train)],temp_train[!is.na(data_train)])) } print("Simple stats done now") ### samples ####################################################### library(ggmcmc) ggd <- ggs(out1$samples) out1_dataset <- subset(ggd,grepl("expNuIndivs",ggd$Parameter)) out1_dataset <- subset(out1_dataset,grepl(",6]",out1_dataset$Parameter)) out1_dataset$index <- as.numeric(interaction(out1_dataset$Iteration,out1_dataset$Chain)) #get actual NuIndiv totalsInfo_mid <- bugs.data$NuIndivs[,6] #get difference between this value and the simulated values mad_dataset <- as.numeric() rmse_dataset <- as.numeric() n.index <- max(out1_dataset$index) useData <- !is.na(totalsInfo_mid) for(i in 1:n.index){ mad_dataset[i] <- mean(abs(totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])) rmse_dataset[i] <- sqrt(mean((totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])^2)) } summary(mad_dataset) summary(rmse_dataset) saveRDS(summary(mad_dataset),file=paste0("MAD_linetransectModel_variables_",task.id,".rds")) saveRDS(summary(rmse_dataset),file=paste0("RMSE_linetransectModel_variables_",task.id,".rds")) print("Done model assessment") ### get site and year predictions ############################ out2 <- update(out1, parameters.to.save = c("Density.pt"),n.iter=10000, n.thin=50) #summary saveRDS(out2$summary,file=paste0("Density.pt_Summary_linetransectModel_variables_",task.id,".rds")) #and samples ggd <- ggs(out2$samples) saveRDS(ggd,file=paste0("Density.pt_linetransectModel_variables_",task.id,".rds")) print("end") ### end ####################################################### <file_sep>/08_uncertainty_analysis.R library(tidyverse) modelPredictions <- readRDS("data/modelPredictions.rds") #total nationwide abundance is just: sum(modelPredictions$occ_mean * modelPredictions$density_mean)#yep, about right #1168194 ### occupancy #### resampleOcc <- function(modelPredictions,focalGrid){ nonfocalDensity <- modelPredictions$occ_mean[-focalGrid]*modelPredictions$density_mean[-focalGrid] focalDensity <- modelPredictions$density_mean[focalGrid] totalNu <- as.numeric() for(i in 1:1000){ newOccSample <- rnorm(1,modelPredictions$occ_mean[focalGrid],modelPredictions$occ_sd[focalGrid]) totalNu[i] <- sum(nonfocalDensity,newOccSample*focalDensity) } data.frame(grid=focalGrid,meanPop=mean(totalNu),medianPop=median(totalNu),sdPop=sd(totalNu)) } #apply function to each grid sensitivityOcc <- 1:nrow(modelPredictions) %>% map_dfr(~resampleOcc(modelPredictions,focalGrid=.x)) sensitivityOcc$x <- varDF$x sensitivityOcc$y <- varDF$y qplot(x,y, data=sensitivityOcc, colour = meanPop)+ scale_colour_viridis_c() qplot(x,y, data=sensitivityOcc, colour = sdPop)+ scale_colour_viridis_c() qplot(x,y, data=modelPredictions, colour = occ_sd)+ scale_colour_viridis_c() mygrid[] <- NA mygrid[varDF$grid] <- sensitivityOcc$sdPop crs(mygrid) <- equalM t1 <- tm_shape(mygrid)+ tm_raster(title="Occupancy SD",palette="Spectral", style="cont", breaks=c(0,50,75,100,125,150)) modelPredictions$sdPop <- sensitivityOcc$sdPop qplot(occ_mean, occ_sd, data=modelPredictions,colour=log(sdPop))+ scale_colour_viridis_c() qplot(occ_mean, occ_sd, data=subset(modelPredictions,log(sdPop)>3.9),colour=log(sdPop))+ scale_colour_viridis_c() ### abundance model #### resampleDensity <- function(modelPredictions,focalGrid){ nonfocalDensity <- modelPredictions$occ_mean[-focalGrid]*modelPredictions$density_mean[-focalGrid] focalOcc<- modelPredictions$occ_mean[focalGrid] totalNu <- as.numeric() for(i in 1:1000){ newDensitySample <- rnorm(1,modelPredictions$density_mean[focalGrid],modelPredictions$density_sd[focalGrid]) totalNu[i] <- sum(nonfocalDensity,newDensitySample*focalOcc) } data.frame(grid=focalGrid,meanPop=mean(totalNu),medianPop=median(totalNu),sdPop=sd(totalNu)) } #apply function to each grid sensitivityDensity <- 1:nrow(modelPredictions) %>% map_dfr(~resampleDensity(modelPredictions,focalGrid=.x)) sensitivityDensity$x <- varDF$x sensitivityDensity$y <- varDF$y qplot(x,y, data=sensitivityDensity, colour = meanPop)+ scale_colour_viridis_c() qplot(x,y, data=sensitivityDensity, colour = sdPop)+ scale_colour_viridis_c() qplot(x,y, data=modelPredictions, colour = density_sd)+ scale_colour_viridis_c() mygrid[] <- NA mygrid[varDF$grid] <- sensitivityDensity$sdPop crs(mygrid) <- equalM t2 <- tm_shape(mygrid)+ tm_raster(title="Density SD ",palette="Spectral", style="cont", breaks=c(0,50,75,100,125,150)) ### combine #### tmaptools::palette_explorer() tmap_arrange(t1,t2,nrow=1) median(sensitivityDensity$sdPop) median(sensitivityOcc$sdPop) temp <- tmap_arrange(t1,t2,nrow=1) temp tmap_save(temp, "plots/Fig_6.png",width = 6, height = 4) ### end ####################################### <file_sep>/05_HPC_abundance_cross_validation.R #script to analysis line transect data on the HPC library(tidyverse) library(sp) library(rgeos) library(raster) library(maptools) #specify top level folder #myfolder <- "Data" #on local PC myfolder <- "/data/idiv_ess/ptarmiganUpscaling" #HPC ### ptarmigan data ############################################################### #read in data frame allData <- readRDS(paste(myfolder,"allData.rds",sep="/")) #subset to years of interest - 2008 onwards allData <- subset(allData,Year>2007 & Year<2018) #remove hyphens for help with subsetting allData$Fylkesnavn <- gsub("-"," ",allData$Fylkesnavn) allData$Fylkesnavn[which(allData$Rapporteringsniva=="Indre Troms")] <- "Troms" #mistake with 1405 - transect length allData$LengdeTaksert[which(allData$LinjeID==1405&allData$LengdeTaksert==1100)] <- 11000 ### remove outliers (see section below) ############################# #LinjeID 1925 has twice as high counts as all others allData <- subset(allData, LinjeID!=1925) #remove LinjeID 131?? -only 503 m long - smallest transect #drop lines visited in less than 5 years - see below allData <- subset(allData, !LinjeID %in% c(935,874,876,882,884,936,2317,2328,2338,878,886,1250,1569,2331,2339)) ### aggregate data to the lines ###################################### #Get statistics per year and line tlDF <- allData %>% dplyr::group_by(LinjeID,Year) %>% dplyr::summarise(nuGroups = length(totalIndiv[!is.na(totalIndiv)]), totalsInfo = sum(totalIndiv,na.rm=T), groupSize = mean(totalIndiv,na.rm=T), length = mean(LengdeTaksert,na.rm=T)) sum(tlDF$totalsInfo,na.rm=T) #insert NA when there is no transect but evidence of a survey tlDF$length[is.na(tlDF$length)] <- 0 tlDF$nuGroups[tlDF$length==0 ] <- NA tlDF$totalsInfo[tlDF$length==0] <- NA tlDF$groupSize[tlDF$length==0] <- NA summary(tlDF) sum(tlDF$length==0) ### get environ data ################################################# bufferData <- readRDS(paste(myfolder, "varDF_allEnvironData_buffers_idiv.rds",sep="/")) bufferData <- subset(bufferData, !LinjeID %in% c(935,874,876,882,884,936,2317,2328,2338,878,886,1250,1569,2331,2339,1925)) tlDF <- subset(tlDF, LinjeID %in% bufferData$LinjeID) siteInfo_ArtsDaten <- readRDS(paste(myfolder, "siteInfo_ArtsDaten.rds",sep="/")) ### make siteInfo ###################################### tlDF$siteIndex <- as.numeric(as.factor(tlDF$LinjeID)) siteInfo <- unique(tlDF[,c("LinjeID","siteIndex")]) siteInfo <- arrange(siteInfo,siteIndex) siteInfo$adm <- bufferData$adm[match(siteInfo$LinjeID,bufferData$LinjeID)] siteInfo$admN <- as.numeric(as.factor(siteInfo$adm)) ### choose model ############################################## modelTaskID <- read.delim(paste(myfolder,"modelTaskID_distanceModel_CV.txt",sep="/"),as.is=T) #get task id task.id = as.integer(Sys.getenv("SLURM_ARRAY_TASK_ID", "1")) #get model for this task mymodel <- modelTaskID$Model[which(modelTaskID$TaskID==task.id)] mymodel ### folds ######################################################## folds <- readRDS(paste(myfolder,"folds_distanceModel_bands.rds",sep="/")) siteInfo$fold <- folds$fold[match(siteInfo$LinjeID,folds$LinjeID)] #select fold of this task fold.id = modelTaskID$Fold[which(modelTaskID$TaskID==task.id)] #split into test and train siteInfo_test <- subset(siteInfo,fold == fold.id) siteInfo_train<- subset(siteInfo,fold != fold.id) tlDF_train <- subset(tlDF,siteIndex %in% siteInfo_train$siteIndex) tlDF_test <- subset(tlDF,siteIndex %in% siteInfo_test$siteIndex) ### make arrays ################################################### #cast into arrays groupInfo <- reshape2::acast(tlDF_train,siteIndex~Year,value.var="nuGroups") totalsInfo <- reshape2::acast(tlDF_train,siteIndex~Year,value.var="totalsInfo") groupSizes <- reshape2::acast(tlDF_train,siteIndex~Year,value.var="groupSize") transectLengths <- reshape2::acast(tlDF_train,siteIndex~Year,value.var="length") #check alignment with other datasets all(row.names(groupInfo)==siteInfo_train$siteIndex) ### detection data ################################################ allDetections <- subset(allData, !is.na(totalIndiv) & totalIndiv!=0 & LinjeID %in% siteInfo_train$LinjeID) allDetections$yearIndex <- as.numeric(factor(allDetections$Year)) allDetections$siteIndex <- siteInfo$siteIndex[match(allDetections$LinjeID, siteInfo$LinjeID)] #same for testing dataset groupSizes_test <- reshape2::acast(tlDF_test,siteIndex~Year,value.var="groupSize") transectLengths_test <- reshape2::acast(tlDF_test,siteIndex~Year,value.var="length") totalsInfo_test <- reshape2::acast(tlDF_test,siteIndex~Year,value.var="totalsInfo") ### group sizes ################################################### #predict possible ESW for all transects - impute for mean value when it is missing meanGS = apply(groupSizes,1,function(x)median(x[!is.na(x)])) for(i in 1:nrow(groupSizes)){ for(j in 1:ncol(groupSizes)){ groupSizes[i,j] <- ifelse(is.na(groupSizes[i,j]), meanGS[i], groupSizes[i,j]) } } meanGS_test = apply(groupSizes_test,1,function(x)median(x[!is.na(x)])) for(i in 1:nrow(groupSizes_test)){ for(j in 1:ncol(groupSizes_test)){ groupSizes_test[i,j] <- ifelse(is.na(groupSizes_test[i,j]), meanGS_test[i], groupSizes_test[i,j]) } } ### make bugs objects ########################################### bugs.data <- list(#For the state model nsite_train = length(unique(siteInfo_train$siteIndex)), nsite_test = length(unique(siteInfo_test$siteIndex)), nyear = length(unique(allData$Year)), nadm = length(unique(siteInfo$admN)), site = siteInfo$siteIndex, adm = siteInfo$admN, NuIndivs = totalsInfo, TransectLength_train = transectLengths, TransectLength_test = transectLengths_test, #For the distance model W = 200, ndetections_train = nrow(allDetections), y = allDetections$LinjeAvstand, ln_GroupSize = log(allDetections$totalIndiv+1), groupSizes_train = groupSizes, groupSizes_test = groupSizes_test, zeros.dist = rep(0,nrow(allDetections))) names(bugs.data) ### scale vars ################################################ bufferData[,-1] <- plyr::numcolwise(scale)(bufferData[,-1]) #train dataset bufferData_train <- subset(bufferData,LinjeID %in% siteInfo_train$LinjeID) all(siteInfo_train$LinjeID==bufferData_train$LinjeID) #test dataset bufferData_test <- subset(bufferData,LinjeID %in% siteInfo_test$LinjeID) all(siteInfo_test$LinjeID==bufferData_test$LinjeID) ### standard model ########################################### #variables selected based on first simple analyses if(mymodel == "linetransectModel_variables_CV.txt"){ #add new variables to the bugs data bugs.data$occDM_train <- model.matrix(~ bufferData_train$bio6 + bufferData_train$bio5 + bufferData_train$tree_line + I(bufferData_train$tree_line^2))[,-1] #predictions to full grid bugs.data$occDM_test <- model.matrix(~ bufferData_test$bio6 + bufferData_test$bio5 + bufferData_test$tree_line + I(bufferData_test$tree_line^2))[,-1] ### indicator model selection ################################ #or lasso #all linear and select quadratic } else { bugs.data$occDM_train <- model.matrix(~ bufferData_train$bio6 + bufferData_train$bio5 + bufferData_train$y + bufferData_train$distCoast + bufferData_train$tree_line + bufferData_train$MountainBirchForest + bufferData_train$Bog + bufferData_train$ODF + bufferData_train$Meadows + bufferData_train$OSF + bufferData_train$Mire + bufferData_train$SnowBeds + I(bufferData_train$bio6^2) + I(bufferData_train$bio5^2) + I(bufferData_train$y^2) + I(bufferData_train$distCoast^2) + I(bufferData_train$tree_line^2) + I(bufferData_train$MountainBirchForest^2) + I(bufferData_train$Bog^2) + I(bufferData_train$ODF^2) + I(bufferData_train$Meadows^2) + I(bufferData_train$OSF^2) + I(bufferData_train$Mire^2) + I(bufferData_train$SnowBeds^2))[,-1] # #predictions to full grid bugs.data$occDM_test <- model.matrix(~ bufferData_test$bio6 + bufferData_test$bio5 + bufferData_test$y + bufferData_test$distCoast + bufferData_test$tree_line + bufferData_test$MountainBirchForest + bufferData_test$Bog + bufferData_test$ODF + bufferData_test$Meadows + bufferData_test$OSF + bufferData_test$Mire + bufferData_test$SnowBeds + I(bufferData_test$bio6^2) + I(bufferData_test$bio5^2) + I(bufferData_test$y^2) + I(bufferData_test$distCoast^2) + I(bufferData_test$tree_line^2) + I(bufferData_test$MountainBirchForest^2) + I(bufferData_test$Bog^2) + I(bufferData_test$ODF^2) + I(bufferData_test$Meadows^2) + I(bufferData_test$OSF^2) + I(bufferData_test$Mire^2) + I(bufferData_test$SnowBeds^2))[,-1] } bugs.data$n.covs <- ncol(bugs.data$occDM_train) ### fit model ################################################# library(rjags) library(jagsUI) params <- c("int.d","line.d.sd","year.d.sd","beta", "mid.expNuIndivs_train","mid.expNuIndivs_test", "mean.expNuIndivs_train","mean.expNuIndivs_test") modelfile <- paste(myfolder,mymodel,sep="/") n.iterations <- 50000 n.cores = as.integer(Sys.getenv("SLURM_CPUS_PER_TASK", "1")) Sys.time() out1 <- jags(bugs.data, inits=NULL, params, modelfile, n.thin=50, n.chains=n.cores, n.burnin=n.iterations/2, n.iter=n.iterations, parallel=T) saveRDS(out1$summary,file="outSummary_linetransectModel_CV.rds") Sys.time() print("Done main model") ### summary annual ################################### temp <- data.frame(out1$summary) temp$Param <- row.names(temp) #train temp_train <- subset(temp, grepl("mid.expNuIndivs_train", temp$Param))$mean data_train <- bugs.data$NuIndivs[,6] mean(abs(data_train[!is.na(data_train)] - temp_train[!is.na(data_train)])) cor.test(data_train[!is.na(data_train)],temp_train[!is.na(data_train)]) #test temp_test <- subset(temp, grepl("mid.expNuIndivs_test", temp$Param))$mean data_test <- totalsInfo_test[,6] mean(abs(data_test[!is.na(data_test)] - temp_test[!is.na(data_test)])) cor.test(data_test[!is.na(data_test)],temp_test[!is.na(data_test)]) print("Simple annual stats done now") ### summary mean ############################# temp_train <- subset(temp, grepl("mean.expNuIndivs_train", temp$Param))$mean data_train <- as.numeric(apply(bugs.data$NuIndivs,1,mean,na.rm=T)) mean(abs(data_train[!is.na(data_train)] - temp_train[!is.na(data_train)])) cor.test(data_train[!is.na(data_train)],temp_train[!is.na(data_train)]) #test temp_test <- subset(temp, grepl("mean.expNuIndivs_test", temp$Param))$mean data_test <- as.numeric(apply(totalsInfo_test,1,mean,na.rm=T)) mean(abs(data_test[!is.na(data_test)] - temp_test[!is.na(data_test)])) cor.test(data_test[!is.na(data_test)],temp_test[!is.na(data_test)]) print("Simple mean stats done now") ### annual samples ################################### library(ggmcmc) ggd <- ggs(out1$samples) #train out1_dataset <- subset(ggd,grepl("mid.expNuIndivs_train",ggd$Parameter)) out1_dataset$index <- as.numeric(interaction(out1_dataset$Iteration,out1_dataset$Chain)) #get actual NuIndiv totalsInfo_mid <- as.numeric(totalsInfo[,6]) useData <- !is.na(totalsInfo_mid) #get difference between this value and the simulated values mad_dataset <- as.numeric() rmse_dataset <- as.numeric() n.index <- max(out1_dataset$index) for(i in 1:n.index){ mad_dataset[i] <- mean(abs(totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])) rmse_dataset[i] <- sqrt(mean((totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])^2)) } summary(mad_dataset) summary(rmse_dataset) saveRDS(summary(mad_dataset),file=paste0("MAD_train_linetransectModel_CV_",task.id,".rds")) saveRDS(summary(rmse_dataset),file=paste0("RMSE_train_linetransectModel_CV_",task.id,".rds")) #test out1_dataset <- subset(ggd,grepl("mid.expNuIndivs_test",ggd$Parameter)) out1_dataset$index <- as.numeric(interaction(out1_dataset$Iteration,out1_dataset$Chain)) #get actual NuIndiv totalsInfo_mid <- as.numeric(totalsInfo_test[,6]) useData <- !is.na(totalsInfo_mid) #get difference between this value and the simulated values mad_dataset <- as.numeric() rmse_dataset <- as.numeric() n.index <- max(out1_dataset$index) for(i in 1:n.index){ mad_dataset[i] <- mean(abs(totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])) rmse_dataset[i] <- sqrt(mean((totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])^2)) } summary(mad_dataset) summary(rmse_dataset) saveRDS(summary(mad_dataset),file=paste0("MAD_test_linetransectModel_CV_",task.id,".rds")) saveRDS(summary(rmse_dataset),file=paste0("RMSE_test_linetransectModel_CV_",task.id,".rds")) ### mean samples ################################### library(ggmcmc) ggd <- ggs(out1$samples) #train out1_dataset <- subset(ggd,grepl("mean.expNuIndivs_train",ggd$Parameter)) out1_dataset$index <- as.numeric(interaction(out1_dataset$Iteration,out1_dataset$Chain)) #get actual NuIndiv totalsInfo_mid <- as.numeric(apply(totalsInfo,1,mean,na.rm=T)) useData <- !is.na(totalsInfo_mid) #get difference between this value and the simulated values mad_dataset <- as.numeric() rmse_dataset <- as.numeric() n.index <- max(out1_dataset$index) for(i in 1:n.index){ mad_dataset[i] <- mean(abs(totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])) rmse_dataset[i] <- sqrt(mean((totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])^2)) } summary(mad_dataset) summary(rmse_dataset) saveRDS(summary(mad_dataset),file=paste0("mMAD_train_linetransectModel_CV_",task.id,".rds")) saveRDS(summary(rmse_dataset),file=paste0("mRMSE_train_linetransectModel_CV_",task.id,".rds")) #test out1_dataset <- subset(ggd,grepl("mean.expNuIndivs_test",ggd$Parameter)) out1_dataset$index <- as.numeric(interaction(out1_dataset$Iteration,out1_dataset$Chain)) #get actual NuIndiv totalsInfo_mid <- as.numeric(apply(totalsInfo_test,1,mean,na.rm=T)) useData <- !is.na(totalsInfo_mid) #get difference between this value and the simulated values mad_dataset <- as.numeric() rmse_dataset <- as.numeric() n.index <- max(out1_dataset$index) for(i in 1:n.index){ mad_dataset[i] <- mean(abs(totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])) rmse_dataset[i] <- sqrt(mean((totalsInfo_mid[useData] - out1_dataset$value[out1_dataset$index==i][useData])^2)) } summary(mad_dataset) summary(rmse_dataset) saveRDS(summary(mad_dataset),file=paste0("mMAD_test_linetransectModel_CV_",task.id,".rds")) saveRDS(summary(rmse_dataset),file=paste0("mRMSE_test_linetransectModel_CV_",task.id,".rds")) print("End") ### end ########################################################################
da023fd8498e4216bea90093c858fc339cebc9e3
[ "Markdown", "R" ]
17
R
bowlerbear/ptarmiganUpscaling
3283d62795edecb672613b87c1c5b92df69e2222
92e48762edba81dcf488300bb8cb67e87a418209
refs/heads/master
<repo_name>nahlahani/Register-Login-Angular2<file_sep>/src/app/user.ts export class User { id: number; username: string; passsword: <PASSWORD>; pp: string; constructor( public userName = '', public password = '', public profilePic = '' ) { } }
2e1c4510c9543f8b7824f29151d169717ceca650
[ "TypeScript" ]
1
TypeScript
nahlahani/Register-Login-Angular2
02214f46144893be2ff044526554565c93e659f7
507886c887af08867fc77d4a05f1bacaf554c93d
refs/heads/master
<file_sep>public class Main { public static int arraySum(String[][] twoDimensionalArray) throws MyArraySizeException, MyArrayDataException { if (twoDimensionalArray.length != 4) { throw new MyArraySizeException("Длина массива != 4"); } for (String[] array : twoDimensionalArray) { if (array.length != 4) { throw new MyArraySizeException("Высота массива != 4"); } } int sum = 0; for (int i = 0; i < twoDimensionalArray.length; i++) { for (int j = 0; j < twoDimensionalArray[i].length; j++) { try { sum += Integer.parseInt(twoDimensionalArray[i][j]); } catch (NumberFormatException e) { throw new MyArrayDataException("Не число в элементе:" + i + "," + j); } } } return sum; } public static void main(String[] args) { String[][] successArray = {{"2", "3", "6", "12"}, {"13", "43", "555", "16"}, {"91", "3", "8", "6", "7"}, {"3", "3", "35", "3"}}; Integer[][] array = new Integer[4][]; array[0] = new Integer[4]; array[0] = new Integer[5]; array[0] = new Integer[4]; try { System.out.println(arraySum(successArray)); } catch (MyArraySizeException e) { e.printStackTrace(); } catch (MyArrayDataException e) { e.printStackTrace(); } String[][] invalidDataArray = {{"111", "332", "545", "612"}, {"12", "6rg", "53", "64"}, {"1", "3", "5", "65"}, {"7", "9", "09", "34"}}; try { System.out.println(arraySum(invalidDataArray)); } catch (MyArraySizeException e) { e.printStackTrace(); } catch (MyArrayDataException e) { e.printStackTrace(); } } }
de8011dd50f2bac6490c67ce4f116e1522546833
[ "Java" ]
1
Java
PavelEfanov/Lesson2_Core
42cd494d8946a19d929217b0d6cd647c32618728
36c12616010976783b6ee3aa07fd6dc34b185312
refs/heads/master
<file_sep>// import React, { useState } from 'react' import React from 'react' import './App.css' // import { create } from 'domain' // import * as R from 'ramda' // import { Alert, Row, Form, FormControl, Nav, Navbar } from 'react-bootstrap' import { CreateTodoContainer } from './containers/create' import { TodosContainer } from './containers/todos' import { FiltersContainer } from './containers/filters' /* const doneLens = R.lensProp('done') const taskLens = R.lensProp('task') const Todo = ({ todo, idx, toggleDone, removeTodo }) => ( <Row className='justify-content-md-center'> <Alert variant='info'> { <InputGroup.Prepend> <InputGroup.Checkbox /> </InputGroup.Prepend> <FormControl> </FormControl> <InputGroup.Append> <InputGroup.Text>x</InputGroup.Text> </InputGroup.Append> } <input type='checkbox' checked={ todo.done } onChange={ () => toggleDone(idx) }></input> <p style={{display: 'inline', margin: '0 1.5vw', color: todo.done? 'grey':'black', textDecoration: todo.done? 'line-through': ''}}> { todo.task }</p> <input type='button' value='x' onClick={ () => removeTodo(idx) }></input> </Alert> </Row> ) // export const CreateTodo = ({ setTodo, submitTodo }) => ( // <div className='bg-info'> // <form className='p-3' onSubmit={ submitTodo }> // <input placeholder='add a new todo' onChange={ e => setTodo(e.target.value) } /> // <input type='submit' value='create' /> // </form> // </div> // ) // const CreateTodoContainer = ({ todoList, setTodoList }) => { // const [todo, setTodo] = useState('') // const createTodo = task => { // // const newList = [ ...todoList, { task } ] // const newList = R.append({ task, done: false }, todoList) // setTodoList(newList) // } // const submitTodo = (e) => { // e.preventDefault() // prevent reverting to default // createTodo(todo) // } // return <CreateTodo setTodo={ setTodo } submitTodo={ submitTodo } /> // } const App = ({ todoList, setTodoList, toggleDone, removeTodo, filterDone, setSearchStr }) => ( <div className='App mt-0'> {// <CreateTodoContainer todoList={ todoList } setTodoList={ setTodoList } /> } <CreateTodoContainer /> <header className='App-header mt-0'> <p className='mt-3'> React To-do List </p> <Navbar bg='info' expand='lg'> // { <Navbar.Brand href='#home'>My To-do List</Navbar.Brand> } <Navbar.Toggle aria-controls='basic-navbar-nav' /> <Navbar.Collapse id='basic-navbar-nav'> <Nav.Link className='text-black-50' onClick={ filterDone }>show/hide done todos</Nav.Link> <Form inline> <FormControl id='searchForm' type='text' placeholder='Search' className='mr-sm-2' onChange={ e => setSearchStr(e.target.value) } /> { <Button variant='outline-dark' type='submit'>Search</Button> } </Form> </Navbar.Collapse> </Navbar> </header> <div> { todoList.map((todo, idx) => <Todo todo={ todo } idx={ todo.idx } toggleDone={ toggleDone } removeTodo={ removeTodo } key={ `todo-${idx}` } />) } </div> </div> ) const AppContainer = () => { const [todoList, setTodoList] = useState([{ task: 'Do laundry', done: false }, { task: 'Take out trash', done: false }]) const [hide, setHide] = useState(false) const [searchStr, setSearchStr] = useState('') const toggleDone = (idx) => { const newList = [ ...todoList ] // newList[idx].done = R.not(newList[idx].done) newList[idx] = R.over(doneLens, R.not, newList[idx]) setTodoList(newList) } const removeTodo = (idx) => { const newList = R.remove(idx, 1, todoList) // const newList = R.without([R.nth(idx, todoList)], todoList) // const nthSingleton = (idx, list) => [R.nth(idx, list)] // creates list only containing nth elem // const removeNth = R.compose(R.without, nthSingleton) // doesn't take args for some reason? // const newList = removeNth(idx, todoList) setTodoList(newList) } const filteredList = R.pipe( todos => todos.map((todo, idx) => R.assoc('idx', idx, todo)), R.reject(hide ? R.view(doneLens, R.__) : R.F), R.filter(todo => R.view(taskLens, todo).toUpperCase().includes(searchStr.toUpperCase())) )(todoList) const filterDone = () => { // const filteredList = R.reject(R.view(doneLens, R.__), todoList) // reject done todos, show not done // // to hide done todos, save todoList as tempList and show filtered list // // to show all again, restore tempList as todoList // setTempList(todoList) // setTodoList(hide? filteredList : tempList) setHide(R.not(hide)) } // const isSubstr = (searchStr, todo) => { // // this todo arg receives undefined props // // alert(todo.done) // alert(todo.task) // return todo.task.toUpperCase.includes(searchStr.toUpperCase) // // const upperTask = R.toUpper(todo.task) // // return R.includes(R.toUpper(matchStr), upperTask) // } // const search = () => { // // react-bootstrap elem's value field not recognized by VS Code but is correct // // Never use this in React // // const matchStr = document.getElementById('searchForm').value // // gets right search val & type but gets stuck here // const searchResults = R.filter(isSubstr(searchStr, R.__), todoList) // // const searchResults = R.filter(R.includes(, R.__.task), todoList) // // alert(searchResults) // setTempList(todoList) // // alert(todoList) // setTodoList(searchResults) // } return <App todoList={ filteredList } setTodoList={ setTodoList } toggleDone={ toggleDone } removeTodo={ removeTodo } filterDone={ filterDone } setSearchStr={ setSearchStr } /> } */ // const App = ({ todoList, setTodoList, toggleDone, removeTodo, filterDone, setSearchStr }) => ( const App = () => ( <div className='App mt-0'> {/* { <CreateTodoContainer todoList={ todoList } setTodoList={ setTodoList } /> } */} <CreateTodoContainer /> <FiltersContainer /> {/* <header className='App-header mt-0'> <p className='mt-3'> React To-do List </p> <Navbar bg='info' expand='lg'> { <Navbar.Brand href='#TAKEOUT'>My To-do List</Navbar.Brand> } <Navbar.Toggle aria-controls='basic-navbar-nav' /> <Navbar.Collapse id='basic-navbar-nav'> <Nav.Link className='text-black-50' onClick={ filterDone }>show/hide done todos</Nav.Link> <Form inline> <FormControl id='searchForm' type='text' placeholder='Search' className='mr-sm-2' onChange={ e => setSearchStr(e.target.value) } /> <Button href='TAKEOUT!' variant='outline-dark' type='submit'>Search</Button> </Form> </Navbar.Collapse> </Navbar> </header> */} <TodosContainer /> {/* <div> { todoList.map((todo, idx) => <Todo todo={ todo } idx={ todo.idx } toggleDone={ toggleDone } removeTodo={ removeTodo } key={ `todo-${idx}` } />) } </div> */} </div> ) export default App<file_sep>import React from 'react' // export const CreateTodo = ({ setTodo, submitTodo, value }) => ( // <div className='bg-info'> // {/* <form className='p-3' onSubmit={ submitTodo }> */} // <form className='p-3' onSubmit={ () => submitTodo(value) }> // <input placeholder='add a new todo' onChange={ e => setTodo(e.target.value)} value={ value } /> // <input type='submit' value='create' /> // </form> // </div> // ) export const CreateTodo = ({ setTodo, submitTodo, value }) => ( <div className='bg-info' style={{ padding: '10px' }}> <input placeholder='add a new todo' onChange={ e => setTodo(e.target.value)} value={ value } /> <input type='submit' value='create' onClick={() => submitTodo(value)} /> </div> )<file_sep>import { connect } from 'react-redux' import { TodoList } from '../components/todos' import { bindActionCreators } from 'redux' import * as actions from '../actions' import { selectFilteredList } from '../selectors/filterList' // const doneLens = R.lensProp('done') // const taskLens = R.lensProp('task') const mapStateToProps = state => ({ todos: selectFilteredList(state) }) // todos: R.pipe( // todos => todos.map((todo, idx) => R.assoc('idx', idx, todo)), // R.reject(state.filters.hide ? R.view(doneLens, R.__) : R.F), // R.filter(todo => R.view(taskLens, todo).toUpperCase().includes(state.filters.search.toUpperCase())) // )(state.todos) const mapDispatchToProps = dispatch => ({ toggleDone: bindActionCreators(actions.doneToggled, dispatch), removeTodo: bindActionCreators(actions.deleteTodo, dispatch) }) export const TodosContainer = connect(mapStateToProps, mapDispatchToProps)(TodoList)<file_sep>import { DELETE_TODO, DONE_TOGGLED, CREATE_SUBMITTED } from '../consts' import * as R from 'ramda' export const selectTodos = R.prop('todos') export const initState = [{ task: 'Do laundry', done: false}, { task: 'Take out trash', done: false}] export const reducer = (state = initState, action) => { switch (action.type) { case DELETE_TODO: return R.remove(action.payload, 1, state) case DONE_TOGGLED: const idx = action.payload // const newList = [...state] // newList[idx] = R.over(doneLens, R.not, newList[idx]) return R.assocPath([idx, 'done'], !state[idx].done, state) case CREATE_SUBMITTED: return [...state, { task: action.payload, done: false }] default: return state } } <file_sep>import { Navbar, Nav, Form, FormControl } from 'react-bootstrap' import React from 'react' export const Filter = ({ filterDone, setSearchStr, hide }) => ( <header className='App-header mt-0'> <p className='mt-3'> React To-do List </p> <Navbar bg='info' expand='lg'> {/* { <Navbar.Brand href='#TAKEOUT'>My To-do List</Navbar.Brand> } */} <Navbar.Toggle aria-controls='basic-navbar-nav' /> <Navbar.Collapse id='basic-navbar-nav'> <Nav.Link className='text-black-50' onClick={ () => filterDone(hide) }>show/hide done todos</Nav.Link> <Form inline> <FormControl id='searchForm' type='text' placeholder='Search' className='mr-sm-2' onChange={ e => setSearchStr(e.target.value) } /> {/* <Button href='TAKEOUT!' variant='outline-dark' type='submit'>Search</Button> */} </Form> </Navbar.Collapse> </Navbar> </header> ) <file_sep>import * as R from 'ramda' import { createSelector } from 'reselect' import { selectFilters } from '../reducers/filters' import { selectTodos } from '../reducers/todos' const doneLens = R.lensProp('done') export const selectFilteredList = createSelector( selectTodos, selectFilters, // (todos, filters) => { // const newTodos = todos.map((todo, idx) => R.assoc('idx', idx, todo)) // // const rej = R.reject(filters.hide ? R.view(doneLens, R.__) : R.F)(newTodos) // const rej = R.reject(filters.hide ? R.view(doneLens, R.__) : R.F)(newTodos) // const filt = R.filter(todo => todo.task.toUpperCase().includes(selectSearch(filters).toUpperCase()))(rej) // return filt // } (todos, filters) => todos.map((todo, idx) => ({ ...todo, idx })) .filter(todo => filters.hide ? !todo.done: true) .filter(todo => todo.task.toUpperCase().includes(filters.search.toUpperCase())) )<file_sep>import { Row, Alert } from 'react-bootstrap' import React from 'react' const Todo = ({ todo, idx, toggleDone, removeTodo }) => ( <Row className='justify-content-md-center'> <Alert variant='info'> {/* { <InputGroup.Prepend> <InputGroup.Checkbox /> </InputGroup.Prepend> <FormControl> </FormControl> <InputGroup.Append> <InputGroup.Text>x</InputGroup.Text> </InputGroup.Append> } */} <input type='checkbox' checked={ todo.done } onChange={ () => toggleDone(idx) }></input> <p style={{display: 'inline', margin: '0 1.5vw', color: todo.done? 'grey':'black', textDecoration: todo.done? 'line-through': ''}}> { todo.task }</p> <input type='button' value='x' onClick={ () => removeTodo(idx) }></input> </Alert> </Row> ) export const TodoList = ({ todos, toggleDone, removeTodo }) => ( <div> { todos.map((todo, idx) => <Todo todo={ todo } idx={ todo.idx } toggleDone={ toggleDone } removeTodo={ removeTodo } key={ `todo-${idx}` } />) } </div> )
0f1e621d1aac6967dd7401636591f31fffcdb42f
[ "JavaScript" ]
7
JavaScript
jackcho626/react-todo-list
1f95d4e894d59ce0ee115166ec4cfc3747c5a56e
1ac3825377d51573b7b1c3c51aa5ec50b7eca66b
refs/heads/master
<file_sep>package com.alikaraca.mvc.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.alikaraca.mvc.services.ProjectServices; @Controller @RequestMapping("/projects") public class ProjectController { private ProjectServices projectServices; @RequestMapping(value="/projects/{projectId}") public String findProject(Model model, @PathVariable("projectId") String projectId) { System.out.println("Proje"); model.addAttribute("project",this.projectServices.find(projectId)); return "project"; } @RequestMapping(value="/find") public String find(Model model) { //model.addAttribute("projects", this.projectServices.findAll()); System.out.println("Bulundu"); return "projects"; } /* @RequestMapping(value="/add" ,method=RequestMethod.GET) public String addproject() { System.out.println("Ekleme sayfası"); return "project_add"; } @RequestMapping(value="/add",method=RequestMethod.POST) public String saveProject() { System.out.println("Kayıt"); return "project_add"; } @RequestMapping(value="/deneme", method=RequestMethod.GET) public String deneme() { System.out.println("Deneme"); return "deneme"; }*/ } <file_sep>package com.alikaraca.mvc.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.alikaraca.data.Project; @Controller public class HomeController { @RequestMapping("/") public String home() { /*Project project=new Project(); project.setName("<NAME>"); project.setSponsor("NASA"); project.setDescription("Bu Nasa'nin destekledigi basit bir projedir."); model.addAttribute("currentProject", project);*/ return "Anasayfa"; } } <file_sep>package com.alikaraca.data; public class Project { private String name; private String projectId; private String description; private String sponsor; public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSponsor() { return sponsor; } public void setSponsor(String sponsor) { this.sponsor = sponsor; } }
988b2db8dacd4de0334ab0d0717abd10b8c6e0f7
[ "Java" ]
3
Java
alikaraca/Proje
adddafd65ea4b815fb1c65be46629374ff53298a
1884affadc241ef06c8ca2afcfa6a407b0de3ed7
refs/heads/master
<repo_name>asdlei99/lavue<file_sep>/routes/web.php <?php use App\Http\Middleware\CheckAge; Route::get('/', "IndexController@index"); Route::get('/home/{age}', function() { return "这个是我写的页面哦"; })->middleware(CheckAge::class); Route::get('/forbidden', function() { return "您的年龄太小,不能访问哦"; }); //Index Route::get('/blog_{id}', "IndexController@detail"); Route::get('/watch_{id}', "IndexController@detail"); Route::get('/incre_{id}', "AjaxController@incre"); Route::get('/hotkey', "IndexController@hotkey"); Route::get('/weibo', "IndexController@weibo"); Route::get('/keywords', "IndexController@keywords"); Route::get('/hotsearch', "IndexController@hotsearch"); //Ajax Route::get('/baidu_tuisong', "AjaxController@baidu_tuisong"); Route::get('/body_src_repl', "AjaxController@body_src_repl"); Route::get('/image', "ApiController@img"); Route::get('/kx', "ApiController@getkx"); Route::get('/hotweibo', "ApiController@hotweibo"); //Login Route::get('/login', "LoginController@index"); Route::get('/register', "LoginController@register"); Route::get('/logout', "LoginController@logout"); Route::get('/check/{check_str}', "LoginController@check"); Route::post('/login', "LoginController@login_post"); Route::post('/register', "LoginController@register_post"); Route::any('/captcha', function() { return captcha(); }); //List Route::get('/list_{type}', "ListController@lists"); Route::get('/search_{keywords}_{page}', "ListController@search"); Route::get('/type_{keywords}_{page}', "ListController@type"); Route::get('/baidu_{id}', "ListController@baidusearch"); Route::get('/weibo_{id}', "ListController@weibosearch"); Route::get('/keys_{key}_{page}', "ListController@keys"); Route::get('/author_{author}', "ListController@author"); Route::get('/keys', "ListController@keywords"); Route::get('/news', "ListController@news"); Route::get('/hots', "ListController@hots"); //Caijing $router->get('/getDates', 'EconomicController@getDates'); $router->get('/getPastorWillFd', 'EconomicController@getPastorWillFd'); $router->get('/getWeekData', 'EconomicController@getWeekData'); $router->get('/getjiedu', 'EconomicController@getjiedu'); $router->get('/getjiedudata', 'EconomicController@getjiedudata'); $router->get('/getcjdatas', 'EconomicController@getcjdatas'); $router->get('/getcjevent', 'EconomicController@getcjevent'); $router->get('/getcjholiday', 'EconomicController@getcjholiday'); $router->get('/fedata', 'EconomicController@fedata'); $router->get('/rili', 'EconomicController@rili'); //kuaixun $router->get('/kuaixun', 'KuaixunController@kuaixun'); $router->get('/kuaixun_{id}', 'KuaixunController@kuaixun_detail'); //hq $router->get('/hq_btc', 'HqController@index'); //other $router->get('/sitemap.xml', 'ToolController@sitemap'); $router->get('/xmlsitemap/article{page}.xml', 'ToolController@site'); $router->post('/trans', 'ToolController@trans_downfile'); Route::get('/test', "Test2Controller@index"); //candy $router->get('/residential', 'HouseController@residential'); $router->get('/house', 'HouseController@history'); $router->get('/areahouse', 'HouseController@getAreaResidential'); $router->get('/residentialinfo', 'HouseController@getResidentialInfo'); $router->post('/crawlinfo', 'HouseController@crawlinfo'); $router->post('/crawl/{name}', 'HouseController@crawl');
0a258244f4069bdcb644690b746812e5b9d654ae
[ "PHP" ]
1
PHP
asdlei99/lavue
5ad069dd5dd980190910b86ca60f4290c080ef8b
77472d20617fa2c0b02c06837804bbc86fada8ef
refs/heads/master
<repo_name>mdouang/ttt-5-move-rb-online-web-sp-000<file_sep>/display_board.rb # Define display_board that accepts a board and prints # out the current state. def display_board def say_display_board_ten_times phrase1 = " | | " phrase2 = "-----------" puts phrase1 puts phrase2 puts phrase1 puts phrase2 puts phrase1 end
3ab673405b11a34b0810251cbe1918f4b96d1ebb
[ "Ruby" ]
1
Ruby
mdouang/ttt-5-move-rb-online-web-sp-000
a407d3383b5e0adc723dc54cc7e216491937ea42
36f3573020444e0ae3aa07e7d92e31edd6f0aee4
refs/heads/master
<file_sep>require "bithour/range" class RangeTest < Test::Unit::TestCase def setup @range = Bithour::Range.new end def test_new assert_not_nil(@range) end def test_add_single @range.add(0) assert_equal([0], @range.to_a) end def test_add_multiple @range.add(2..4) assert_equal([2, 3, 4], @range.to_a) end def test_add_two_times @range.add(0) @range.add(2) assert_equal([0, 2], @range.to_a) end def test_remove @range.add(0) @range.add(2..4) @range.remove([2, 3]) assert_equal([0, 4], @range.to_a) end def test_include @range.add(0) assert_true(@range.include?(0)) assert_false(@range.include?(1)) end def test_max @range.add(24) assert_true(@range.include?(0)) end def test_to_a @range.add(0..1) assert_equal([0, 1], @range.to_a) end end <file_sep># Bithour [![Gem Version](https://badge.fury.io/rb/bithour.svg)](http://badge.fury.io/rb/bithour) [![Build Status](https://secure.travis-ci.org/myokoym/bithour.png?branch=master)](http://travis-ci.org/myokoym/bithour) A library for range of hours in bits. ## Installation Add this line to your application's Gemfile: ```ruby gem 'bithour' ``` And then execute: $ bundle Or install it yourself as: $ gem install bithour ## Usage See [test/test-range.rb](https://github.com/myokoym/bithour/blob/master/test/test-range.rb). ## Authors * <NAME> `<<EMAIL>>` ## License MIT License. See LICENSE.txt for details. ## Contributing 1. Fork it ( https://github.com/myokoym/bithour/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request <file_sep>require "bithour/range" require "bithour/version" module Bithour end <file_sep>module Bithour class Range def initialize(max=24) @hour_bits = 0 @max = max end def add(hours) update(hours, "1") end def remove(hours) update(hours, "0") end def include?(hour) @hour_bits[hour] == 1 end def to_a bits = ("%0#{@max}d" % @hour_bits.to_s(2)).reverse.split(//) hours = bits.collect.with_index {|hour, i| [i, hour]} hours.select! {|hour| hour[1] == "1"} hours.collect {|hour, bit| hour} end private def update(_hours, bit) if _hours.respond_to?(:each) hours = _hours else hours = [_hours] end hour_str = "%0#{@max}d" % @hour_bits.to_s(2) hour_str.reverse! hours.each do |i| hour_str[i % @max] = bit end @hour_bits = hour_str.reverse.to_i(2) end end end
a41d4c9fb57aac8f10dfc4fbce280fb5352d278c
[ "Markdown", "Ruby" ]
4
Ruby
myokoym/bithour
632f395661fc9be0b175be89b833a1ee59d8a1fc
b809deb58770365624d516ce975556b00a86bc4e
refs/heads/master
<repo_name>jmohan8/myappl<file_sep>/app/src/main/java/com/example/myappl/MainActivity.kt package com.example.myappl import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class Name { var id: Int = 0 var userName: String? = null constructor(id: Int, userName: String) { this.id = id this.userName = userName } constructor(userName: String) { this.userName = userName } } class MindOrksDBOpenHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase) { val CREATE_PRODUCTS_TABLE = ("CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT" + ")") db.execSQL(CREATE_PRODUCTS_TABLE) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME) onCreate(db) } fun addName(name: Name) { val values = ContentValues() values.put(COLUMN_NAME, name.userName) val db = this.writableDatabase db.insert(TABLE_NAME, null, values) db.close() } fun getAllName(): Cursor? { val db = this.readableDatabase return db.rawQuery("SELECT * FROM $TABLE_NAME", null) } companion object { private val DATABASE_VERSION = 1 private val DATABASE_NAME = "mindorksName.db" val TABLE_NAME = "name" val COLUMN_ID = "_id" val COLUMN_NAME = "username" } } class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnAddToDb.setOnClickListener { val dbHandler = MindOrksDBOpenHelper(this, null) val user = Name(etName.text.toString()) dbHandler.addName(user) Toast.makeText(this, etName.text.toString() + " Added to database", Toast.LENGTH_LONG).show() } btnShowDatafromDb.setOnClickListener { tvDisplayName.text = "" val dbHandler = MindOrksDBOpenHelper(this, null) val cursor = dbHandler.getAllName() cursor!!.moveToFirst() tvDisplayName.append((cursor.getString(cursor.getColumnIndex(MindOrksDBOpenHelper.COLUMN_NAME)))) while (cursor.moveToNext()) { tvDisplayName.append((cursor.getString(cursor.getColumnIndex(MindOrksDBOpenHelper.COLUMN_NAME)))) tvDisplayName.append("\n") } cursor.close() } } } <file_sep>/settings.gradle rootProject.name='MyAppl' include ':app'
6c54ac75e067a5d5b44df2cadc1b66ff739b3353
[ "Kotlin", "Gradle" ]
2
Kotlin
jmohan8/myappl
0208ad196172e6b45a5a05ee93590d92ed7bc4e4
97cd5ae7e395c1a576614710ba5eb8e80cc69efa
refs/heads/master
<repo_name>FedeMITIC/cli-assignment<file_sep>/src/commands.js const commander = require('commander'); const colors = require('colors'); /* If the script is launched without any command, use the guided mode */ const init = require('./greetings'); const _announceBirth = require('./birth'); const _announceDeath = require('./death'); const processCommands = (() => { const _date = new Date(); // Use the template string to coerce automatically to a string const _today = `${_date.getDate()}/${_date.getMonth() + 1}/${_date.getFullYear()}`; const _printHelp = (error) => { if (error) { console.log('%s\n%s\n\n', colors.red.bold('One or more parameters were not recognised.'), colors.red.bold('Please see the help section printed below.')); } console.log('%s\n%s\n%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n\n%s', 'Hi, this is a CLI utility to announce the birth or the death of a person.', 'Below you will find the available commands to interact with this tool along with their description.', 'All the parameter are mandatory, except the date that defaults to today.', colors.green.bold('birth, b: announce the birth of a person'), colors.bgCyan.bold('The birth command must be combined with the following commands'), '-n, --name: the name of the newborn (please insert also the surname)', '-r, --relationship: your relationship to the newborn (father, mother, ...)', '-y, --yourname: your name (please use your fullname)', `-d, --date: the date of the birth (defaults to today, ${_today})`, colors.red.bold('death, d: announce the death of a person'), colors.bgCyan.bold('The death command must be combined with the following commands'), '-a, --age: the age of the deceased', '-n, --name: the name of the deceased (please use the fullname)', '-r, --relationship: your relationship to the deceased (father, mother, ...)', '-y, --yourname: your name (please use your fullname)', `-d, --date: the date of the death (defaults to today, ${_today})`, colors.bgCyan.bold('Call this utility without any parameter to activate the guided version.')); console.log('\n%s\n\n%s\n%s\n%s', colors.green.bold('Copyright information (c)'), '(c) <NAME>, federico.macchi (at) aalto.fi - https://github.com/FedeMITIC/cli-assignment', 'All packages used are under MIT (or similar) license.', 'This package has a MIT license, thus it is possible to modify or redistribuite it.', '\nThis package is provided AS IS and does not serve any purpose besides being a demo for an assignment.'); if (error) { process.exit(1); } }; const initializeCommands = () => { commander // Route all unrecognized commands and activate the guided mode. .command('*') .action(() => _printHelp(true)); commander .command('birth') .alias('b') .description('Announce the birth of a person.') .option('-n, --name [value]', 'Name of the newborn') .option('-r, --relationship [value]', 'How are you related to the newbord? (father, mother, ...)') .option('-y, --yourname [value]', 'What is your name?') .option('-d, --date [value]', 'Date of the birth', _today) .action((args) => { _announceBirth.init(args.name, args.relationship, args.yourname, args.date); }); commander .command('death') .alias('d') .description('Announce the death of a person.') .option('-a, --age [value]', 'How old was the deceased?') .option('-n, --name [value]', 'Name of the deceased') .option('-r, --relationship [value]', 'How are you related to the deceased? (father, mother, ...)') .option('-y, --yourname [value]', 'What is your name?') .option('-d, --date [value]', 'Date of the death', _today) .action((args) => { _announceDeath.init(args.age, args.name, args.relationship, args.yourname, args.date); }); commander .command('help') .alias('-h') .alias('--h') .description('print the help text') .action(() => _printHelp(false)); commander.parse(process.argv); // No parameter supplied, use the guided mode. if (commander.args.length === 0) { init.start(); } }; /** * Exposes public functions and variables */ return { initializeCommands, }; })(); module.exports = processCommands; <file_sep>/src/questions/deathQuestions.js /** Private * Contains only the questions related to the death of a person. */ const deathQuestions = [ { type: 'input', name: 'age', message: 'What was the age of the deceased?', /* Validate user input */ validate: (answer) => { if (answer.length > 0) { return true; } return 'Please insert a name'; }, }, { type: 'input', name: 'name', message: 'What was the name of the deceased? (Please insert the full name)', /* Validate user input */ validate: (answer) => { if (answer.length > 0) { return true; } return 'Please insert a name'; }, }, { type: 'input', name: 'relationship', message: 'What is your relationship to the deceased? (Father/Mother/Daughter/Son/...)', /* Validate user input */ validate: (answer) => { if (answer.length > 0) { return true; } return 'Please insert a value'; }, }, ]; module.exports = deathQuestions; <file_sep>/src/questions/initialQuestions.js const initialQuestion = [ { type: 'checkbox', name: 'operation', message: 'Please check 1 of the options below.\nDo you want to announce the birth OR the death of a person?', choices: [ { name: 'Birth', }, { name: 'Death', }, { name: 'Exit', }, ], /* Validate user input */ validate: (answer) => { // I want just one answer. if (answer.length < 1) { return 'Please select one of the option above.'; } if (answer.length > 1) { return 'Please select just one option.'; } return true; }, }, ]; module.exports = initialQuestion; <file_sep>/src/birth.js const colors = require('colors'); const checkParams = require('./checkParam'); const birth = (() => { const init = (name, rel, yname, date) => { console.log('Hi, I\'m the announce birth service.'); console.log(`I received the following data: \nName of the newborn: ${name}, \nYour relationship to the newborn: ${rel}, \nYour full name is: ${yname}, \nBirthday: ${date}`); const status = checkParams('birth', name, rel, yname, date); if (status.length === 0) { console.log('%s', colors.green.bold('\nEverything is ok. The registration process is now complete.')); } else { console.log('%s', colors.red.bold('\nWe are still missing some data.')); for (let i = 0; i < status.length; i += 1) { console.log(`${status[i]}: missing`); } console.log('\nRemember that all the field are mandatory except the date (defaults to today'); } }; return { init, }; })(); module.exports = birth; <file_sep>/src/questions/birthQuestions.js /** Private * Contains only the questions related to the birth of a person. */ const birthQuestions = [ { type: 'input', name: 'name', message: 'What is the name of the newborn? (Please insert the full name)', /* Validate user input */ validate: (answer) => { if (answer.length > 0) { return true; } return 'Please insert a name'; }, }, { type: 'input', name: 'relationship', message: 'What is your relationship to the newborn? (Father/Mother/...)', /* Validate user input */ validate: (answer) => { if (answer.length > 0) { return true; } return 'Please insert a value'; }, }, ]; module.exports = birthQuestions; <file_sep>/src/greetings.js const inquire = require('inquirer'); const colors = require('colors'); const _announceBirth = require('./birth'); const _announceDeath = require('./death'); /* Import the questions */ const _birthQuestions = require('./questions/birthQuestions'); const _deathQuestions = require('./questions/deathQuestions'); const _finalQuestions = require('./questions/finalQuestions'); const _initialQuestion = require('./questions/initialQuestions'); const greetings = (() => { const start = () => { inquire.prompt(_initialQuestion).then((answers) => { // Check if the user wants to quit the application. if (answers.operation[0] === 'Exit') { process.exit(0); } // Will contain all the data acquired from the user that will be forwarded to death.js/birth.js const userData = []; // Since there are only 2 possibilities, if isBirth is true the user wants to report the birth of someone, otherwise the death. const isBirth = answers.operation[0] === 'Birth'; if (isBirth) { inquire.prompt([{ type: 'confirm', name: 'confirmBirth', message: 'You are announcing a birth, is this OK?', default: true, }]).then((confirmation) => { if (confirmation.confirmBirth) { inquire.prompt(_birthQuestions).then((birthAnswers) => { console.log('\n%s', colors.green.bold('I received the following data:')); console.log(`\nName of the newborn: ${birthAnswers.name}`); console.log(`\nYour relationship to the newborn: ${birthAnswers.relationship}\n`); inquire.prompt([{ type: 'confirm', name: 'confirmBirthData', message: 'Are the data displayed above correct?', default: true, }]).then((confirmation2) => { if (confirmation2.confirmBirthData) { userData.push(birthAnswers); inquire.prompt(_finalQuestions).then((finalAnswers) => { console.log('\n%s', colors.green.bold('I received the following data:')); console.log(`\nYour fullname: ${finalAnswers.yourname}`); console.log(`\nDate of birth: ${finalAnswers.date}\n`); inquire.prompt([{ type: 'confirm', name: 'confirmFinalData', message: 'Are the data displayed above correct?', default: true, }]).then((confirmation3) => { if (confirmation3.confirmFinalData) { userData.push(finalAnswers); _announceBirth.init(userData[0].name, userData[0].relationship, userData[1].yourname, userData[1].date); } else { return console.log('\n%s', colors.red.bold('Operation aborted.')); } }); }); } else { return console.log('\n%s', colors.red.bold('Operation aborted.')); } }); }); } else { return console.log('\n%s', colors.red.bold('Operation aborted.')); } }); } else { inquire.prompt([{ type: 'confirm', name: 'confirmDeath', message: 'You are announcing a death, is this OK?', default: true, }]).then((confirmation) => { if (confirmation.confirmDeath) { inquire.prompt(_deathQuestions).then((deathAnswers) => { console.log('\n%s', colors.green.bold('I received the following data:')); console.log(`\nAge of the deceased: ${deathAnswers.name}`); console.log(`\nName of the deceased: ${deathAnswers.name}`); console.log(`\nYour relationship to the deceased: ${deathAnswers.relationship}\n`); inquire.prompt([{ type: 'confirm', name: 'confirmDeathData', message: 'Are the data displayed above correct?', default: true, }]).then((confirmation2) => { if (confirmation2.confirmDeathData) { userData.push(deathAnswers); inquire.prompt(_finalQuestions).then((finalAnswers) => { console.log('\n%s', colors.green.bold('I received the following data:')); console.log(`\nYour fullname: ${finalAnswers.yourname}`); console.log(`\nDate of death: ${finalAnswers.date}\n`); inquire.prompt([{ type: 'confirm', name: 'confirmFinalData', message: 'Are the data displayed above correct?', default: true, }]).then((confirmation3) => { if (confirmation3.confirmFinalData) { userData.push(finalAnswers); _announceDeath.init(userData[0].age, userData[0].name, userData[0].relationship, userData[1].yourname, userData[1].date); } else { return console.log('\n%s', colors.red.bold('Operation aborted.')); } }); }); } else { return console.log('\n%s', colors.red.bold('Operation aborted.')); } }); }); } else { return console.log('\n%s', colors.red.bold('Operation aborted.')); } }); } }); }; /** * Exposes public functions and variables */ return { start, }; })(); module.exports = greetings; <file_sep>/src/death.js const colors = require('colors'); const checkParams = require('./checkParam'); const death = (() => { const _displayAnnounce = (age, name, rel, yname, date) => { console.log('\n%s\n\n', colors.red.bold('Announce of death:')); console.log(`It is with great sadness that ${yname}, ${rel} of ${name}, announces his passing on ${date} at the age of ${age} years.`); }; const init = (age, name, rel, yname, date) => { console.log('Hi, I\'m the announce death service.'); console.log(`I received the following data: \nAge of the deceased: ${age}, \nName of the deceased: ${name}, \nYour relationship to the deceased: ${rel}, \nYour full name is: ${yname}, \nBirthday: ${date}`); const status = checkParams('death', age, name, rel, yname, date); if (status.length === 0) { console.log('%s', colors.green.bold('\nEverything is ok. The registration process is now complete.')); } else { console.log('%s', colors.red.bold('\nWe are still missing some data.')); for (let i = 0; i < status.length; i += 1) { console.log(`${status[i]}: missing`); } console.log('\nRemember that all the field are mandatory except the date (defaults to today'); } _displayAnnounce(age, name, rel, yname, date); }; return { init, }; })(); module.exports = death; <file_sep>/package.json { "name": "cli-assignment", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "repository": { "type": "git", "url": "git+https://github.com/FedeMITIC/cli-assignment.git" }, "author": "", "license": "MIT", "bugs": { "url": "https://github.com/FedeMITIC/cli-assignment/issues" }, "homepage": "https://github.com/FedeMITIC/cli-assignment#readme", "dependencies": { "colors": "^1.3.2", "commander": "^2.19.0", "eslint": "^5.9.0", "eslint-config-airbnb-base": "^13.1.0", "eslint-plugin-import": "^2.14.0", "inquirer": "^6.2.0" } } <file_sep>/src/questions/finalQuestions.js const date = new Date(); // Use the template string to coerce automatically to a string const today = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`; /** Private * Contains the final common questions */ const finalQuestions = [ { type: 'input', name: 'yourname', message: 'What is your name? (Please insert your full name)', /* Validate user input */ validate: answer => answer.length > 0, }, { type: 'input', name: 'date', message: `Please, insert the date of the birth/death [format dd/mm/YYYY] (defaults to today, ${today})`, default: today, }, ]; module.exports = finalQuestions; <file_sep>/README.md # CLI Assignment for CS-E5220 - User Interface Construction Student: <NAME> Topic: Announce the death or the birth of a person ![alt text](https://github.com/FedeMITIC/cli-assignment/blob/master/images/Welcome%20screen-final.png "Welcome screen") *Welcome screen.* ## How to use the CLI The CLI has two different modes that can be used: - Guided mode - Advanced mode In the guided mode, the CLI will be interactive: it will ask the user a set of questions and give constant feedback. In the advanced mode, only one command is necessary to complete the whole task. ## Instructions for installation and usage To run the CLI, first install node.js from the [Node JS website](https://nodejs.org/en/). Download (or clone) this repository in your pc. Using the terminal, navigate inside the downloaded folder and run `npm i` Finally, run `node index.js` to start the CLI in the guided mode `node index.js help` to display the help screen `node index.js <parameters>` to use the CLI in the advanced mode The list of parameters is included in the help screen. For example: `node index.js d -a 72 -n "A" -r Father -y "B"` Will results in the announcement of the death of a person named *A*, that died today at 72 years old. The announcement was made by *B*, the father of *A*. ## Screenshots ![alt text](https://github.com/FedeMITIC/cli-assignment/blob/master/images/Welcome%20screen-final.png "Welcome screen") *Welcome screen.* ![alt text](https://github.com/FedeMITIC/cli-assignment/blob/master/images/Initial%20status-final.png "Initial status") *Initial status of the CLI.* ![alt text](https://github.com/FedeMITIC/cli-assignment/blob/master/images/Feedback%201-final.png "First feedback") *First feedback.* ![alt text](https://github.com/FedeMITIC/cli-assignment/blob/master/images/Feedback%202-final.png "Second feedback") *Second feedback with more data.* ![alt text](https://github.com/FedeMITIC/cli-assignment/blob/master/images/Final%20screen-final.png "Final screen") *Final screen.*<file_sep>/src/checkParam.js const deathArgs = ['Age of the deceased', 'Name of the deceased', 'Your relationship to the deceased', 'Your fullname', 'Date of death']; const birthArgs = ['Name of the newborn', 'Your relationship to the newborn', 'Your fullname', 'Date of birth']; module.exports = function checkParams(...args) { const errors = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === undefined) { if (args[0] === 'death') { errors.push(`${deathArgs[i - 1]}`); } else { errors.push(`${birthArgs[i - 1]}`); } } } return errors; };
a41f6c1ed8c877e3c7dc4038dce6585641ce5feb
[ "JavaScript", "JSON", "Markdown" ]
11
JavaScript
FedeMITIC/cli-assignment
cd0eeee73cf029335cbd5e5682b62b19e4ee365b
7746f16344d81fab4d59454adcf3687100577018
refs/heads/master
<repo_name>LuoDi-Nate/my_website<file_sep>/src/main/java/com/wx/website/serviceimpl/ShoppingCartServiceImpl.java package com.wx.website.serviceimpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.ModelAttribute; import com.wx.website.dao.ShoppingCartMapper; import com.wx.website.model.ShoppingCart; import com.wx.website.service.ShoppingCartService; @Service public class ShoppingCartServiceImpl implements ShoppingCartService{ @Autowired private ShoppingCartMapper shoppingCartMapper; public String addOrder(@ModelAttribute("order")ShoppingCart order) { return "aa"; } public ShoppingCart selectById() { // TODO Auto-generated method stub return null; } public int deleteOrder() { // TODO Auto-generated method stub return 0; } public int updateOrder() { // TODO Auto-generated method stub return 0; } public ShoppingCart addCart() { // TODO Auto-generated method stub return null; } public int deleteCart() { // TODO Auto-generated method stub return 0; } public int updateCart() { // TODO Auto-generated method stub return 0; } } <file_sep>/src/main/java/com/wx/website/model/ShoppingCart.java package com.wx.website.model; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.stereotype.Component; @Component public class ShoppingCart { private Integer userId; private String goodsId; private String goodsName; private Integer count; private Double price; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getGoodsId() { return goodsId; } public void setGoodsId(String goodsId) { this.goodsId = goodsId == null ? null : goodsId.trim(); } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName == null ? null : goodsName.trim(); } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } List<OrderLine> items = new ArrayList<OrderLine>(); public List<OrderLine> getItems() { return items; } public void setItems(List<OrderLine> items) { this.items = items; } public void add(OrderLine order) { for (Iterator<OrderLine> iter = items.iterator(); iter.hasNext();) { OrderLine item = iter.next(); if(item.getEstore().getGoodsId() == order.getEstore().getGoodsId()) { item.setCount(item.getCount() + 1); return; } } items.add(order); } public double getTotalPrice() { double d = 0.0; for(Iterator<OrderLine> it = items.iterator(); it.hasNext(); ) { OrderLine current = it.next(); d += current.getEstore().getPrice() * current.getCount(); } return d; } public void deleteItemById(String goodsId) { for (Iterator<OrderLine> iter = items.iterator(); iter.hasNext();) { OrderLine item = iter.next(); if(item.getEstore().getGoodsId().equals(goodsId)) { iter.remove(); return; } } } }
7d8ddafe5c36aefc822cd9d0f01ae26110a791a0
[ "Java" ]
2
Java
LuoDi-Nate/my_website
846d55435326e9d3dffa1869ce1e82c3470d8266
cb5737239860c9983b00dad5b4e2feb5ed28d95c
refs/heads/master
<repo_name>EduardBabuscov/SistemBirocratic<file_sep>/src/sistem/Ghiseu.java package sistem; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Ghiseu { private List<Client> _clienti; private boolean _isOpen; private List<String> _documentTypes; private String _numeGhiseu; public Ghiseu(List<String> documentTypes,String numeGhiseu){ _clienti = new LinkedList<>(); _isOpen = true; _documentTypes = new ArrayList<>(documentTypes); _numeGhiseu = numeGhiseu; } public synchronized boolean isOpen(){ return _isOpen; } public synchronized void changeState(){ System.out.println("Se schimba starea la ghiseul "+ _numeGhiseu); _isOpen =!_isOpen; if(_isOpen){ System.out.println("Ghiseul "+ _numeGhiseu+ " este deschis"); }else{ System.out.println("Ghiseul "+ _numeGhiseu+ " este inchis"); } } public synchronized void addClient(Client client){ //System.out.println("add" + _clienti.size()); _clienti.add(client); } public synchronized void removeClient(Client client){ _clienti.remove(client); //System.out.println("remove" + _clienti.size()); } public boolean doWork(Client client,Document act) throws Exception { if(!_isOpen || !_documentTypes.contains(act.getType()) || !client.dosar.checkIfDocumentHasAllRequired(act)){ return false; } addClient(client); if(!isOpen()) throw new Exception(); if(!_isOpen){ removeClient(client); System.out.println("Clientul" + client.getId() + " nu a putut obtine actul " + act.getType() + " pt ca s-a inchis ghiseul "+_numeGhiseu); return false; } synchronized (this) { if(_clienti.get(0).getId()!=client.getId()){ Thread.currentThread().wait(); } System.out.println("Clientului " + client.getId() + " i-a venit randul pt actul " + act.getType() + " la ghiseul "+_numeGhiseu); try { Thread.sleep(1000);//sleep pentru a simula munca ghiseului } catch (InterruptedException e) { e.printStackTrace(); removeClient(client); return false; } client.dosar.markDocumentAsObtained(act); removeClient(client); if(_clienti.size()>0){ _clienti.get(0).notify(); } } return true; } public synchronized int getNumarClienti(){ return _clienti.size(); } }<file_sep>/src/sistem/Client.java package sistem; import java.util.List; public class Client implements Runnable{ public Dosar dosar; private int id; private Institutie institutie; public Client(int number,Dosar d, Institutie institutie) { dosar = d; id = number; this.institutie = institutie; } public int getId(){ return id; } @Override public void run() { List<Document> acte = dosar.getAllDocuments(); String message = ""; for(Document act:acte){ message += act.getType() + " "; } System.out.println("Actele necesare pentru clientul " + id +" sunt:" + message ); Document act = null; while((act=dosar.getNextObtainableDocument())!=null){ boolean notOk = true; while (notOk) { try { if (institutie.getGhiseuPentruDocument(act).doWork(this, act)) { System.out.println("Clientul " + id + " a obtinut actul " + act.getType()); notOk = false; } else { System.out.println("Clientul" + id + " cauta alt birou, fiindca biroul la care statea s-a inchis."); } }catch (Exception e) { System.out.println("Clientul" + id + " cauta alt birou, fiindca biroul la care statea s-a inchis."); } } } if(dosar.noMoreDocumentsToObtain()){ System.out.println("Clientul " + id + " a reusit sa obtina toate actele."); } else{ System.out.println("Structura de acte nu este valida pentru clientul " + id); } } }<file_sep>/src/sistem/Dosar.java package sistem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dosar { private List<Document> _acteObtinute; private Map<String,Document> _documenteNecesare; public Dosar(Document actNecesar) { _acteObtinute = new ArrayList<Document>(); _documenteNecesare = new HashMap<>(); flattenAndAddDocuments(actNecesar); } public Dosar(List<Document> acteNecesare){ _acteObtinute = new ArrayList<Document>(); _documenteNecesare = new HashMap<String,Document>(); for(Document document:acteNecesare){ if(!_documenteNecesare.containsKey(document.getType())){ flattenAndAddDocuments(document); } } } public Document getNextObtainableDocument(){ List<Document> tmpList = new ArrayList<>(_documenteNecesare.values()); for(Document candidate:tmpList){ boolean flag=true; for(Document docNecesar: candidate.getDocumenteNecesare()){ flag = checkIfDocumentIsOwned(docNecesar); if(flag==false){ break; } } if(flag==true){ return candidate; } } return null; } public boolean checkIfDocumentHasAllRequired(Document document){ for(Document doc:document.getDocumenteNecesare()){ if(!checkIfDocumentIsOwned(doc)){ return false; } } return true; } private boolean checkIfDocumentIsOwned(Document document){ for(Document doc:_acteObtinute){ if(doc.getType().equals(document.getType())){ return true; } } return false; } public void markDocumentAsObtained(Document doc){ _acteObtinute.add(doc); _documenteNecesare.remove(doc.getType()); } private void flattenAndAddDocuments(Document actNecesar){ ArrayList<Document> documents = getAllDocuments(actNecesar); for(Document doc:documents){ _documenteNecesare.put(doc.getType(), doc); } } public List<Document> getAllDocuments(){ return new ArrayList<Document>(_documenteNecesare.values()); } public boolean noMoreDocumentsToObtain(){ return _documenteNecesare.size()==0; } private ArrayList<Document> getAllDocuments(Document act){ if(act==null){ return null; }else{ ArrayList<Document> result = new ArrayList<Document>(); result.add(act); for(Document document:act.getDocumenteNecesare()){ if(!_documenteNecesare.containsKey(document.getType())){ result.addAll(getAllDocuments(document)); } } return result; } } }
90f1c546465e9ce413f2fcf2d149d963ad031da9
[ "Java" ]
3
Java
EduardBabuscov/SistemBirocratic
32eb8f151afcbb24be51590cad73b0dc20a2839b
48986f1dca6cfd761ce64d065ce211be589a534b
refs/heads/master
<repo_name>jdhmtl/card.bb<file_sep>/app/Session.php <?php namespace App; class Session { protected $data = []; public function __construct() { $this->data = &$_SESSION; } public function delete($key) { unset($this->data[$key]); } public function destroy() { $this->data = []; session_destroy(); } public function get($key) { return array_key_exists($key, $this->data) ? $this->data[$key] : null; } public function set($key, $value) { $this->data[$key] = $value; } } <file_sep>/app/templates/views/profile.php <div class="profile-wrap"> <div class="profile-photo"> <img src="/assets/img/warren_03.jpg" alt="<NAME>"> </div> <div class="profile-info"> <div class="profile-text-content"> <h1><NAME></h1> <span class="game-attended">Games Attended</span> <span class="game-attended-num"><?= $this->stats['games']; ?></span> </div> </div> </div> <div class="row-four-square-wrap"> <div class="square dark"> <div class="square-text"> <h2>Home Runs</h2> <span class="sub">Home Runs witnessed</span> <span class="regular-digits"><?= $this->stats['homeruns']; ?></span> </div> </div> <div class="square medium"> <div class="square-text"> <h2>Triples</h2> <span class="sub">Triples witnessed</span> <span class="regular-digits"><?= $this->stats['triples']; ?></span> </div> </div> <div class="square dark"> <div class="square-text"> <h2>Doubles</h2> <span class="sub">Doubles witnessed</span> <span class="regular-digits"><?= $this->stats['doubles']; ?></span> </div> </div> <div class="square medium"> <div class="square-text"> <h2>Singles</h2> <span class="sub">Singles witnessed</span> <span class="regular-digits"><?= $this->stats['singles']; ?></span> </div> </div> </div> <div class="big-square-row row"> <div class="big-square left light"> <div class="big-square-content"> <h1 class="big-heading">Grand Slam</h1> <span class="sub">Grand slam witnessed aka the Big Smalami</span> <span class="big-digits">05</span> </div> </div> <div class="big-square dark right-dark-big-square stolen"> <div class="big-square-content "> <h1 class="big-heading"> Stolen bases</h1> <span class="sub">Number of stolen bases witnessed</span> <span class="big-digits"><?= $this->stats['stolenbases']; ?></span> </div> </div> </div> <div class="last-row row"> <div class='recto-square-wrap'> <div class="square dark"> <div class="square-text"> <h2>Fast ball</h2> <span class="sub">Speedies witnessed</span> <span class="regular-digits">210</span> </div> </div> <div class="square light-box last"> <div class="square-text"> <h2>Strike outs</h2> <span class="sub">Strike outs witnessed</span> <span class="regular-digits"><?= $this->stats['strikeouts']; ?></span> </div> </div> <div class="square dark"> <div class="square-text"> <h2>Double play</h2> <span class="sub">Double plays witnessed</span> <span class="regular-digits"><?= $this->stats['doubleplays']; ?></span> </div> </div> <div class="square light-box last"> <div class="square-text"> <h2>triple play</h2> <span class="sub">triple plays witnessed</span> <span class="regular-digits"><?= $this->stats['tripleplays']; ?></span> </div> </div> <div class="highest-score"> <div class="highest-score-content"> <div class="square-text"> <h2>Highest Score</h2> <span class="sub">Highest score witnessed</span> <span class="regular-digits"><?= $this->stats['hsbt']; ?></span> </div> </div> </div> </div> <div class="recto perfect-game"> <div class="perfect-game-content"> <h1 class="big-heading"> Perfect game</h1> <span class="sub">Perfect game witnessed</span> <p>A perfect game is defined by Major League Baseball as a game in which a pitcher (or combination of pitchers) pitches a victory that lasts a minimum of nine innings and in which no opposing player reaches base</p> <span class="big-digits">ZERO</span> </div> </div> </div> <?php /* <div id="card"> <div class="games"> <h4>Games Attended</h4> <span><?= $this->stats['games']; ?></span> </div> <div class="hsbt"> <h4>Most Runs By Team</h6> <span><?= $this->stats['hsbt']; ?></span> </div> <div class="singles"> <h4>Singles</h4> <span><?= $this->stats['singles']; ?></span> </div> <div class="doubles"> <h4>Doubles</h4> <span><?= $this->stats['doubles']; ?></span> </div> <div class="triples"> <h4>Triples</h4> <span><?= $this->stats['triples']; ?></span> </div> <div class="homeruns"> <h4>Home Runs</h4> <span><?= $this->stats['homeruns']; ?></span> </div> <div class="stolenbases"> <h4>Bases Stolen</h4> <span><?= $this->stats['stolenbases']; ?></span> </div> <div class="strikeouts"> <h4>Strikeouts</h4> <span><?= $this->stats['strikeouts']; ?></span> </div> <div class="doubleplays"> <h4>Double Plays</h4> <span><?= $this->stats['doubleplays']; ?></span> </div> <div class="tripleplays"> <h4>Triple Plays</h4> <span><?= $this->stats['tripleplays']; ?></span> </div> </div> */ ?> <file_sep>/app/SportsData.php <?php namespace App; use \GuzzleHttp\Client as Guzzle; class SportsData { protected $Guzzle; protected $key; protected $base = 'http://api.sportsdatallc.org/mlb-t5'; public function __construct(Guzzle $guzzle, $key) { $this->Guzzle = $guzzle; $this->key = $key; } } <file_sep>/app/Controllers/UsersController.php <?php namespace App\Controllers; use \App\Controller; use \Exception; use \Model; class UsersController extends Controller { public function login() { $user = $this->app->session()->get('user'); if ($user) { return $this->response->redirect('/'); } return $this->service->render(VIEWS_DIR . 'login.php'); } public function logout() { $this->app->session()->destroy(); return $this->response->redirect('/'); } public function register() { $this->service->render(VIEWS_DIR . 'register.php'); } public function doLogin() { $post = $this->request->paramsPost(); $user = Model::factory('App\Models\User')->where('username', $post->username)->findOne(); if ($user && $user->authorize($post->password)) { $this->app->session()->set('user', $user->id); $this->response->redirect('/'); } else { $this->service->flash('Invalid credentials', 'error'); $this->service->back(); } } public function doRegister() { try { $this->service->validateParam('username', 'Please enter a username')->notNull(); $this->service->validateParam('password', 'Please enter a password')->notNull(); $post = $this->request->paramsPost(); $user = Model::factory('App\Models\User')->create(); $registered = $user->register($post->username, $post->password); if ($registered) { $this->app->session()->set('user', $user->id); $this->service->flash('Your account has been created', 'message'); $this->response->redirect('/'); } } catch (Exception $e) { $this->service->flash($e->getMessage(), 'error'); $this->service->back(); } } } <file_sep>/app/Models/Profile.php <?php namespace App\Models; use \Model; class Profile { protected $model; public function __construct() { $this->model = Model::factory('App\Models\Game'); } public function getStats() { $stats = [ 'hsbt' => 0, 'singles' => 0, 'doubles' => 0, 'triples' => 0, 'homeruns' => 0, 'stolenbases' => 0, 'strikeouts' => 0, 'doubleplays' => 0, 'tripleplays' => 0, ]; $games = $this->model->findMany(); $stats['games'] = count($games); foreach ($games as $game) { if ($game->hsbt > $stats['hsbt']) { $stats['hsbt'] = $game->hsbt; } $stats['singles'] += $game->singles; $stats['doubles'] += $game->doubles; $stats['triples'] += $game->triples; $stats['homeruns'] += $game->homeruns; $stats['stolenbases'] += $game->stolenbases; $stats['strikeouts'] += $game->strikeouts; $stats['doubleplays'] += $game->doubleplays; $stats['tripleplays'] += $game->tripleplays; } return $stats; } } <file_sep>/app/Controller.php <?php namespace App; use \Klein\Klein; class Controller { protected $request; protected $response; protected $service; protected $app; public function __construct(Klein $klein) { $this->request = $klein->request(); $this->response = $klein->response(); $this->service = $klein->service(); $this->app = $klein->app(); } }<file_sep>/config/schema/users.sql CREATE TABLE `users` ( `id` char(36) NOT NULL DEFAULT '', `username` varchar(60) NOT NULL DEFAULT '', `password` varchar(255) NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;<file_sep>/app/templates/partials/flash.php <?php if (!empty($this->errors)): ?> <ul class="errors"> <?php foreach ($this->errors as $error): ?> <li><?= $error; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <?php if (!empty($this->messages)): ?> <ul class="messages"> <?php foreach ($this->messages as $message): ?> <li><?= $message; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <file_sep>/app/Models/Game.php <?php namespace App\Models; use \Model; class Game extends Model { public static $_table = 'games'; } <file_sep>/app/templates/views/calendar.php <div id="calendars"> <?php for ($month = 1; $month <= 12; $month++): $day = 1; $time = mktime(0, 0, 0, $month, 1, $this->year); $end = cal_days_in_month(CAL_GREGORIAN, $month, $this->year); ?> <table class="calendar"> <tr> <th colspan="7"><?= date('F Y', $time); ?></th> </tr> <?php while ($day < $end): ?> <tr> <?php $row = 0; ?> <?php if ($day == 1): ?> <?php for ($space = 0; $space < date('w', $time); $space++): ?> <?php $row++; ?> <td></td> <?php endfor; ?> <?php endif; ?> <?php while ($row < 7 && $day <= $end): ?> <td> <a href="#" data-date="<?= $this->year . '/' . str_pad($month, 2, '0', STR_PAD_LEFT) . '/' . str_pad($day, 2, '0', STR_PAD_LEFT); ?>"><?= $day; ?></a> </td> <?php $day++; $row++; ?> <?php endwhile; ?> <?php if ($day > $end && $row < 7): ?> <?php while ($row < 7): ?> <td></td> <?php $row++; ?> <?php endwhile; ?> <?php endif; ?> </tr> <?php endwhile; ?> </table> <?php endfor; ?> </div> <div id="games"></div> <file_sep>/app/Models/User.php <?php namespace App\Models; use \Model; use \Rhumsaa\Uuid\Uuid; class User extends Model { public static $_table = 'users'; public function authorize($password) { return $this->verifyPassword($password); } protected function generateID() { return Uuid::uuid4()->toString(); } protected function hashPassword($password) { return password_hash($password, PASSWORD_DEFAULT); } public function register($username, $password) { $unique = $this->uniqueUser($username); if (!$unique) { throw new \Exception('Username is already in use.'); } $this->id = $this->generateID(); $this->username = $username; $this->password = $<PASSWORD>($<PASSWORD>); return $this->save(); } protected function uniqueUser($username) { $count = $this->orm->where('username', $username)->count(); return $count === 0; } protected function verifyPassword($password) { return password_verify($password, $this->password); } } <file_sep>/config/routes.php <?php $router->respond('/', function() use ($router) { $profile = new \App\Models\Profile(); $stats = $profile->getStats(); $router->service()->render(VIEWS_DIR . 'profile.php', ['stats' => $stats]); }); $router->get('/login/?', function() use ($router) { $router->app()->userController()->login(); }); $router->post('/login/?', function() use ($router) { $router->app()->userController()->doLogin(); }); $router->get('/logout/?', function() use ($router) { $router->app()->userController()->logout(); }); $router->get('/register/?', function() use ($router) { $router->app()->userController()->register(); }); $router->post('/register/?', function() use ($router) { $router->app()->userController()->doRegister(); }); $router->respond('/calendar/?[i:year]?', function() use ($router) { $year = isset($router->request()->year) ? $router->request()->year : date('Y'); $router->service()->render(VIEWS_DIR . 'calendar.php', ['year' => $year]); }); $router->respond('/schedule/[:year]/[:month]/[:day]', function() use ($router) { $game = $router->app()->game(); $schedule = $game->schedule($router->request()->year, $router->request()->month, $router->request()->day); echo json_encode($schedule); exit; }); $router->respond('/summary/[:game]', function() use ($router) { $game = $router->app()->game(); $summary = $game->summary($router->request()->game); $record = Model::factory('App\Models\Game')->create(); $record->id = $router->request()->game; foreach ($summary as $key => $value) { $record->{$key} = $value; } try { $record->save(); } catch (Exception $e) { // Shut up } }); <file_sep>/config/bootstrap.php <?php require_once dirname(__DIR__) . '/vendor/autoload.php'; Dotenv::load(dirname(__DIR__)); ORM::configure([ 'connection_string' => 'mysql:host=' . getenv('DBHOST') . ';dbname=' . getenv('DBNAME'), 'username' => getenv('DBUSER'), 'password' => getenv('<PASSWORD>'), ]); define('LAYOUTS_DIR', dirname(__DIR__) . '/app/templates/layouts/'); define('VIEWS_DIR', dirname(__DIR__) . '/app/templates/views/'); define('PARTIALS_DIR', dirname(__DIR__) . '/app/templates/partials/'); $router = new \Klein\Klein(); $router->respond(function() use ($router) { $router->service()->startSession(); $router->app()->register('session', function() { return new App\Session; }); $router->app()->register('guzzle', function() { return new GuzzleHttp\Client; }); $router->app()->register('game', function() use ($router) { return new App\SportsData\Game($router->app()->guzzle(), getenv('API_KEY')); }); $router->app()->register('userController', function() use ($router) { return new App\Controllers\UsersController($router); }); $router->service()->layout(LAYOUTS_DIR . 'default.php'); $router->service()->title = 'Fan Card'; $router->service()->errors = $router->service()->flashes('error'); $router->service()->messages = $router->service()->flashes('message'); }); require_once __DIR__ . '/routes.php'; $router->onHttpError(function($code, $klein) { $klein->response()->redirect('/'); }); return $router; <file_sep>/app/SportsData/Game.php <?php namespace App\SportsData; use \App\SportsData as Data; class Game extends Data { public function boxscore($game_id) { $endpoint = "{$this->base}/games/{$game_id}/boxscore.json"; $response = $this->Guzzle->get($endpoint, [ 'query' => ['api_key' => $this->key] ]); $status = $response->getStatusCode(); var_dump($response->json()); exit; } public function playByPlay($game_id) { $endpoint = "{$this->base}/games/{$game_id}/pbp.json"; $response = $this->Guzzle->get($endpoint, [ 'query' => ['api_key' => $this->key] ]); $status = $response->getStatusCode(); $plays = $response->json(); header('Content-Type: application/json'); echo json_encode($plays); exit; } public function schedule($year, $month, $day) { $endpoint = "{$this->base}/games/{$year}/{$month}/{$day}/schedule.json"; $response = $this->Guzzle->get($endpoint, [ 'query' => ['api_key' => $this->key] ]); $status = $response->getStatusCode(); $games = []; if ($status == 200) { $data = $response->json(); foreach ($data['league']['games'] as $game) { $games[$game['id']] = "{$game['away']['abbr']} at {$game['home']['abbr']}"; } } return $games; } public function summary($game_id) { $endpoint = "{$this->base}/games/{$game_id}/summary.json"; $response = $this->Guzzle->get($endpoint, [ 'query' => ['api_key' => $this->key] ]); $status = $response->getStatusCode(); $data = $response->json(); $parsed = $this->parseGameStats($data); return $parsed; } public function parseGameStats($data) { $home = $data['game']['home']['statistics']; $away = $data['game']['away']['statistics']; $stats = [ 'hsbt' => intval(max($data['game']['home']['runs'], $data['game']['away']['runs'])), 'singles' => intval($home['hitting']['onbase']['s'] + $away['hitting']['onbase']['s']), 'doubles' => intval($home['hitting']['onbase']['d'] + $away['hitting']['onbase']['d']), 'triples' => intval($home['hitting']['onbase']['t'] + $away['hitting']['onbase']['t']), 'homeruns' => intval($home['hitting']['onbase']['hr'] + $away['hitting']['onbase']['hr']), 'stolenbases' => intval($home['hitting']['steal']['stolen'] + $away['hitting']['steal']['stolen']), 'strikeouts' => intval($home['pitching']['outs']['ktotal'] + $away['pitching']['outs']['ktotal']), 'doubleplays' => intval($home['fielding']['dp'] + $away['fielding']['dp']), 'tripleplays' => intval($home['fielding']['tp'] + $away['fielding']['tp']), ]; return $stats; } } <file_sep>/app/templates/layouts/default.php <!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="stylesheet" type="text/css" href="//cloud.typography.com/6832954/712126/css/fonts.css"> <link rel="stylesheet" href="/assets/css/style.css"> <link rel="stylesheet" href="/assets/css/cal.css"> <title><?= $this->title; ?></title> </head> <body> <div class="container"> <?= $this->partial(PARTIALS_DIR . 'flash.php'); ?> <?= $this->yieldView(); ?> </div> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script> <script src="/assets/js/site.js"></script> </body> </html> <file_sep>/public/index.php <?php $app = require_once dirname(__DIR__) . '/config/bootstrap.php'; $app->dispatch(); <file_sep>/config/schema/games.sql CREATE TABLE `games` ( `id` char(36) NOT NULL DEFAULT '', `hsbt` tinyint(3) unsigned NOT NULL DEFAULT '0', `singles` tinyint(3) unsigned NOT NULL DEFAULT '0', `doubles` tinyint(3) unsigned NOT NULL DEFAULT '0', `triples` tinyint(3) unsigned NOT NULL DEFAULT '0', `homeruns` tinyint(3) unsigned NOT NULL DEFAULT '0', `stolenbases` tinyint(3) unsigned NOT NULL DEFAULT '0', `strikeouts` tinyint(3) unsigned NOT NULL DEFAULT '0', `doubleplays` tinyint(3) unsigned NOT NULL DEFAULT '0', `tripleplays` tinyint(3) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;<file_sep>/public/assets/js/site.js $(document).ready(function() { $('.calendar a').click(function(e) { e.preventDefault(); var date = $(this).data('date'); $.ajax({ url: '/schedule/' + $(this).data('date'), dataType: 'json' }).done(function(data) { var list = '<h3>' + date + '</h3><ul>'; $.each(data, function(key, value) { list += '<li><a href="#" data-game="' + key + '">' + value + '</a></li>'; }); list += '</ul>'; $('#games').html(list); }) }); $('#games').on('click', 'a', function(e) { e.preventDefault(); $.ajax({ url: '/summary/' + $(this).data('game') }); }) }); <file_sep>/README.md # card.bb Montreal Baseball Hack Day 2015
af879a423818920cd306bd0aaacfa8e7a4d7ec69
[ "JavaScript", "SQL", "Markdown", "PHP" ]
19
PHP
jdhmtl/card.bb
cfc7b9cb40c7a8dfa420f83c615bd343226290b6
e6706987c5ffa45dd3558a95262bf823a00fd7af
refs/heads/master
<repo_name>muhammadkonainkhan/Calculator-Assignment<file_sep>/index.js // var a =prompt("Enter a Numner"); // var b =prompt("Enter a Length"); // for ( i=1; i<=10; i++){ // for(j=0;j=b.length; j++){ // document.write(a + "x" + a + "=" + a*j + "<br>") // } // document.write(a + "x" + i + "=" + a*i + "<br>") // console.log("2" + "x" + i + "=" + 2*i + "<br>") // } function getNumber(num){ // console.log(num); var result = document.getElementById("result") result.value += num; } function clearResult(){ var result = document.getElementById("result") result.value = "" } function getResult(){ var result = document.getElementById("result") result.value = eval(result.value) }
ab87ad7f2b755bcf6ea813102148a570ba0a5747
[ "JavaScript" ]
1
JavaScript
muhammadkonainkhan/Calculator-Assignment
ac99e7cd3d9c371902ba040e0a152c3d5796d98a
9300712b7d20179d60ea82f4f7040774d86d80a9
refs/heads/master
<file_sep>const Access = require('./Access'); const User = require('./User'); const Client = require('./Client'); const Diagnosis = require('./Diagnosis'); const IsDiagnosed = require('./IsDiagnosed'); const Relation = require('./Relation'); const Procedure = require('./Procedure'); const Treatment = require('./Treatment'); const Form = require('./Form'); const Record = require('./Record'); /**********************************/ /***** MANY-TO-MANY RELATIONS *****/ /**********************************/ User.belongsToMany(Client, { through: Relation, foreignKey: 'user_id' }); Client.belongsToMany(User, { through: Relation, foreignKey: 'client_id' }) Diagnosis.belongsToMany(Relation, { through: IsDiagnosed, foreignKey: 'dx_id' }); Relation.belongsToMany(Diagnosis, { through: IsDiagnosed, foreignKey: 'relation_id' }); Procedure.belongsToMany(Relation, { through: Treatment, foreignKey: 'procedure_id' }); Relation.belongsToMany(Procedure, { through: Treatment, foreignKey: 'relation_id' }); Treatment.belongsToMany(Form, { through: Record, foreignKey: 'tx_id' }); Form.belongsToMany(Treatment, { through: Record, foreignKey: 'form_id' }); /*********************************/ /***** ONE-TO-MANY RELATIONS *****/ /*********************************/ // onDelete: 'CASCADE', // onUpdate: 'CASCADE' // ???????????????????? Access.hasMany(User, { foreignKey: 'access_id' }); User.belongsTo(Access, { foreignKey: 'access_id' }); Diagnosis.hasMany(IsDiagnosed, { foreignKey: 'dx_id' }); IsDiagnosed.belongsTo(Diagnosis, { foreignKey: 'dx_id' }); Relation.hasMany(IsDiagnosed, { foreignKey: 'relation_id' }); IsDiagnosed.belongsTo(Relation, { foreignKey: 'relation_id' }); Client.hasMany(Relation, { foreignKey: 'client_id' }); Relation.belongsTo(Client, { foreignKey: 'client_id' }); User.hasMany(Relation, { foreignKey: 'user_id' }); Relation.belongsTo(User, { foreignKey: 'user_id' }); Relation.hasMany(Treatment, { foreignKey: 'relation_id' }); Treatment.belongsTo(Relation, { foreignKey: 'relation_id' }); Procedure.hasMany(Treatment, { foreignKey: 'procedure_id' }); Treatment.belongsTo(Procedure, { foreignKey: 'procedure_id' }); Treatment.hasMany(Record, { foreignKey: 'tx_id' }); Record.belongsTo(Treatment, { foreignKey:'tx_id' }); Form.hasMany(Record, { foreignKey: 'form_id' }); Record.belongsTo(Form, { foreignKey:'form_id' }); module.exports = { Access, User, Client, Diagnosis, IsDiagnosed, Relation, Procedure, Treatment, Form, Record }; <file_sep>const router = require('express').Router(); const { Client, Relation } = require('../../models'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { Client.create(req.body) .then(dbClientData => { console.log('dbClientData.client_id***********', dbClientData.client_id); console.log('req.session.user_id***********', req.session.user_id); Relation.create({ user_id: req.session.user_id, client_id: dbClientData.client_id }) .then(dbRelationData => res.json(dbRelationData)) .catch(err => { console.log(err); res.status(500).json(err); }); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { Client.findAll({ //attributes: { exclude: ['password'] } }) .then(dbClientData => res.json(dbClientData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { Client.findOne({ where: { client_id: req.params.id } }) .then(dbClientData => { if (!dbClientData) { res.status(404).json({ message: 'No client found' }); return; } res.json(dbClientData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { Client.update(req.body, { where: { client_id: req.params.id } }) .then(dbClientData => { console.log(dbClientData); if (!dbClientData[0]) { res.status(404).json({ message: 'No client found' }); return; } res.json(dbClientData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { Client.destroy({ where: { client_id: req.params.id } }) .then(dbClientData => { if (!dbClientData) { res.status(404).json({ message: 'No client found '}); return; } res.json(dbClientData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>const router = require('express').Router(); const { User, Access, Client, Relation } = require('../../models'); const sequelize = require('../../config/connection'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { User.create(req.body) .then(dbUserData => res.json(dbUserData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.post('/login', (req, res) => { User.findOne({ where: { username: req.body.username }, include: { model: Access, attribute: ['access_id'] } }) .then(dbUserData => { if (!dbUserData) { res.status(400).json({ message: 'No user found with that username' }); return; } // verify user const validPassword = dbUserData.checkPassword(req.body.password); if (!validPassword) { res.status(400).json({ message: 'Incorrect password!' }); return; } // create session and send response back req.session.save(() => { req.session.user_id = dbUserData.user_id; req.session.username = dbUserData.username; req.session.access_id = dbUserData.access.access_id; req.session.loggedIn = true; res.json({ user: dbUserData, message: 'You are now logged in!' }); }); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.post('/logout', (req, res) => { if (req.session.loggedIn) { req.session.destroy(() => res.status(204).end()); } else { res.status(404).end(); } }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { User.findAll({ attributes: [ 'user_id', 'username', 'first_name', 'last_name', 'primary_phone', 'alt_phone', 'email', 'dob', 'ssn', 'active', 'license_expiration',[sequelize.literal( '(SELECT COUNT(DISTINCT relation.client_id) FROM relation WHERE user.user_id = relation.user_id)' ), 'clients_nb'] ], order: ['last_name'], include: [ { model: Access, attributes: ['access_id', 'access_type'] }, { model: Client, attributes: ['first_name', 'last_name', 'primary_phone', 'alt_phone', 'email'], through: { model: Relation, attributes: ['start_date', 'end_date'] } } ] }) .then(dbUserData => res.json(dbUserData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { User.findOne({ where: { user_id: req.params.id }, attributes: [ 'user_id', 'first_name', 'last_name', 'primary_phone', 'alt_phone', 'email', [sequelize.literal( '(SELECT COUNT(DISTINCT relation.client_id) FROM relation WHERE user.user_id = relation.user_id)' ), 'clients_nb'] ], include: [ { model: Access, attributes: ['access_id', 'access_type'] }, { model: Client, attributes: ['first_name', 'last_name', 'primary_phone', 'alt_phone', 'email'], through: { model: Relation, attributes: ['start_date', 'end_date'] } } ] }) .then(dbUserData => { if (!dbUserData) { res.status(404).json({ message: 'No user found' }); return; } res.json(dbUserData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { User.update(req.body, { individualHooks: true, where: { user_id: req.params.id } }) .then(dbUserData => { if (!dbUserData[0]) { res.status(404).json({ message: 'No user found' }); return; } res.json(dbUserData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.post('/register', (req, res) => { // update user with username and password provided User.update(req.body, { individualHooks: true, where: { email: req.body.email }, //attributes: ['user_id'], // include: { // model: Access, // attribute: ['access_id'] // } }) .then(dbUserData => { if (!dbUserData) { res.status(400).json({ message: "You are not an authorized user. Please contact Shrinko's administrator to set up your account." }); return; } // create session and send response back const registeredUser = dbUserData[1][0].get({ plain: true }); req.session.save(() => { req.session.user_id = registeredUser.user_id; req.session.username = registeredUser.username; req.session.access_id = registeredUser.access_id; req.session.loggedIn = true; res.json({ user: dbUserData, message: 'Welcome to Shrinko EMHR system. You are now registered and logged in!' }); }); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { User.destroy({ where: { user_id: req.params.id } }) .then(dbUserData => { if (!dbUserData) { res.status(404).json({ message: 'No user found' }); return; } res.json(dbUserData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/connection'); class Access extends Model {} Access.init( { access_id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true }, access_type: { type: DataTypes.STRING, allowNull: false, validate: { isIn: [['superuser', 'administrator', 'clinician', 'basic', 'biller']], } }, access_desc: { type: DataTypes.TEXT, allowNull: false } }, { sequelize, freezeTableName: true, underscored: true, modelName: 'access' } ); module.exports = Access;<file_sep>DROP DATABASE IF EXISTS shrinko_db; CREATE DATABASE shrinko_db;<file_sep>const router = require('express').Router(); const { Treatment, Relation, User, Client, Procedure } = require('../../models'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { Treatment.create(req.body) .then(dbTxData => res.json(dbTxData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { Treatment.findAll({ attributes: ['tx_id', 'tx_date'], include: [ { model: Relation, attributes: ['start_date', 'end_date'], include: [{ model: User, attributes: ['first_name', 'last_name'] }, { model: Client, attributes: ['first_name', 'last_name'] // include: [{ // model: Diagnosis, // attributes: ['dx_code', 'dx_name'], // through: { // model: IsDiagnosed, // attributes: ['dx_date'] // } // }] }] }, { model: Procedure, attributes: ['procedure_name', 'cpt_code', 'procedure_desc', 'duration'] } // { // model: Form, // attributes: ['form_name'], // through: { // model: Record, // attributes: ['record_date'] // } // } ] }) .then(dbTxData => res.json(dbTxData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { Treatment.findOne({ where: { tx_id: req.params.id }, include: [ { model: Relation, attributes: ['start_date', 'end_date'], include: [{ model: User, attributes: ['first_name', 'last_name'] }, { model: Client, attributes: ['first_name', 'last_name'] // include: [{ // model: Diagnosis, // attributes: ['dx_code', 'dx_name'], // through: { // model: IsDiagnosed, // attributes: ['dx_date'] // } // }] }] }, { model: Procedure, attributes: ['procedure_name', 'cpt_code', 'procedure_desc', 'duration'] } // { // model: Form, // attributes: ['form_name'], // through: { // model: Record, // attributes: ['record_date'] // } // } ] }) .then(dbTxData => { if (!dbTxData) { res.status(404).json({ message: "This treatment was not found" }); return; } res.json(dbTxData) }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { Treatment.update(req.body, { where: { tx_id: req.params.id } }) .then(dbTxData => { if (!dbTxData[0]) { res.status(404).json({ message: 'This treatment was not found' }); return; } res.json(dbTxData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { Treatment.destroy({ where: { tx_id: req.params.id } }) .then(dbTxData => { if (!dbTxData) { res.status(404).json({ message: 'This treatment was not found' }); return; } res.json(dbTxData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>const { Form } = require('../models') const formArr = [ { "form_id": 1, "form_name": "SOAP", "form_desc": "Therapy progress note", "createdAt": "2020-08-30T14:19:58.000Z", "updatedAt": "2020-08-30T14:19:58.000Z" }, { "form_id": 2, "form_name": "Patient Demographics", "form_desc": "Patient demographics form", "createdAt": "2020-08-30T14:20:08.000Z", "updatedAt": "2020-08-30T14:20:08.000Z" }, { "form_id": 3, "form_name": "Patient History", "form_desc": "Patient history form", "createdAt": "2020-08-30T14:20:16.000Z", "updatedAt": "2020-08-30T14:20:16.000Z" }, { "form_id": 4, "form_name": "Tx Intake", "form_desc": "Initial Therapy Intake", "createdAt": "2020-08-30T14:20:29.000Z", "updatedAt": "2020-08-30T14:20:29.000Z" }, { "form_id": 5, "form_name": "n648 Intake", "form_desc": "Intake for n648 clients", "createdAt": "2020-08-30T14:20:39.000Z", "updatedAt": "2020-08-30T14:20:39.000Z" }, { "form_id": 6, "form_name": "Med-Legal Intake", "form_desc": "Intake for med-legal cases", "createdAt": "2020-08-30T14:20:49.000Z", "updatedAt": "2020-08-30T14:20:49.000Z" } ] const seedForm = () => Form.bulkCreate(formArr) module.exports = seedForm<file_sep>const router = require('express').Router(); const userRoutes = require('./user-routes.js'); const accessRoutes = require('./access-routes.js'); const clientRoutes = require('./client-routes.js'); const relationRoutes = require('./relation-routes.js'); const procedureRoutes = require('./procedure-routes.js'); const txRoutes = require('./treatment-routes.js'); const formRoutes = require('./form-routes.js'); const recordRoutes = require('./record-routes.js'); const diagnosisRoutes = require('./diagnosis-routes.js'); const isDiagnosedRoutes = require('./isdiagnosed-routes.js'); router.use('/users', userRoutes); router.use('/access', accessRoutes); router.use('/clients', clientRoutes); router.use('/relations', relationRoutes); router.use('/procedures', procedureRoutes); router.use('/tx', txRoutes); router.use('/forms', formRoutes); router.use('/records', recordRoutes); router.use('/dx', diagnosisRoutes); router.use('/dxed', isDiagnosedRoutes); module.exports = router;<file_sep>const router = require('express').Router(); const { Record, Form, Treatment } = require('../../models'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { Record.create(req.body) .then(dbRecordData => res.json(dbRecordData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { Record.findAll({ attributes: ['record_id', 'record_date'], include: [ { model: Form, attributes: ['form_name'] }, { model: Treatment, attributes: ['tx_date'] }] // { // model: Client, // attributes: ['first_name', 'last_name'] // // include: [{ // // model: Diagnosis, // // attributes: ['dx_code', 'dx_name'], // // through: { // // model: IsDiagnosed, // // attributes: ['dx_date'] // // } // // }] // } }) .then(dbRecordData => res.json(dbRecordData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { Record.findAll({ where: { record_id: req.params.id }, attributes: ['record_date'], include: [ { model: Form, attributes: ['form_name'] }, { model: Treatment, attributes: ['tx_date'] }] // { // model: Client, // attributes: ['first_name', 'last_name'] // // include: [{ // // model: Diagnosis, // // attributes: ['dx_code', 'dx_name'], // // through: { // // model: IsDiagnosed, // // attributes: ['dx_date'] // // } // // }] // } }) .then(dbRecordData => { if (!dbRecordData) { res.status(404).json({ message: "This treatment was not found" }); return; } res.json(dbRecordData) }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { Record.update(req.body, { where: { record_id: req.params.id } }) .then(dbRecordData => { if (!dbRecordData[0]) { res.status(404).json({ message: 'This record was not found' }); return; } res.json(dbRecordData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { Record.destroy({ where: { record_id: req.params.id } }) .then(dbRecordData => { if (!dbRecordData) { res.status(404).json({ message: 'This record was not found' }); return; } res.json(dbRecordData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>const router = require('express').Router(); const sequelize = require('../config/connection'); const { Procedure } = require('../models'); //display all procedures router.get('/', (req, res) => { if (req.session.loggedIn) { Procedure.findAll({ attributes: ['procedure_name', 'procedure_desc', 'cpt_code', 'duration'] }) .then(dbProcedureData => { const procedures = dbProcedureData.map(procedure => procedure.get({ plain: true })); res.render('procedures', { procedures }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); module.exports = router;<file_sep>const router = require('express').Router(); const sequelize = require('../config/connection'); const { Diagnosis } = require('../models'); //display all Diagnosis router.get('/', (req, res) => { if (req.session.loggedIn) { Diagnosis.findAll({ attributes: ['dx_name', 'dx_code', 'dx_desc'] }) .then(dbDiagnosisData => { const diagnosis = dbDiagnosisData.map(diagnosis => diagnosis.get({ plain: true })); res.render('diagnosis', { diagnosis }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); module.exports = router;<file_sep>async function editClientFormHandler(event) { event.preventDefault(); // collect client_id const idx = window.location.toString().split('/').length-1; const client_id = window.location.toString().split('/')[idx]; // collect values of form elements const first_name = document.querySelector('#clientFirstName').value.trim(); const last_name = document.querySelector('#clientLastName').value.trim(); const active = document.querySelector('#clientActive').value; const dob = document.querySelector('#clientDob').value.trim(); const ssn = document.querySelector('#clientSsn').value.trim(); const email = document.querySelector('#clientEmail').value.trim(); const primary_phone = document.querySelector('#clientPrimaryPhone').value.trim(); const alt_phone = document.querySelector('#clientAltPhone').value.trim(); const street_address = document.querySelector('#clientStreetAddress').value.trim(); const city = document.querySelector('#clientCity').value.trim(); const state = document.querySelector('#clientState').value.trim(); const zip = document.querySelector('#clientZip').value.trim(); // build the PUT request const response = await fetch(`/api/clients/${client_id}`, { method: 'PUT', body: JSON.stringify({ first_name, last_name, active, dob, ssn, email, primary_phone, alt_phone, street_address, city, state, zip }), headers: { 'Content-Type': 'application/json' } }); if (response.ok) { document.location.replace(`/clients/${client_id}`); } } document.querySelector('#client-form').addEventListener('submit', editClientFormHandler);<file_sep>const router = require('express').Router(); const { IsDiagnosed, User, Client, Relation, Diagnosis } = require('../../models'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { IsDiagnosed.create(req.body) .then(dbIsDiagnosedData => res.json(dbIsDiagnosedData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { IsDiagnosed.findAll({ attributes: ['id', 'relation_id', 'dx_id', 'dx_date'], include: [ { model: Relation, attributes: ['relation_id', 'start_date', 'end_date'], include: [{ model: User, attributes: ['user_id', 'first_name', 'last_name'] }, { model: Client, attributes: ['client_id', 'first_name', 'last_name'] }] }, { model: Diagnosis, attributes: ['dx_id', 'dx_name', 'dx_code', 'dx_desc'] } ] }) .then(dbIsDiagnosedData => res.json(dbIsDiagnosedData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { IsDiagnosed.findOne({ where: { id: req.params.id }, attributes: ['id', 'relation_id', 'dx_id', 'dx_date'], include: [ { model: Relation, attributes: ['relation_id', 'start_date', 'end_date'], include: [{ model: User, attributes: ['user_id', 'first_name', 'last_name'] }, { model: Client, attributes: ['client_id', 'first_name', 'last_name'] }] }, { model: Diagnosis, attributes: ['dx_id', 'dx_name', 'dx_code', 'dx_desc'] } ] }) .then(dbIsDiagnosedData => { if (!dbIsDiagnosedData) { res.status(404).json({ message: 'No occurrence found' }); return; } res.json(dbIsDiagnosedData) }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { IsDiagnosed.update(req.body, { where: { id: req.params.id } }) .then(dbIsDiagnosedData => { if (!dbIsDiagnosedData[0]) { res.status(404).json({ message: 'No occurrence found' }); return; } res.json(dbIsDiagnosedData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { IsDiagnosed.destroy({ where: { id: req.params.id } }) .then(dbIsDiagnosedData => { if (!dbIsDiagnosedData) { res.status(404).json({ message: 'No occurrence found' }); return; } res.json(dbIsDiagnosedData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>const router = require('express').Router(); const { Procedure } = require('../../models'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { Procedure.create(req.body) .then(dbProcedureData => res.json(dbProcedureData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { Procedure.findAll() .then(dbProcedureData => res.json(dbProcedureData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { Procedure.findOne({ where: { procedure_id: req.params.id } }) .then(dbProcedureData => { if (!dbProcedureData) { res.status(404).json({ message: 'This procedure was not found' }); return; } res.json(dbProcedureData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { Procedure.update(req.body, { where: { procedure_id: req.params.id } }) .then(dbProcedureData => { if (!dbProcedureData[0]) { res.status(404).json({ message: 'This procedure was not found' }); return; } res.json(dbProcedureData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { Procedure.destroy({ where: { procedure_id: req.params.id } }) .then(dbProcedureData => { if (!dbProcedureData) { res.status(404).json({ message: 'This procedure was not found' }); return; } res.json(dbProcedureData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>const { Relation } = require('../models') const relationArr = [ { "relation_id": 1, "user_id": "6c808d65-ff34-4e35-a87c-cbe3724cfef9", "client_id": "008229bf-2006-4262-894b-e4ae22561ec7", "start_date": "2020-01-03 18:42:23", "end_date": "2020-01-10 18:42:23" }, { "relation_id": 2, "user_id": "926bbf97-3956-49b9-8815-d4ee6882be01", "client_id": "008229bf-2006-4262-894b-e4ae22561ec7", "start_date": "2020-01-17 18:42:23" }, { "relation_id": 3, "user_id": "926bbf97-3956-49b9-8815-d4ee6882be01", "client_id": "13a64c44-bb67-42d3-b7c1-4e0452ad311b", "start_date": "2020-01-17 17:42:23" }, { "relation_id": 4, "user_id": "a4694d93-3ccc-4ddf-87de-237da04b04a1", "client_id": "e012b3e7-074e-43ab-9af2-2372360302c6", "start_date": "2020-01-24 17:42:23" }, { "relation_id": 5, "user_id": "75981688-b1a5-4ed8-98d6-83950f103eff", "client_id": "e3f6979d-e2bd-4afe-87c9-67a2e6571864", "start_date": "2020-01-10 17:42:23" } ] const seedRelation = () => Relation.bulkCreate(relationArr) module.exports = seedRelation<file_sep>const { Record } = require('../models') const recordArr = [ { "record_id": 1, "tx_id": 1, "form_id": 3, "record_date": "2020-01-03 18:42:23" }, { "record_id": 2, "tx_id": 1, "form_id": 2, "record_date": "2020-01-03 18:42:23" }, { "record_id": 3, "tx_id": 2, "form_id": 4, "record_date": "2020-01-10 18:42:23" }, { "record_id": 4, "tx_id": 3, "form_id": 1, "record_date": "2020-01-10 18:42:23" }, { "record_id": 5, "tx_id": 4, "form_id": 1, "record_date": "2020-01-24 17:42:23" }, { "record_id": 6, "tx_id": 5, "form_id": 6, "record_date": "2020-01-10 17:42:23" } ] const seedRecords = () => Record.bulkCreate(recordArr) module.exports = seedRecords<file_sep>const { Access } = require('../models') const accessArr = [ { "access_id": 1, "access_type": "superuser", "access_desc": "complete access throughout", "createdAt": "2020-08-30T14:05:39.000Z", "updatedAt": "2020-08-30T14:05:39.000Z" }, { "access_id": 2, "access_type": "administrator", "access_desc": "access and edit all data, except for access privileges and data related to security and authentication", "createdAt": "2020-08-30T14:05:48.000Z", "updatedAt": "2020-08-30T14:05:48.000Z" }, { "access_id": 3, "access_type": "clinician", "access_desc": "access and edit own clients only (documentation, notes, billing, and reports)", "createdAt": "2020-08-30T14:05:58.000Z", "updatedAt": "2020-08-30T14:05:58.000Z" }, { "access_id": 4, "access_type": "basic", "access_desc": "access and edit user, client descriptive data as well diagnosis and procedure libraries but cannot see any data related to clinical interventions (documentation, notes and reports on clients)", "createdAt": "2020-08-30T14:06:09.000Z", "updatedAt": "2020-08-30T14:06:09.000Z" }, { "access_id": 5, "access_type": "biller", "access_desc": "manage billing for all clients, but cannot see any data related to clinical interventions (documentation, notes and reports on clients)", "createdAt": "2020-08-30T14:06:20.000Z", "updatedAt": "2020-08-30T14:06:20.000Z" } ] const seedAccess = () => Access.bulkCreate(accessArr) module.exports = seedAccess;<file_sep>[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) # SHRINKO ## Description Shrinko is a web based electronic mental health records system that provides clinicians and administrative staff easy access to client records. This application has been deployed on Heroku and can be found [here](https://shrinko.herokuapp.com/). ## Table of Contents * [Models Structure](#models) * [Packages Used](#packages) * [Installation](#installation) * [Tests](#tests) * [Collaborators](#collaborators) ## Models ![ScreenShot](erdiagscreenshot.png) ## Packages Node.js, Express.js, MySQL and the Sequelize ORM, UUID, bcrypt, express-session, connect-session-sequelize, express-handlebars, dotenv ## Installation 1. To install the dependencies, type ` npm i ` at the command line. 2. Create a `.env` file and add your database name, MySQL username, and MySQL password as follows: ``` DB_NAME='shrinko_db' DB_USER='your_mysql_username' DB_PW='<PASSWORD>' SESSION_SECRET='your_top_secret' ``` 3. Open MySQL shell and migrate the database schema by typing `source schema.sql` 4. Type `exit` to exit the MySQL shell 5. Create a `.gitignore` file and the following folder and files: ``` node_modules .DS_Store .env ``` ## Tests 1. At the command line run `npm run seed` to seed data to the database so you can test the routes 2. Start the server by typing `npm start` 3. Test the routes in Insomnia or other API design platform ## Collaborators - <NAME> ([@seanc0ne](https://github.com/seanc0ne)) - <NAME> ([@PetitsPoissons](https://github.com/PetitsPoissons/)) - <NAME> ([@designurhappy](https://github.com/designurhappy)) <file_sep>const { Treatment } = require('../models') const treatmentArr = [ { "tx_id": 1, "procedure_id": 1, "relation_id": 1, "tx_date": "2020-01-03 18:42:23" }, { "tx_id": 2, "procedure_id": 2, "relation_id": 1, "tx_date": "2020-01-10 18:42:23" }, { "tx_id": 3, "procedure_id": 3, "relation_id": 3, "tx_date": "2020-01-10 18:42:23" }, { "tx_id": 4, "procedure_id": 1, "relation_id": 4, "tx_date": "2020-01-24 17:42:23" }, { "tx_id": 5, "procedure_id": 1, "relation_id": 5, "tx_date": "2020-01-10 17:42:23" } ] const seedTreatment = () => Treatment.bulkCreate(treatmentArr) module.exports = seedTreatment<file_sep>const router = require('express').Router(); const sequelize = require('../config/connection'); const { Client, User, Relation } = require('../models'); //////////////////////////////////////////// // render template to create a new client // //////////////////////////////////////////// router.get('/new', (req, res) => { if (req.session.loggedIn) { res.render('create-client'); } else { res.render('login'); } }); //////////////////////////////////////////// // render template to display all clients // //////////////////////////////////////////// router.get('/', (req, res) => { if (req.session.loggedIn) { Client.findAll({ attributes: ['client_id', 'first_name', 'last_name', 'email', 'primary_phone', 'active'], include: [ { model: User, attributes: ['first_name', 'last_name'], through: { model: Relation } } ], order: ['last_name'] }) .then(dbClientData => { const clients = dbClientData.map(client => client.get({ plain: true })); res.render('clients', { clients }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); ////////////////////////////////////////////// // render single-client template - READONLY // ////////////////////////////////////////////// router.get('/:id', (req, res) => { if (req.session.loggedIn) { Client.findOne({ attributes: { include: [ 'first_name', 'last_name', 'dob', 'ssn', 'email', 'primary_phone', 'alt_phone', 'street_address', 'city', 'state', 'zip', 'insurance', 'active', [sequelize.literal( '(SELECT COUNT(DISTINCT relation.user_id) FROM relation WHERE client.client_id = relation.client_id)' ), 'clinicians_nb'] ] }, where: { client_id: req.params.id } }) .then(dbClientData => { if (!dbClientData) { res.status(404).json({ message: 'No client found' }); return; } // serialize the data const client = dbClientData.get({ plain: true }); // pass data to template res.render('single-client', { client }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); /////////////////////////////////////////////// // render single-client template - EDIT FORM // /////////////////////////////////////////////// router.get('/edit/:id', (req, res) => { if (req.session.loggedIn) { Client.findOne({ attributes: { include: [ 'first_name', 'last_name', 'dob', 'ssn', 'email', 'primary_phone', 'alt_phone', 'street_address', 'city', 'state', 'zip', 'insurance', 'active', [sequelize.literal( '(SELECT COUNT(DISTINCT relation.user_id) FROM relation WHERE client.client_id = relation.client_id)' ), 'clinicians_nb'] ] }, where: { client_id: req.params.id } }) .then(dbClientData => { if (!dbClientData) { res.status(404).json({ message: 'No client found' }); return; } // serialize the data const client = dbClientData.get({ plain: true }); // pass data to template res.render('edit-single-client', { client }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); module.exports = router;<file_sep>const router = require('express').Router(); const apiRoutes = require('./api'); const startRoutes = require('./feStartRoutes'); const userRoutes = require('./feUserRoutes'); const formRoutes = require('./feFormRoutes'); const procedureRoutes = require('./feProcedureRoutes'); const diagnosisRoutes = require('./feDiagnosisRoutes'); const clientRoutes = require('./feClientRoutes'); const dashboardRoutes = require('./feDashboardRoutes'); router.use('/api', apiRoutes); router.use('/', startRoutes); router.use('/users', userRoutes); router.use('/forms', formRoutes); router.use('/procedures', procedureRoutes); router.use('/diagnosis', diagnosisRoutes); router.use('/clients', clientRoutes); router.use('/dashboard', dashboardRoutes); router.use((req, res) => { res.status(404).end(); }); module.exports = router;<file_sep>const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/connection'); class Client extends Model {} Client.init( { client_id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, allowNull: false }, first_name: { type: DataTypes.STRING, allowNull: false, validate: { len: [1, 45] } }, last_name: { type: DataTypes.STRING, allowNull: false, validate: { len: [1, 45] } }, dob: { type: DataTypes.DATE, allowNull: false }, ssn: { type: DataTypes.STRING, allowNull: false }, primary_phone: { type: DataTypes.STRING, allowNull: false }, alt_phone: { type: DataTypes.STRING }, email: { type: DataTypes.STRING, }, street_address: { type: DataTypes.STRING, allowNull: false, validate: { len: [1, 45] } }, city: { type: DataTypes.STRING, allowNull: false, validate: { len: [1, 45] } }, state: { type: DataTypes.STRING, allowNull: false }, zip: { type: DataTypes.STRING, allowNull: false }, insurance: { type: DataTypes.BOOLEAN, //allowNull: false defaultValue: false }, active: { type: DataTypes.BOOLEAN, defaultValue: true } }, { sequelize, timestamps: true, freezeTableName: true, underscored: true, modelName: 'client' } ); module.exports = Client; <file_sep>const { Procedure } = require('../models') const procedureArr = [ { "procedure_id": 1, "procedure_name": "Intake", "procedure_desc": "Psychiatric diagnostic interview examination", "cpt_code": "90791", "duration": "1 to 2 units/hours", "createdAt": "2020-08-30T14:17:45.000Z", "updatedAt": "2020-08-30T14:17:45.000Z" }, { "procedure_id": 2, "procedure_name": "Individual psychotherapy - 30 mns", "procedure_desc": "Individual psychotherapy - 30 mns", "cpt_code": "90832", "duration": "30 minutes (.5 unit/hour)", "createdAt": "2020-08-30T14:17:55.000Z", "updatedAt": "2020-08-30T14:17:55.000Z" }, { "procedure_id": 3, "procedure_name": "Individual psychotherapy - 45 mns", "procedure_desc": "Individual psychotherapy - 45 mns", "cpt_code": "90834", "duration": "45 minutes (1 unit/hour)", "createdAt": "2020-08-30T14:18:05.000Z", "updatedAt": "2020-08-30T14:18:05.000Z" }, { "procedure_id": 4, "procedure_name": "Individual psychotherapy - 60 mns", "procedure_desc": "Individual psychotherapy - 60 mns", "cpt_code": "90837", "duration": "60 minutes (1 unit/hour) or longer based on units billed", "createdAt": "2020-08-30T14:18:15.000Z", "updatedAt": "2020-08-30T14:18:15.000Z" }, { "procedure_id": 5, "procedure_name": "Family psychotherapy - w/o patient", "procedure_desc": "Family psychotherapy - without the patient present", "cpt_code": "90846", "duration": "1 to 2 units/hours", "createdAt": "2020-08-30T14:18:26.000Z", "updatedAt": "2020-08-30T14:18:26.000Z" }, { "procedure_id": 6, "procedure_name": "Family psychotherapy - w/ patient", "procedure_desc": "Family psychotherapy (including conjoint) - with the patient present", "cpt_code": "90847", "duration": "1 to 2 units/hours", "createdAt": "2020-08-30T14:18:36.000Z", "updatedAt": "2020-08-30T14:18:36.000Z" }, { "procedure_id": 7, "procedure_name": "Group psychotherapy", "procedure_desc": "Group psychotherapy", "cpt_code": "90853", "duration": "1 to 2 units/hours", "createdAt": "2020-08-30T14:18:45.000Z", "updatedAt": "2020-08-30T14:18:45.000Z" }, { "procedure_id": 8, "procedure_name": "Testing", "procedure_desc": "Testing, psychological - submission of test results and evaluation of results are required by VCB", "cpt_code": "96101", "duration": "up to 8 units/hours", "createdAt": "2020-08-30T14:18:55.000Z", "updatedAt": "2020-08-30T14:18:55.000Z" }, { "procedure_id": 9, "procedure_name": "Telehealth", "procedure_desc": "Telehealth, non-psychiatrist - limit 5 units/hours per VCB application", "cpt_code": "98968", "duration": "30 minutes (.5 unit/hour) to 1 unit/hour", "createdAt": "2020-08-30T14:19:04.000Z", "updatedAt": "2020-08-30T14:19:04.000Z" } ] const seedProcedure = () => Procedure.bulkCreate(procedureArr) module.exports = seedProcedure<file_sep>const router = require('express').Router(); const sequelize = require('../config/connection'); const { Client, Relation, Treatment, Procedure } = require('../models'); /////////////////////////////////////////////////////////////// // render template to create a new client for this clinician // /////////////////////////////////////////////////////////////// router.get('/client/new', (req, res) => { if (req.session.loggedIn) { res.render('dash-create-client'); } else { res.render('login'); } }); /////////////////////////////////////////////////////////////// // render template to display all clients for this clinician // /////////////////////////////////////////////////////////////// router.get('/', (req, res) => { Relation.findAll({ where: { user_id: req.session.user_id }, attributes: ['relation_id', 'user_id', 'client_id', 'start_date', 'end_date', [sequelize.literal( '(SELECT COUNT(DISTINCT treatment.tx_date) FROM treatment WHERE treatment.relation_id = relation.relation_id)' ), 'tx_dates_nb']], include: [ { model: Client, attributes: ['first_name', 'last_name', 'email', 'primary_phone'] } ], order: ['start_date'] }) .then(dbRelationData => { // serialize data const relations = dbRelationData.map(relation => relation.get({ plain: true })); // render data res.render('dashboard', { relations, loggedIn: true }); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /////////////////////////////////////////////////////////////// // display all treatments for this client-clinician relation // /////////////////////////////////////////////////////////////// router.get('/tx/:id', (req, res) => { req.session.save(() => { req.session.relation_id = req.params.id; }); console.log('***************req.session', req.session); Treatment.findAll({ where: { relation_id: req.params.id }, attributes: ['tx_date'], include: [ { model: Procedure, attributes: ['procedure_name', 'cpt_code', 'duration'] }, { model: Relation, attributes: ['relation_id'], include: { model: Client, attributes: ['client_id', 'first_name', 'last_name', 'active', 'dob', 'ssn', 'email', 'primary_phone', 'alt_phone', 'street_address', 'city', 'state', 'zip'] } } ], order: ['tx_date'] }) .then(dbTxData => { // serialize data const treatments = dbTxData.map(tx => tx.get({ plain: true })); const client = treatments[0].relation.client; // render data res.render('treatments', { treatments, client, loggedIn: true }); }) }) /////////////////////////////////////////////////////// // render dashboard-edit-client template - EDIT FORM // /////////////////////////////////////////////////////// router.get('/tx/edit/client/:id', (req, res) => { if (req.session.loggedIn) { Client.findOne({ attributes: { include: [ 'first_name', 'last_name', 'dob', 'ssn', 'email', 'primary_phone', 'alt_phone', 'street_address', 'city', 'state', 'zip', 'insurance', 'active', [sequelize.literal( '(SELECT COUNT(DISTINCT relation.user_id) FROM relation WHERE client.client_id = relation.client_id)' ), 'clinicians_nb'] ] }, where: { client_id: req.params.id } }) .then(dbClientData => { if (!dbClientData) { res.status(404).json({ message: 'No client found' }); return; } // serialize the data const client = dbClientData.get({ plain: true }); // pass data and relation_id to template res.render('dash-edit-client', { client }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); module.exports = router;<file_sep>const router = require('express').Router(); const { Relation, User, Client, Access } = require('../../models'); /******************/ /***** CREATE *****/ /******************/ router.post('/', (req, res) => { Relation.create(req.body) .then(dbRelationData => res.json(dbRelationData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /****** READ ******/ /******************/ router.get('/', (req, res) => { Relation.findAll({ attributes: ['relation_id', 'user_id', 'client_id'], include: [ { model: User, attributes: ['user_id', 'first_name', 'last_name'], include: [{ model: Access, attributes: ['access_type'] }] }, { model: Client, attributes: ['client_id', 'first_name', 'last_name'] // include: [{ // model: Diagnosis, // attributes: ['dx_code', 'dx_name'], // through: { // model: IsDiagnosed, // attributes: ['dx_date'] // } // }] } // { // model: Procedure, // attributes: ['procedure_name', 'duration'], // through: { // model: Treatment, // attributes: ['tx_date'], // include: [{ // model: Form, // attributes: ['form_name'], // through: { // model: Record, // attributes: ['record_date'] // } // }] // } // } ] }) .then(dbRelationData => res.json(dbRelationData)) .catch(err => { console.log(err); res.status(500).json(err); }); }); router.get('/:id', (req, res) => { Relation.findOne({ where: { relation_id: req.params.id }, include: [ { model: User, attributes: ['first_name', 'last_name'], include: [{ model: Access, attributes: ['access_type'] }] }, { model: Client, attributes: ['first_name', 'last_name'] // include: [{ // model: Diagnosis, // attributes: ['dx_code', 'dx_name'], // through: { // model: IsDiagnosed, // attributes: ['dx_date'] // } // }] } // { // model: Procedure, // attributes: ['procedure_name', 'duration'], // through: { // model: Treatment, // attributes: ['tx_date'], // include: [{ // model: Form, // attributes: ['form_name'], // through: { // model: Record, // attributes: ['record_date'] // } // }] // } // } ] }) .then(dbRelationData => { if (!dbRelationData) { res.status(404).json({ message: 'This relation was not found' }); return; } res.json(dbRelationData) }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** UPDATE *****/ /******************/ router.put('/:id', (req, res) => { Relation.update(req.body, { where: { relation_id: req.params.id } }) .then(dbRelationData => { if (!dbRelationData[0]) { res.status(404).json({ message: 'This relation was not found' }); return; } res.json(dbRelationData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); /******************/ /***** DELETE *****/ /******************/ router.delete('/:id', (req, res) => { Relation.destroy({ where: { relation_id: req.params.id } }) .then(dbRelationData => { if (!dbRelationData) { res.status(404).json({ message: 'This relation was not found' }); return; } res.json(dbRelationData); }) .catch(err => { console.log(err); res.status(500).json(err); }); }); module.exports = router;<file_sep>module.exports = { format_date: date => { const d = new Date(date); let month = d.getMonth() + 1; if (month < 10) { month = `0${month}`; } let day = d.getDate(); if (day < 10) { day = `0${day}`; } return `${new Date(date).getFullYear()}-${month}-${day}`; }, format_phone: phone => { return `${phone.replace('-', '')}`; }, format_plural: (word, amount) => { if (amount > 1) { return `${word}s`; } return word; }, format_ssn: val => { val = val.replace(/\D/g, ''); val = val.replace(/^(\d{3})/, '$1-'); val = val.replace(/-(\d{2})/, '-$1-'); val = val.replace(/(\d)-(\d{4}).*/, '$1-$2'); return val; // val="135711458" ==> "135-71-1458" } } <file_sep>const { IsDiagnosed } = require('../models') const isDxArr = [ { "id": 1, "relation_id": 1, "dx_id": 1, "dx_date": "2020-01-03 18:42:23" }, { "id": 2, "relation_id": 1, "dx_id": 3, "dx_date": "2020-01-10 18:42:23" }, { "id": 3, "relation_id": 2, "dx_id": 4, "dx_date": "2020-01-17 18:42:23" }, { "id": 4, "relation_id": 3, "dx_id": 2, "dx_date": "2020-01-17 18:42:23" }, { "id": 5, "relation_id": 4, "dx_id": 5, "dx_date": "2020-01-24 18:42:23" }, { "id": 6, "relation_id": 5, "dx_id": 4, "dx_date": "2020-01-10 18:42:23" } ] const seedIsDx = () => IsDiagnosed.bulkCreate(isDxArr) module.exports = seedIsDx<file_sep>const router = require('express').Router(); const sequelize = require('../config/connection'); const { Form } = require('../models'); // display all documents router.get('/', (req, res) => { if (req.session.loggedIn) { Form.findAll({ attributes: ['form_name', 'form_desc'] }) .then(dbFormData => { const forms = dbFormData.map(form => form.get({ plain: true })); res.render('forms', { forms }); }) .catch(err => { console.log(err); res.status(500).json(err); }); } else { res.render('login'); } }); module.exports = router;
561979ee6f1345e2961f6a3bbb8aec381eacc080
[ "JavaScript", "SQL", "Markdown" ]
28
JavaScript
PetitsPoissons/admin-patient-system
67854afb602b3af0acb8b121db6f956fcc289937
817c49c49d4eb817b89879586a3e03dd7c9c1654
refs/heads/master
<repo_name>jkr78/JPM<file_sep>/test_trade.py #!/usr/bin/env python3 import datetime import unittest from datetime import timedelta import stock import trade class TestTradeMethods(unittest.TestCase): def test_trade(self): stock1 = stock.StockFactory( 'Common', 'TEST1', last_dividend=8, par_value=100) o = trade.Trade( stock1, datetime.datetime.now(), 1, 'Buy', 2) self.assertIsInstance(o, trade.Trade) o = trade.Trade( stock1, datetime.datetime.now(), 1, 'Sell', 2) self.assertIsInstance(o, trade.Trade) o = trade.Trade( stock1, datetime.datetime.now(), 1, trade.TradeIndicator.BUY, 2) self.assertIsInstance(o, trade.Trade) with self.assertRaises(Exception) as context: o = trade.Trade( stock1, datetime.datetime.now(), 1, '__BAD_INDICATOR__', 2) self.assertTrue( 'is not a valid TradeIndicator' in str(context.exception)) class TestSimpleTradeListMethods(unittest.TestCase): def setUp(self): self.stock1 = stock.StockFactory( 'Common', 'TEST1', last_dividend=8, par_value=100) self.stock2 = stock.PreferredStock( 'TEST2', last_dividend=8, fixed_dividend=2, par_value=100) self.stock3 = stock.CommonStock( 'TEST3', last_dividend=0, par_value=100) def test_volume_weighted_stock_price(self): now = datetime.datetime.now() stl1 = trade.SimpleTradeList() trade1 = trade.Trade(self.stock1, now - timedelta(minutes=3), 1, 'Buy', 2) stl1.record_trade(trade1) trade2 = trade.Trade(self.stock1, now - timedelta(minutes=2), 1, 'Buy', 3) stl1.record_trade(trade2) trade3 = trade.Trade(self.stock1, now - timedelta(minutes=1), 1, 'Buy', 4) stl1.record_trade(trade3) self.assertEqual( stl1.volume_weighted_stock_price(self.stock1.symbol, now=now), 3) stl2 = trade.SimpleTradeList() trade1 = trade.Trade(self.stock1, now - timedelta(minutes=3), 2, 'Buy', 2) stl2.record_trade(trade1) trade2 = trade.Trade(self.stock1, now - timedelta(minutes=2), 3, 'Buy', 5) stl2.record_trade(trade2) trade3 = trade.Trade(self.stock1, now - timedelta(minutes=1), 4, 'Buy', 6) stl2.record_trade(trade3) self.assertAlmostEqual( stl2.volume_weighted_stock_price(self.stock1.symbol, now=now), 4.77, places=1) # by default we check last 15 minutes, so stock with price 10 # must not be calculated in stl3 = trade.SimpleTradeList() trade1 = trade.Trade(self.stock1, now - timedelta(minutes=20), 1, 'Buy', 10) stl3.record_trade(trade1) trade2 = trade.Trade(self.stock1, now - timedelta(minutes=10), 1, 'Buy', 20) stl3.record_trade(trade2) trade3 = trade.Trade(self.stock1, now - timedelta(minutes=5), 1, 'Buy', 30) stl3.record_trade(trade3) self.assertEqual( stl3.volume_weighted_stock_price(self.stock1.symbol, now=now), 25) def test_geometric_mean(self): now = datetime.datetime.now() stl1 = trade.SimpleTradeList() trade1 = trade.Trade(self.stock1, now - timedelta(minutes=2), 1, 'Buy', 2) stl1.record_trade(trade1) trade2 = trade.Trade(self.stock2, now - timedelta(minutes=1), 1, 'Buy', 8) stl1.record_trade(trade2) self.assertEqual(stl1.geometric_mean(), 4) # 2, 8 = 4 stl2 = trade.SimpleTradeList() trade1 = trade.Trade(self.stock1, now - timedelta(minutes=3), 1, 'Buy', 4) stl2.record_trade(trade1) trade2 = trade.Trade(self.stock2, now - timedelta(minutes=2), 1, 'Buy', 1) stl2.record_trade(trade2) trade3 = trade.Trade(self.stock3, now - timedelta(minutes=1), 1, 'Buy', 1 / 32) stl2.record_trade(trade3) # 4, 1, 1/32 = 1/2 self.assertAlmostEqual(stl2.geometric_mean(), 1 / 2) if __name__ == '__main__': unittest.main() <file_sep>/README.md # Solution to Example Assignment – Super Simple Stock Market * Code is written in Python3. * I have not used external libraries (like numpy) purposely. I have tried to write code with no external requirements * I have made SimpleTradeList() very simple. No extra methods (except add record and make calculations). * Code is checked with PEP8 * To run tests you can execute: `python test_stock.py` or `python test_trade.py` <file_sep>/stock.py #!/usr/bin/env python3 from abc import ABC, abstractmethod from enum import Enum class StockType(Enum): COMMON = 'Common' PREFERRED = 'Preferred' class StockABC(ABC): def __init__(self, symbol, last_dividend, fixed_dividend, par_value): """Initialise StockABC Interface for all Stock objects Args: symbol: Stock Symbol. last_dividend: Last Dividend. fixed_dividend: Fixed Dividend. par_value: Par Value. """ self.symbol = symbol self.last_dividend = last_dividend self.fixed_dividend = fixed_dividend self.par_value = par_value @abstractmethod def dividend_yield(self, price): pass def pe_ratio(self, price): """Calculate P/E Ratio for a given Price No information is given about rounding rules. So no rounding, ceiling or flooring is applied. I do not use Decimal for precision since pennies are used as currency. And no information is given about precision requirements. Args: price: Price in pennies Returns: P/E Ratio or 0 using formula: Price / Dividend If Dividend happens to be 0 - return 0 """ dividend_yield = self.dividend_yield(price) if dividend_yield == 0: return 0 return price / dividend_yield class CommonStock(StockABC): def __init__(self, symbol, last_dividend, par_value): """Initialise CommonStock Args: symbol: Stock Symbol. last_dividend: Last Dividend. par_value: Par Value. """ super().__init__( symbol, last_dividend=last_dividend, fixed_dividend=None, par_value=par_value) def dividend_yield(self, price): """Calculate Dividend Yield for a given Price No information is given about rounding rules. So no rounding, ceiling or flooring is applied. I do not use Decimal for precision since pennies are used as currency. And no information is given about precision requirements. Args: price: Price in pennies Returns: Dividend Yield using formula: Last Dividend / Price If price is 0 - dividend yield is 0. """ if price == 0: return 0 return self.last_dividend / price def __repr__(self): return 'CommonStock({symbol!r}, {last_dividend!r}, ' \ '{par_value!r})'.format( symbol=self.symbol, last_dividend=self.last_dividend, par_value=self.par_value) class PreferredStock(StockABC): def __init__(self, symbol, last_dividend, fixed_dividend, par_value): """Initialise PreferredStock Args: symbol: Stock Symbol. last_dividend: Last dividend fixed_dividend: Fixed Dividend. par_value: Par Value. """ super().__init__( symbol, last_dividend=last_dividend, fixed_dividend=fixed_dividend, par_value=par_value) def dividend_yield(self, price): """Calculate Dividend Yield for a given Price No information is given about rounding rules. So no rounding, ceiling or flooring is applied. I do not use Decimal for precision since pennies are used as currency. And no information is given about precision requirements. Args: price: Price in pennies Returns: Dividend Yield using formula: (Fixed Dividend * Par Value) / Price If Price is 0 - Dividend Yield is 0. """ if price == 0: return 0 # fixed_dividend is in percents, we have to divide by 100 return (self.fixed_dividend * self.par_value) / (price * 100) def __repr__(self): return 'PreferredStock({symbol!r}, {last_dividend!r}, ' \ '{fixed_dividend!r}, {par_value!r})'.format( symbol=self.symbol, last_dividend=self.last_dividend, fixed_dividend=self.fixed_dividend, par_value=self.par_value) class StockFactory(object): """Returns stock object depending on type >>> StockFactory(StockType.COMMON, 'TEA', last_dividend=0, par_value=100) CommonStock('TEA', 0, 100) >>> StockFactory(StockType.PREFERRED, 'GIN', last_dividend=8, fixed_dividend=2, par_value=100) PreferredStock('GIN', 8, 2, 100) >>> StockFactory('Common', 'POP', last_dividend=8, par_value=100) CommonStock('POP', 8, 100) """ stock_types = { StockType.COMMON: CommonStock, StockType.PREFERRED: PreferredStock, } def __new__(self, stock_type, *args, **kwargs): stock = self.stock_types[StockType(stock_type)](*args, **kwargs) return stock if __name__ == "__main__": # no requirements for cui or gui, just run doctests if exist import doctest doctest.testmod() <file_sep>/trade.py #!/usr/bin/env python3 import datetime import math from datetime import timedelta from enum import Enum from stock import StockABC class TradeIndicator(Enum): BUY = 'Buy' SELL = 'Sell' class Trade(object): def __init__(self, stock, timestamp, quantity, indicator, traded_price): """Initialise Trade object Contains information about stock purchase/sale denoted by indicator (Buy/Sell) at specified timestamp. Each purchase/sale contains quantity and traded price also. Args: stock: Stock. Must be an instance of StockABC. timestamp: The timestamp of purchase/sale. Must be an instance of time, date or datetime. quantity: The quantity. indicator: purchase/sale idicator as TradeIndicator. traded_price: The traded price. """ assert isinstance(stock, StockABC), \ 'stock is not an instance of StockABC' assert isinstance(timestamp, (datetime.date, datetime.time)), \ 'timestamp is not an instance of date, time or datetime' self.stock = stock self.timestamp = timestamp self.quantity = quantity self.indicator = TradeIndicator(indicator) self.traded_price = traded_price def __repr__(self): return 'Trade({stock!r}, {timestamp!r}, {quantity!r}, ' \ '{indicator!r}, {traded_price!r})'.format( stock=self.stock, timestamp=self.timestamp, quantity=self.quantity, indicator=self.indicator, traded_price=self.traded_price) class SimpleTradeList(object): """This is the simple Trade record list This trade list expects that all records are added in already sorted order (by timestamp). Though more than one trade symbol is allowed per same timestamp. I have implemented this List in very simple way. Though it contains some performance enhancments it is far from good. For real trade app Red-Black/AVL (depending on the needs) or other specialised data structure may be used. """ def __init__(self): """Initialise Empty Simple Trade List The trade is stored as dict, where key is trade symbol and value is list of trades in sorted order. Empty Simple Trade List does not sort or in other way change the order on appended trades. User must make sure to add trades in correct order (though I could use bisect to this, but it would require another list or implement comparision in Trade on timestamp). traded_price_count contains number of total trades per all symbols it total_traded_price_log contains precompiled log for all traded prices I will use first sum(log()), then exp(1/n) to make sure not overflow then multiplying prices """ self.records = {} self.traded_price_count = 0 self.total_traded_price = 0 self.total_traded_price_log = 0 self.last_timestamp = None def record_trade(self, trade): assert isinstance(trade, Trade), \ 'trade is not an instance of Trade: {}'.format(trade) stock_symbol = trade.stock.symbol trade_list = self.records.setdefault(stock_symbol, []) assert (len(trade_list) == 0 or trade_list[-1].timestamp <= trade.timestamp), \ 'trade.timestamp is not in order for {}: {}'.format( stock_symbol, trade) trade_list.append(trade) self.traded_price_count += 1 self.total_traded_price += trade.traded_price self.total_traded_price_log += math.log(trade.traded_price) if self.last_timestamp is None: self.last_timestamp = trade.timestamp else: self.last_timestamp = max(self.last_timestamp, trade.timestamp) def get_last_timestamp(self, stock_symbol=None): """Last stored timestamp Args: stock_symbol: if specified returns last timestamp for this stock """ if stock_symbol is None: return self.last_timestamp trades = self.records.get(stock_symbol) if not trades: return None return trades[-1].timestamp def geometric_mean(self): """Calculate Geometric Mean for all stocks Returns: Geometric mean of all stock traded prices """ if self.traded_price_count < 1: return 0 # idea based on: http://stackoverflow.com/a/43099751 # but i am not using numpy and precalculating log(traded_price) r = math.exp(self.total_traded_price_log / self.traded_price_count) return r def volume_weighted_stock_price(self, stock_symbol, now=None, trade_timedelta=timedelta(minutes=15)): """Calculate Volume Weighted Stock Price based on trades Args: stock_symbol: Stock Symbol to calculate for. now: timestamp to start calculation from. trade_timedelta: timedelta denoting how much trades to calc. Returns: Volume Weighted Stock Price If now is not specified (or is None) we will use current PC timestamp. To get last stored timestamp use get_last_timestamp() function """ trades = self.records.get(stock_symbol) if not trades: return 0 # not found total_traded = 0 total_quantity = 0 if now is None: # for the last timestamp in records use: now = trades[-1].timestamp now = datetime.datetime.now() for i in range(len(trades) - 1, -1, -1): # lets go back in time if now - trade_timedelta > trades[i].timestamp: break total_traded += (trades[i].traded_price * trades[i].quantity) total_quantity += trades[i].quantity if total_quantity == 0: return 0 return total_traded / total_quantity if __name__ == "__main__": # no requirements for cui or gui, just run doctests if exist import doctest doctest.testmod() <file_sep>/test_stock.py #!/usr/bin/env python3 import random import sys import unittest import stock class TestStockFactory(unittest.TestCase): def test_factory(self): with self.assertRaises(Exception) as context: o = stock.StockFactory( '_', '_', last_dividend=8, fixed_dividend=2, par_value=10) self.assertTrue('is not a valid StockType' in str(context.exception)) o = stock.StockFactory( 'Common', 'POP', last_dividend=8, par_value=100) self.assertIsInstance(o, stock.CommonStock) o = stock.StockFactory( stock.StockType.COMMON, 'TEA', last_dividend=0, par_value=100) self.assertIsInstance(o, stock.CommonStock) o = stock.StockFactory( stock.StockType.PREFERRED, 'GIN', last_dividend=8, fixed_dividend=2, par_value=10) self.assertIsInstance(o, stock.PreferredStock) o = stock.StockFactory( 'Preferred', 'GIN', last_dividend=8, fixed_dividend=2, par_value=10) self.assertIsInstance(o, stock.PreferredStock) class TestStockMethods(unittest.TestCase): def test_common_stock_dividend_yield(self): o = stock.CommonStock( 'TEST', last_dividend=0, par_value=0) self.assertEqual(o.dividend_yield(0), 0) self.assertEqual(o.dividend_yield(1), 0) self.assertEqual(o.dividend_yield(-1), 0) self.assertEqual(o.dividend_yield(sys.maxsize), 0) self.assertEqual(o.dividend_yield(-sys.maxsize), 0) x = random.randint(0, sys.maxsize) self.assertEqual(o.dividend_yield(x), 0) x = random.randint(-sys.maxsize, 0) self.assertEqual(o.dividend_yield(x), 0) x = random.randint(-sys.maxsize, sys.maxsize) self.assertEqual(o.dividend_yield(x), 0) o = stock.CommonStock( 'TEST', last_dividend=120, par_value=0) self.assertEqual(o.dividend_yield(0), 0) self.assertEqual(o.dividend_yield(1), 120) # 120 / 120 self.assertEqual(o.dividend_yield(2), 60) # 120 / 2 self.assertEqual(o.dividend_yield(3), 40) # 120 / 2 self.assertEqual(o.dividend_yield(120), 1) # 120 / 120 def test_preferred_stock_dividend_yield(self): o = stock.PreferredStock( 'TEST', last_dividend=8, fixed_dividend=2, par_value=100) self.assertEqual(o.dividend_yield(0), 0) self.assertEqual(o.dividend_yield(1), 2) # 2% * 100 / 1 self.assertEqual(o.dividend_yield(2), 1) # 2% * 100 / 2 def test_pe_ratio(self): o = stock.CommonStock( 'TEST', last_dividend=120, par_value=0) self.assertEqual(o.pe_ratio(0), 0) self.assertEqual(o.pe_ratio(1), 1 / 120) # 120 / 1 = 120; 1 / 120 self.assertAlmostEqual(o.pe_ratio(2), 2 / 60) # 120 / 2 = 60; 2 / 60 self.assertEqual(o.pe_ratio(60), 30) # 120 / 60 = 2; 60 / 2 = 30 self.assertEqual(o.pe_ratio(120), 120) # 120 / 120 = 1; 120 / 1 = 120 if __name__ == '__main__': unittest.main()
23d4ed2607801b85523ea567cf0dae1ada47b16c
[ "Markdown", "Python" ]
5
Python
jkr78/JPM
0bac10b8861a63c8069e15793bf4bceecc495a42
6422c1b035a27d1aaf16ce834b30460b005e5cbc
refs/heads/master
<file_sep>package org.git2; public class Git2 { public static void main(String[] args) { System.out.println("1"); System.out.println("2"); System.out.println("3"); System.out.println("1A"); System.out.println("1B"); System.out.println("2A"); } }
dad1e03d0ec60815b30d890a2cd1b5af64775e58
[ "Java" ]
1
Java
siivashanmugam09/git2
2e8f0428712085528e6d96b68214c911d4b0578e
829fe6d17721d6055c55dcb707a772cb877cdc6f
refs/heads/master
<repo_name>clkangta/SublimePhpBox<file_sep>/readme.md # PhpBox ## 插件作用 提供php与sublime 的通信,便于用户开发tp5命令来扩展sublime的功能。 ## python技巧 ### 参数默认值 ### utf8字符串的输出 ### json ### base64 ### 异常 ## sublime ui ok_cancel_dialog status_message message_dialog error_message show_quick_panel show_input_panel create_output_panel find_output_panel<file_sep>/php_box.py # -*- coding: utf-8 -*- import sublime, sublime_plugin, sys # import sublime_lib import os, subprocess, string, json, threading, re, time import base64 from .thread_progress import ThreadProgress package_name = 'PhpBox' packages_path = os.path.split(os.path.realpath(__file__))[0] command_bin = packages_path + os.sep + 'tp5' + os.sep + 'public' + os.sep + 'index.php' def PKGPATH(): return os.path.join(sublime.packages_path(), "PhpBox") def CMD_DIR(): return os.path.join(ChigiArgs.PKGPATH(), 'sublime_php_command') def CMD_PATH(): return os.path.join(ChigiArgs.CMD_DIR(), 'sublime.php') class php_execute(threading.Thread): def __init__(self, cmd, args): self.cmd = cmd self.args = args global command_bin self.php_bin = command_bin threading.Thread.__init__(self) def run(self): command_text = 'php "' + command_bin + '" sublime/index/run/call/'+self.cmd+'/args/'+ base64.b64encode(json.dumps(self.args, sort_keys=True).encode('utf-8')).decode('utf-8') print(command_text) cloums = os.popen(command_text) data = cloums.read() print(data) self.parse_php_result(data) def parse_php_result(self, out): try: print(out) result_str_raw = out # out = out.decode("UTF-8") except UnicodeDecodeError as e: print(out) try: result_str = base64.b64decode(out) except (TypeError): print(out) pass except (binascii.Error): print(out) pass result = 0; try: result = json.loads(result_str.decode('utf-8')) except (ValueError): print('The return value for the php plugin is wrong JSON.',True) if len(result_str) > 0: try: sublime.error_message(u"PHP ERROR:\n{0}".format(result_str.decode('utf-8'))) except(UnicodeDecodeError): sublime.error_message(u"PHP ERROR:\n{0}".format(result_str_raw)) pass print(type(result)) print(result) # ------------------------------------------------------------------- # PHP 通信完成,开始处理结果 # ------------------------------------------------------------------- self.executeReceive(result) def executeReceive(self, result): if result['code'] == 200: if result['type'] == 'error_dialog': sublime.error_message(u"{0}".format(result['msg'])) elif result['type'] == 'msg_dialog': sublime.message_dialog(u"{0}".format(result['msg'])) elif result['type'] == 'ok_cancel_dialog': ret = sublime.ok_cancel_dialog(u"{0}".format(result['msg']), u"{0}".format(result['ok_title'])) if ret is True: if result['ok_cmd'] != []: self.executeReceive(result['ok_cmd']) elif result['type'] == 'yes_no_cancel_dialog': ret = sublime.yes_no_cancel_dialog(u"{0}".format(result['msg']), u"{0}".format(result['yes_title']), u"{0}".format(result['no_title'])) if ret == sublime.DIALOG_CANCEL: pass elif ret == sublime.DIALOG_YES: if result['yes_cmd'] != []: self.executeReceive(result['yes_cmd']) elif ret == sublime.DIALOG_NO: if result['no_cmd'] != []: self.executeReceive(result['no_cmd']) elif result['type'] == 'set_clipboard': ret = sublime.set_clipboard(u"{0}".format(result['str'])) elif result['type'] == 'run_command': self.window.run_command(u"{0}".format(result['cmd']), result['args']) elif result['type'] == 'show_quick_panel': def on_quick_done(index): if result['on_done_cmd'] == []: pass else: # result.args 合并 index self.window.run_command(u"{0}".format(result['on_done_cmd']['cmd']), result['on_done_cmd']['args']) def on_quick_highlighted(index): if result['on_highlighted_cmd'] == []: pass else: # result.args 合并 index self.window.run_command(u"{0}".format(result['on_highlighted_cmd']['cmd']), result['on_highlighted_cmd']['args']) elif result['type'] == 'show_input_panel': def on_input_done(str): if result['on_done_cmd'] == []: pass else: # result.args 合并 str self.window.run_command(u"{0}".format(result['on_done_cmd']['cmd']), result['on_done_cmd']['args']) def on_input_change(str): if result.on_change_cmd == []: pass else: # result['args'] 合并 str self.window.run_command(u"{0}".format(result.on_change_cmd['cmd']), result.on_change_cmd['args']) def on_input_cancel(): if result.on_change_cmd == []: pass else: self.window.run_command(u"{0}".format(result.on_cancel_cmd['cmd']), result.on_cancel_cmd['args']) ret = self.view.show_input_panel(u"{0}".format(result.caption), u"{0}".format(result.initial_text), on_input_done, on_input_change, on_input_cancel) else: sublime.error_message(u"{0}".format(result['msg'])) class PhpBoxCommand(sublime_plugin.TextCommand): def run(self, edit, call, cmd_args): self.setting = sublime.load_settings("PhpBox.sublime-settings") print(command_bin) thread = php_execute('test_yes', {'msg':'好123', 'ok_title':'确认'}) thread.start() ThreadProgress(thread, 'Is excuting', 'Finding Done') # thread = UpgradeAllPackagesThread(self.window, package_renamer) # thread.start() # ThreadProgress(thread, 'Loading repositories', '') <file_sep>/tp5/application/sublime/common.php <?php use \Sublime\Ret; function test_alert($msg){ return Ret::alert($msg); } function test_msg($msg){ return Ret::msg($msg); } function test_ok($msg, $ok_title='', $ok_cmd=[]){ return Ret::ok($msg, $ok_title, $ok_cmd); } function test_yes($msg, $yes_title, $no_title, $yes_cmd=[], $no_cmd=[], $cancel_cmd =[]){ return Ret::yes($msg, $yes_title, $no_title, $yes_cmd, $no_cmd, $cancel_cmd); }<file_sep>/tp5/extend/Sublime/Ret.php <?php namespace Sublime; class Ret{ const RETURN_TYPE_ALERT = 'error_dialog'; const RETURN_TYPE_MSG = 'msg_dialog'; const RETURN_TYPE_OK = 'ok_cancel_dialog'; const RETURN_TYPE_YES = 'yes_no_cancel_dialog'; const RETURN_TYPE_CMD_SET_CLIPBOARD = 'set_clipboard'; const RETURN_TYPE_CMD_RUN_COMMAND = 'run_command'; const RETURN_TYPE_SHOW_QUICK_PANEL = 'show_quick_panel'; const RETURN_TYPE_SHOW_INPUT_PANEL = 'show_input_panel'; const SUBLIMT_CONSTS = [ 'MONOSPACE_FONT' => 1, 'KEEP_OPEN_ON_FOCUS_LOST' => 2, ]; public static function alert($msg, $cmd=''){ $arr = [ 'code' => 404, 'type' => self::RETURN_TYPE_ALERT, 'msg' => $msg, ]; return self::encode($arr); } public static function msg($msg){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_MSG, 'msg' => $msg, ]; return self::encode($arr); } public static function ok($msg, $ok_title='', $ok_cmd=[]){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_OK, 'msg' => $msg, 'ok_title' => $ok_title, 'ok_cmd' => $ok_cmd, ]; return self::encode($arr); } public static function yes($msg, $yes_title, $no_title, $yes_cmd=[], $no_cmd=[], $cancel_cmd =[]){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_YES, 'msg' => $msg, 'yes_title' => $yes_title, 'yes_cmd' => $yes_cmd, 'no_title' => $no_title, 'no_cmd' => $no_cmd, 'cancel_cmd' => $cancel_cmd, ]; return self::encode($arr); } public static function set_clipboard($str){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_CMD_SET_CLIPBOARD, 'str' => $str, ]; return self::encode($arr); } /** * [show_quick_panel] * @param array $items 字符串数组或者键值数组 * @param array $on_done_cmd 选择结束命令 cmd 和args * @param int $flag sublime.MONOSPACE_FONT 或 KEEP_OPEN_ON_FOCUS_LOST * @param integer $selected_index 选中的list 的index * @param array $on_highlighted_cmd 高亮命令 * @return string */ public static function show_quick_panel($items, $on_done_cmd = [], $flag, $selected_index = -1, $on_highlighted_cmd = []){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_SHOW_QUICK_PANEL, 'items' => $items, 'on_done_cmd' => $on_done_cmd, 'flag' => $flag, 'on_highlighted_cmd' => $on_highlighted_cmd, ]; return self::encode($arr); } public static function show_input_panel($caption, $initial_text = '', $on_done_cmd = [], $on_change_cmd = [], $on_cancel_cmd = []){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_SHOW_INPUT_PANEL, 'caption' => $caption, 'initial_text' => $initial_text, 'on_done_cmd' => $on_done_cmd, 'on_change_cmd' => $on_change_cmd, 'on_cancel_cmd' => $on_cancel_cmd, ]; return self::encode($arr); } public static function run_command($cmd, $args=[]){ $arr = [ 'code' => 200, 'type' => self::RETURN_TYPE_CMD_RUN_COMMAND, 'cmd' => $cmd, 'args' => $args, ]; return self::encode($arr); } public static function encode($arr){ return base64_encode(json_encode($arr, JSON_UNESCAPED_UNICODE)); } public static function decode($str){ return json_decode(base64_decode($str), true); } }
6e7b588c23f1afa9aacbccb0d453bc05031edf85
[ "Markdown", "Python", "PHP" ]
4
Markdown
clkangta/SublimePhpBox
6258012b89b11ceca4c6dad601fc2cca52541064
203d9eefd49555978775d6ba8aaa98948311597f
refs/heads/master
<file_sep>#!/bin/bash chmod -R 755 * echo " 888888b. 888 888 .d8888b. 888 888 88b 888 888 d88P Y88b 888 888 .88P 888 888 888 888 888 8888888K. 888 8888b. .d8888b 888 888 888 888 888 888 888888 888 Y88b 888 88b d88P 888 .88P 888 888 888 888 888 888 888 888 .d888888 888 888888K 888 888 888 888 888 888 d88P 888 888 888 Y88b. 888 88b Y88b d88P Y88b 888 Y88b. 8888888P 888 Y888888 Y8888P 888 888 Y8888P Y88888 Y888 " echo Welcome please install our services. echo press enter to install packages read echo installing.... sleep 1 echo installing.... sleep 1 echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1echo installing.... sleep 1 echo installing.... sleep 1 https://github.com/Sect0rCatalyst/Black0ut_Tools.git sleep 5 echo press enter to finish read echo ending.. sleep 5 end
483fe527b2ded5811cb57de2fbcfad2bcb8f6c9d
[ "Shell" ]
1
Shell
Sect0rCatalyst/Install
0c135703d3279ea6efb5f5f18e3f6e5fa36a6bb9
0a7408db1d2128c1079fd1b55746cfd007c16a6a
refs/heads/master
<repo_name>StanislavKharkiv/data-grid<file_sep>/src/store/actions.js import store from './store' export function addUsersToState(users) { return { type: 'ADD_DATA', payload: users, } } export function isLoading() { return { type: 'IS_LOADING', payload: !store.getState().loading, } } <file_sep>/src/components/Table.jsx import React from 'react' import PropTypes from 'prop-types' import * as _ from 'lodash' function parseAddress(address) { return ( <> <div>{address.city}</div> <div>{address.street}</div> <div>{address.zipcode}</div> </> ) } function getDate(time) { const date = new Date(time).toLocaleString() return date.slice(0, date.indexOf(',')) } export default function Table({ users }) { const table = users.map(({ id, name, email, address, phone, website, active, getTime }) => ( <tr key={id}> <td>{name}</td> <td>{email}</td> <td>{parseAddress(address)}</td> <td>{_.replace(phone, ' x', '-')}</td> <td>{website}</td> <td>{active ? 'online' : 'offline'}</td> <td>{getDate(getTime)}</td> </tr> )) return ( <table className="table"> <caption>users table</caption> <tbody> <tr> <th>name</th> <th>email</th> <th>address</th> <th>phone</th> <th>website</th> <th>status</th> <th>date</th> </tr> {table} </tbody> </table> ) } Table.propTypes = { users: PropTypes.array.isRequired, }
47ac94a5e42a9b8200f1c9d7aa77179f03e4fee5
[ "JavaScript" ]
2
JavaScript
StanislavKharkiv/data-grid
f87ae7c21cba200826c83eea998068700714a9ff
57f4fac645c7841c1d3c2b8c420ca282e5a0a766
refs/heads/main
<repo_name>MityaAndreevich/AboutMeApp<file_sep>/AboutMeApp/ViewControllers/FinalViewController.swift // // FinalViewController.swift // AboutMeApp // // Created by <NAME> on 31.08.2021. // import UIKit class FinalViewController: UIViewController { @IBOutlet weak var finalLabel: UILabel! var user: User! override func viewDidLoad() { super.viewDidLoad() finalLabel.text = user.person.finale } } <file_sep>/AboutMeApp/ViewControllers/AboutMeViewController.swift // // AboutMeViewController.swift // AboutMeApp // // Created by <NAME> on 29.08.2021. // import UIKit class AboutMeViewController: UIViewController { @IBOutlet weak var firstFact: UILabel! @IBOutlet weak var secondFact: UILabel! @IBOutlet weak var thirdFact: UILabel! var user: User! override func viewDidLoad() { super.viewDidLoad() firstFact.text = user.person.eduation secondFact.text = user.person.job thirdFact.text = user.person.hobby } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let finalVC = segue.destination as? FinalViewController else { return } finalVC.user = user } @IBAction func unwind(for lastSegue: UIStoryboardSegue) { } } <file_sep>/AboutMeApp/Models/User.swift // // User.swift // AboutMeApp // // Created by <NAME> on 29.08.2021. // struct User { let login: String let password: String let person: Person static func getInfo() -> User { User( login: "User", password: "<PASSWORD>", person: Person.getPersonInfo() ) } } struct Person { let name: String let surname: String let hobby: String let eduation: String let job: String let finale: String var fullName: String { "\(name) \(surname)" } static func getPersonInfo() -> Person { Person( name: "Dmitry", surname: "Logachev", hobby: "Hobby: Psychology, Sports, cars, Swift", eduation: "Education: Master of Economics", job: "Jobs: Researcher in jato, entrepreneurship", finale: "No! That's all folks!" ) } }
49039879c1a0d33e23702c0f26a7a6a1ce696b4b
[ "Swift" ]
3
Swift
MityaAndreevich/AboutMeApp
5773b9a53ea066d302b939d5b478ba4646dde744
684a6445e96bf62f43132030cdb03fcfa63b4fe2
refs/heads/master
<file_sep> <li class="sidebarFeatured__story"> <a href="#"> <span class="sidebarFeatured__story__heading">Калі хочаш даведацца, разарвуць цябе феміністкі ці не</span><i class="commentsCount">37</i> <p class="sidebarFeatured__story__short">Прайдзі тэст, каб зразумець, наколькі ты адпавядаеш грамадству свабоднаму ад гендэрных пытанняў</p> </a> </li> <file_sep>'use strict'; let gulp = require('gulp'), sass = require('gulp-sass'), postcss = require('gulp-postcss'), sourcemaps = require('gulp-sourcemaps'), autoprefixer = require('autoprefixer'), lost = require('lost'), fileinclude = require('gulp-file-include'), webserver = require('gulp-webserver'), svgstore = require('gulp-svgstore'), watch = require('gulp-watch'), inject = require('gulp-inject'), rimraf = require('rimraf'), cleanCss = require('gulp-clean-css'), babel = require('gulp-babel') let path = { build: { html: 'build/', css: 'build/css/', js: 'build/js/', fonts: 'build/fonts/', images: 'build/img/' }, src: { html: 'src/*.html', style: 'src/main.scss', js: 'src/assets/js/**/*.js', svg: 'src/assets/svg/**/*.svg', fonts: 'src/assets/fonts/*', images: 'src/img/**/*', }, watch: { html: 'src/**/*.html', style: 'src/**/*.scss', fonts: 'src/assets/fonts/*', js: 'src/assets/js/**/*.js', }, clean: './build' }; gulp.task('html:build', function() { let svgs = gulp .src(path.src.svg) .pipe(svgstore({ inlineSvg: true })) function fileContents (filePath, file) { return file.contents.toString(); } gulp.src(path.src.html) .pipe(fileinclude({ prefix: '@@', basepath: './src/modules/', })) .pipe(inject(svgs, { transform: fileContents })) .pipe(gulp.dest(path.build.html)); }) gulp.task('style:build', function() { return gulp.src(path.src.style) .pipe(sourcemaps.init()) .pipe(sass()) .pipe(postcss([ lost(), autoprefixer() ])) .pipe(cleanCss()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(path.build.css)); }) gulp.task('fonts:build', function() { gulp.src(path.src.fonts) .pipe(gulp.dest(path.build.fonts)) }); gulp.task('images:build', function() { gulp.src(path.src.images) .pipe(gulp.dest(path.build.images)) }); gulp.task('js:build', function() { gulp.src(path.src.js) .pipe(babel({ presets: ['es2015'] })) .pipe(gulp.dest(path.build.js)) }); gulp.task('build', [ 'html:build', 'style:build', 'fonts:build', 'images:build', 'js:build', ]); gulp.task('watch', ['webserver'], function(){ watch([path.watch.html], function(event, cb) { gulp.start('html:build'); }) watch([path.watch.style], function(event, cb) { gulp.start('style:build'); }) watch([path.watch.fonts], function(event, cb) { gulp.start('fonts:build'); }) watch([path.watch.js], function(event, cb) { gulp.start('js:build'); }) }); gulp.task('clean', function (cb) { rimraf(path.clean, cb); }); gulp.task('webserver', function() { gulp.src(path.build.html) .pipe(webserver({ livereload: true, open: false, directoryListing: { enable: true, path: path.build.html } })); }); <file_sep>@@include('head/head.html') @@include('header/header.html') @@include('nav/nav.html') <div class="container"> <div class="content"> <div class="row"> @@include('featured/featured.html') @@include('itemHeaded/itemHeaded.html', { "col": "-3" }) </div> <div class="row"> @@include('item/item.html', { "col": "-3" }) @@include('item/item.html', { "col": "-3" }) @@include('item/item.html', { "col": "-3" }) </div> <div class="row"> @@include('item/item.html', { "col": "-3" }) @@include('item/item.html', { "col": "-3" }) @@include('item/item.html', { "col": "-3" }) </div> <div class="row"> @@include('itemBordered/itemBordered.html') @@include('featured/featured.html') </div> <div class="b"> <img src="img/banner728.png" alt=""> </div> </div> <div class="sidebar"> <div class="b"> <img src="img/banner240.png" alt=""> </div> <span class="sidebar__category">Каментары</span> <ul class="sidebarComments"> @@include('sidebarComments/sidebarComments.html') @@include('sidebarComments/sidebarComments.html') @@include('sidebarComments/sidebarComments.html') </ul> </div> </div> <div class="container"> <div class="row"> @@include('item/item.html', { "col": "-4" }) @@include('item/item.html', { "col": "-4" }) @@include('item/item.html', { "col": "-4" }) @@include('item/item.html', { "col": "-4" }) </div> <div class="row"> @@include('item/item.html', { "col": "-4" }) @@include('item/item.html', { "col": "-4" }) @@include('item/item.html', { "col": "-4" }) @@include('item/item.html', { "col": "-4" }) </div> </div> <button class="moreNews">больш навін</button> @@include('footer/footer.html')
c09465e9d77b6b4667d0793c52540ee4baf50035
[ "JavaScript", "HTML" ]
3
HTML
Zewkin/nashanina
3dcd6b9182984f956f705d14928ba9fb039c3f5b
d9c2553e27272504caa53ae5a0d5fa8fa65c5dbb
refs/heads/master
<repo_name>petershatunov/spring-boot-graphql<file_sep>/src/main/java/com/example/DemoGraphQL/model/GenericBook.java package com.example.DemoGraphQL.model; public interface GenericBook { Long getId(); String getTitle(); String getInn(); String getIsbn(); Author getAuthor(); Integer getPageCount(); } <file_sep>/src/main/java/com/example/DemoGraphQL/repository/PocketBookrepository.java package com.example.DemoGraphQL.repository; import com.example.DemoGraphQL.model.PocketBook; import org.springframework.data.repository.CrudRepository; public interface PocketBookrepository extends CrudRepository<PocketBook, Long> { PocketBook findByTitle(String title); } <file_sep>/src/main/java/com/example/DemoGraphQL/repository/BookRepository.java package com.example.DemoGraphQL.repository; import com.example.DemoGraphQL.model.Author; import com.example.DemoGraphQL.model.Book; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; public interface BookRepository extends CrudRepository<Book, Long> { Book findByAuthor(Author author); Book findByTitle(String title); } <file_sep>/src/main/java/com/example/DemoGraphQL/model/ManagingFirm.java package com.example.DemoGraphQL.model; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.math.BigInteger; import java.time.LocalDate; import java.util.Date; @Entity @Getter @Setter @Table(name = "MANAGING_FIRM") public class ManagingFirm { @Id @Column(name = "PARTY_ID") private Long partyId; @Column(name = "MF_CODE") private String kbk; @Column(name = "GISRD_ID") private String gisrdId; @Column(name = "MF_TYPE_ID") private String mfTypeId; @Column(name = "IS_ACTIVE") private String isActive; @Column(name = "LIC_NUM") private String licNum; @Column(name = "ISSUANCE_DATE") private Date issuanceDate; @Column(name = "ISSUED_BY") private String issuedBy; @Column(name = "LIC_STATE") private String licState; @Column(name = "HOUSE_CNT") private String houseCnt; @Column(name = "SA_IND_ID") private String saIndId; @Column(name = "SA_ORG_ID") private String saOrgId; @Column(name = "BA_IND_ID") private String baIndId; @Column(name = "BA_ORG_ID") private String baOrgId; @Column(name = "BCC_PRINCIPAL") private String bccPrincipal; @Column(name = "BCC_PENI") private String bccPeni; @Column(name = "BCC_DUTY") private String bccDuty; @Column(name = "DATE_FROM") private Date dateFrom; } <file_sep>/src/main/java/com/example/DemoGraphQL/model/Organization.java package com.example.DemoGraphQL.model; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.*; import javax.persistence.CascadeType; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.Table; import java.util.Date; import java.util.Set; @Entity @Getter @Setter @Table(name = "ORGANIZATION") public class Organization { @Id @Column(name = "PARTY_ID") private Long id; @Column(name = "FULL_NAME") private String fullName; @Column(name = "SHORT_NAME") private String shortName; @Column(name = "INN") private String inn; @Column(name = "OGRN") private String ogrn; @Column(name = "OGRN_ASSIGN_DATE") private Date ogrnAssignDate; @Column(name = "OGRN_AUTHORITY") private String ogrnAuthority; @Column(name = "CODE_OKPO") private String codeOkpo; @Column(name = "MAIN_ACTIVITY_CODE") private String okved; @Column(name = "KPP") private String kpp; @Column(name = "SPR_OPF_CODE") private String okopf; @Column(name = "REG_OKTMO") private String oktmo; @Column(name = "REG_OKATO") private String okato; @Column(name = "IS_AUTHORITY") private String isAuthority; @Column(name = "IS_PUBLIC_OWNERSHIP") private String isPublicOwnership; @Column(name = "PUBLIC_OWNERSHIP_TYPE") private String publicOwnershipType; @Column(name = "IS_PUBLIC_PAYER") private String isPublicPayer; @Column(name = "REG_CAPITAL_TYPE") private String regCapitalType; @Column(name = "REG_CAPITAL_RUB") private String regCapitalRub; @Column(name = "MAIN_ACTIVITY_CV") private String mainActivityCv; @Column(name = "MAIN_ACTIVITY_DESC") private String mainActivityDesc; @Column(name = "LEGAL_CAPACITY") private String legalCapacity; @Column(name = "INCAP_STATUS_CODE") private String incapStatusCode; @Column(name = "INCAP_STATUS_DESC") private String incapStatusDesc; @Column(name = "INCAP_DATE") private Date incapDate; @Column(name = "EXCL_DEC_DATE") private Date exclDecDate; @Column(name = "EXCL_DEC_NUM") private String exclDecNum; @Column(name = "EXCL_PUB_DATE") private Date exclPubDate; @Column(name = "EXCL_PUB_MAG") private String exclPubMag; @Column(name = "IS_TERMINATED") private String isTerminated; @Column(name = "TERM_CASE_CODE") private String termCaseCode; @Column(name = "TERM_CASE_DESC") private String termCaseDesc; @Column(name = "TERMINATION_DATE") private Date terminationDate; @Column(name = "SUCCESSOR_ID") private String successorId; @Column(name = "DATE_FROM") private Date dateFrom; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "PARTY_ID") @NotFound(action= NotFoundAction.IGNORE) private ManagingFirm managingFirm; @Formula("(select 'test addr' from dual)") private String registrationAddress; @Formula("(select 'test addr' from dual)") private String factAddress; @OneToMany(mappedBy = "accountOwner", fetch = FetchType.LAZY) @Fetch(FetchMode.JOIN) @NotFound(action= NotFoundAction.IGNORE) private Set<SettlementAccount> settlementAccounts; @OneToMany(mappedBy = "accountOwner", fetch = FetchType.LAZY) @Fetch(FetchMode.JOIN) @NotFound(action= NotFoundAction.IGNORE) private Set<BusinessAccount> businessAccounts; public Organization() { } }
8e0953463b11b1ad2b40df499e00582468245532
[ "Java" ]
5
Java
petershatunov/spring-boot-graphql
a5c064e28de1509d403c81930dc0dad0b08d4717
0bd0f748f9059ff33af4b8eac92f148186ec2807
refs/heads/master
<repo_name>Mahmudqosim/mqbani<file_sep>/mqbani/platforms/new.js alert("my code"); <file_sep>/README.md # mqbani web
3c239b829e0b60e5b78431e869f5c02fc8e95a25
[ "JavaScript", "Markdown" ]
2
JavaScript
Mahmudqosim/mqbani
e3b64af1b1f77530d790e74451d4bd1e841f7729
36e3caccebbdafb9f56b79003296c39272125621
refs/heads/master
<repo_name>DisDylan/get_next_line<file_sep>/get_next_line.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpoinsu <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/26 19:50:15 by dpoinsu #+# #+# */ /* Updated: 2020/12/01 14:45:38 by dpoinsu ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static char *ft_strncpy(char *dst, char *src, size_t n) { size_t i; if (dst == 0 && src == 0) return (dst); i = 0; while (i < n) { dst[i] = src[i]; i++; } return (dst); } static char *ft_strjoin(char *s1, char *s2) { char *nstr; if (!s1 && !s2) return (NULL); if (!(nstr = (char*)malloc(sizeof(nstr) * (ft_strlen(s1) + ft_strlen(s2) + 1)))) return (NULL); ft_strncpy(nstr, s1, ft_strlen(s1)); ft_strncpy(nstr + ft_strlen(s1), s2, ft_strlen(s2)); nstr[ft_strlen(s1) + ft_strlen(s2)] = '\0'; return (nstr); } static char *ft_strdup(char *s, size_t len) { char *nstr; if (!(nstr = (char*)malloc(sizeof(nstr) * (len + 1)))) return (NULL); ft_strncpy(nstr, s, len); nstr[len] = '\0'; return (nstr); } static int make_new_line(char **save, char **line, char *str) { char *tmp; if (str != NULL) { *line = ft_strdup(*save, str - *save); tmp = ft_strdup(str + 1, ft_strlen(str + 1)); free(*save); *save = tmp; return (1); } if (*save != NULL) { *line = *save; *save = NULL; } else *line = ft_strdup("", 1); return (0); } int get_next_line(int fd, char **line) { static char *save[256]; char buffer[BUFFER_SIZE + 1]; char *tmp; char *str; int len; if (fd < 0 || line == NULL || BUFFER_SIZE <= 0) return (-1); while ((str = ft_strchr(save[fd], '\n')) == 0 && (len = read(fd, buffer, BUFFER_SIZE)) > 0) { buffer[len] = 0; if (save[fd] == NULL) tmp = ft_strdup(buffer, len); else tmp = ft_strjoin(save[fd], buffer); if (save[fd] != 0) free(save[fd]); save[fd] = tmp; } if (len < 0) return (-1); return (make_new_line(&save[fd], line, str)); }
9403bf1977c55ef17945d76a55b12d46bc607099
[ "C" ]
1
C
DisDylan/get_next_line
f06602c85f32ef3a7d2f18297f800daec183de65
1a18823f3263f591c04e1b9222375191a8149400
refs/heads/main
<repo_name>supperhellokitty20/wifi_weather<file_sep>/README.md ## Wifi weather **Usage** * Register for openweather and input API_KEY in main.cpp * To run ```bash pio run -t upload ``` * Serial monitor ```bash pio device monitor ``` <file_sep>/src/main.cpp #include<Arduino.h> #include <LiquidCrystalIO.h> #include <IoAbstractionWire.h> #include <Wire.h> #include <Arduino_JSON.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> #include <ESP8266WiFi.h> #include <stdio.h> #include <String> //Open weather API key #define API_KEY "" #define SSID "" #define PW "" #define city_id "1580578" double temp ; double humid ; // THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES // For a final application, check the API call limits per hour/minute to avoid getting blocked/banned unsigned long lastTime = 0; // Timer set to 10 minutes (600000) //unsigned long timerDelay = 600000; // Set timer to 10 seconds (10000) unsigned long timerDelay = 10000; LiquidCrystalI2C_RS_EN(lcd,0x27,false) ; String jsonBuffer; void setup() { Serial.begin(9600); Wire.begin() ; lcd.begin(16,2); WiFi.begin(SSID, PW); Serial.println("Connecting"); while(WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to WiFi network with IP Address: "); Serial.println(WiFi.localIP()); Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading."); //Setting up the lcd taskManager.scheduleFixedRate(250, [] { // (note: line 1 is the second row, since counting begins with 0): lcd.noBlink(); lcd.setCursor(0,0) ; lcd.print(F("Temp:")); lcd.print(temp) ; // print the number of seconds since reset: //float secondsFraction = millis() / 1000.0F; lcd.setCursor(0, 1); lcd.print(F("Humid:")); lcd.print(humid); lcd.print(F("%")); }); } String httpGETRequest(const char* serverName) { WiFiClient client; HTTPClient http; // Your IP address with path or Domain name with URL path http.begin(client, serverName); // Send HTTP POST request int httpResponseCode = http.GET(); String payload = "{}"; if (httpResponseCode>0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); payload = http.getString(); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } // Free resources http.end(); return payload; } void loop() { // Send an HTTP GET request if ((millis() - lastTime) > timerDelay) { // Check WiFi connection status if(WiFi.status()== WL_CONNECTED){ String serverPath = "http://api.openweathermap.org/data/2.5/weather?id=" city_id "&units=imperial&APPID=" API_KEY; jsonBuffer = httpGETRequest(serverPath.c_str()); Serial.println(jsonBuffer); JSONVar myObject = JSON.parse(jsonBuffer); // JSON.typeof(jsonVar) can be used to get the type of the var if (JSON.typeof(myObject) == "undefined") { Serial.println("Parsing input failed!"); return; } temp = myObject["main"]["temp"]; humid= myObject["main"]["humidity"]; Serial.print("JSON object = "); Serial.println(myObject); Serial.print("Temperature: "); Serial.println(temp); Serial.print("Humidity: "); Serial.println(humid); /** Serial.println(myObject["main"]["temp"]); Serial.print("Pressure: "); Serial.println(myObject["main"]["pressure"]); Serial.print("Humidity: "); Serial.println(myObject["main"]["humidity"]); Serial.print("Wind Speed: "); Serial.println(myObject["wind"]["speed"]); **/ } else { Serial.println("WiFi Disconnected"); } lastTime = millis(); taskManager.runLoop() ; } }
2538ec4b406012e49aaca405cc8feba448c09cb1
[ "Markdown", "C++" ]
2
Markdown
supperhellokitty20/wifi_weather
5281cd8d436b8195d231e6f21e1ab86362ec1c4c
9dfd875c386ce248fda11efd57b0241d56686a54
refs/heads/master
<file_sep>package mocks import context "golang.org/x/net/context" import dc "distcron/dc" import metadata "google.golang.org/grpc/metadata" import mock "github.com/stretchr/testify/mock" // DistCron_GetJobOutputServer is an autogenerated mock type for the DistCron_GetJobOutputServer type type DistCron_GetJobOutputServer struct { mock.Mock } // Context provides a mock function with given fields: func (_m *DistCron_GetJobOutputServer) Context() context.Context { ret := _m.Called() var r0 context.Context if rf, ok := ret.Get(0).(func() context.Context); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(context.Context) } } return r0 } // RecvMsg provides a mock function with given fields: m func (_m *DistCron_GetJobOutputServer) RecvMsg(m interface{}) error { ret := _m.Called(m) var r0 error if rf, ok := ret.Get(0).(func(interface{}) error); ok { r0 = rf(m) } else { r0 = ret.Error(0) } return r0 } // Send provides a mock function with given fields: _a0 func (_m *DistCron_GetJobOutputServer) Send(_a0 *dc.Output) error { ret := _m.Called(_a0) var r0 error if rf, ok := ret.Get(0).(func(*dc.Output) error); ok { r0 = rf(_a0) } else { r0 = ret.Error(0) } return r0 } // SendHeader provides a mock function with given fields: _a0 func (_m *DistCron_GetJobOutputServer) SendHeader(_a0 metadata.MD) error { ret := _m.Called(_a0) var r0 error if rf, ok := ret.Get(0).(func(metadata.MD) error); ok { r0 = rf(_a0) } else { r0 = ret.Error(0) } return r0 } // SendMsg provides a mock function with given fields: m func (_m *DistCron_GetJobOutputServer) SendMsg(m interface{}) error { ret := _m.Called(m) var r0 error if rf, ok := ret.Get(0).(func(interface{}) error); ok { r0 = rf(m) } else { r0 = ret.Error(0) } return r0 } // SetHeader provides a mock function with given fields: _a0 func (_m *DistCron_GetJobOutputServer) SetHeader(_a0 metadata.MD) error { ret := _m.Called(_a0) var r0 error if rf, ok := ret.Get(0).(func(metadata.MD) error); ok { r0 = rf(_a0) } else { r0 = ret.Error(0) } return r0 } // SetTrailer provides a mock function with given fields: _a0 func (_m *DistCron_GetJobOutputServer) SetTrailer(_a0 metadata.MD) { _m.Called(_a0) } <file_sep>package dc import ( "bytes" "encoding/gob" "fmt" "net" "sync" "time" "github.com/docker/leadership" "github.com/golang/glog" "github.com/hashicorp/serf/serf" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/load" "github.com/shirou/gopsutil/mem" "golang.org/x/net/context" ) /* * 1. Maintains membership within a cluster * 2. Continuously runs for leader within a cluster * 3. Acquires telemetry from other nodes when in leader mode * * Nodes within cluster are expected to have unique node names * Serf also has snapshotting feature to automatically restore cluster membership after restart * */ type ClusterConfig struct { NodeName string BindAddr string BindPort int GRPCAddress string } type queryResponder func(query *serf.Query) (interface{}, error) type cronNode struct { sync.RWMutex cancel context.CancelFunc config *ClusterConfig serfChannel chan serf.Event serf *serf.Serf candidate *leadership.Candidate leaderChannel chan bool leader bool telemetryChannel chan *TelemetryInfo db *DB queryResponders map[string]queryResponder } const cElectionWaitTimeout = time.Second * 20 const cSleepBetweenElections = time.Second * 10 const cDefaultLeaderLock = time.Second * 20 const cQueryTimeout = time.Second * 15 const cTelemetryAcquisitionPeriod = time.Second * 15 // must be > then cQueryTimeout const cQueryTelemetry = "DC_TELE" func NewClusterNode(config *ClusterConfig, db *DB, leaderChannel chan bool, telemetryChannel chan *TelemetryInfo) (Node, error) { node := &cronNode{ db: db, config: config, serfChannel: make(chan serf.Event, cChanBuffer), leaderChannel: leaderChannel, leader: false, telemetryChannel: telemetryChannel, } node.queryResponders = map[string]queryResponder{ cQueryTelemetry: queryRespondTelemetry, } serfConfig := serf.DefaultConfig() serfConfig.QueryResponseSizeLimit = 4096 serfConfig.EventCh = node.serfChannel serfConfig.RejoinAfterLeave = true serfConfig.MemberlistConfig.BindAddr = config.BindAddr serfConfig.MemberlistConfig.BindPort = config.BindPort serfConfig.NodeName = config.NodeName var err error node.serf, err = serf.Create(serfConfig) if err != nil { glog.Error(err) return nil, err } return node, err } func (node *cronNode) Start(parentCtx context.Context) { ctx, _ := context.WithCancel(parentCtx) go node.run(ctx) } type TelemetryInfo struct { Node string Mem *mem.VirtualMemoryStat `json:"mem"` Cpu []cpu.InfoStat `json:"cpu"` Load *load.AvgStat `json:"load"` } func queryRespondTelemetry(query *serf.Query) (interface{}, error) { var err error info := TelemetryInfo{} if info.Load, err = load.Avg(); err != nil { glog.Error(err) } if info.Cpu, err = cpu.Info(); err != nil { glog.Error(err) } if info.Mem, err = mem.VirtualMemory(); err != nil { glog.Error(err) } return info, nil } func (node *cronNode) queryRequestTelemetry(ctx context.Context) { q, err := node.serf.Query(cQueryTelemetry, []byte{}, &serf.QueryParam{ RequestAck: false, Timeout: cQueryTimeout, }) if err != nil { glog.Error(err) return } defer q.Close() respChannel := q.ResponseCh() for !q.Finished() { var resp serf.NodeResponse var ok bool select { case <-ctx.Done(): return case resp, ok = <-respChannel: if !ok { return } } tm := TelemetryInfo{} if err := gob.NewDecoder(bytes.NewReader(resp.Payload)).Decode(&tm); err != nil { glog.Error(err) } else { tm.Node = resp.From node.telemetryChannel <- &tm } } } func (node *cronNode) processSerfQuery(query *serf.Query) { if fn, there := node.queryResponders[query.Name]; there { var encBuffer bytes.Buffer gobEncoder := gob.NewEncoder(&encBuffer) if response, err := fn(query); err != nil { glog.Errorf("[%s] Error responding query %v: %v", node.config.NodeName, query, err) } else if err = gobEncoder.Encode(response); err != nil { glog.Errorf("[%s] Cannot encode response to query %v : %v", response, err) } else if err = query.Respond(encBuffer.Bytes()); err != nil { glog.Errorf("[%s] Failed to respond to query: %v, answer was %d bytes", node.GetName(), err, len(encBuffer.Bytes())) } } } func (node *cronNode) run(ctx context.Context) { leaderChannel := make(chan bool, cChanBuffer) go node.electionLoop(ctx, leaderChannel) var telemetryTicker *time.Ticker var telemetryTickerChannel <-chan time.Time = make(<-chan time.Time) for { select { case <-ctx.Done(): glog.Infof("[%s] Node shutdown", node.GetName()) glog.Infof("[%s] Serf shutdown : %v", node.GetName(), node.serf.Shutdown()) return case leader := <-leaderChannel: node.leaderChannel <- leader if leader { telemetryTicker = time.NewTicker(cTelemetryAcquisitionPeriod) telemetryTickerChannel = telemetryTicker.C go node.queryRequestTelemetry(ctx) } else if telemetryTicker != nil { telemetryTicker.Stop() } glog.Infof("[%s] Leader status : %v", node.GetName(), leader) case <-telemetryTickerChannel: glog.Infof("[%s] Requesting telemetry", node.GetName()) // we could create a timeout context but serf query have internal timeout // so just to ensure once we're shutting down that would be picked up as well go node.queryRequestTelemetry(ctx) case serfEvent := <-node.serfChannel: glog.V(cLogDebug).Infof("[%s] %v", node.config.NodeName, serfEvent) if serfEvent.EventType() == serf.EventQuery { go node.processSerfQuery(serfEvent.(*serf.Query)) } } } } func (node *cronNode) electionLoop(ctx context.Context, leaderChannel chan bool) { node.candidate = leadership.NewCandidate(node.db.store, CLeadershipKey, node.config.NodeName, cDefaultLeaderLock) electionChan, errorChan := node.candidate.RunForElection() for { select { case <-ctx.Done(): glog.Infof("[%s] Stop election loop", node.GetName()) node.candidate.Stop() return case err := <-errorChan: glog.Errorf("[%s] Error from election %v", node.GetName(), err) leaderChannel <- false glog.Infof("[%s] Will retry election in %v", node.GetName(), cSleepBetweenElections) time.Sleep(cSleepBetweenElections) electionChan, errorChan = node.candidate.RunForElection() case elected := <-electionChan: node.Lock() node.leader = elected node.Unlock() leaderChannel <- elected } } } func (node *cronNode) GetName() string { return node.config.NodeName } func (node *cronNode) IsLeader() bool { node.RLock() defer node.RUnlock() return node.leader } func (node *cronNode) GetLeader() (name string, addr net.IP, err error) { kv, err := node.db.store.Get(CLeadershipKey) if err != nil { glog.Errorf("[%s] : cannot fech leader: %v", node.config.NodeName, err) return "", nil, err } name = string(kv.Value) for _, n := range node.serf.Members() { if n.Name == name { return name, n.Addr, err } } return "", nil, fmt.Errorf("Node %s not found", name) } func (node *cronNode) SerfMembersCount() int { return node.serf.NumNodes() } func (node *cronNode) SerfMembers() []serf.Member { return node.serf.Members() } func (node *cronNode) Join(addr []string) error { _, err := node.serf.Join(addr, true) return err } <file_sep>all: proto tests build tests: go test -race -v distcron/dc/... -alsologtostderr build: go build -o /code/build/distcron distcron proto: protoc -I dc/ dc/dcron.proto --go_out=plugins=grpc:dc .PHONY: build tests proto all <file_sep>package mocks import context "golang.org/x/net/context" import dc "distcron/dc" import grpc "google.golang.org/grpc" import mock "github.com/stretchr/testify/mock" // DistCronClient is an autogenerated mock type for the DistCronClient type type DistCronClient struct { mock.Mock } // GetJobOutput provides a mock function with given fields: ctx, in, opts func (_m *DistCronClient) GetJobOutput(ctx context.Context, in *dc.JobHandle, opts ...grpc.CallOption) (dc.DistCron_GetJobOutputClient, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 dc.DistCron_GetJobOutputClient if rf, ok := ret.Get(0).(func(context.Context, *dc.JobHandle, ...grpc.CallOption) dc.DistCron_GetJobOutputClient); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(dc.DistCron_GetJobOutputClient) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.JobHandle, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // GetJobStatus provides a mock function with given fields: ctx, in, opts func (_m *DistCronClient) GetJobStatus(ctx context.Context, in *dc.JobHandle, opts ...grpc.CallOption) (*dc.JobStatus, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *dc.JobStatus if rf, ok := ret.Get(0).(func(context.Context, *dc.JobHandle, ...grpc.CallOption) *dc.JobStatus); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobStatus) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.JobHandle, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // RunJob provides a mock function with given fields: ctx, in, opts func (_m *DistCronClient) RunJob(ctx context.Context, in *dc.Job, opts ...grpc.CallOption) (*dc.JobHandle, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *dc.JobHandle if rf, ok := ret.Get(0).(func(context.Context, *dc.Job, ...grpc.CallOption) *dc.JobHandle); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobHandle) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.Job, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // RunJobOnThisNode provides a mock function with given fields: ctx, in, opts func (_m *DistCronClient) RunJobOnThisNode(ctx context.Context, in *dc.Job, opts ...grpc.CallOption) (*dc.JobHandle, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *dc.JobHandle if rf, ok := ret.Get(0).(func(context.Context, *dc.Job, ...grpc.CallOption) *dc.JobHandle); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobHandle) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.Job, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // StopJob provides a mock function with given fields: ctx, in, opts func (_m *DistCronClient) StopJob(ctx context.Context, in *dc.JobHandle, opts ...grpc.CallOption) (*dc.JobStatus, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *dc.JobStatus if rf, ok := ret.Get(0).(func(context.Context, *dc.JobHandle, ...grpc.CallOption) *dc.JobStatus); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobStatus) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.JobHandle, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } <file_sep>package dc import ( "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "time" "github.com/golang/glog" "golang.org/x/net/context" ) type runner struct { } func NewRunner() Runner { return &runner{} } func (r *runner) RunJob(ctx context.Context, job *Job) (cid string, err error) { tmpDir, err := ioutil.TempDir("", "dcron") if err != nil { return "", err } defer os.RemoveAll(tmpDir) cidFile := filepath.Join(tmpDir, "cid") cmd := exec.Command("docker", "run", "--cidfile", cidFile, "--cpus", fmt.Sprintf("%.1f", job.CpuLimit), "--memory", fmt.Sprintf("%dm", job.MemLimitMb), job.ContainerName) if out, err := cmd.CombinedOutput(); err != nil { glog.Errorf("Failed to run cmd %v : %v", cmd, err) glog.Error(string(out)) return "", err } else if cidBytes, err := ioutil.ReadFile(cidFile); err != nil { glog.Error(err) return "", err } else { return string(cidBytes), nil } } const cBufSize = 1024 // how much time to wait for cmd.Wait() completion const cmdWaitTimeout = time.Second // GetJobStatus won't parse Docker output and just return as is, thus every time status might be different for MVP purpose func (r *runner) GetJobStatus(ctx context.Context, cid string) (status *JobStatus, err error) { cmd := exec.Command("docker", "ps", "--all", "--format", "{{.Status}}", "--filter", fmt.Sprintf("id=%s", cid)) if out, err := cmd.Output(); err != nil { glog.Errorf("%v failed: %v", cmd, err) return nil, InternalError } else { return &JobStatus{string(out)}, nil } } func (r *runner) StopJob(ctx context.Context, cid string) (status *JobStatus, err error) { cmd := exec.Command("docker", "stop", cid) out, err := cmd.CombinedOutput() if err != nil { glog.Error(cid, err, string(out)) return &JobStatus{string(out)}, InternalError } return r.GetJobStatus(ctx, cid) } func copyProcOutput(ctx context.Context, reader io.ReadCloser, fn DataCopyFn) error { data := make([]byte, cBufSize) for { select { case <-ctx.Done(): reader.Close() return RequestTimeoutError default: } n, err := reader.Read(data) if err != nil { if err != io.EOF { glog.Error(err) } break } if err = fn(data[0:n]); err != nil { glog.Error(err) reader.Close() return err } } return nil } func (r *runner) GetJobOutput(ctx context.Context, cid string, fn DataCopyFn) (err error) { cmd := exec.Command("docker", "logs", "--follow", cid) stdout, err := cmd.StdoutPipe() if err != nil { return err } if err = cmd.Start(); err != nil { glog.Error(err) return err } if err = copyProcOutput(ctx, stdout, fn); err != nil { glog.Error(err) } // cmd.Wait() may be waiting indefinitely on process completion // due to stdout not exhausted thus a workaround timeoutCtx, timeoutCancel := context.WithTimeout(ctx, cmdWaitTimeout) go func() { defer timeoutCancel() if err = cmd.Wait(); err != nil { glog.Error(err) } }() <-timeoutCtx.Done() if timeoutCtx.Err() == context.DeadlineExceeded { glog.Error("cmd.Wait timeout for %s", cid) err = RequestTimeoutError } return err } <file_sep>.PHONY all: docker-compose run distcron <file_sep>package dc import ( "fmt" "io" "strings" "testing" "time" "github.com/golang/glog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/net/context" "google.golang.org/grpc" ) const maxRetries = 20 const retryDelay = time.Second func TestBasicService(t *testing.T) { ctx, stop := context.WithCancel(context.Background()) defer stop() cfg := []ClusterConfig{ ClusterConfig{ NodeName: "A", BindAddr: "127.0.0.1", BindPort: 5006, }, ClusterConfig{ NodeName: "B", BindAddr: "127.0.0.1", BindPort: 5007, }, ClusterConfig{ NodeName: "C", BindAddr: "127.0.0.1", BindPort: 5008, }} svc := mkServiceCluster(ctx, t, cfg) for len(svc) >= 1 { leader := waitForLeader(t, svc) waitUntilAvailable(ctx, t, leader.service) testAllApiBasics(ctx, t, svc) svc = killLeader(t, svc) } } func mkApiClient(dialTo string) (DistCronClient, error) { if conn, err := grpc.Dial(dialTo, grpc.WithInsecure()); err != nil { return nil, err } else { return NewDistCronClient(conn), nil } } type cronSvc struct { cfg ClusterConfig stop context.CancelFunc service *DistCron } func mkServiceCluster(ctx context.Context, t *testing.T, config []ClusterConfig) (svc []cronSvc) { dbHosts := []string{"consul:8500"} if len(config) < 2 { require.Fail(t, "Cluster requires at least 2 nodes") } svc = make([]cronSvc, len(config)) basePort := 5555 for i, _ := range config { var c context.Context var err error svc[i].cfg = config[i] c, svc[i].stop = context.WithCancel(ctx) svc[i].service, err = NewDistCron(c, &config[i], dbHosts, fmt.Sprintf(":%d", basePort+i)) require.NoError(t, err) } joinTo := []string{fmt.Sprintf("%s:%d", config[0].BindAddr, config[0].BindPort)} for i := 1; i < len(config); i++ { require.NoError(t, svc[i].service.JoinTo(joinTo)) } return svc } func waitForLeader(t *testing.T, svc []cronSvc) *cronSvc { t.Logf("Waiting for leader, %d nodes", len(svc)) for retry := 0; retry < maxRetries; retry++ { var leaderSvc *cronSvc = nil t.Logf("Retry %d", retry) for i, _ := range svc { if svc[i].service.IsLeader() { if leaderSvc != nil { require.Fail(t, "Multiple nodes report being leader : %v and %v", leaderSvc.service.GetNodeName(), svc[i].service.GetNodeName()) return nil } leaderSvc = &svc[i] t.Logf("%s, IS a leader", svc[i].service.GetNodeName()) } else { t.Logf("%s, is NOT a leader", svc[i].service.GetNodeName()) } } if leaderSvc != nil { return leaderSvc } time.Sleep(retryDelay) } require.Fail(t, "Timed out waiting for cluster leader") return nil } // kills current leader and returns truncated service list func killLeader(t *testing.T, svc []cronSvc) []cronSvc { for i, s := range svc { if !s.service.IsLeader() { continue } glog.Infof("Killing leader %s", s.service.GetNodeName()) t.Logf("Killing leader %s", s.service.GetNodeName()) s.stop() return append(svc[:i], svc[i+1:]...) } require.Fail(t, "No leader in cluster") return nil } // ping a node until it stops returning No nodes available error func waitUntilAvailable(ctx context.Context, t *testing.T, service *DistCron) { client, err := service.GetRpcForNode(ctx, service.GetNodeName()) for retry := 0; retry < maxRetries; retry++ { _, err = client.RunJob(ctx, &Job{ ContainerName: "hello-world", CpuLimit: 0.1, MemLimitMb: 10, }) if err == nil { return } // can't get grpc.rpcError.desc field which contains our error code if !strings.Contains(err.Error(), NoNodesAvailableError.Error()) { require.NoError(t, err) return } time.Sleep(retryDelay) } require.Fail(t, "Timed out waiting for node %s readiness", service.GetNodeName()) } func testAllApiBasics(ctx context.Context, t *testing.T, svc []cronSvc) { for _, s := range svc { client, err := s.service.GetRpcForNode(ctx, s.cfg.NodeName) require.NoError(t, err) testApiBasics(ctx, client, t) t.Logf("%s API test complete", s.cfg.NodeName) } } func testApiBasics(ctx context.Context, client DistCronClient, t *testing.T) { err := NoNodesAvailableError var handle *JobHandle handle, err = client.RunJob(ctx, &Job{ ContainerName: "hello-world", CpuLimit: 1, MemLimitMb: 500, }) require.NoError(t, err) _, err = client.StopJob(ctx, handle) assert.NoError(t, err) _, err = client.GetJobStatus(ctx, handle) assert.NoError(t, err) output, err := client.GetJobOutput(ctx, handle) require.NoError(t, err) linesPrinted := 0 maxLines := 2 for { data, err := output.Recv() if err == io.EOF { break } else if err != nil { t.Error(err) break } if linesPrinted < maxLines { t.Log(string(data.Data)) linesPrinted++ } } } <file_sep>package dc import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/net/context" ) func TestRunner(t *testing.T) { r := NewRunner() ctx := context.Background() cid, err := r.RunJob(ctx, &Job{ ContainerName: "hello-world", CpuLimit: 1, MemLimitMb: 500, }) require.NoError(t, err) st, err := r.StopJob(ctx, cid) assert.NoError(t, err) t.Log(st) r.GetJobOutput(ctx, cid, print(t)) assert.NoError(t, err) _, err = r.StopJob(ctx, "no-such-container") if assert.Error(t, err) { assert.Equal(t, InternalError, err) } } func print(t *testing.T) DataCopyFn { return func(data []byte) error { if len(data) > 0 { t.Log(string(data)) } return nil } } <file_sep>package main import ( "flag" "fmt" "os" "os/signal" "distcron/dc" "github.com/golang/glog" "golang.org/x/net/context" ) var nodeName = flag.String("node", "", "Node name, should be unique") var nodeBindPort = flag.Int("nodeBindPort", 5000, "Node cluster RPC port") var nodeBindAddr = flag.String("nodeBindAddr", "127.0.0.1", "Node clust RPC address") var apiPort = flag.Int("apiPort", 5050, "GRPC API port") var etcd = flag.String("etcd", "172.17.8.101:2379", "ETCD address and port") var joinTo = flag.String("join", "", "Other cluster addresses to join to") func main() { flag.Parse() if *nodeName == "" { *nodeName = fmt.Sprintf("dc_%s:%d", *nodeBindAddr, *nodeBindPort) } ctx, stop := context.WithCancel(context.Background()) svc, err := dc.NewDistCron(ctx, &dc.ClusterConfig{ NodeName: *nodeName, BindAddr: *nodeBindAddr, BindPort: *nodeBindPort, }, []string{*etcd}, fmt.Sprintf(":%d", *apiPort)) if err != nil { glog.Fatal(err) } if *joinTo != "" { svc.JoinTo([]string{*joinTo}) } c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) <-c stop() } <file_sep>package dc import ( "testing" "distcron/dc" "distcron/dc/mocks" "github.com/hashicorp/serf/serf" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/load" "github.com/shirou/gopsutil/mem" "github.com/stretchr/testify/require" "golang.org/x/net/context" ) var testJob *dc.Job = &dc.Job{ContainerName: "hello-world", CpuLimit: 1.0, MemLimitMb: 500} func mkFailingClient(ctx context.Context) *mocks.DistCronClient { client := new(mocks.DistCronClient) client.On("RunJobOnThisNode", ctx, testJob).Return(nil, dc.InternalError) return client } func mkClient(ctx context.Context, handle string) *mocks.DistCronClient { client := new(mocks.DistCronClient) client.On("RunJobOnThisNode", ctx, testJob).Return(&dc.JobHandle{handle}, nil) return client } func mkSerfMembers(names []string) []serf.Member { members := make([]serf.Member, len(names)) for i, _ := range members { members[i].Name = names[i] members[i].Status = serf.StatusAlive } return members } func mkNode(name string, leader bool, members []serf.Member) *mocks.Node { node := new(mocks.Node) node.On("GetName").Return(name) node.On("IsLeader").Return(leader) node.On("SerfMembers").Return(members) node.On("SerfMembersCount").Return(len(members)) return node } func mkTelemetry(name string, availCpu int32, availRam uint64, load5 float64) *dc.TelemetryInfo { return &dc.TelemetryInfo{ Node: name, Mem: &mem.VirtualMemoryStat{Available: availRam}, Cpu: []cpu.InfoStat{cpu.InfoStat{Cores: availCpu}}, Load: &load.AvgStat{Load5: load5}, } } func TestDispatcherBasics(t *testing.T) { ctx, stop := context.WithCancel(context.Background()) defer stop() telemetryChannel := make(chan *dc.TelemetryInfo) telemetryUpdate := make(chan bool, 2) rpc := new(mocks.RpcInfo) serfMembers := mkSerfMembers([]string{"A", "B"}) node := mkNode("A", true, serfMembers) disp := dc.NewDispatcher(node, rpc, telemetryChannel, telemetryUpdate) disp.Start(ctx) // nodes are available, but no telemetry ever receieved, // will fail as resources are unknown, won't try to invoke RPC _, err := disp.NewJob(ctx, testJob) require.EqualError(t, err, dc.NoNodesAvailableError.Error()) // report resource availability, should return from node B rpc.On("GetRpcForNode", ctx, "B").Return(mkClient(ctx, "B"), nil).Once() telemetryChannel <- mkTelemetry("A", 2, 5000, 2.5) telemetryChannel <- mkTelemetry("B", 2, 2000, 0.5) <-telemetryUpdate <-telemetryUpdate handle, err := disp.NewJob(ctx, testJob) require.NoError(t, err) require.EqualValues(t, &dc.JobHandle{"B"}, handle) // node B starts to fail, should fail now - A doesn't have any resources available rpc.On("GetRpcForNode", ctx, "B").Return(mkFailingClient(ctx), nil).Once() handle, err = disp.NewJob(ctx, testJob) require.EqualError(t, err, dc.NoNodesAvailableError.Error()) // node A gets resources, B is still in back-off state, A should be selected telemetryChannel <- mkTelemetry("A", 2, 5000, 0.1) <-telemetryUpdate rpc.On("GetRpcForNode", ctx, "A").Return(mkClient(ctx, "A"), nil).Once() testJob.CpuLimit = 1.3 handle, err = disp.NewJob(ctx, testJob) require.NoError(t, err) require.EqualValues(t, &dc.JobHandle{"A"}, handle) } <file_sep>## Overview A comprehensive discussion on distributed job schedulers is available from [Google](https://queue.acm.org/detail.cfm?id=2745840) and [Facebook](https://facebook.github.io/bistro/static/bistro_ATC_final.pdf) we will borrow most design decisions from there. ## Clustering ### Membership Hosts join the cluster and maintain its membership based on gossip protocol. [See Serf](https://github.com/hashicorp/serf). A node will need to be aware about any other node in order to join the cluster. Maintaining list of previously known peers and other auto discovery mechanisms such as provided by GCP and AWS environments are left out of scope for this implementation. ## Leader Leader election is based on acquiring distributed lock over KV storage, see github.com/docker/leadership ## Followers When node is in Follower state, it will only be able to accept commands from Leader to run a specific task. ## Jobs & Schedule The usecase of distributed job scheduler will unlikely be limited to running a typical local CRON tasks doing local host housekeeping, but likely more complex workloads users expect to be elastically executed across available infrastructure. In such scenarios, distributing and updating software including its dependencies will likely be a major issue, and using pre-built Docker containers a more natural choice rather then just supplying an executable and custom files to run. By using Docker, we can [limit container resources](https://docs.docker.com/engine/admin/resource_constraints/) without need to create cgroups and namespaces manually. Use of Docker also provides path towards [live migration](https://github.com/docker/docker/blob/master/experimental/checkpoint-restore.md) support. ### Output Logging For production environment, forwarding logs from individual Docker container run to centralized location by means of custom logging driver might be a solution of choice. Browsing historical or real-time feed would be a matter of filtering logs by specific job ID then. In our simplified case, we will just bind output of docker logs command with HTTP API in order to provide live view to remote observer. ### Scheduler Every job is defined by set of runtime parameters, and execution constraints. The scheduler main loop will: * Calculate next time a job should be run * Notify followers that certain job is about to launch, and update its next scheduled run time * Selects next available node (see below) * Spawns process on remote node * Notify followers that job is now running on certain node * Remote node should notify current leader on job completion, after that Leader notifies followers on job completion Followers notification is done via Raft, and is strong consistency operation. ### Concurrent execution Distributed CRON will spawn jobs when time comes. In case it might be needed to maintain strictly single instance of a job, one may implement a distributed lock using i.e. etcd or Raft to prevent certain jobs executing concurrently, similar to flock usage with local crond. ### Node selection Nodes will continuously provide update on their available resources, such as CPU, RAM and DISK via gossip protocol. Scheduler will maintain a state table of nodes, and will apply a naive algorithm to pick machine with most (at least 25%) available resources to execute next workload. For simplicity, it will not try to estimate whether target host is a best fit for the given workload. If no such machine is found for the task, the task will fail. ## Configuration and API * Only Leader will serve API requests and update configuration via Raft, using flat files for internal configuration storage, in order to minimize external dependency requirements (i.e. external database). * If API request arrives to a node which is currently in Follower state, it will issue an HTTP 302 (temporary redirect). In production environment it might transparently proxy the request torwards the Leader host. * As part of Leader node election we may also enable dynamic API discovery features, such as automatic registration of Leader IP address within a dynamic DNS service or registration on external HTTPS load balancer. ## Configuration ## Failure and Recovery In the event of Leader failure, Raft protocol provides a mechanism to elect a new Leader, along with state replication and snapshotting mechanisms in order to keep it up to date. The following situations may happen in our current design: (incomplete) * Master declares a certain job as 'about to run' but fails to actually run it ## Authentication and Security For simplicity, no authentication and transport layer security will be in place for this implementation. <file_sep>package mocks import context "golang.org/x/net/context" import mock "github.com/stretchr/testify/mock" import net "net" import serf "github.com/hashicorp/serf/serf" // Node is an autogenerated mock type for the Node type type Node struct { mock.Mock } // GetLeader provides a mock function with given fields: func (_m *Node) GetLeader() (string, net.IP, error) { ret := _m.Called() var r0 string if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } var r1 net.IP if rf, ok := ret.Get(1).(func() net.IP); ok { r1 = rf() } else { if ret.Get(1) != nil { r1 = ret.Get(1).(net.IP) } } var r2 error if rf, ok := ret.Get(2).(func() error); ok { r2 = rf() } else { r2 = ret.Error(2) } return r0, r1, r2 } // GetName provides a mock function with given fields: func (_m *Node) GetName() string { ret := _m.Called() var r0 string if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } return r0 } // IsLeader provides a mock function with given fields: func (_m *Node) IsLeader() bool { ret := _m.Called() var r0 bool if rf, ok := ret.Get(0).(func() bool); ok { r0 = rf() } else { r0 = ret.Get(0).(bool) } return r0 } // Join provides a mock function with given fields: addr func (_m *Node) Join(addr []string) error { ret := _m.Called(addr) var r0 error if rf, ok := ret.Get(0).(func([]string) error); ok { r0 = rf(addr) } else { r0 = ret.Error(0) } return r0 } // SerfMembers provides a mock function with given fields: func (_m *Node) SerfMembers() []serf.Member { ret := _m.Called() var r0 []serf.Member if rf, ok := ret.Get(0).(func() []serf.Member); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]serf.Member) } } return r0 } // SerfMembersCount provides a mock function with given fields: func (_m *Node) SerfMembersCount() int { ret := _m.Called() var r0 int if rf, ok := ret.Get(0).(func() int); ok { r0 = rf() } else { r0 = ret.Get(0).(int) } return r0 } // Start provides a mock function with given fields: _a0 func (_m *Node) Start(_a0 context.Context) { _m.Called(_a0) } <file_sep>package dc import ( "fmt" "time" "github.com/golang/glog" "golang.org/x/net/context" "google.golang.org/grpc" ) /* * binds everything together into single service */ type DistCron struct { node Node dispatcher Dispatcher runner Runner db *DB api *apiService leaderChannel chan bool } type rpcInfo struct { Addr string `json:"addr"` Ts time.Time `json:"ts"` } func NewDistCron(ctx context.Context, clusterConfig *ClusterConfig, dbHosts []string, rpcAddr string, ) (*DistCron, error) { db, err := ConnectDB(dbHosts) if err != nil { glog.Error(err) return nil, err } cron := &DistCron{ leaderChannel: make(chan bool, cChanBuffer), db: db, runner: NewRunner(), } telemetryChan := make(chan *TelemetryInfo, cChanBuffer) if cron.node, err = NewClusterNode(clusterConfig, cron.db, cron.leaderChannel, telemetryChan); err != nil { glog.Error(err) return nil, err } cron.dispatcher = NewDispatcher(cron.node, cron, telemetryChan, nil) if cron.api, err = NewApiServer(cron.runner, cron.dispatcher, cron); err != nil { glog.Error(err) return nil, err } cron.node.Start(ctx) cron.dispatcher.Start(ctx) cron.api.Start(ctx, rpcAddr) go cron.run(ctx) return cron, nil } func (cron *DistCron) JoinTo(addr []string) (err error) { if err = cron.node.Join(addr); err != nil { glog.Error(err) } return } func (cron *DistCron) GetLeaderNode() (string, error) { node, _, err := cron.node.GetLeader() return node, err } func (cron *DistCron) IsLeader() bool { return cron.node.IsLeader() } func (cron *DistCron) GetNodeName() string { return cron.node.GetName() } func (cron *DistCron) SetRpcForNode(node, addr string) (err error) { err = cron.db.Put(fmt.Sprintf("%s/%s", CRPCPrefix, node), &rpcInfo{ Addr: addr, Ts: time.Now(), }) if err != nil { glog.Errorf("Can't publish RPC address for a node : %v", err) } return } func (cron *DistCron) GetRpcForNode(ctx context.Context, node string) (DistCronClient, error) { info := rpcInfo{} if err := cron.db.Get(fmt.Sprintf("%s/%s", CRPCPrefix, node), &info); err != nil { glog.Error(err) return nil, err } conn, err := grpc.DialContext(ctx, info.Addr, grpc.WithInsecure()) if err != nil { glog.Errorf("fail to dial %s: %v", info.Addr, err) return nil, err } return NewDistCronClient(conn), nil } func (cron *DistCron) run(ctx context.Context) { for { select { case <-ctx.Done(): glog.Infof("[%s] Cron service stop", cron.GetNodeName()) return case leader := <-cron.leaderChannel: glog.V(cLogDebug).Infof("[%s] Leader %v", cron.GetNodeName(), leader) // we may wish to pause other services // but only side effect right now is that node stops collecting telemetry // which it automatically does when leadership is lost } } } <file_sep>package dc import ( "math" "sync" "time" "github.com/golang/glog" "github.com/hashicorp/serf/serf" "golang.org/x/net/context" ) /* * Dispatcher receives job run requests and decides which node should run it * * Also listens to cluster membership and telemetry events from Node * to be aware of current workloads * * If there are no nodes matching the load available, it simply rejects new job * */ type dispatcher struct { sync.Mutex api RpcInfo node Node nodeInfo map[string]*nodeInfo telemetryChannel chan *TelemetryInfo telemetryUpdated chan bool // debug channel for tests synchronization } type nodeInfo struct { errorCount int backoffUntil time.Time memAvailable int64 cpuAvailable float64 } const cMB = 2 << 19 const cMinRAM = cMB * 500 const cMinCPU = 0.0 func NewDispatcher(node Node, api RpcInfo, telemetryChannel chan *TelemetryInfo, telemetryUpdated chan bool) Dispatcher { return &dispatcher{ api: api, node: node, nodeInfo: make(map[string]*nodeInfo), telemetryChannel: telemetryChannel, telemetryUpdated: telemetryUpdated, } } func (d *dispatcher) Start(parentCtx context.Context) { ctx, _ := context.WithCancel(parentCtx) go d.run(ctx) } func (d *dispatcher) NewJob(ctx context.Context, job *Job) (*JobHandle, error) { for retry := 0; retry <= d.node.SerfMembersCount(); retry++ { select { case <-ctx.Done(): glog.Errorf("[%s] Job %v rejected, context %v", d.node.GetName(), job, ctx.Err()) return nil, RequestTimeoutError default: } node, err := d.getAvailableNode(job) if err != nil { glog.Errorf("[%s] Job %v, retry=%d - no more nodes available, giving up", d.node.GetName(), job, retry) return nil, NoNodesAvailableError } if handle, err := d.newJob(ctx, job, node); err == nil { return handle, err } } glog.Errorf("[%s] Job %v, max retries, giving up", d.node.GetName(), job) return nil, NoNodesAvailableError } func (d *dispatcher) newJob(ctx context.Context, job *Job, node string) (*JobHandle, error) { rpc, err := d.api.GetRpcForNode(ctx, node) if err != nil { glog.Error(err) // maybe this node just joined and did not register yet - backoff d.nodeFailed(node) return nil, err } handle, err := rpc.RunJobOnThisNode(ctx, job) if err != nil { glog.Errorf("[%s] Job %v failed to run on node %s : %v", d.node.GetName(), job, node, err) d.nodeFailed(node) return nil, err } glog.V(cLogDebug).Infof("[%s] Job %v running on %s, handle %v", d.node.GetName(), job, node, handle) d.clearNodeErrors(node) return handle, nil } func fitForJob(info *nodeInfo, job *Job) bool { return (int64(info.memAvailable)-job.MemLimitMb*cMB >= cMinRAM) || (info.cpuAvailable-float64(job.CpuLimit) >= cMinCPU) } func (d *dispatcher) getAvailableNode(job *Job) (string, error) { members := d.node.SerfMembers() now := time.Now() d.Lock() defer d.Unlock() for _, member := range members { if member.Status == serf.StatusAlive { if info := d.getNodeInfo(member.Name); info.backoffUntil.Before(now) && fitForJob(info, job) { glog.V(cLogDebug).Infof("[%s] selected node %s:%+v to run %v", d.node.GetName(), member.Name, info, job) return member.Name, nil } else { glog.V(cLogDebug).Infof("[%s] job %v can't run on %s:%+v", d.node.GetName(), job, member.Name, info) } } } glog.V(cLogDebug).Infof("[%s] Couldn't find any nodes for job %v", d.node.GetName(), job) return "", NoNodesAvailableError } /* * main dispatcher activity is monitoring other nodes load, while in leadership mode * */ func (d *dispatcher) run(ctx context.Context) { for { select { case <-ctx.Done(): return case tm := <-d.telemetryChannel: d.updateTelemetry(tm) } } } func (d *dispatcher) updateTelemetry(tm *TelemetryInfo) { d.Lock() defer d.Unlock() info := d.getNodeInfo(tm.Node) cpu := 0.0 for _, proc := range tm.Cpu { cpu += float64(proc.Cores) } info.cpuAvailable = cpu - tm.Load.Load5 info.memAvailable = int64(tm.Mem.Available) glog.V(cLogDebug).Infof("[%s] Telemetry in : %v => %+v", d.node.GetName(), tm, info) select { case d.telemetryUpdated <- true: default: } } func (d *dispatcher) getNodeInfo(name string) *nodeInfo { info, there := d.nodeInfo[name] if !there { info = &nodeInfo{} d.nodeInfo[name] = info } return info } func (d *dispatcher) nodeFailed(name string) { d.Lock() defer d.Unlock() info := d.nodeInfo[name] info.errorCount++ info.backoffUntil = time.Now().Add(backoff(info.errorCount)) } func (d *dispatcher) clearNodeErrors(name string) { d.Lock() defer d.Unlock() info := d.nodeInfo[name] info.errorCount = 0 } const cMaxDelay = time.Minute * 5 func backoff(errCount int) time.Duration { delay := time.Millisecond * time.Duration(int64(1000*(math.Pow(2, float64(errCount))-1)/2)) if delay > cMaxDelay { return cMaxDelay } else { return delay } } <file_sep>package mocks import context "golang.org/x/net/context" import dc "distcron/dc" import mock "github.com/stretchr/testify/mock" // DistCronServer is an autogenerated mock type for the DistCronServer type type DistCronServer struct { mock.Mock } // GetJobOutput provides a mock function with given fields: _a0, _a1 func (_m *DistCronServer) GetJobOutput(_a0 *dc.JobHandle, _a1 dc.DistCron_GetJobOutputServer) error { ret := _m.Called(_a0, _a1) var r0 error if rf, ok := ret.Get(0).(func(*dc.JobHandle, dc.DistCron_GetJobOutputServer) error); ok { r0 = rf(_a0, _a1) } else { r0 = ret.Error(0) } return r0 } // GetJobStatus provides a mock function with given fields: _a0, _a1 func (_m *DistCronServer) GetJobStatus(_a0 context.Context, _a1 *dc.JobHandle) (*dc.JobStatus, error) { ret := _m.Called(_a0, _a1) var r0 *dc.JobStatus if rf, ok := ret.Get(0).(func(context.Context, *dc.JobHandle) *dc.JobStatus); ok { r0 = rf(_a0, _a1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobStatus) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.JobHandle) error); ok { r1 = rf(_a0, _a1) } else { r1 = ret.Error(1) } return r0, r1 } // RunJob provides a mock function with given fields: _a0, _a1 func (_m *DistCronServer) RunJob(_a0 context.Context, _a1 *dc.Job) (*dc.JobHandle, error) { ret := _m.Called(_a0, _a1) var r0 *dc.JobHandle if rf, ok := ret.Get(0).(func(context.Context, *dc.Job) *dc.JobHandle); ok { r0 = rf(_a0, _a1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobHandle) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.Job) error); ok { r1 = rf(_a0, _a1) } else { r1 = ret.Error(1) } return r0, r1 } // RunJobOnThisNode provides a mock function with given fields: _a0, _a1 func (_m *DistCronServer) RunJobOnThisNode(_a0 context.Context, _a1 *dc.Job) (*dc.JobHandle, error) { ret := _m.Called(_a0, _a1) var r0 *dc.JobHandle if rf, ok := ret.Get(0).(func(context.Context, *dc.Job) *dc.JobHandle); ok { r0 = rf(_a0, _a1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobHandle) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.Job) error); ok { r1 = rf(_a0, _a1) } else { r1 = ret.Error(1) } return r0, r1 } // StopJob provides a mock function with given fields: _a0, _a1 func (_m *DistCronServer) StopJob(_a0 context.Context, _a1 *dc.JobHandle) (*dc.JobStatus, error) { ret := _m.Called(_a0, _a1) var r0 *dc.JobStatus if rf, ok := ret.Get(0).(func(context.Context, *dc.JobHandle) *dc.JobStatus); ok { r0 = rf(_a0, _a1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobStatus) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.JobHandle) error); ok { r1 = rf(_a0, _a1) } else { r1 = ret.Error(1) } return r0, r1 } <file_sep>package dc import ( "encoding/json" "fmt" "github.com/docker/libkv" "github.com/docker/libkv/store" "github.com/docker/libkv/store/consul" "github.com/golang/glog" ) /* * KV database stores the following: * * 1. cluster leader node name * 2. cluster node RPC addresses - as a sole convenience for testing within a single host * * Jobs are not persisted in this particular database * as etcd doesn't support ever growing databases * https://coreos.com/etcd/docs/latest/dev-guide/limit.html * */ const CLeadershipKey = "distcron/leader" const CRPCPrefix = "distcron/rpc" type DB struct { store store.Store } func init() { consul.Register() } func ConnectDB(hosts []string) (db *DB, err error) { db = &DB{} db.store, err = libkv.NewStore(store.CONSUL, hosts, &store.Config{Bucket: "distcron"}) return } func (db *DB) Put(key string, obj interface{}) error { data, err := json.Marshal(obj) if err != nil { ex := fmt.Errorf("Cant serialize value for key %s : %v", key, err) glog.Error(ex) return ex } else { glog.V(cLogDebug).Infof("DB %s <-- %s", key, string(data)) } if err = db.store.Put(key, data, nil); err != nil { glog.Errorf("Can't store value for key %s : %v", key, err) return err } return nil } func (db *DB) Get(key string, obj interface{}) error { kv, err := db.store.Get(key) if err != nil { ex := fmt.Errorf("Cant fetch key %s: %v", key, err) glog.Error(ex) return ex } else { glog.V(cLogDebug).Infof("DB %s --> %s", key, string(kv.Value)) } if err = json.Unmarshal(kv.Value, obj); err != nil { glog.Error(err) return err } return nil } <file_sep>package dc import ( "bytes" "encoding/base64" "encoding/gob" "fmt" "net" "github.com/golang/glog" "github.com/hashicorp/serf/serf" "golang.org/x/net/context" ) // log levels const cLogDebug = 0 // 1 for development and testing // 64-256 for production const cChanBuffer = 1 type Node interface { // GetName returns this node logical name, must be unique in the cluster GetName() string // IsLeader returns true if this node is a current cluster leader IsLeader() bool // GetLeader returns current cluster leader node GetLeader() (name string, addr net.IP, err error) SerfMembers() []serf.Member SerfMembersCount() int // Starts node service, use context to terminate Start(context.Context) // Join other known nodes in the cluster, should be in form addr:port Join(addr []string) error } type RpcInfo interface { // current node name GetNodeName() string // is current node a leader IsLeader() bool // returns leader node name GetLeaderNode() (string, error) // stores RPC address for a given node in some distributed storage SetRpcForNode(node, addr string) error // given a node name, provides RPC client instance GetRpcForNode(ctx context.Context, node string) (DistCronClient, error) } type Dispatcher interface { // Start dispatcher service. Use context to stop the service Start(context.Context) // NewJob places a job on next available node, taking care of resources // if no node is available, NoNodesAvailableError is returned NewJob(ctx context.Context, job *Job) (*JobHandle, error) } type DataCopyFn func(data []byte) error type Runner interface { // RunJob spawns new job, returns internal container ID RunJob(ctx context.Context, job *Job) (cid string, err error) // GetJobStatus returns job status as reported by docker daemon, format is unspecified GetJobStatus(ctx context.Context, cid string) (status *JobStatus, err error) // StopJob requests docker daemon to stop a job and returns current status StopJob(ctx context.Context, cid string) (status *JobStatus, err error) // GetJobOutput provides streaming of container most recent output GetJobOutput(ctx context.Context, cid string, fn DataCopyFn) (err error) } /* * simple and insecure : job handle is node name + container ID * in real life should be GUID and stored in DB * * provides mapping to PB JobHandle message */ type jobHandle struct { Node, CID string } func (h *jobHandle) Handle() *JobHandle { var buf bytes.Buffer enc := gob.NewEncoder(&buf) enc.Encode(h) return &JobHandle{base64.StdEncoding.EncodeToString(buf.Bytes())} } func (handle *JobHandle) ToInternal() (*jobHandle, error) { var hdl jobHandle data, err := base64.StdEncoding.DecodeString(handle.Handle) if err != nil { glog.Error(handle, err) return nil, err } if err := gob.NewDecoder(bytes.NewBuffer(data)).Decode(&hdl); err != nil { glog.Error(handle, err) return nil, err } else { return &hdl, nil } } // no nodes currently available. this may be a transient error when cluster is rebalancing var NoNodesAvailableError = fmt.Errorf("E_NO_NODES_AVAILABLE") // don't want to expose details var InternalError = fmt.Errorf("E_INTERNAL_ERROR") // deadline exceeded for request var RequestTimeoutError = fmt.Errorf("E_REQUEST_TIMEOUT") <file_sep>package mocks import context "golang.org/x/net/context" import dc "distcron/dc" import mock "github.com/stretchr/testify/mock" // RpcInfo is an autogenerated mock type for the RpcInfo type type RpcInfo struct { mock.Mock } // GetLeaderNode provides a mock function with given fields: func (_m *RpcInfo) GetLeaderNode() (string, error) { ret := _m.Called() var r0 string if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { r1 = ret.Error(1) } return r0, r1 } // GetNodeName provides a mock function with given fields: func (_m *RpcInfo) GetNodeName() string { ret := _m.Called() var r0 string if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } return r0 } // GetRpcForNode provides a mock function with given fields: ctx, node func (_m *RpcInfo) GetRpcForNode(ctx context.Context, node string) (dc.DistCronClient, error) { ret := _m.Called(ctx, node) var r0 dc.DistCronClient if rf, ok := ret.Get(0).(func(context.Context, string) dc.DistCronClient); ok { r0 = rf(ctx, node) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(dc.DistCronClient) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { r1 = rf(ctx, node) } else { r1 = ret.Error(1) } return r0, r1 } // IsLeader provides a mock function with given fields: func (_m *RpcInfo) IsLeader() bool { ret := _m.Called() var r0 bool if rf, ok := ret.Get(0).(func() bool); ok { r0 = rf() } else { r0 = ret.Get(0).(bool) } return r0 } // SetRpcForNode provides a mock function with given fields: node, addr func (_m *RpcInfo) SetRpcForNode(node string, addr string) error { ret := _m.Called(node, addr) var r0 error if rf, ok := ret.Get(0).(func(string, string) error); ok { r0 = rf(node, addr) } else { r0 = ret.Error(0) } return r0 } <file_sep>package mocks import context "golang.org/x/net/context" import dc "distcron/dc" import mock "github.com/stretchr/testify/mock" // Dispatcher is an autogenerated mock type for the Dispatcher type type Dispatcher struct { mock.Mock } // NewJob provides a mock function with given fields: ctx, job func (_m *Dispatcher) NewJob(ctx context.Context, job *dc.Job) (*dc.JobHandle, error) { ret := _m.Called(ctx, job) var r0 *dc.JobHandle if rf, ok := ret.Get(0).(func(context.Context, *dc.Job) *dc.JobHandle); ok { r0 = rf(ctx, job) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobHandle) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.Job) error); ok { r1 = rf(ctx, job) } else { r1 = ret.Error(1) } return r0, r1 } // Start provides a mock function with given fields: _a0 func (_m *Dispatcher) Start(_a0 context.Context) { _m.Called(_a0) } <file_sep>package mocks import context "golang.org/x/net/context" import dc "distcron/dc" import mock "github.com/stretchr/testify/mock" // Runner is an autogenerated mock type for the Runner type type Runner struct { mock.Mock } // GetJobOutput provides a mock function with given fields: ctx, cid, fn func (_m *Runner) GetJobOutput(ctx context.Context, cid string, fn dc.DataCopyFn) error { ret := _m.Called(ctx, cid, fn) var r0 error if rf, ok := ret.Get(0).(func(context.Context, string, dc.DataCopyFn) error); ok { r0 = rf(ctx, cid, fn) } else { r0 = ret.Error(0) } return r0 } // GetJobStatus provides a mock function with given fields: ctx, cid func (_m *Runner) GetJobStatus(ctx context.Context, cid string) (*dc.JobStatus, error) { ret := _m.Called(ctx, cid) var r0 *dc.JobStatus if rf, ok := ret.Get(0).(func(context.Context, string) *dc.JobStatus); ok { r0 = rf(ctx, cid) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobStatus) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { r1 = rf(ctx, cid) } else { r1 = ret.Error(1) } return r0, r1 } // RunJob provides a mock function with given fields: ctx, job func (_m *Runner) RunJob(ctx context.Context, job *dc.Job) (string, error) { ret := _m.Called(ctx, job) var r0 string if rf, ok := ret.Get(0).(func(context.Context, *dc.Job) string); ok { r0 = rf(ctx, job) } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func(context.Context, *dc.Job) error); ok { r1 = rf(ctx, job) } else { r1 = ret.Error(1) } return r0, r1 } // StopJob provides a mock function with given fields: ctx, cid func (_m *Runner) StopJob(ctx context.Context, cid string) (*dc.JobStatus, error) { ret := _m.Called(ctx, cid) var r0 *dc.JobStatus if rf, ok := ret.Get(0).(func(context.Context, string) *dc.JobStatus); ok { r0 = rf(ctx, cid) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dc.JobStatus) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { r1 = rf(ctx, cid) } else { r1 = ret.Error(1) } return r0, r1 } <file_sep>package dc import ( "io" "net" "github.com/golang/glog" "golang.org/x/net/context" "google.golang.org/grpc" ) type apiService struct { runner Runner dispatcher Dispatcher rpcInfo RpcInfo server *grpc.Server } /* * API calls get forwarded to either relevant node or to a leader * No authentication for sample implementation */ func NewApiServer(runner Runner, dispatcher Dispatcher, rpcInfo RpcInfo) (*apiService, error) { apiSvc := &apiService{ runner: runner, dispatcher: dispatcher, server: grpc.NewServer(), rpcInfo: rpcInfo, } return apiSvc, nil } func (api *apiService) Start(ctx context.Context, listenTo string) error { lc, err := net.Listen("tcp", listenTo) if err != nil { glog.Errorf("can't listen: %v", err) return err } err = api.rpcInfo.SetRpcForNode(api.rpcInfo.GetNodeName(), listenTo) if err != nil { glog.Error(err) return err } RegisterDistCronServer(api.server, api) go func() { glog.Error(api.server.Serve(lc)) }() go func() { <-ctx.Done() api.server.GracefulStop() }() return nil } func (api *apiService) getLeaderRpc(ctx context.Context) (DistCronClient, error) { leaderNode, err := api.rpcInfo.GetLeaderNode() if err != nil { glog.Errorf("[%s] getLeaderRpc %v", api.rpcInfo.GetNodeName(), err) return nil, err } leaderRpc, err := api.rpcInfo.GetRpcForNode(ctx, leaderNode) if err != nil { glog.Errorf("[%s] getLeaderRpc %v", api.rpcInfo.GetNodeName(), err) return nil, err } return leaderRpc, nil } func (api *apiService) getRpcFromHandle(ctx context.Context, jh *JobHandle) (*jobHandle, DistCronClient, error) { handle, err := jh.ToInternal() if err != nil { return nil, nil, err } if handle.Node == api.rpcInfo.GetNodeName() { return handle, nil, nil } rpc, err := api.rpcInfo.GetRpcForNode(ctx, handle.Node) return handle, rpc, err } func (api *apiService) RunJob(ctx context.Context, job *Job) (*JobHandle, error) { if api.rpcInfo.IsLeader() { handle, err := api.dispatcher.NewJob(ctx, job) if err != nil { glog.Errorf("[%s] RunJob %v", api.rpcInfo.GetNodeName(), err) } return handle, err } leaderRpc, err := api.getLeaderRpc(ctx) if err != nil { glog.Errorf("[%s] RunJob %v", api.rpcInfo.GetNodeName(), err) return nil, InternalError } return leaderRpc.RunJob(ctx, job) } // RunJobOnThisNode is internal API method to execute job on the node which received the call func (api *apiService) RunJobOnThisNode(ctx context.Context, job *Job) (*JobHandle, error) { cid, err := api.runner.RunJob(ctx, job) if err != nil { glog.Errorf("[%s] RunJobOnThisNode %v", api.rpcInfo.GetNodeName(), err) return nil, err } return (&jobHandle{CID: cid, Node: api.rpcInfo.GetNodeName()}).Handle(), nil } func (api *apiService) StopJob(ctx context.Context, jh *JobHandle) (*JobStatus, error) { handle, nodeRpc, err := api.getRpcFromHandle(ctx, jh) if err != nil { glog.Errorf("[%s] StopJob %v", api.rpcInfo.GetNodeName(), err) return nil, InternalError } if nodeRpc != nil { return nodeRpc.StopJob(ctx, jh) } return api.runner.StopJob(ctx, handle.CID) } func (api *apiService) GetJobStatus(ctx context.Context, jh *JobHandle) (*JobStatus, error) { handle, nodeRpc, err := api.getRpcFromHandle(ctx, jh) if err != nil { glog.Errorf("[%s] GetJobStatus %v", api.rpcInfo.GetNodeName(), err) return nil, InternalError } if nodeRpc != nil { return nodeRpc.GetJobStatus(ctx, jh) } return api.runner.GetJobStatus(ctx, handle.CID) } func (api *apiService) streamLocalJobOutput(handle *jobHandle, stream DistCron_GetJobOutputServer) error { err := api.runner.GetJobOutput(stream.Context(), handle.CID, func(data []byte) error { return stream.Send(&Output{data}) }) if err != nil { glog.Error(err) return InternalError } return nil } func streamJobOutputFromNode(jh *JobHandle, nodeRpc DistCronClient, stream DistCron_GetJobOutputServer) error { ctx := stream.Context() output, err := nodeRpc.GetJobOutput(ctx, jh) if err != nil { glog.Error(err) return err } for { select { case <-ctx.Done(): break default: } data, err := output.Recv() if err == io.EOF { break } else if err != nil { glog.Error(err) return err } if err = stream.Send(data); err != nil { glog.Error(err) return err } } return nil } func (api *apiService) GetJobOutput(jh *JobHandle, stream DistCron_GetJobOutputServer) error { handle, nodeRpc, err := api.getRpcFromHandle(stream.Context(), jh) if err != nil { glog.Error(err) return InternalError } if nodeRpc != nil { // forward to the node where it was executed return streamJobOutputFromNode(jh, nodeRpc, stream) } return api.streamLocalJobOutput(handle, stream) }
238e5e94b96d1ffe4258de01b372b4afae386248
[ "Makefile", "Go", "Markdown" ]
21
Go
DenisMishin/distcron
60d77af426cae045ad1a414dec49dff32f0a1992
2f9bdc0538919b4d7e699eb2e010dcf3db183e61
refs/heads/master
<repo_name>vtk13/confirm-user-registration<file_sep>/confirm-user-registration.php <?php /* Plugin Name: Confirm User Registration Plugin URI: http://www.horttcore.de/ Description: Admins have to confirm a user registration - a notification will be send when the account gets activated Author: <NAME> Version: 2.1.5 Author URI: http://horttcore.de/ */ /** * Security, checks if WordPress is running **/ if ( !function_exists('add_action') ) : header('Status: 403 Forbidden'); header('HTTP/1.1 403 Forbidden'); exit(); endif; /** * * Plugin Definitions * */ define( 'RH_CUR_BASENAME', plugin_basename(__FILE__) ); define( 'RH_CUR_BASEDIR', dirname( plugin_basename(__FILE__) ) ); /** * */ class Confirm_User_Registration { protected $per_page = 100; protected $current_page = 1; /** * Total items found by last get_authed_users() or get_pending_users() * * @var int */ protected $total_found = 0; /** * * Construct * */ function __construct() { add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'admin_print_scripts-users_page_confirm-user-registration', array( $this, 'enqueue_scripts' ) ); add_action( 'admin_print_styles-users_page_confirm-user-registration', array( $this, 'enqueue_styles' ) ); add_action( 'wp_ajax_confirm-user-registration-save_settings', array( $this, 'save_settings' ) ); add_action( 'admin_init', array( $this, 'load_plugin_textdomain' ) ); add_action( 'wp_authenticate_user', array( $this, 'wp_authenticate_user' ) ); # Prevent login if user is not authed register_activation_hook( __FILE__, array( $this, 'activation' ) ); $this->current_page = isset($_GET['paged']) ? (int)$_GET['paged'] : 1; } /** * Plugin activation * * @access public * @return void * @author <NAME> **/ public function activation() { // First time installation if ( $this->is_first_time() ) : $users = get_users(); if ( $users ) : foreach ( $users as $user ) : update_usermeta( $user->ID, 'authentication', '1' ); endforeach; endif; add_option( 'confirm-user-registration', array( # Notifcation to admin 'administrator' => get_bloginfo('admin_email'), # Notification to users 'error' => __( '<strong>ERROR:</strong> Your account has to be confirmed by an administrator before you can login', 'confirm-user-registration' ), # Mail 'from' => get_bloginfo('name').' <'.get_bloginfo('admin_email').">\n", 'subject' => __( 'Account Confirmation: ' . get_bloginfo('name'), 'confirm-user-registration' ), 'message' => __( "You account has been approved by an administrator!\nLogin @ ".get_bloginfo('url')."/wp-login.php\n\nThis message is auto generated\n", 'confirm-user-registration' ), )); // Upgrade else : if ( $this->is_upgrade() ) : // Create new option array add_option( 'confirm-user-registration', array( # Notifcation to admin 'administrator' => get_option( 'cur_administrator' ), # Notification to users 'error' => get_option( 'cur_error' ), # Mail 'from' => get_option( 'cur_from' ), 'subject' => get_option( 'cur_subject' ), 'message' => get_option( 'cur_message' ) )); // Cleanup delete_option( 'cur_administrator' ); delete_option( 'cur_error' ); delete_option( 'cur_from' ); delete_option( 'cur_subject' ); delete_option( 'cur_message' ); endif; endif; } /** * Add admin menu page * * @access public * @return void * @author <NAME> **/ public function admin_menu() { add_users_page( _x( 'Confirm User Registration', 'confirm-user-registration' ), _x( 'Confirm User Registration', 'confirm-user-registration' ), 'promote_users', 'confirm-user-registration', array( $this, 'management' ) ); } /** * Authenticate Users * * @access public * @param array $user_ids User IDs to confirm * @return void * @author <NAME> **/ public function auth_users( array $user_ids ) { if ( $user_ids && current_user_can( 'promote_users' ) ) : foreach ( $user_ids as $user_id ) : if ( is_numeric( $user_id ) ) : update_user_meta( $user_id, 'authentication', '1' ); do_action( 'confirm-user-registration-auth-user', $user_id ); $this->send_notification( $user_id ); endif; endforeach; ?> <div class="updated message"> <?php if ( 1 == count( $user_ids) ) : ?> <p><?php _e( '1 user authenticated', 'confirm-user-registration' ) ?></p> <?php else : ?> <p><?php echo count( $user_ids ) . ' ' . __( 'users authenticated', 'confirm-user-registration' ) ?></p> <?php endif; ?> </div> <?php endif; } /** * Block Users * * @access public * @param array $user_ids User IDs to block * @return void * @author <NAME> **/ public function block_users( array $user_ids ) { if ( $user_ids && current_user_can( 'promote_users' ) ) : foreach ( $user_ids as $user_id ) : if ( is_numeric( $user_id ) ) : delete_user_meta( $user_id, 'authentication' ); do_action( 'confirm-user-registration-block-user', $user_id ); endif; endforeach; ?> <div class="updated message"> <?php if ( 1 == count( $user_ids) ) : ?> <p><?php _e( '1 user blocked', 'confirm-user-registration' ) ?></p> <?php else : ?> <p><?php echo count( $user_ids ) . ' ' . __( 'users blocked', 'confirm-user-registration' ) ?></p> <?php endif; ?> </div> <?php endif; } /** * Bulk delete users * * @access public * @param array $user_ids User IDs to block * @return void * @since 2.1 * @author <NAME> **/ public function delete_users( array $user_ids ) { if ( $user_ids && current_user_can( 'delete_users' ) ) : foreach ( $user_ids as $user_id ) : if ( is_numeric( $user_id ) ) : wp_delete_user( $user_id ); do_action( 'confirm-user-registration-delete-user', $user_id ); endif; endforeach; ?> <div class="updated message"> <?php if ( 1 == count( $user_ids) ) : ?> <p><?php _e( '1 user deleted', 'confirm-user-registration' ) ?></p> <?php else : ?> <p><?php echo count( $user_ids ) . ' ' . __( 'users deleted', 'confirm-user-registration' ) ?></p> <?php endif; ?> </div> <?php endif; } /** * Add scripts * * @access public * @return void * @author <NAME> **/ public function enqueue_scripts() { wp_enqueue_script( 'confirm-user-registration', WP_PLUGIN_URL . '/' . RH_CUR_BASEDIR . '/javascript/confirm-user-registration.js' ); $translation_array = array( 'delete_users_warning' => __( 'Are you sure you want to delete these users?', 'confirm-user-registration' ), ); wp_localize_script( 'confirm-user-registration', 'CUR', $translation_array ); } /** * Add styles * * @access public * @return void * @author <NAME> **/ public function enqueue_styles() { wp_enqueue_style( 'confirm-user-registration', WP_PLUGIN_URL . '/' . RH_CUR_BASEDIR . '/css/confirm-user-registration.css' ); } /** * Get authed users * * @access public * @param string $user_search * @return array Users * @author <NAME> **/ public function get_authed_users($user_search = '') { $user_search = new WP_User_Query(array( 'meta_key' => 'authentication', 'meta_compare' => '=', 'meta_value' => 1, 'search' => $user_search ? "*{$user_search}*" : '', 'offset' => ($this->current_page - 1) * $this->per_page, 'number' => $this->per_page, 'count_total' => true, )); $this->total_found = $user_search->get_total(); return (array)$user_search->get_results(); } /** * Get pending users * * @access public * @param string $user_search * @return array Users * @author <NAME> **/ public function get_pending_users($user_search = '') { $user_search = new WP_User_Query(array( 'meta_key' => 'authentication', 'meta_compare' => 'NOT EXISTS', 'orderby' => 'registered', 'order' => 'DESC', 'search' => $user_search ? "*{$user_search}*" : '', 'offset' => ($this->current_page - 1) * $this->per_page, 'number' => $this->per_page, 'count_total' => true, )); $this->total_found = $user_search->get_total(); return (array)$user_search->get_results(); } /** * Checks if user is authenticated * * @access public * @param int $user_id User ID * @return bool * @author <NAME> **/ public function is_authenticated( $user_id ) { if ( 1 == get_user_meta( $user_id, 'authentication', TRUE ) ) : return TRUE; else : return FALSE; endif; } /** * Checks if plugin was installed before * * @access public * @return bool * @author <NAME> **/ public function is_first_time() { if ( !get_option( 'cur_from' ) && !get_option( 'confirm-user-registration' ) ) : return TRUE; else : return FALSE; endif; } /** * Upgrade from 1.x to < 2.0 * * @access public * @return bool * @author <NAME> **/ public function is_upgrade() { if ( get_option( 'cur_from' ) ) : return TRUE; else : return FALSE; endif; } /** * Load plugin textdomain * * @return void * @author <NAME> **/ public function load_plugin_textdomain() { load_plugin_textdomain( 'confirm-user-registration', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); } /** * Management page * * @access public * @return void * @author <NAME> **/ public function management() { ?> <div class="wrap"> <?php $this->management_nav(); ?> <?php $tab = ( isset( $_GET['tab'] ) ) ? $_GET['tab'] : ''; if ( 'settings' == $tab ) : $this->management_settings(); else : $this->management_users( $tab ); endif; ?> </div> <?php } /** * Managment Nav * * @access public * @return void * @author <NAME> **/ public function management_nav() { ?> <h2 class="nav-tab-wrapper"> <a class="nav-tab <?php if ( 'pending' == $_GET['tab'] || !$_GET['tab']) echo 'nav-tab-active' ?>" href="users.php?page=confirm-user-registration&amp;tab=pending"><?php _e( 'Pending Users', 'confirm-user-registration' ); ?></a> <a class="nav-tab <?php if ( 'authed' == $_GET['tab'] ) echo 'nav-tab-active' ?>" href="users.php?page=confirm-user-registration&amp;tab=authed"><?php _e( 'Authenticated Users', 'confirm-user-registration' ); ?></a> <a class="nav-tab <?php if ( 'settings' == $_GET['tab'] ) echo 'nav-tab-active' ?>" href="users.php?page=confirm-user-registration&amp;tab=settings"><?php _e( 'Settings', 'confirm-user-registration' ); ?></a> <a class="nav-tab" href="https://github.com/Horttcore/confirm-user-registration" target="_blank"><?php _e( 'Help' ); ?></a> </h2> <?php } /** * Settings tab * * @access public * @return void * @author <NAME> **/ public function management_settings() { $this->save_settings(); $options = get_option( 'confirm-user-registration' ); ?> <form method="post" id="confirm-user-registration-settings" data-success="<?php _e( 'Settings saved', 'confirm-user-registration' ); ?>" data-error="<?php _e( '<strong>ERROR:</strong> Could not save settings', 'confirm-user-registration' ); ?>"> <div class="icon32" id="icon-tools"><br></div><h2><?php _e( 'Confirm User Registration Settings', 'confirm-user-registration' ); ?></h2> <table class="form-table"> <tr> <th colspan="2"><h3><?php _e( 'Login notice', 'confirm-user-registration' ); ?></h3></th> </tr> <tr> <th><label for="error"><?php _e( 'Error Message', 'confirm-user-registration' )?></label></th> <td><input size="82" type="text" name="error" id="error" value="<?php echo $options['error']; ?>"></td> </tr> <tr> <th colspan="2"><h3><?php _e( 'E-Mail notification', 'confirm-user-registration' ); ?></h3></th> </tr> <tr> <th><label for="from"><?php _e( 'From', 'confirm-user-registration' )?></label></th> <td><input size="82" type="text" name="from" id="from" value="<?php echo $options['from']; ?>" /></td> </tr> <tr> <th><label for="subject"><?php _e( 'Subject', 'confirm-user-registration' )?></label></th> <td><input size="82" type="text" name="subject" id="subject" value="<?php echo $options['subject']; ?>" /></td> </tr> <tr> <th><label for="message"><?php _e( 'Message', 'confirm-user-registration' )?></label></th> <td><textarea name="message" rows="8" cols="80" id="message"><?php echo $options['message']; ?></textarea></td> </tr> <?php do_action( 'confirm-user-registration-options' ) ?> </table> <p class="submit"><button id="save-settings" class="button button-primary" type="submit"><?php _e( 'Save', 'confirm-user-registration' )?></button></p> <?php wp_nonce_field( 'save-confirm-user-registration-settings', 'save-confirm-user-registration-settings-nonce' ) ?> </form> <?php } /** * Display page navigation. * * This function has been copied from WP_List_Table. * * @param $which 'top' or 'bottom' * @param $per_page * @param $total_items * @param $current_page * @return string */ function pagination($which, $per_page, $total_items, $current_page) { $total_pages = ceil($total_items / $per_page); $output = '<span class="displaying-num">' . sprintf( _n( '1 item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . '</span>'; $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); $current_url = remove_query_arg( array( 'hotkeys_highlight_last', 'hotkeys_highlight_first' ), $current_url ); $page_links = array(); $disable_first = $disable_last = ''; if ( $current_page == 1 ) $disable_first = ' disabled'; if ( $current_page == $total_pages ) $disable_last = ' disabled'; $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'first-page' . $disable_first, esc_attr__( 'Go to the first page' ), esc_url( remove_query_arg( 'paged', $current_url ) ), '&laquo;' ); $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'prev-page' . $disable_first, esc_attr__( 'Go to the previous page' ), esc_url( add_query_arg( 'paged', max( 1, $current_page-1 ), $current_url ) ), '&lsaquo;' ); if ( 'bottom' == $which ) $html_current_page = $current_page; else $html_current_page = sprintf( "<input class='current-page' title='%s' type='text' name='paged' value='%s' size='%d' />", esc_attr__( 'Current page' ), $current_page, strlen( $total_pages ) ); $html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) ); $page_links[] = '<span class="paging-input">' . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . '</span>'; $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'next-page' . $disable_last, esc_attr__( 'Go to the next page' ), esc_url( add_query_arg( 'paged', min( $total_pages, $current_page+1 ), $current_url ) ), '&rsaquo;' ); $page_links[] = sprintf( "<a class='%s' title='%s' href='%s'>%s</a>", 'last-page' . $disable_last, esc_attr__( 'Go to the last page' ), esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ), '&raquo;' ); $pagination_links_class = 'pagination-links'; if ( ! empty( $infinite_scroll ) ) $pagination_links_class = ' hide-if-js'; $output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>'; if ( $total_pages ) $page_class = $total_pages < 2 ? ' one-page' : ''; else $page_class = ' no-pages'; return "<div class='tablenav-pages{$page_class}'>$output</div>"; } /** * Users tab * * @access public * @param string $tag {pending|auth} Tab to show * @return void * @author <NAME> **/ public function management_users( $tab ) { global $user_ID; if ( $_POST && 'auth' == $_POST['action'] && wp_verify_nonce( $_POST['confirm-bulk-action-nonce'], 'confirm-bulk-action' ) ) : $this->auth_users( $_POST['users'] ); elseif ( $_POST && 'block' == $_POST['action'] && wp_verify_nonce( $_POST['confirm-bulk-action-nonce'], 'confirm-bulk-action' ) ) : $this->block_users( $_POST['users'] ); elseif ( $_POST && 'delete' == $_POST['action'] && wp_verify_nonce( $_POST['confirm-bulk-action-nonce'], 'confirm-bulk-action' ) ) : $this->delete_users( $_POST['users'] ); endif; $user_search = isset($_REQUEST['s']) ? wp_unslash(trim($_REQUEST['s'])) : ''; $users = ( 'pending' == $tab || '' == $tab ) ? $this->get_pending_users($user_search) : $this->get_authed_users($user_search); $title = ( 'pending' == $tab || '' == $tab ) ? __( 'Authenticate Users', 'confirm-user-registration' ) : __( 'Block Users', 'confirm-user-registration' ); $action_data = ( 'pending' == $tab || '' == $tab ) ? 'auth' : 'block'; ?> <div class="icon32" id="icon-users"><br></div><h2><?php echo $title ?></h2> <form method="get" action="<?php echo admin_url('/users.php'); ?>"> <p class="search-box"> <label class="screen-reader-text" for="<?php echo 'user' ?>"><?php echo __( 'Search Users' ); ?>:</label> <input type="search" id="<?php echo 'user' ?>" name="s" value="<?php _admin_search_query(); ?>" /> <?php submit_button( __( 'Search Users' ), 'button', false, false, array('id' => 'search-submit') ); ?> <input type="hidden" name="page" value="<?php echo $_GET['page']; ?>"> <input type="hidden" name="tab" value="<?php echo $tab; ?>"> </p> </form> <form method="post"> <?php wp_nonce_field( 'confirm-bulk-action', 'confirm-bulk-action-nonce' ) ?> <div class="tablenav top"> <select name="action"> <option value=""><?php _e( 'Bulk Actions' ); ?></option> <option value="<?php echo $action_data ?>"><?php echo $title ?></option> <?php if ( current_user_can( 'delete_users' ) ) : ?> <option value="delete"><?php _e( 'Delete' ); ?></option> <?php endif; ?> </select> <input type="submit" value="<?php _e( 'Apply' ); ?>" class="button action doaction" name="" data-value="<?php echo $action_data ?>"> <?php echo $this->pagination('top', $this->per_page, $this->total_found, $this->current_page); ?> </div> <table class="widefat"> <thead> <tr> <th id="cb"><input type="checkbox" name="check-all" valle="Check all"></th> <th id="gravatar"><?php _e( 'Gravatar', 'confirm-user-registration' ); ?></th> <th id="display_name"><?php _e( 'Name', 'confirm-user-registration' ); ?></th> <th id="email"><?php _e( 'E-Mail', 'confirm-user-registration' ); ?></th> <th id="role"><?php _e( 'Role', 'confirm-user-registration' ); ?></th> <th id="registered"><?php _e( 'Registered', 'confirm-user-registration' ); ?></th> </tr> </thead> <tbody> <?php if ( $users ) : $i = 1; foreach ( $users as $user ) : $class = ( $i % 2 == 1 ) ? 'alternate' : 'default'; $user_data = get_userdata( $user->ID ); $user_registered = mysql2date(get_option('date_format'), $user->user_registered); ?> <tr id="user-<?php echo $user->ID ?>" class="<?php echo $class ?>"> <th> <?php if ( $user->ID != $user_ID ) :?> <input type="checkbox" name="users[]" value="<?php echo $user->ID ?>"> <?php endif; ?> </th> <td><img class="gravatar" src="http://www.gravatar.com/avatar/<?php echo md5( $user->user_email ) ?>?s=32"></td> <td> <a href="user-edit.php?user_id=<?php echo $user->ID ?>"><?php echo $user->display_name ?></a> <div class="row-actions"> <?php if ( current_user_can( 'edit_user', $user->ID ) ) : ?> <span class="edit"><a href="<?php echo admin_url( 'user-edit.php?user_id=' . $user->ID ) ?>"><?php _e( 'Edit' ); ?></a> <?php endif; ?> <?php if ( current_user_can( 'edit_user', $user->ID ) && current_user_can( 'delete_user', $user->ID ) && $user_ID != $user->ID ) : ?> &nbsp;|&nbsp;</span> <?php endif; ?> <?php if ( current_user_can( 'delete_user', $user->ID ) && $user_ID != $user->ID ) : ?> <span class="delete"><a href="<?php echo admin_url( 'users.php?action=delete&user=' . $user->ID . '&_wpnonce=' . wp_create_nonce( 'bulk-users' ) ) ?>"><?php _e( 'Delete' ); ?></a></span> <?php endif; ?> </div> </td> <td><a href="mailto:<?php echo $user->user_email ?>"><?php echo $user->user_email ?></a></td> <td> <?php if ( $user_data->roles ) : foreach ( $user_data->roles as $role ) : echo _x( ucfirst( $role ), 'User role' ) . '<br>'; endforeach; endif; ?> </td> <td><?php echo $user_registered ?></td> </tr> <?php $i++; endforeach; else : ?> <tr> <td colspan="6"><strong><?php _e( 'No Users found', 'confirm-user-registration' ); ?></strong></td> </tr> <?php endif; ?> </tbody> </table> <div class="tablenav bottom"> <?php echo $this->pagination('bottom', $this->per_page, $this->total_found, $this->current_page); ?> </div> </form> <?php } /** * Handles save settings ajax request * * @access public * @return void * @author <NAME> **/ public function save_settings() { if ( $_POST && wp_verify_nonce( $_POST['save-confirm-user-registration-settings-nonce'], 'save-confirm-user-registration-settings' ) ) : $options = array( 'error' => $_POST['error'], 'from' => $_POST['from'], 'subject' => $_POST['subject'], 'message' => $_POST['message'] ); $options = apply_filters( 'confirm-user-registration-save-options', $options ); update_option( 'confirm-user-registration', $options); ?> <div class="updated message"> <p><?php _e( 'Saved' ); ?></p> </div> <?php endif; } /** * Send notification * * @access public * @param int $user_id User ID * @return void * @author <NAME> **/ public function send_notification( $user_id ) { $options = get_option( 'confirm-user-registration' ); $user = get_userdata( $user_id ); $headers = 'FROM:' . $options['from'] . "\r\n"; $headers = apply_filters( 'confirm-user-registration-notification-header', $headers, $user ); $subject = apply_filters( 'confirm-user-registration-notification-subject', $options['subject'], $user ); $message = apply_filters( 'confirm-user-registration-notification-message', $options['message'], $user ); wp_mail( $user->data->user_email, $subject, $message, $headers ); do_action( 'send_user_authentication', $user, $headers, $subject, $message ); } /** * Check if user is authed * * @access public * @return bool | WP_Error * @author <NAME> **/ public function wp_authenticate_user( $user ) { $user = get_user_by( 'login', $user->user_login ); if ( !is_object( $user ) ) return FALSE; $user_id = $user->ID; if ( $this->is_authenticated( $user_id ) ) : return $user; else : $error = new WP_Error(); $options = get_option( 'confirm-user-registration' ); $error_message = apply_filters( 'confirm-user-registration-error-message', $options['error'] ); $error->add( 'error', $error_message ); return apply_filters( 'confirm-user-registration-error', $error, $user ); endif; } } new Confirm_User_Registration;
bef5849dac8915660001f35670bab251b6cfc099
[ "PHP" ]
1
PHP
vtk13/confirm-user-registration
036f84474d5f393fba0f6a6d8040014dc166834f
b202192c2aa06619844d1cb484decb80a239ca81
refs/heads/master
<repo_name>liupy525/TransitionVisualization<file_sep>/CSS3 transition可视化编辑器-设计文档.md # CSS3 transition可视化编辑器-设计文档 标签(空格分隔): 文档 --- ## 页面效果: ```javascript 在浏览器中打开 ./dist/index.html 文件 ``` ## 需求分析 > **基本要求:** > 拖动控制点或填入参数,点击生成按钮,自动生成CSS3 transition代码和演示滑块。 > **加分项:** > 编辑器界面好看,操作流畅,生成的代码兼容性好,有API可以扩展功能 制作一个类似[参考示例](http://cubic-bezier.com/)的页面,实现CSS3动画中`transition`属性的可视化编辑器。 分析示例页面后,列出如下需求: 1. bezier函数控制点可拖动 2. cubic-bezier参数实时展示 3. 输出CSS3 transition完整代码 2. 演示功能 4. Library功能,即记录功能 ## 设计思路 ### bezier函数控制点 首先使用canvas的`bezierCurveTo`函数画出bezier函数曲线,再使用`lineTo`函数画出连线,使用div画出圆形的控制点,通过监听其mousedown、mousemove即mouseup事件实现对其的拖动控制,再根据控制点的位置计算出bezier曲线的参数来更新曲线 ### bezier参数实时展示 通过控制点的坐标及画布参数,计算出bezier参数,并在页面上展示出来 ### 输出CSS3 transition完整代码 通过显示fixed的方框来显示代码,代码是由字符串及参数拼接组成 ### 演示功能 通过页面的不同组件获取transition动画的各个属性的value,具体包括:`transition-timing-function`,`transition-duration`,`transition-property`,`tranform`属性的value,然后使用JavaScript将其添加到演示用的div上,通过类名的改变实现动画效果 ###Library功能 使用`window.localStorage`来保存用户想要记录的参数及当前曲线的参数,在页面特定位置使用canvas画出该曲线,在点击储存曲线后更新当前曲线 ## 技术选型 我最近刚学习Vue.js的基础知识,还没用其进行过开发,所以第一时间想到使用Vue.js来进行练习并完成任务,虽然题目要求有提到: > 2.主体用原生JavaScript实现,尽量不使用现成的脚本库API。。 但考虑到Vue.js是MVVM的框架,而不是题目要求中提到的“脚本库API”,所以个人认为其不与要求冲突 ## 模块划分 考虑到模块的复用及减小组件间的耦合,模块划分如下: ### bezier.js 该文件是使用原生JavaScript实现的库文件,用来进行画图,包括边框、bezier曲线、控制点连线等,使用ES2015中的class实现,初始化后使用`draw`函数即可画图 ### eventUtil.js 该文件是使用原生JavaScript实现的库文件,用来处理事件绑定、拆除等工作,有较好兼容性 ### storage.js 该文件是使用原生JavaScript实现的库文件,用来处理localStorage存取数据等工作,有较好兼容性 ### Tile.vue 绘制bezier曲线的模块,该模块需要传入canvas的各种参数及bezier曲线的参数 ### MoveButton.vue 绘制控制点的模块,可以绘制可拖拽及不可拖拽两种控制点 ### BezierDrawPlane.vue 负责绘制可调节bezier曲线的模块,包含Tile及MoveButton两个子模块,用Tile模块画出bezier曲线,用MoveButton设置控制点,当控制点变动时,计算新的bezier曲线的参数,传入Tile,绘制实时曲线 ### ShowParams.vue 实时展示Bezier曲线参数的模块,传入曲线参数即可展示美化的参数,包含Save及Export按钮,点击Save即可保存当前曲线,点击Export即可弹出弹窗显示当前transitoin属性 ### PreviewCompare.vue 展示和比较模块,包含Tile子模块,可以选择何种动画效果(移动、旋转、扩张)以及动画持续时间,包含Run按钮及两个展示用模块,点击Run按钮后,展示模块执行指定动画 ### Library.vue 展示所有记录的曲线,包含Tile子模块,将所有记录的曲线绘制出来,并横向排列 ### Modal.vue 可定制弹窗模块,可指定弹窗里的具体内容 ### APP.vue 页面程序主模块,包含BezierDrawPlane、ShowParams、PreviewCompare、Library及Modal子模块,负责将页面上所有元素组织起来 ## UI设计 题目要求有提到: > 4.UI界面允许参考其他的网站,素材允许使用其他网站的素材。 所以,我直接仿照[参考示例](http://cubic-bezier.com/)的界面进行开发 ## TODO 1. 由于时间关系,测试做的不够,要完善各项功能 2. 添加按键操控bezier函数控制点功能 3. 想办法添加用户自定义动画功能 <file_sep>/README.md # Transition Visualization 360前端星的选拔?作业题 题目要求如下: > **基本要求:** > 拖动控制点或填入参数,点击生成按钮,自动生成CSS3 transition代码和演示滑块。 > **加分项:** > 编辑器界面好看,操作流畅,生成的代码兼容性好,有API可以扩展功能 > 点击查看[参考示例](http://cubic-bezier.com/) > 和参考例子不同的是,参考例子只生成了bezier参数,作业要求生成完整的css3动画代码。 例如,编辑之后点击 export 按钮输出代码: > ```css div{ -webkit-transition: all 600ms cubic-bezier(0.39, 0.575, 0.565, 1); transition: all 600ms cubic-bezier(0.39, 0.575, 0.565, 1); } ``` ## 运行 只看效果: ```javascript git clone https://github.com/liupy525/Visual-CSS.git cd Visual-CSS/dist/ 在浏览器中打开 index.html 文件 ``` 再次开发: ```javascript git clone https://github.com/liupy525/Visual-CSS.git cd Visual-CSS npm run install npm run dev 浏览器打开 http://localhost:8080 ``` ## 需求分析 制作一个类似[参考示例](http://cubic-bezier.com/)的页面,实现CSS3动画中`transition`属性的可视化编辑器。 分析示例页面后,列出如下需求: 1. bezier函数控制点可拖动 2. cubic-bezier参数实时展示 3. 输出CSS3 transition完整代码 2. 演示功能 4. Library功能,即记录功能 ## 设计思路 ### bezier函数控制点 首先使用canvas的`bezierCurveTo`函数画出bezier函数曲线,再使用`lineTo`函数画出连线,使用div画出圆形的控制点,通过监听其mousedown、mousemove即mouseup事件实现对其的拖动控制,再根据控制点的位置计算出bezier曲线的参数来更新曲线 ### bezier参数实时展示 通过控制点的坐标及画布参数,计算出bezier参数,并在页面上展示出来 ### 输出CSS3 transition完整代码 通过显示fixed的方框来显示代码,代码是由字符串及参数拼接组成 ### 演示功能 通过页面的不同组件获取transition动画的各个属性的value,具体包括:`transition-timing-function`,`transition-duration`,`transition-property`,`tranform`属性的value,然后使用JavaScript将其添加到演示用的div上,通过类名的改变实现动画效果 ###Library功能 使用`window.localStorage`来保存用户想要记录的参数及当前曲线的参数,在页面特定位置使用canvas画出该曲线,在点击储存曲线后更新当前曲线 ## 技术选型 我最近刚学习Vue.js的基础知识,还没用其进行过开发,所以第一时间想到使用Vue.js来进行练习并完成任务,虽然题目要求有提到: > 2.主体用原生JavaScript实现,尽量不使用现成的脚本库API。。 但考虑到Vue.js是MVVM的框架,而不是题目要求中提到的“脚本库API”,所以个人认为其不与要求冲突 ## 模块划分 考虑到模块的复用及减小组件间的耦合,模块划分如下: ### bezier.js 该文件是使用原生JavaScript实现的库文件,用来进行画图,包括边框、bezier曲线、控制点连线等,使用ES2015中的class实现,初始化后使用`draw`函数即可画图 ### eventUtil.js 该文件是使用原生JavaScript实现的库文件,用来处理事件绑定、拆除等工作,有较好兼容性 ### storage.js 该文件是使用原生JavaScript实现的库文件,用来处理localStorage存取数据等工作,有较好兼容性 ### Tile.vue 绘制bezier曲线的模块,该模块需要传入canvas的各种参数及bezier曲线的参数 ### MoveButton.vue 绘制控制点的模块,可以绘制可拖拽及不可拖拽两种控制点 ### BezierDrawPlane.vue 负责绘制可调节bezier曲线的模块,包含Tile及MoveButton两个子模块,用Tile模块画出bezier曲线,用MoveButton设置控制点,当控制点变动时,计算新的bezier曲线的参数,传入Tile,绘制实时曲线 ### ShowParams.vue 实时展示Bezier曲线参数的模块,传入曲线参数即可展示美化的参数,包含Save及Export按钮,点击Save即可保存当前曲线,点击Export即可弹出弹窗显示当前transitoin属性 ### PreviewCompare.vue 展示和比较模块,包含Tile子模块,可以选择何种动画效果(移动、旋转、扩张)以及动画持续时间,包含Run按钮及两个展示用模块,点击Run按钮后,展示模块执行指定动画 ### Library.vue 展示所有记录的曲线,包含Tile子模块,将所有记录的曲线绘制出来,并横向排列 ### Modal.vue 可定制弹窗模块,可指定弹窗里的具体内容 ### APP.vue 页面程序主模块,包含BezierDrawPlane、ShowParams、PreviewCompare、Library及Modal子模块,负责将页面上所有元素组织起来 ## UI设计 题目要求有提到: > 4.UI界面允许参考其他的网站,素材允许使用其他网站的素材。 所以,我直接仿照[参考示例](http://cubic-bezier.com/)的界面进行开发 <file_sep>/src/main.js import Vue from 'vue' import App from './components/App.vue' import './assets/normalize.css' import './assets/main.css' /* eslint-disable no-new */ Vue.config.debug = true new Vue({ el: 'body', components: { App } }) // import BezierDrawer from './components/bezier.js' // // let bezier = new BezierDrawer('#drawing', 10, 310, 310, 10) // console.log(bezier.draw(250, 250, 110, 110)) <file_sep>/src/lib/bezier.js class BezierDrawer { constructor(el, startX, startY, endX, endY, data, standard=true) { let drawing = document.querySelector(el) this.context = drawing.getContext('2d') this.startX = startX this.startY = startY this.endX = endX this.endY = endY this.width = this.endX - this.startX this.height = this.startY - this.endY this.standard = standard if (standard) { this.settings = {bezier: {lineWidth: 5, strokeStyle: '#000000'}, linklines: {lineWidth: 3, strokeStyle: '#606060'}} } else { this.settings = {bezier: {lineWidth: 2, strokeStyle: '#ffffff'}, linklines: {lineWidth: 1, strokeStyle: '#ffffff'}} } this.draw(data) } drawBorder() { let context = this.context // 绘制边框 context.beginPath() context.moveTo(this.startX, this.endY) context.lineTo(this.startX, this.startY) context.lineTo(this.endX, this.startY) context.lineWidth = 1 context.strokeStyle = '#000000' context.stroke() context.closePath() } drawStartAndEndPoint() { let context = this.context // 绘制曲线起点及终点 context.beginPath() context.moveTo(this.startX, this.startY) context.arc(this.startX, this.startY, 5, 0, 2 * Math.PI, false) context.moveTo(this.endX, this.endY) context.arc(this.endX, this.endY, 5, 0, 2 * Math.PI, false) context.fillStyle = '#000000' context.fill() context.closePath() } drawStandardLine() { let context = this.context // 连接起点和终点 context.beginPath() context.moveTo(this.startX, this.startY) context.lineTo(this.endX, this.endY) context.lineWidth = 4 context.strokeStyle = 'rgba(0,0,0,.1)' context.stroke() context.closePath() } drawLinklines(x1, y1, x2, y2) { let context = this.context // 绘制参数点到起始点的连线 context.beginPath() context.moveTo(x1, y1) context.lineTo(this.startX, this.startY) context.moveTo(x2, y2) context.lineTo(this.endX, this.endY) context.lineWidth = this.settings.linklines.lineWidth context.strokeStyle = this.settings.linklines.strokeStyle context.stroke() context.closePath() } drawParamsPoints(x1, y1, x2, y2) { let context = this.context // 绘制调节bezier曲线的两个点 context.beginPath() context.moveTo(x1, y1) context.arc(x1, y1, 1.5, 0, 2 * Math.PI, false) context.moveTo(x2, y2) context.arc(x2, y2, 1.5, 0, 2 * Math.PI, false) context.fillStyle = '#ffffff' context.fill() context.closePath() } drawBezier(x1, y1, x2, y2) { let context = this.context // 绘制bezier曲线 context.beginPath() context.moveTo(this.startX, this.startY) context.bezierCurveTo(x1, y1, x2, y2, this.endX, this.endY) context.lineWidth = this.settings.bezier.lineWidth context.strokeStyle = this.settings.bezier.strokeStyle context.stroke() context.closePath() } draw(data) { if (this.standard) { this.draw = function (data) { let x1 = data[0] * this.width + this.startX let y1 = this.startY - data[1] * this.height let x2 = data[2] * this.width + this.startX let y2 = this.startY - data[3] * this.height this.clear() this.drawBorder() this.drawLinklines(x1, y1, x2, y2) this.drawStandardLine() this.drawBezier(x1, y1, x2, y2) } this.draw(data) } else { this.draw = function (data) { let x1 = data[0] * this.width + this.startX let y1 = this.startY - data[1] * this.height let x2 = data[2] * this.width + this.startX let y2 = this.startY - data[3] * this.height this.clear() this.drawParamsPoints(x1, y1, x2, y2) this.drawLinklines(x1, y1, x2, y2) this.drawBezier(x1, y1, x2, y2) } this.draw(data) } } clear() { let canvas = this.context.canvas this.context.clearRect(0, 0, canvas.width, canvas.height) } } export default BezierDrawer <file_sep>/src/lib/storage.js const storageKey = 'BEZIER' const currentKey = 'CURRENT' const compareKey = 'COMPARE' const INIT_DATA = [{name:'ease', params:[0.25,0.1,0.25,1]}, {name:'linear', params:[0,0,1,1]}, {name:'ease-in', params:[0.42,0,1,1]}, {name:'ease-out', params:[0,0,0.58,1]}, {name:'ease-in-out', params:[0.42,0,0.58,1]}] let storage = getLocalStorage() function getLocalStorage() { if (localStorageSupported()) { return window.localStorage } else { return { // 不支持LocalStorage时,仿造一个 _data: {}, setItem(id, val) { return this._data[id] = String(val) }, getItem(id) { return this._data.hasOwnProperty(id) ? this._data[id] : undefined }, removeItem(id) { return delete this._data[id] }, clear() { return this._data = {} } } } } function localStorageSupported() { let testKey = 'test', storage = window.localStorage try { storage.setItem(testKey, '1') storage.removeItem(testKey) return true } catch (error) { return false } } function saveTile(item, type='all') { if (type==='current') { storage.setItem(currentKey, JSON.stringify(item)) } else { let tiles = getTiles() tiles.push(item) storage.setItem(storageKey, JSON.stringify(tiles)) } } function getTiles(type='all') { if (type==='current') { let data = storage.getItem(currentKey) return data ? JSON.parse(data) : data } else { let data = storage.getItem(storageKey) if (data) { return JSON.parse(data) } else { storage.setItem(storageKey, JSON.stringify(INIT_DATA)) return INIT_DATA } } } function removeTile(index) { let tiles = getTiles() tiles.splice(index, 1) storage.setItem(storageKey, JSON.stringify(tiles)) } export default { saveTile, getTiles, removeTile }
9f95d7ff75a586a9157246c5f1f236ef62b65e3d
[ "Markdown", "JavaScript" ]
5
Markdown
liupy525/TransitionVisualization
1e32511f6e23e0b397042a3f9e1d24c7d74d1b61
6b7ed9465e6a3ac6ee742ea6999a9a91864671f3
refs/heads/master
<file_sep>package com.example.josh.organiise; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class EditGoalsAndSleepTimes extends AppCompatActivity { //the integers the user submits. EditText sleepHour, sleepMinute, wakeupHour, wakeupMinute; //the confirm button Button confirmTimes; //The message that will display if the user has entered something that is not correct e.g. 34 in the hour slot. TextView errorMsg; boolean mBounded; Actions mServer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_goals_and_sleep_times); android.support.v7.widget.Toolbar toolbar = ( android.support.v7.widget.Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); sleepHour = (EditText) findViewById(R.id.hours); sleepMinute = (EditText) findViewById(R.id.minutes); wakeupHour = (EditText) findViewById(R.id.wakeUpHour); wakeupMinute = (EditText) findViewById(R.id.wakeupMinutes); confirmTimes = (Button) findViewById(R.id.submitTime); errorMsg = (TextView) findViewById(R.id.error); ActionBar app_bar = getSupportActionBar(); app_bar.setDisplayShowTitleEnabled(false); //boolean for if the user wakes up the same day they sleep. //if the submitTimes button has been pressed. confirmTimes.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //ints which the values of the EditTexts will be placed. int sHour = 0; int sMinute = 0; int wHour = 0; int wMinute = 0; boolean sameDay = false; //only fill out the time variables if they all have values, else we will be parsing nothing thus crashing program. if(!TextUtils.isEmpty(sleepHour.getText().toString()) || !TextUtils.isEmpty(sleepMinute.getText().toString()) || !TextUtils.isEmpty(wakeupHour.getText().toString()) || !TextUtils.isEmpty(wakeupMinute.getText().toString())) { //getting value from edit texts and converting it to an int for the prgram. sHour = Integer.parseInt(sleepHour.getText().toString()); sMinute = Integer.parseInt(sleepMinute.getText().toString()); wHour = Integer.parseInt(wakeupHour.getText().toString()); wMinute = Integer.parseInt(wakeupMinute.getText().toString()); System.out.println("sleep hour: " + sHour + " sleep minute: " + sMinute + " wakeup hour: " + wHour + " wakeupMinute: " + wMinute); } else { errorMsg.setText("Please fill out all boxes."); } //if either sleephour or wakeup hour is something higher than 24 then it is not a real time, so we will not sent it. if(sHour > 23 || wHour > 23) { errorMsg.setText("Time not valid."); } //if either the sleep minute or wakeup minute is above 59 then it's not a valid time. else if(sMinute > 59 || wMinute > 59) { errorMsg.setText("Time not valid."); } //if the user enters 24:00 we will convert this to 00 hours instead. else if(sHour == 24 || wHour == 24) { if(sHour == 24) { sHour = 0; } if(wHour == 24) { wHour = 0; } } else { //if wakeup hour is more than sleep hour this means that the user has gone to sleep the same day as they wake up e.g. 01:00 to 08:00 if(wHour > sHour) { sameDay = true; mServer.setSleepAndWakeupTimes(sameDay, sHour, sMinute,wHour,wMinute); //now we have to determine if this is the same day as today or tomorrow. errorMsg.setText("Thank you :)"); } //else the wakeuptime is less than the sleep time e.g. 23:00 sleep and 07:00 wakeup, so they are seperate days. else { sameDay = false; mServer.setSleepAndWakeupTimes(sameDay, sHour, sMinute,wHour,wMinute); errorMsg.setText("Thank you :)"); } } } }); } @Override protected void onStart() { super.onStart(); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); System.out.println("Started"); Intent mIntent = new Intent(this, Actions.class); bindService(mIntent, mConnection, BIND_AUTO_CREATE); }; ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Toast.makeText(EditGoalsAndSleepTimes.this, "Service is disconnected", 1000).show(); mBounded = false; mServer = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Toast.makeText(EditGoalsAndSleepTimes.this, "Service is connected", 1000).show(); mBounded = true; Actions.LocalBinder mLocalBinder = (Actions.LocalBinder)service; mServer = mLocalBinder.getServerInstance(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { String menu1 = getResources().getString(R.string.menuText1); String menu2 = getResources().getString(R.string.menuText2); String menu3 = getResources().getString(R.string.menuText3); String menu4 = getResources().getString(R.string.menuText4); String menu5 = getResources().getString(R.string.menuText5); if(item.toString().equals(menu1)) { Intent editPage = new Intent (this, ChartDailyPreview.class); startActivity(editPage); } else if(item.toString().equals(menu2)) { Intent editPage = new Intent (this, ChartMonthlyPreview.class); startActivity(editPage); } else if(item.toString().equals(menu3)) { Intent editPage = new Intent (this, ChartYearlyPreview.class); startActivity(editPage); } else if(item.toString().equals(menu4)) { Intent editPage = new Intent (this, Edit.class); startActivity(editPage); } else if(item.toString().equals(menu5)) { Intent editPage = new Intent (this, EditGoalsAndSleepTimes.class); startActivity(editPage); } return super.onOptionsItemSelected(item); } } <file_sep># Organiise Tracks users progress towards a goal. On each hour of the day this application asks the user for what they have accomplished, and at the end of the day the application summarises what the user has accomplished, and on daily/monthly/yearly intervals the application compares how much work you have done to your goals. <file_sep>package com.example.josh.organiise; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Color; import android.os.IBinder; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Toast; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.utils.ColorTemplate; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class ChartMonthlyPreview extends AppCompatActivity { Button back; boolean mBounded; Actions mServer; ArrayList<String> elementNames; ArrayList<Integer> elementData; PieChart dailyBarChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chart_monthly_preview); dailyBarChart = (PieChart) findViewById(R.id.DailyChartPreview); android.support.v7.widget.Toolbar toolbar = ( android.support.v7.widget.Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); ActionBar app_bar = getSupportActionBar(); app_bar.setDisplayShowTitleEnabled(false); /* back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent home = new Intent(ChartDailyPreview.this, MainActivity.class); startActivity(home); } }); */ } @Override protected void onStart() { super.onStart(); Intent mIntent = new Intent(this, Actions.class); bindService(mIntent, mConnection, BIND_AUTO_CREATE); }; ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Toast.makeText(ChartMonthlyPreview.this, "Service is disconnected", 1000).show(); mBounded = false; mServer = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Toast.makeText(ChartMonthlyPreview.this, "Service is connected", 1000).show(); mBounded = true; Actions.LocalBinder mLocalBinder = (Actions.LocalBinder)service; mServer = mLocalBinder.getServerInstance(); //if there are some actions in the array. if(mServer.getActionArray().size() != 0) { elementNames = mServer.getMonthlyActionArray(); } //if there are integers attributed to this data. if(mServer.getActionCounter().size() != 0) { elementData = mServer.getMonthlyActionCounter(); } createDailyPieChart(); } }; private void createDailyPieChart() { if(dailyBarChart != null) { System.out.println("WARNING!: chart null, program will crash..."); //list that will fill pie chart. List<PieEntry> actions = new ArrayList<>(); //looping through the actions, and the counters. if (elementNames != null) { for (int i = 0; i < elementNames.size(); i = i + 1) { actions.add(new PieEntry(elementData.get(i), elementNames.get(i))); } ArrayList<Integer> colours = new ArrayList<>(); //for loop that loops through each of the elements in the actions array, from there it creates a random color to each one which is assigned to the colours array list. //this is different for each of the elements in the chart. for (int i = 0; i < elementNames.size(); i = i + 1) { //creating random RGB elements between 0 and 255. int r = ThreadLocalRandom.current().nextInt(0, 255 + 1); int g = ThreadLocalRandom.current().nextInt(0, 255 + 1); int b = ThreadLocalRandom.current().nextInt(0, 255 + 1); //System.out.println("R: " + r + " G: " + g + " B: " + b); //System.out.println(r); int colour = Color.rgb(r, g, b); colours.add(colour); } PieDataSet actionData = new PieDataSet(actions, "Pie chart for yesterdays actions."); actionData.setColors(colours); PieData data = new PieData(actionData); //dailyBarChart.getAxisLeft().setTextColor(R.color.white); // left y-axis //dailyBarChart.getXAxis().setTextColor(R.color.white); //dailyBarChart.animateX(500); Legend l = dailyBarChart.getLegend(); l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER); dailyBarChart.getLegend().setWordWrapEnabled(true); dailyBarChart.getLegend().setXEntrySpace(15f); // set the space between the legend entries on the x-axis dailyBarChart.getLegend().setYEntrySpace(3f); dailyBarChart.setData(data); dailyBarChart.animateY(500); dailyBarChart.invalidate(); //dailyBarChart.getLegend().setWordWrapEnabled(true); dailyBarChart.getLegend().setTextColor(Color.WHITE); dailyBarChart.getLegend().setTextSize(12.0f); //dailyBarChart.getLegend().setPosition(Legend.LegendPosition.RIGHT_OF_CHART_CENTER); // set custom labels and colors //l.setCustom(ColorTemplate.VORDIPLOM_COLORS, actions); } } } /* @Override protected void onStop() { super.onStop(); if(mBounded) { unbindService(mConnection); mBounded = false; } }; */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { String menu1 = getResources().getString(R.string.menuText1); String menu2 = getResources().getString(R.string.menuText2); String menu3 = getResources().getString(R.string.menuText3); String menu4 = getResources().getString(R.string.menuText4); String menu5 = getResources().getString(R.string.menuText5); if(item.toString().equals(menu1)) { Intent editPage = new Intent (this, ChartDailyPreview.class); startActivity(editPage); } else if(item.toString().equals(menu2)) { Intent editPage = new Intent (this, ChartMonthlyPreview.class); startActivity(editPage); } else if(item.toString().equals(menu3)) { Intent editPage = new Intent (this, ChartYearlyPreview.class); startActivity(editPage); } else if(item.toString().equals(menu4)) { Intent editPage = new Intent (this, Edit.class); startActivity(editPage); } else if(item.toString().equals(menu5)) { Intent editPage = new Intent (this, EditGoalsAndSleepTimes.class); startActivity(editPage); } return super.onOptionsItemSelected(item); } }
f4f4bbe5362ab02c69bb002ec37847d633ab8c80
[ "Markdown", "Java" ]
3
Java
joshua-cross/Organiise
dd589f101308b25c4f595e53eb78b5924c8dab38
8bd15ccf640c6c02b4e5d2843b9b53deb3f20b51
refs/heads/master
<file_sep>/** \file Shapes.h * \brief Library to draw various shapes. * \details The program illustrates a multifile. * \author <NAME> * \version 0.1 * \date 13/05/2021 * \copyright University of Nicosia. */ #ifndef SHAPES_H #define SHAPES_H void drawHorizontalLine(const int length, const char ch); void drawVerticalLine(const int height, const char ch); void drawSquare(const int size, const char ch); void drawRectangle(const int height, const int length, const char ch); void menu(); #endif <file_sep>/** \file Tutorial4Part1 * \brief A little program. * \details The program illustrates a multifile. * \author <NAME> * \version 0.1 * \date 13/05/2021 * \bug No bugs so far. * \copyright University of Nicosia. */ #include<iostream> #include<cassert> #include "Shapes.h" using namespace std; int main() { int option; char symbol; int len, height; const int MAX_ARRAY = 10; srand(time(NULL)); do { menu(); cin >> option; switch (option) { case 1: //Horizontal Line do { cout << "Enter length (>0): " << endl; cin >> len; } while (len < 1); cout << "Enter symbol: " << endl; cin >> symbol; drawHorizontalLine(len, symbol); break; case 2: //Vertical Line do { cout << "Enter length (>0): " << endl; cin >> len; } while (len < 1); cout << "Enter symbol: " << endl; cin >> symbol; drawVerticalLine(len, symbol); break; case 3: //Square do { cout << "Enter length (>0): " << endl; cin >> len; } while (len < 2); cout << "Enter symbol: " << endl; cin >> symbol; drawSquare(len, symbol); break; case 4: //Rectangle do { cout << "Enter height (>0): " << endl; cin >> height; cout << "Enter length (>0): " << endl; cin >> len; } while (len < 2); cout << "Enter symbol: " << endl; cin >> symbol; drawRectangle(height, len, symbol); break; case 5: //Exit break; default: cout << "Wrong choice!!" << endl; } } while (option != 5); }<file_sep>/** \file Shapes.cpp * \brief Library to draw various shapes,implementation. * \details The program illustrates a multifile. * \author <NAME> * \version 0.1 * \date 13/05/2021 * \copyright University of Nicosia. */ #include "Shapes.h" #include <iostream> using namespace std; /** * Function <code>drawHorizontalLine<code> draws a horizontal line according to the arguments. * <BR> * @param length The length of the line to be drawn. * @param ch The symbol used to draw the line. */ void drawHorizontalLine(const int length, const char ch) { cout << "HorizontalLine (" << length << ", '" << ch << "')" << endl; cout << endl; for (int i = 0; i < length; i++) { cout << ch; } cout << endl; } /** * Function <code>drawVerticalLine<code> draws a vertical line according to the arguments. * <BR> * @param length The length of the line to be drawn. * @param ch The symbol used to draw the line. */ void drawVerticalLine(const int height, const char ch) { cout << "Vertical Line (" << height << ", '" << ch << "')" << endl; cout << endl; for (int i = 0; i < height; i++) { cout << ch << endl; } } /** * Function <code>drawSquare<code> draws a square according to the arguments. * <BR> * @param size The size of the square. * @param ch The symbol used to draw the square. */ void drawSquare(const int size, const char ch) { cout << "Square (" << size << ", '" << ch << "')" << endl; cout << endl; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (i == 0 || i == size - 1 || j == 0 || j == size - 1) { cout << ch; } else cout << " "; } cout << endl; } } /** * Function <code>drawRectangle<code> draws a rectangle according to the arguments. * <BR> * @param height The height of the rectangle. * @param length The length of the rectangle. * @param ch The symbol used to draw the rectangle. */ void drawRectangle(const int height, const int length, const char ch) { cout << "Rectangle (" << height << ", '" << length << ", '" << ch << "')" << endl; cout << endl; for (int i = 0; i < height; i++) { for (int j = 0; j < length; j++) { if (i == 0 || i == height - 1 || j == 0 || j == length - 1) { cout << ch; } else cout << " "; } cout << endl; } } /** * Function <code>menu<code> is the menu with the options that the user has. * <BR> */ void menu() { cout << "1) Draw a horizontal line" << endl; cout << "2) Draw a vertical line" << endl; cout << "3) Draw a square" << endl; cout << "4) Draw a rectangle" << endl; cout << "5) Quit" << endl; cout << "Enter your Option: "; }
fea717c95709c05af01d24ee5db90982aec580f8
[ "C", "C++" ]
3
C
COMP118-Petros/Tutorial4Part1
f0639111301b7eedd61e2320138976c0473356e6
bb1e445acb102a77622007afe5971af82861076a
refs/heads/master
<file_sep><?php /* Plugin Name: WooCommerce Payment Gateway - CoinGate Plugin URI: https://coingate.com Description: Accept Bitcoin via CoinGate in your WooCommerce store Version: 1.0.1 Author: CoinGate Author URI: https://coingate.com License: MIT License License URI: https://github.com/coingate/woocommerce-plugin/blob/master/LICENSE.md Github Plugin URI: https://github.com/coingate/woocommerce-plugin */ add_action('plugins_loaded', 'coingate_init'); define('COINGATE_WOOCOMMERCE_VERSION', '1.0.1'); function coingate_init() { if (!class_exists('WC_Payment_Gateway')) { return; }; define('PLUGIN_DIR', plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__)) . '/'); require_once(dirname(__FILE__) . '/lib/coingate_merchant.class.php'); class WC_Gateway_Coingate extends WC_Payment_Gateway { public function __construct() { global $woocommerce; $this->id = 'coingate'; $this->has_fields = false; $this->method_title = __('CoinGate', 'woocommerce'); $this->icon = apply_filters('woocommerce_paypal_icon', PLUGIN_DIR . 'assets/bitcoin.png'); $this->init_form_fields(); $this->init_settings(); $this->title = $this->settings['title']; $this->description = $this->settings['description']; $this->app_id = $this->settings['app_id']; $this->api_key = $this->settings['api_key']; $this->api_secret = $this->settings['api_secret']; $this->receive_currency = $this->settings['receive_currency']; $this->test = $this->settings['test']; add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options')); add_action('woocommerce_thankyou_coingate', array($this, 'thankyou')); add_action('coingate_callback', array($this, 'payment_callback')); add_action('woocommerce_api_wc_gateway_coingate', array($this, 'check_callback_request')); } public function admin_options() { ?> <h3><?php _e('CoinGate', 'woothemes'); ?></h3> <p><?php _e('Accept Bitcoin through the CoinGate.com and receive payments in euros and US dollars.', 'woothemes'); ?></p> <table class="form-table"> <?php $this->generate_settings_html(); ?> </table> <?php } function init_form_fields() { $this->form_fields = array( 'enabled' => array( 'title' => __('Enable CoinGate', 'woocommerce'), 'label' => __('Enable Bitcoin payment via CoinGate', 'woocommerce'), 'type' => 'checkbox', 'description' => '', 'default' => 'no' ), 'description' => array( 'title' => __('Description', 'woocommerce'), 'type' => 'textarea', 'description' => __('This controls the description which the user sees during checkout.', 'woocommerce'), 'default' => __('Pay with Bitcoin via Coingate') ), 'title' => array( 'title' => __('Title', 'woocommerce'), 'type' => 'text', 'description' => __('Payment method title that the customer will see on your website.', 'woocommerce'), 'default' => __('Bitcoin', 'woocommerce') ), 'app_id' => array( 'title' => __('App ID', 'woocommerce'), 'type' => 'text', 'description' => __('CoinGate App ID', 'woocommerce'), 'default' => '' ), 'api_key' => array( 'title' => __('API Key', 'woocommerce'), 'type' => 'text', 'description' => __('CoinGate API Key', 'woocommerce'), 'default' => __('', 'woocommerce') ), 'api_secret' => array( 'title' => __('API Secret', 'woocommerce'), 'type' => 'text', 'default' => '', 'description' => __('CoinGate API Secret', 'woocommerce'), ), 'receive_currency' => array( 'title' => __('Receive Currency', 'woocommerce'), 'type' => 'select', 'options' => array( 'EUR' => __('Euros (€)', 'woocommerce'), 'USD' => __('US Dollars ($)', 'woocommerce'), 'BTC' => __('Bitcoin (฿)', 'woocommerce') ), 'description' => __('Currency in which you wish to receive your payments. Currency conversions are done at CoinGate.', 'woocomerce'), 'default' => 'EUR' ), 'test' => array( 'title' => __('Test', 'woocommerce'), 'type' => 'checkbox', 'label' => __('Enable test mode', 'woocommerce'), 'default' => 'no', 'description' => __('Enable this to accept test payments (sandbox.coingate.com). <a href="http://support.coingate.com/knowledge_base/topics/how-can-i-test-your-service-without-signing-up" target="_blank">Read more about testing</a>', 'woocommerce'), ), ); } function thankyou() { if ($description = $this->get_description()) { echo wpautop(wptexturize($description)); } } function process_payment($order_id) { global $woocommerce, $page, $paged; $order = new WC_Order($order_id); $coingate = $this->init_coingate_merchant_class(); $description = array(); foreach ($order->get_items('line_item') as $item) { $description[] = $item['qty'] . ' × ' . $item['name']; } $token = get_post_meta($order->id, 'coingate_order_token', true); if ($token == '') { $token = substr(md5(rand()), 0, 32); update_post_meta( $order_id, 'coingate_order_token', $token ); } $coingate->create_order(array( 'order_id' => $order->id, 'price' => number_format($order->get_total(), 2, '.', ''), 'currency' => get_woocommerce_currency(), 'receive_currency' => $this->receive_currency, 'cancel_url' => $order->get_cancel_order_url(), 'callback_url' => trailingslashit(get_bloginfo('wpurl')) . '?wc-api=wc_gateway_coingate&token=' . $token, 'success_url' => add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(woocommerce_get_page_id('thanks')))), 'title' => get_bloginfo( 'name', 'display' ) . ' Order #' . $order->id, 'description' => join($description, ', ') )); if ($coingate->success) { $coingate_response = json_decode($coingate->response, true); return array( 'result' => 'success', 'redirect' => $coingate_response['payment_url'] ); } else { return array( 'result' => 'fail' ); } } function check_callback_request() { @ob_clean(); do_action('coingate_callback', $_REQUEST); } function payment_callback($request) { global $woocommerce; $order = new WC_Order($request['order_id']); try { if (!$order || !$order->id) throw new Exception('Order #' . $request['order_id'] . ' does not exists'); $token = get_post_meta($order->id, 'coingate_order_token', true); if ($token == '' || $_GET['token'] != $token) throw new Exception('Token: '.$_GET['token'].' do not match'); $coingate = new CoingateMerchant(array('app_id' => $this->app_id, 'api_key' => $this->api_key, 'api_secret' => $this->api_secret, 'mode' => $this->test == 'yes' ? 'sandbox' : 'live')); $coingate->get_order($request['id']); if (!$coingate->success) throw new Exception('CoinGate Order #' . $order->id . ' does not exists'); $coingate_response = json_decode($coingate->response, true); if (!is_array($coingate_response)) throw new Exception('Something wrong with callback'); if ($coingate_response['status'] == 'paid') { $order->add_order_note(__('Payment was completed successfully', 'woocomerce')); $order->payment_complete(); } elseif (in_array($coingate_response['status'], array('invalid', 'expired', 'canceled'))) { $order->update_status('failed', __('Payment failed', 'woocomerce')); } } catch (Exception $e) { echo get_class($e) . ': ' . $e->getMessage(); } } private function init_coingate_merchant_class() { return new CoingateMerchant( array( 'app_id' => $this->app_id, 'api_key' => $this->api_key, 'api_secret' => $this->api_secret, 'mode' => $this->test == 'yes' ? 'sandbox' : 'live', 'user_agent' => 'CoinGate - WooCommerce Plugin v' . COINGATE_WOOCOMMERCE_VERSION ) ); } } function add_coingate_gateway($methods) { $methods[] = 'WC_Gateway_Coingate'; return $methods; } add_filter('woocommerce_payment_gateways', 'add_coingate_gateway'); } <file_sep><?php /** * PHP CoinGate Merchant Class * * @author CoinGate <<EMAIL>> * @version 1.0.2 * @link http://developer.coingate.com * @license MIT */ define('CLASS_VERSION', '1.0.2'); class CoingateMerchant { private $app_id = ''; private $api_key = ''; private $api_secret = ''; private $mode = 'sandbox'; // live or sandbox private $version = 'v1'; private $api_url = ''; private $user_agent = ''; private $user_agent_origin = 'CoinGate PHP Merchant Class'; public function __construct($options = array()) { foreach($options as $key => $value) { if (in_array($key, array('app_id', 'api_key', 'api_secret', 'mode', 'user_agent'))) { $this->$key = trim($value); } if (empty($this->user_agent)) { $this->user_agent = $this->user_agent_origin . ' v' . CLASS_VERSION; } } $this->set_api_url(); } public function create_order($params = array()) { $this->request('/orders', 'POST', $params); } public function get_order($order_id) { $this->request('/orders/' . $order_id); } public function request($url, $method = 'GET', $params = array()) { $url = $this->api_url . $url; $nonce = $this->nonce(); $message = $nonce . $this->app_id . $this->api_key; $signature = hash_hmac('sha256', $message, $this->api_secret); $headers = array(); $headers[] = 'Access-Key: ' . $this->api_key; $headers[] = 'Access-Nonce: ' . $nonce; $headers[] = 'Access-Signature: ' . $signature; $curl = curl_init(); $curl_options = array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url ); if ($method == 'POST') { $headers[] = 'Content-Type: application/x-www-form-urlencoded'; array_merge($curl_options, array(CURLOPT_POST => 1)); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params)); } curl_setopt_array($curl, $curl_options); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); $response = curl_exec($curl); $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); $this->success = $http_status == 200; $this->status_code = $http_status; $this->response = $response; } private function nonce() { return time(); } private function set_api_url() { $this->api_url = strtolower($this->mode) == 'live' ? 'https://coingate.com/api/' : 'https://sandbox.coingate.com/api/'; $this->api_url .= $this->version; } } ?><file_sep>=== CoinGate for WooCommerce === Contributors: CoinGate Donate link: https://coingate.com/ Tags: coingate, bitcoin, payment gateway, woocommerce, btc, xbt Requires at least: 4.0 Tested up to: 4.2.2 Stable tag: trunk License: MIT License URI: https://github.com/coingate/woocommerce-plugin/blob/master/LICENSE.md Accept Bitcoin through the CoinGate.com and receive payments in euros and US dollars == Description == Bitcoin is an innovative payment network and a new kind of money. It uses peer-to-peer technology to operate with no central authority or banks. Bitcoin is open-source; its design is public, nobody owns or controls Bitcoin and everyone can take part. CoinGate is a bitcoin payment processor, which allows businesses to receive payments in euros and US dollars through the Bitcoin payment network, seamlessly connecting innovations of Bitcoin with comfort of familiar currencies and user-friendly interface. == Installation == 1. Install plugin. It can do it in three ways: * Install through [Wordpress Plugin Manager](https://codex.wordpress.org/Plugins_Add_New_Screen): Admin » Plugins » Add New » Enter "coingate woocommerce" in search » Click "Install Now" * [Upload ZIP](https://codex.wordpress.org/Plugins_Add_New_Screen#Upload_Tab): Admin » Plugins » Add New » Upload Plugin * Extract ZIP and upload extracted directory to the `/wp-content/plugins/` through FTP 3. Activate the plugin through the 'Plugins' menu in WordPress 4. Create API Credentials in [coingate.com](https://coingate.com/) (or [sandbox.coignate.com](https://sandbox.coignate.com/) for testing) 5. Enter API Credentials (App ID, Api Key, Api Secret) data to WooCommerce-Coingate Plugin Settings: Admin » WooCommerce » Click on Checkout tab » Find "Bitcoin" in Payment Gateways table » Click "Settings" 6. Don't forget check "Enable Bitcoin payment via CoinGate" checkbox in WooCommerce-Coingate Plugin settings [Plugin not working? Most common plugin issues](http://support.coingate.com/knowledge_base/topics/plugin-slash-extension-slash-module-not-working-common-issues) == Screenshots == 1. WooCommerce-Coingate Plugin Settings 2. Payout options in Woocommerce Checkout page 3. CoinGate Payment Page <file_sep># Installation 1. Download [latest release](https://github.com/coingate/woocommerce-plugin/releases) plugin and extract ZIP archive 2. Upload `woocommerce-coingate/` to the `/wp-content/plugins/` directory 3. Activate the plugin through the 'Plugins' menu in WordPress 4. Create API Credentials in [coingate.com](https://coingate.com/) (or [sandbox.coingate.com](https://sandbox.coignate.com/) for testing) 5. Enter API Credentials (App ID, Api Key, Api Secret) data to WooCommerce-Coingate Plugin Settings: Admin » WooCommerce » Click on Checkout tab » Find "Bitcoin" in Payment Gateways table » Click "Settings" 6. Don't forget check "Enable Bitcoin payment via CoinGate" checkbox in WooCommerce-Coingate Plugin settings
8bdc97795aebf1b4fdd4898e80d150f7e3afde47
[ "Markdown", "Text", "PHP" ]
4
PHP
wp-plugins/coingate-for-woocommerce
d377a03b1b809b7558b67c87c95a0a54dde1fde9
fe30c3ce72b08b49f93217e5ed85fcf30bb8f93a
refs/heads/master
<file_sep>// Rock crushes scissors, You Win! // Paper covers Rock, You Win! // Scissors cut paper, You Win! // Rock crushes scissors, You Lose! // Paper covers Rock, You Lose! // Scissors cut paper, You Lose! const userScore_span = document.getElementById("user-score"); //dom elemments and span since they are placed in the span element const compScore_span = document.getElementById("comp-score"); const result = document.getElementById("result"); let userInput = null; let computerInput = 'rock'; // generates random computer response function computerRespnse() { let rps = ['rock', 'scissors', 'paper'] computerInput = rps[Math.floor(Math.random()*3)]; } let x = 'a'; // for border() let cond = 3; // for updateScore() // uses several conditions to check various values and derive result according to the responses function compare() { if(userInput == 'rock' && computerInput == 'scissors') { console.log('user wins'); borders(); document.getElementById(x).classList.add("green-glow"); setTimeout(() => document.getElementById(x).classList.remove("green-glow"), 500); result.innerHTML = 'Rock crushes Scissors, You Win!'; cond = 0; } else if(userInput == 'rock' && computerInput == 'paper') { console.log('computer wins'); borders(); document.getElementById(x).classList.add("red-glow"); setTimeout(function() {document.getElementById(x).classList.remove("red-glow")}, 500); result.innerHTML = 'Rock crushes Scissors, You Lose!'; cond = 1 } else if(userInput == 'scissors' && computerInput == 'paper') { console.log('user wins'); borders(); document.getElementById(x).classList.add("green-glow"); setTimeout(function() {document.getElementById(x).classList.remove("green-glow")}, 500); result.innerHTML = 'Scissors cut Paper, You Win!'; cond = 0; } else if(userInput == 'scissors' && computerInput == 'rock') { console.log('computer wins'); borders(); document.getElementById(x).classList.add("red-glow"); setTimeout(function() {document.getElementById(x).classList.remove("red-glow")}, 500); result.innerHTML = 'Scissors cut Paper, You lose!'; cond = 1; } else if(userInput == 'paper' && computerInput == 'rock') { console.log('user wins'); borders(); document.getElementById(x).classList.add("green-glow"); setTimeout(function() {document.getElementById(x).classList.remove("green-glow")}, 500); result.innerHTML = 'Paper covers Rock, You Win!'; cond = 0; } else if(userInput == 'paper' && computerInput == 'scissors') { console.log('computer wins'); borders(); document.getElementById(x).classList.add("red-glow"); setTimeout(function() {document.getElementById(x).classList.remove("red-glow")}, 500); result.innerHTML = 'Paper covers Rock, You Lose!'; cond = 1; } else { console.log('its a draw!!!'); result.innerHTML = 'Its a Draw!' borders(); document.getElementById(x).classList.add("grey-glow"); setTimeout(function() {document.getElementById(x).classList.remove("grey-glow")}, 500); cond = 2; } } let userScore = document.getElementById("user-score").innerHTML; let compScore = document.getElementById("comp-score").innerHTML; // updates the score on the screen from 0:0 function updateScore() { compare(); if(cond == 0) { userScore++; userScore_span.innerHTML = userScore; compScore_span.innerHTML = compScore; } else if(cond == 1) { compScore++; userScore_span.innerHTML = userScore; compScore_span.innerHTML = compScore; } else if(cond == 2) { userScore_span.innerHTML = userScore; compScore_span.innerHTML = compScore;; } } // gets computer genetared random response and gets user response and then calls updateScore() which calls compare function getInput(x) { if(x == 1){ computerRespnse(); userInput = 'rock'; updateScore(); } else if(x == 2){ computerRespnse(); userInput = 'paper'; updateScore(); } else if(x == 3){ computerRespnse(); userInput = 'scissors'; updateScore(); } } // used to get the green, red, grey borders when you win, lose or draw function borders() { if(userInput == 'rock') x = 'r'; else if(userInput == 'paper') x = 'p'; else x = 's'; }
24e97c8798378a9abf056ffac952907ce09e142c
[ "JavaScript" ]
1
JavaScript
GuptaPurujit/rock-paper-scissors
3b92ca4bfa67f746e70deab08acfcfb037dac328
c1fd29df0c4f28931692e47136e0b45d7af28fb7
refs/heads/master
<repo_name>kimziou77/Algorithm<file_sep>/README.md <div align="center"> [![Solved.ac프로필](http://mazassumnida.wtf/api/mini/generate_badge?boj=kimziou77)](https://solved.ac/{kimziou77}) [![kimziou77's solvedac profile](http://mazassumnida.wtf/api/v2/generate_badge?boj=kimziou77)](https://solved.ac/profile/kimziou77) <img src="https://user-images.githubusercontent.com/41179265/157101150-5f4a73a3-b98c-4454-a3ee-f9923c232075.jpg" width="35%"> </div> [💚 Solved.ac](https://solved.ac/kimziou77) [💚 Baekjoon](https://www.acmicpc.net/user/kimziou77) [💚 Codeforces](https://codeforces.com/profile/kimziou77) <file_sep>/kakao/2021_kakao_MenuRenewal.py import itertools from collections import defaultdict def solution(orders, course): answer = [] new_order= list() for l in orders: new_order.append(sorted(l)) for num in course: order_count = defaultdict(int) for order in new_order: comb = list(itertools.combinations(order,num)) for com in comb: string_comb = "".join(com) order_count[string_comb] += 1 max_value = max(list(order_count.values()) + [2]) for key, value in order_count.items(): if value == max_value: answer.append(key) # 정답은 문자열 형식으로 배열에 담아 사전 순으로 오름차순 정렬해서 return. return sorted(answer)
59110e6c0a7f8bf65779c83d92643876a2c88f9c
[ "Markdown", "Python" ]
2
Markdown
kimziou77/Algorithm
2ab98f7dbc8e9ca0412925c33c02a560902c60f0
2ddc3ebc0f9701b38e12ea100b980b46af00bfcd
refs/heads/master
<file_sep># -*- encoding : utf-8 -*- require 'spec_helper' describe "admin/articles/index" do before(:each) do assign(:articles, [ stub_model(Article), stub_model(Article) ]) end it "renders a list of admin/articles" do render # Run the generator again with the --webrat flag if you want to use webrat matchers end end <file_sep># -*- encoding : utf-8 -*- class RemotePaginateLinkRenderer < WillPaginate::ActionView::LinkRenderer protected def page_number(page) unless page == current_page tag(:span, link(page, page, :rel => rel_value(page), 'data-remote' => true)) else tag(:span, page, :class => "current") end end def previous_or_next_page(page, text, classname) if page tag(:span, link(text, page, 'data-remote' => true), :class => classname) else tag(:span, text, :class => classname + ' disabled') end end end<file_sep>$(function(){ $("#commands").html("<button id='start_animation' class='btn'>开始</button><button id='stop_animation' class='btn'>停止</button>"); var canvas = $("#canvas"); var context = canvas.get(0).getContext("2d"); var canvas_width = canvas.width(); var canvas_height = canvas.height(); var play_animation = true; var start_button = $("#start_animation"); var stop_button = $("#stop_animation"); start_button.hide(); start_button.click(function(){ $(this).hide(); stop_button.show(); play_animation = true; animate(); }) stop_button.click(function(){ $(this).hide(); start_button.show(); play_animation = false; }) function animate() { context.clearRect(0, 0, canvas_width, canvas_height); var shapes_length = shapes.length; for(var i = 0; i < shapes_length; i++){ var tmp_shape = shapes[i]; tmp_shape.x += tmp_shape.width/10.0; if(tmp_shape.x / canvas_width > 1) { tmp_shape.x = -tmp_shape.width; } //tmpShape.x %= (canvas_width); context.fillStyle = tmp_shape.color; context.fillRect(tmp_shape.x, tmp_shape.y, tmp_shape.width, tmp_shape.width); } if(play_animation){ setTimeout(animate, 33); }; }; var image = new Image(); image.src = "/assets/test.jpg"; $(image).load(function(){ animate(); }) })<file_sep># -*- encoding: utf-8 -*- class Comment < ActiveRecord::Base resourcify include ActsAsCommentable::Comment belongs_to :commentable, :polymorphic => true validates_presence_of :comment, :message => "留言不能为空" validates_presence_of :username, :message => "昵称不能为空" validates_uniqueness_of :comment, :scope => [:username, :commentable_id, :commentable_type], :message => "留言不能重复提交" #default_scope :order => 'created_at ASC' attr_accessible :user_id, :comment, :commentable_id, :commentable_type, :username # NOTE: install the acts_as_votable plugin if you # want user to vote on the quality of comments. #acts_as_voteable # NOTE: Comments belong to a user belongs_to :user end <file_sep># -*- encoding : utf-8 -*- module PublicHelper def remote? return session[:format] != 'html' end end <file_sep># -*- encoding : utf-8 -*- class AdminController < ApplicationController before_filter :should_be_admin def index end def setting AppConfig.entries_perpage = params[:entries_perpage] AppConfig.notice = params[:notice] flash[:notice] = "配置修改成功" redirect_to admin_path end end <file_sep># -*- encoding : utf-8 -*- class User < ActiveRecord::Base resourcify rolify #resourcify必须在rolify之前 # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me attr_accessible :username, :url validates :username, uniqueness: true, presence: true end <file_sep># -*- encoding : utf-8 -*- # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :article do entry_body "草帽一味" tags " 路飞,,卓洛, ,奈美 , 乌索普,,,山治 乔巴,罗宾,弗兰奇 布鲁克 ,," body "路飞\r\n\r\n\r\n卓洛\r\n奈美 乌索普山治乔巴罗宾弗兰奇布鲁克" end end <file_sep># -*- encoding : utf-8 -*- class PublicController < ApplicationController layout "yamato_raven" def index @date = Time.now @tags = Entry.tag_counts_on(:tags).order('count desc') respond_to do |format| format.html { render :layout => false } end end def top if params[:type] session[:format] = cookies[:format] = params[:type] end end def logs per_page = AppConfig.entries_perpage @page = params[:page]||1 @date = Time.now @tags = Entry.tag_counts_on(:tags).order('count desc') @entries = Entry.order('created_at desc').paginate(:page => @page, :per_page => per_page) @hash = "#log" @hash += "-p#{@page}" if params[:page] @sethash = true unless params[:donotsethash] @filter = "全部" end def date per_page = AppConfig.entries_perpage @page = params[:page]||1 now = Time.now @year = params[:year] ||now.year @month = params[:month]||now.month @day = params[:day] ||now.day @hash = "#date" conditions = [] if params[:day] conditions = ["created_at > ? and created_at < ?", Time.new(@year,@month,@day).beginning_of_day, Time.new(@year,@month,@day).end_of_day] @hash += "-y#{@year}-m#{@month}-d#{@day}" @filter = "#{@year}年#{@month}月#{@day}日" elsif params[:month] conditions = ["created_at > ? and created_at < ?", Time.new(@year,@month,1).beginning_of_month, Time.new(@year,@month,1).end_of_month] @hash += "-y#{@year}-m#{@month}" @filter = "#{@year}年#{@month}月" elsif params[:year] conditions = ["created_at > ? and created_at < ?", Time.new(@year,1,1).beginning_of_year, Time.new(@year,1,1).end_of_year] @hash += "-y#{@year}" @filter = "#{@year}年" end if params[:page] @hash += "-p#{@page}" end @entries = Entry.where(conditions).order('created_at desc').paginate(:page => @page, :per_page => per_page) respond_to do |format| format.html { @date = Time.new(@year, @month, @day) @tags = Entry.tag_counts_on(:tags).order('count desc') render :action => :log } format.js { if @should_load_log = params[:should_load_log] || false @date = Time.new(@year, @month, @day) @tags = Entry.tag_counts_on(:tags).order('count desc') end render 'search.js.erb' } end end def tag per_page = AppConfig.entries_perpage @page = params[:page]||1 tag = params[:tag] @entries = Entry.tagged_with(tag).order("created_at desc").paginate(:page => @page, :per_page => per_page) @hash = "#tag-#{tag}" @hash += "-p#{@page}" if params[:page] @filter = "标签[#{tag}]" respond_to do |format| format.html { @date = Time.now @tags = Entry.tag_counts_on(:tags).order('count desc') render :action => :log } format.js { if @should_load_log = params[:should_load_log] || false @date = Time.now @tags = Entry.tag_counts_on(:tags).order('count desc') end render 'search.js.erb' } end end def keyword per_page = AppConfig.entries_perpage @page = params[:page]||1 keyword = params[:keyword] @entries = Entry.where(["body like ?", "%#{keyword}%"]).order("created_at desc").paginate(:page => @page, :per_page => per_page) @hash = "#keyword-#{keyword}" @hash += "-p#{@page}" if params[:page] @filter = "关键词[#{keyword}]" respond_to do |format| format.html { @date = Time.now @tags = Entry.tag_counts_on(:tags).order('count desc') render :action => :log } format.js { if @should_load_log = params[:should_load_log] || false @date = Time.now @tags = Entry.tag_counts_on(:tags).order('count desc') end render 'search.js.erb' } end end def detail end def games @games = Game.order('created_at desc').paginate(:page => params[:page] || 1, :per_page => 10) @hash = "#games" end def game @game = Game.find_by_id params[:id] @hash = "#game#{@game.id}" end def change_format if session[:format] == 'js' session[:format] = cookies[:format] = 'html' else session[:format] = cookies[:format] = 'js' end redirect_to :back end def calendar @date = Time.at(params[:datetime].to_i) respond_to do |format| format.js end end def create_comment @comment = Comment.new(params[:comment]) respond_to do |format| if @comment.save format.html { redirect_to :back, notice: '留言成功' } format.js { render "comment" } else format.html { redirect_to :back, notice: '留言失败' } format.js { render :js => "$('#comment_error_msg_for_e#{@comment.commentable_id}').html('#{@comment.errors.first[1]}')" } end end end end <file_sep># -*- encoding : utf-8 -*- require 'spec_helper' describe Entry do describe "1059 tags" do let(:entry) { FactoryGirl.create :entry, :tags_with_space => " 秀吉 半兵卫 三成,信忠," } it "should return 1059 tags" do entry.tags.map(&:name).join(' ').should == "秀吉 半兵卫 三成 信忠" end pending "正确返回战国条目信息 #{__FILE__}" end describe "naruto tags" do let(:naruto_entry) { FactoryGirl.create :naruto_entry, :tags_with_space => ",,鹿牙 蛇自 ,卡带 ,,,,63 角飞 , 兜鸢 , , " } it "should return naruto tags" do naruto_entry.tags.map(&:name).join(' ').should == "鹿牙 蛇自 卡带 63 角飞 兜鸢" end pending "正确返回火影条目信息 #{__FILE__}" end describe "hiyori body" do let(:hiyori_entry) { FactoryGirl.create :hiyori_entry, :body => "大家的眼睛都死了,搞笑漫画日和" } it "should return hiyori body" do hiyori_entry.body.should == "大家的眼睛都死了,搞笑漫画日和" end pending "正确返回日和条目信息 #{__FILE__}" end end <file_sep>class Admin::CommentsController < ApplicationController before_filter :should_be_admin layout "admin" def index @page = params[:page] || 1 @last_readed_comment_id = AppConfig[:last_readed_comment_id] || 0 @comments = Comment.order('created_at desc').paginate(:page => @page, :per_page => 20) if @page == 1 AppConfig[:last_readed_comment_id] = @comments.first.id end end end <file_sep>class CreateAdminGames < ActiveRecord::Migration def change create_table :games do |t| t.string :title t.string :js_file t.integer :width, :default => "600" t.integer :height, :default => "600" t.timestamps end end end <file_sep>//650x600 $(function(){ var canvas = $("#canvas"); var canvas_width = canvas.width(); var canvas_height = canvas.height(); var context = canvas.get(0).getContext("2d"); context.fillStyle = "rgba(255,255,255,1)"; context.fillRect(0,0,canvas_width,canvas_height); context.fillStyle = "rgb(0,0,0)"; context.strokeStyle = "rgb(0,0,0)"; //context.beginPath(); context.arc(325,300,100,0,Math.Pi * 2,false); //context.closePath(); context.fill(); context.stroke(); var image = new Image(); image.src = "/assets/test.jpg"; $(image).load(function(){ context.drawImage(image,0,0,325,300); context.drawImage(image,325,300,325,300); var imageData = context.getImageData(0,0,325,300); var pixels = imageData.data; var numPixels = pixels.length; for ( var i = 0; i < numPixels; i++ ) { pixels[i*4] = 255-pixels[i*4]; pixels[i*4+1] = 255-pixels[i*4+1]; pixels[i*4+2] = 255-pixels[i*4+2]; }; context.putImageData(imageData,0,300); for ( var i = 0; i < numPixels; i++ ) { var average = (pixels[i*4]+pixels[i*4+1]+pixels[i*4+2])/3; pixels[i*4] = average; pixels[i*4+1] = average; pixels[i*4+2] = average; }; //context.putImageData(imageData,325,0); var tileWidth =12; var tileHeight = 12; var imageData = context.getImageData(0,0,325,300); var pixels = imageData.data; for (var r=0;r<(imageData.height/tileHeight);r++){ for (var c=0;c<(imageData.width/tileWidth);c++){ var x = (c*tileWidth)+(tileWidth/2); var y = (r*tileHeight)+(tileHeight/2); var pos = (Math.floor(y)*(imageData.width*4))+(Math.floor(x)*4); var red = pixels[pos]; var green = pixels[pos+1]; var blue = pixels[pos+2]; context.fillStyle = "rgb("+red+","+green+","+blue+")"; context.strokeStyle = "rgb("+red+","+green+","+blue+")"; context.beginPath(); context.arc(x + 325, y, tileWidth / 2, 0, Math.PI * 2, false); context.closePath(); context.fill(); //context.stroke(); //context.fillRect(x-(tileWidth/2)+325,y-(tileHeight/2),tileWidth,tileHeight); } } context.strokeStyle = "rgb(255,255,255)"; for (i = 0;i<=300;i++) { if(i%5 == 0){ context.beginPath(); //开始路径 context.moveTo(325,300+i); //设置原点 context.lineTo(650,300+i); //设置终点 context.closePath(); //关闭路径 context.stroke(); } }; }) })<file_sep># -*- encoding : utf-8 -*- class AppConfig < RailsSettings::CachedSettings attr_accessible :var end <file_sep># -*- encoding : utf-8 -*- # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :entry do body "1059" end factory :naruto_entry, :parent => :entry do body "naruto" end factory :hiyori_entry, class: Entry do tags_with_space " 奥之细道,, 飞鸟 天国," end end <file_sep># -*- encoding : utf-8 -*- require 'spec_helper' describe Article do describe "article" do let(:article) { FactoryGirl.create :article } it "should return op body" do article.body.should == "路飞 \n \n \n卓洛 \n奈美 乌索普山治乔巴罗宾弗兰奇布鲁克" end it "should return op entry" do article.entry.body.should == "草帽一味" end it "should return op tags" do article.entry.tags.map(&:name).join(' ').should == "路飞 卓洛 奈美 乌索普 山治 乔巴 罗宾 弗兰奇 布鲁克" end pending "正确返回海贼王长文信息 #{__FILE__}" end end <file_sep># -*- encoding : utf-8 -*- class Admin::EntriesController < ApplicationController before_filter :should_be_admin layout "admin" # GET /entries # GET /entries.json def index @entries = Entry.order('created_at desc').paginate(:page => params[:page] || 1, :per_page => 20) respond_to do |format| format.html # index.html.erb format.json { render json: @entries } end end # GET /entries/1 # GET /entries/1.json def show @entry = Entry.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @entry } end end # GET /entries/new # GET /entries/new.json def new @entry = Entry.new respond_to do |format| format.html # new.html.erb format.json { render json: @entry } end end # GET /entries/1/edit def edit @entry = Entry.find(params[:id]) @entry.tags_with_space = @entry.tag_list.split(",").join(" ") end # POST /entries # POST /entries.json def create @entry = Entry.new(params[:entry]) respond_to do |format| if @entry.save format.html { redirect_to [:admin, @entry], notice: 'Entry was successfully created.' } format.json { render json: @entry, status: :created, location: @entry } else format.html { render action: "new" } format.json { render json: @entry.errors, status: :unprocessable_entity } end end end # PUT /entries/1 # PUT /entries/1.json def update @entry = Entry.find(params[:id]) respond_to do |format| if @entry.update_attributes(params[:entry]) format.html { redirect_to [:admin, @entry], notice: 'Entry was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @entry.errors, status: :unprocessable_entity } end end end # DELETE /entries/1 # DELETE /entries/1.json def destroy @entry = Entry.find(params[:id]) @entry.destroy respond_to do |format| format.html { redirect_to admin_entries_url } format.json { head :no_content } end end end <file_sep># -*- encoding : utf-8 -*- # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) AppConfig.entries_perpage = 5 AppConfig.notice = "开业大吉" user = User.create(:username => "六十", :email => "<EMAIL>", :password => "<PASSWORD>", :password_confirmation => "<PASSWORD>") user.add_role(:admin)<file_sep># -*- encoding : utf-8 -*- require 'spec_helper' describe PublicController do describe "GET 'index'" do it "returns http success" do get 'index' response.should be_success end end describe "GET 'log'" do it "returns http success" do get 'log' response.should be_success end end describe "GET 'detail'" do it "returns http success" do get 'detail' response.should be_success end end end <file_sep># -*- encoding : utf-8 -*- class Game < ActiveRecord::Base attr_accessible :js_file, :title, :width, :height mount_uploader :js_file, JsFileUploader end <file_sep>$(function(){ $("#commands").html("<button id='start_animation' class='btn'>开始</button><button id='stop_animation' class='btn'>停止</button>"); var canvas = $("#canvas"); var context = canvas.get(0).getContext("2d"); var canvas_width = canvas.width(); var canvas_height = canvas.height(); var play_animation = true; var start_button = $("#start_animation"); var stop_button = $("#stop_animation"); start_button.hide(); start_button.click(function(){ $(this).hide(); stop_button.show(); play_animation = true; animate(); }) stop_button.click(function(){ $(this).hide(); start_button.show(); play_animation = false; }) })<file_sep># -*- encoding : utf-8 -*- class Entry < ActiveRecord::Base resourcify acts_as_taggable acts_as_commentable attr_accessible :body, :tags_with_space attr_accessor :tags_with_space validates :tags_with_space, :length => { :maximum => 15 } has_one :article before_save :split_tags def split_tags if self.tags_with_space self.tag_list = self.tags_with_space.split(" ").join(',') end end end <file_sep># encoding: utf-8 class ApplicationController < ActionController::Base protect_from_forgery def after_sign_in_path_for(resource_or_scope) ability = Ability.new(current_user) if ability.can? :manage, :all admin_path else top_path end end def after_sign_out_path_for(resource_or_scope) root_path end def check_format if cookies[:format] and not session[:format] session[:format] = cookies[:format] end end def should_be_admin unless current_user && current_user.has_role?("admin") redirect_to top_path, :alert => "您没有操作权限" end end end <file_sep># -*- encoding : utf-8 -*- class Article < ActiveRecord::Base resourcify attr_accessible :body, :entry_body, :tags attr_accessor :entry_body, :tags belongs_to :entry before_create :create_entry before_update :update_entry before_save :gsub_body def create_entry entry = Entry.new entry.body = self.entry_body entry.tags_with_space = self.tags entry.save self.entry = entry end def update_entry entry = self.entry entry.body = self.entry_body entry.tags_with_space = self.tags entry.save end def gsub_body self.body = self.body.blank? ? "" : self.body.gsub(/\r\n/," \n").gsub(/ +/," ") end end
71f52d60cdde1e5c89f258645b918ac90a37168f
[ "JavaScript", "Ruby" ]
24
Ruby
chany229/dame09plus
9c8f25b93ee87caf5e60f8019e39ca174680aaea
623e630a32ffc4c27032fb92c64286c017f35ffc
refs/heads/master
<file_sep>import json import yaml import os import sys import subprocess import tempfile from datetime import datetime def run_command(full_command): proc = subprocess.Popen(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) proc.communicate() return proc.returncode def create_repository(repository, git_context): print('Updating Repository: {} GIT Context: {}'.format(str(repository), git_context)) run_command('codefresh add repository {} -c {}'.format(str(repository), git_context)) def create_pipeline(repository, pipeline_file): fd, path = tempfile.mkstemp(suffix='.yaml') try: with open(pipeline_file) as f, open(path, 'w') as tmp: pipeline = yaml.load(f) full_name = '/'.join([str(repository), pipeline['metadata']['name']]) pipeline['metadata']['project'] = str(repository) pipeline['metadata']['name'] = full_name yaml.dump(pipeline, tmp) # Start Debugging # with open(path) as f: # print f.read() # End Debugging with open(path) as f: print('Attempting to update Pipeline for Repository: {} Using file: {}'.format(str(repository), pipeline_file)) if run_command('codefresh get pipeline {}'.format(pipeline['metadata']['name'])) == 1: print('Pipeline {} Not Found for Repository: {}'.format(pipeline['metadata']['name'], str(repository))) print('Creating...') run_command('codefresh create -f {}'.format(path)) else: print('Pipeline {} Found for Repository: {}'.format(pipeline['metadata']['name'], str(repository))) print('Updating...') run_command('codefresh replace -f {}'.format(path)) finally: os.remove(path) def main(): creator_file_path = os.getenv('CREATOR_FILE_PATH', './codefresh_creator.yaml') with open(creator_file_path) as f: creator_json = json.dumps(yaml.load(f)) for repository_data in json.loads(creator_json): repository = repository_data['repository'] if 'git_context' not in repository_data: git_context = 'github' else: git_context = repository_data['git_context'] create_repository(repository, git_context) pipelines = repository_data['pipelines'] for pipeline_file in pipelines: create_pipeline(repository, pipeline_file) if __name__ == "__main__": main() <file_sep># cfstep-pipeline-creator Programmatically add repositories and pipelines to Codefresh Account using YAML file. Store your repositories and pipeline spec files in a separate repository and update them from a single location. Example `codefresh-creator.yaml`: ``` yaml - repository: dustinvanbuskirk/repository-1 git_context: github pipelines: - ./pipelines/pipeline-spec1.yaml - ./pipelines/pipeline-spec2.yaml - repository: dustinvanbuskirk/repository-2 pipelines: - ./pipelines/pipeline-spec2.yaml ``` Using the file above we will create the repository if it does not exist for the Codefresh account and the pipelines for that repository. This Fresh Step should be integrated in with the repository containing the file above. ``` yaml version: '1.0' steps: CreatePipelines: image: codefresh/cfstep-pipeline-creator:latest environment: - CREATOR_FILE_PATH='./example/codefresh-creator.yaml' ``` The step above will pick up the codefresh-creator.yaml in the examples folder. In that file the pipeline's YAML files have been defined according to the repositories layout which is automatically set as the `working_directory` of the script explaining the relative paths. This will create repositories as needed and keep all pipelines up-to-date with file using replace. <file_sep>FROM python:3.7.2-alpine3.7 ENV LANG C.UTF-8 RUN apk update && \ apk upgrade && \ apk add --no-cache \ git \ nodejs && \ npm config set unsafe-perm true && \ npm install codefresh -g COPY script/pipeline_creator.py /pipeline_creator.py ENTRYPOINT ["python", "/pipeline_creator.py"]
21d95eb243b5e7ee941c13a62ad6d2f591a24f60
[ "Markdown", "Python", "Dockerfile" ]
3
Python
codefresh-contrib/cfstep-pipeline-creator
61de2cd63d36d759041a5ed6b3b6da097979cab5
228c07d976674a41c9dae6337af65038e694377b
refs/heads/master
<file_sep>const express = require('express'); const router = express.Router(); const User = require('../models/User'); const bcrypt = require('bcryptjs'); const bcryptSalt = 10; const passport = require('passport'); const Movie = require('../models/Movie'); const uploader = require('../config/cloud'); // API router.get('/api/users', (req,res,next)=>{ if(req.user){ User.find() .then((eachUser)=>{ res.json(eachUser); }) .catch((err)=>{ next(err) }) } }) router.get('/signup', (req,res,next)=>{ res.render('signup' , {message : req.flash('error')}) }); router.post('/signup', uploader.single('the-picture'), (req,res,next)=>{ User.findOne({username: req.body.username}) .then((theUser)=>{ if(theUser!==null){ req.flash('error', 'sorry, that username is taken') res.redirect('/signup') } const salt = bcrypt.genSaltSync(10); const theHash = bcrypt.hashSync(req.body.password, salt); User.create({ username: req.body.username, password: <PASSWORD>, admin: false, profilePic: req.file.url }) .then((theUser)=>{ req.login(theUser, (err)=>{ if (err){ req.flash('error', 'something went wrong with auto login, please log in manually') res.redirect('/login') return; } res.redirect('/profile') }); }) .catch((err)=>{ next(err); }) }) .catch((err)=>{ next(err); }) }); router.get('/profile', (req,res,next)=>{ Movie.find({watcher:req.user._id}) .then((watcher)=>{ res.render('profile', {user: req.user, movie: watcher }) }) .catch((err)=>{ next(err); }) }) //End of POST router.get('/login', (req, res, next)=>{ if(req.user){ req.flash('error', 'you are alredy logged in') res.redirect('/') } else{ res.render('login', {message: req.flash('error')}) } }); // POST LOGIN router.post('/login', passport.authenticate("local", { successRedirect: "/", failureRedirect: '/signup', failureFlash: true, passReqToCallback: true })); // (req,res,next)=>{ // const username = req.body.username; // const password = <PASSWORD>; // if(username === "" || password === "") // { // res.render("login" , {errorMessage: "Indicate a username and a password to login"}) // return; // } // User.findOne({username:username}) // .then((user)=>{ // if(!user) // { // res.render('login', {errorMessage: "Sorry, that username does not exist"}) // return; // } // if(bcrypt.compareSync(password, user.password)) // { // req.session.currentUser = user; // res.redirect("/"); // } // else // { // res.render('login', {errorMessage : "Incorrect password"}); // } // }) // .catch((err)=>{ // next(err); // }) // }); //END OF POST router.get('/logout', (req,res,next)=>{ req.logout(); res.redirect('/login') // req.session.destroy((err)=>{ // res.redirect('/login') // }) }) router.get('/secret', (req, res, next) => { if(!req.user){ res.render('login', {message:'You have to be logged in'}); return; } else if(!req.user.admin){ res.render('index', {message:'You have to be admin'}) return; } else { res.render('secret' ,{theUser: req.user}) } }); module.exports = router;<file_sep>const express = require('express'); const router = express.Router(); const Celebrity = require('../models/celebrity'); const Movie = require('../models/Movie'); router.get('/movies', (req, res, next) => { if(!req.user){ req.flash('error', 'page not available'); res.redirect('/login') return; } Movie.find().populate('celebrity') .then((eachMovie)=>{ res.render('movies/index', {movies : eachMovie , message : req.flash('error')}); }) .catch((err)=>{ next(err) }) }); router.get('/movies/new', (req,res,next)=>{ if(!req.user){ req.flash('error', 'sorry you must be loggeed in to create movie'); res.redirect('login') return; } Celebrity.find() .then((allStars)=>{ res.render('movies/newMovie',{allStars}); }) .catch((err)=>{ next(err); }) }) router.post('/movies/new', (req, res, next)=>{ const NewMovie = req.body; NewMovie.watcher = req.user._id; Movie.create(NewMovie) .then(()=>{ res.redirect('/movies') }) .catch((err)=>{ next(err); }) }) router.get('/movies/:id', (req, res, next) => { Movie.findById(req.params.id).populate('celebrity').populate('watcher') .then((eachMovie)=>{ res.render('movies/showMovie', {pickedMovie : eachMovie}); }) .catch((err)=>{ next(err) }) }); router.post('/movies/:id/delete' , (req,res,next)=>{ if(req.user.admin){ Movie.findByIdAndRemove(req.params.id) .then(()=>{ res.redirect('/movies') }) .catch((err)=>{ next(err) }) } else{ req.flash('error', "you have to be admin to delete movie") res.redirect('/movies') } }) router.get('/movies/:id/edit', (req,res,next)=>{ Movie.findById(req.params.id) .then((theMovie)=>{ Celebrity.find() .then((allStars)=>{ allStars.forEach((star)=>{ if(star._id.equals(theMovie.celebrity)){ star.yes = true; } }) console.log(allStars) res.render('movies/edit' , {theMovie: theMovie, allStars: allStars }) }) .catch((err)=>{ next(err) }) }) .catch((err)=>{ next(err) }) }) router.post('/movies/:id/edit' , (req,res,next)=>{ Movie.findByIdAndUpdate(req.params.id , req.body) .then(()=>{ res.redirect('/movies/'+req.params.id); }) .catch((err)=>{ next(err) }) }) module.exports = router;<file_sep>const express = require('express'); const router = express.Router(); const Celebrity = require('../models/celebrity') /* GET celebrities page */ router.get('/celebrities', (req, res, next) => { Celebrity.find() .then((eachCelebrity)=>{ res.render('celebrities/index', {celebrities: eachCelebrity}); }) .catch((err)=>{ next(err) }) }); router.get('/celebrities/new', (req,res,next)=>{ res.render('celebrities/new') }) router.post('/celebrities/new', (req, res, next)=>{ Celebrity.create(req.body) .then(()=>{ res.redirect('/celebrities') }) .catch((err)=>{ next(err); }) }) router.get('/celebrities/:id', (req, res, next) => { Celebrity.findById(req.params.id) .then((eachStar)=>{ res.render('celebrities/show', {Stars : eachStar}); }) .catch((err)=>{ next(err) }) }); router.post('/celebrities/:id/delete' , (req,res,next)=>[ Celebrity.findByIdAndRemove(req.params.id) .then(()=>{ res.redirect('/celebrities') }) .catch((err)=>{ next(err) }) ]) router.get('/celebrities/:id/edit', (req,res,next)=>{ Celebrity.findById(req.params.id) .then((theStar)=>{ res.render('celebrities/edit' , {theStar: theStar}) }) .catch((err)=>{ next(err) }) }) router.post('/celebrities/:id/edit' , (req,res,next)=>{ Celebrity.findByIdAndUpdate(req.params.id , req.body) .then(()=>{ res.redirect('/celebrities/'+req.params.id); }) .catch((err)=>{ next(err) }) }) module.exports = router;
e0fdd9864c74c297129d89e1a1897a75840fa5a1
[ "JavaScript" ]
3
JavaScript
Rustam1993/lab-mongoose-movies
5617091005d813008aaeacd33b7c724347b73381
73de1d05432d98f39ca0beb63b77d171d46acc74
refs/heads/main
<file_sep>package dev.uten2c.serversideitem.mixin; import dev.uten2c.serversideitem.ServerSideItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.packet.s2c.play.InventoryS2CPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.List; @Mixin(InventoryS2CPacket.class) public class MixinInventoryS2CPacket<E> { @Shadow private List<ItemStack> contents; @SuppressWarnings("unchecked") @Redirect(method = "<init>(ILnet/minecraft/util/collection/DefaultedList;)V", at = @At(value = "INVOKE", target = "Ljava/util/List;set(ILjava/lang/Object;)Ljava/lang/Object;")) private E ssi_set(List<E> list, int index, E element) { ItemStack stack = (ItemStack) element; Item item = stack.getItem(); if (item instanceof ServerSideItem) { stack = ((ServerSideItem) item).createVisualStack(stack); } return (E) contents.set(index, stack); } } <file_sep>package dev.uten2c.serversideitem.mixin.accessor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(ItemStack.class) public interface ItemStackAccessor { @Accessor("item") void setItem(Item item); } <file_sep>plugins { java id("fabric-loom") version "0.6-SNAPSHOT" `maven-publish` } base { archivesBaseName = "serverside-item-fabric" group = "dev.uten2c" version = "1.16.5+6" } tasks.getByName<ProcessResources>("processResources") { filesMatching("fabric.mod.json") { expand(mutableMapOf("version" to project.version)) } } repositories { mavenCentral() maven("https://uten2c.github.io/repo/") } dependencies { minecraft(group = "com.mojang", name = "minecraft", version = "1.16.5") mappings(group = "net.fabricmc", name = "yarn", version = "1.16.5+build.5", classifier = "v2") modImplementation("net.fabricmc:fabric-loader:0.11.3") } val remapJar = tasks.getByName<net.fabricmc.loom.task.RemapJarTask>("remapJar") val remapSourcesJar = tasks.getByName<net.fabricmc.loom.task.RemapSourcesJarTask>("remapSourcesJar") val sourcesJar = tasks.create<Jar>("sourcesJar") { archiveClassifier.set("sources") from(sourceSets["main"].allSource) } publishing { publications { create<MavenPublication>("maven") { groupId = project.group.toString() artifactId = project.base.archivesBaseName version = project.version.toString() artifact(remapJar) { builtBy(remapJar) } artifact(sourcesJar) { builtBy(remapSourcesJar) } } } repositories { maven { url = uri("${System.getProperty("user.home")}/maven-repo") println(uri("${System.getProperty("user.home")}/maven-repo")) } } }<file_sep>package dev.uten2c.serversideitem; public final class Constants { public static final String TAG_KEY = "0cf10e31-a339-43ca-9785-a01beb08e008"; private Constants() { } } <file_sep>![Maven metadata URL](https://img.shields.io/maven-metadata/v?metadataUrl=https%3A%2F%2Futen2c.github.io%2Frepo%2Fdev%2Futen2c%2Fserverside-item-fabric%2Fmaven-metadata.xml) # ServerSideItem サーバーサイドのみで新しいアイテムを追加するやつ ### Groovy DSL ```groovy repositories { maven { url 'https://uten2c.github.io/repo/' } } dependencies { implementation 'dev.uten2c:serverside-item-fabric:VERSION' } ``` ### Kotlin DSL ```kotlin repositories { maven("https://uten2c.github.io/repo/") } dependencies { implementation("dev.uten2c:serverside-item-fabric:VERSION") } ``` ### Example ```java public class ExampleMod implements ModInitializer { public static final Item TEST_ITEM = new TestItem(new Item.Settings()); @Override public void onInitialize() { Registry.register(Registry.ITEM, new Identifier("example", "test_item"), TEST_ITEM); } } public class TestItem extends Item implements ServerSideItem { public TestItem(Settings settings) { super(settings); } @Override public Item getVisualItem() { return Items.DIAMOND; } } ``` Get item ``` /give @s example:test_item ```<file_sep>package dev.uten2c.serversideitem.mixin; import dev.uten2c.serversideitem.Constants; import dev.uten2c.serversideitem.ServerSideItem; import dev.uten2c.serversideitem.mixin.accessor.ItemStackAccessor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.packet.c2s.play.CreativeInventoryActionC2SPacket; import net.minecraft.server.network.ServerPlayNetworkHandler; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(ServerPlayNetworkHandler.class) public class MixinServerPlayNetworkHandler { @Redirect(method = "onCreativeInventoryAction", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/packet/c2s/play/CreativeInventoryActionC2SPacket;getItemStack()Lnet/minecraft/item/ItemStack;")) private ItemStack ssi_swapStack(CreativeInventoryActionC2SPacket packet) { ItemStack stack = packet.getItemStack(); CompoundTag tag = stack.getTag(); if (tag != null && tag.contains(Constants.TAG_KEY)) { Identifier id = new Identifier(tag.getString(Constants.TAG_KEY)); Item item = Registry.ITEM.get(id); if (item instanceof ServerSideItem) { return ssi_convertStack(stack); } } return stack; } @SuppressWarnings("ConstantConditions") private ItemStack ssi_convertStack(ItemStack stack) { ItemStack copy = stack.copy(); Identifier id = new Identifier(copy.getOrCreateTag().getString(Constants.TAG_KEY)); Item item = Registry.ITEM.get(id); ((ItemStackAccessor) (Object) copy).setItem(item); CompoundTag tag = copy.getTag(); if (tag != null) { tag.remove(Constants.TAG_KEY); ItemStack defaultVisualStack = ((ServerSideItem) item).createVisualStack(item.getDefaultStack()); CompoundTag displayTag1 = copy.getSubTag("display"); CompoundTag displayTag2 = defaultVisualStack.getSubTag("display"); if (displayTag1 != null && displayTag2 != null) { Tag nameTag1 = displayTag1.get("Name"); if (nameTag1 != null && nameTag1.equals(displayTag2.get("Name"))) { displayTag1.remove("Name"); } if (displayTag1.isEmpty()) { tag.remove("display"); } } if (tag.isEmpty()) { copy.setTag(null); } } return copy; } } <file_sep>package dev.uten2c.serversideitem.mixin; import com.mojang.datafixers.util.Pair; import dev.uten2c.serversideitem.ServerSideItem; import net.minecraft.entity.EquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.packet.s2c.play.EntityEquipmentUpdateS2CPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(EntityEquipmentUpdateS2CPacket.class) public class MixinEntityEquipmentUpdateS2CPacket { @Redirect(method = "write", at = @At(value = "INVOKE", target = "Lcom/mojang/datafixers/util/Pair;getSecond()Ljava/lang/Object;"), remap = false) private Object swapStack(Pair<EquipmentSlot, ItemStack> pair) { ItemStack stack = pair.getSecond(); Item item = stack.getItem(); if (item instanceof ServerSideItem) { return ((ServerSideItem) item).createVisualStack(stack); } return stack; } }
b69efab38ddeff0425eb415d0566aec56520a0c9
[ "Markdown", "Java", "Kotlin" ]
7
Java
uTen2c/serverside-item-fabric
33849dc80d35f8bb7a2ecefde99b17f3a807a755
793c85137f62efea64d75e114d116610d1643aa9
refs/heads/master
<file_sep>// JavaScript Document window.onload=function(){ var deviceWidth=document.documentElement.clientWidth; if(deviceWidth>720) deviceWidth = 720; if(deviceWidth<320) deviceWidth = 320; document.documentElement.style.fontSize=deviceWidth/7.2+'px'; } window.onresize=function(){ var deviceWidth = document.documentElement.clientWidth; if(deviceWidth>720) deviceWidth=720; if(deviceWidth<320) deviceWidth = 320; document.documentElement.style.fontSize=deviceWidth/7.2 + 'px'; } //菜单点击 var oMenu=document.getElementById('iconMenu'); var oMenuList=document.getElementById('menuList'); var oShade=document.getElementById('shade'); var onOff=true; oMenu.onclick=function() { if(onOff) { oMenuList.style.display="block"; oShade.style.display="block"; onOff=false; oShade.onclick=function() { oMenuList.style.display="none"; oShade.style.display="none"; onOff=true; } }else { oMenuList.style.display="none"; oShade.style.display="none"; onOff=true; } }<file_sep><!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <link href="css/public.css" rel="stylesheet" type="text/css" /> <link href="css/collogePage.css" rel="stylesheet" type="text/css" /> <script src="js/jquery.min.js"></script> <script src="js/index.js"></script> </head> <body> <!--[if IE 6]> <script type="text/javascript" src="js/Janrong.js"></script> <script type="text/javascript"> DD_belatedPNG.fix('.png'); </script> <![endif]--> <div class="boardTop"> <div class="boardTop_editor"> <div class="boardTop_editor_left"> <ul> <li><a href="#">网站导航 |</a></li> <li><a href="#">关于佳航</a></li> </ul> </div> <div class="boardTop_editor_right"> <p class="icoP"> <a href="#"><img src="img/index/QQ_img.jpg"> QQ</a> <a href="#"> <img src="img/index/weibo_img.jpg"> 微博</a> <a href="#"> <img src="img/index/weixin_img.jpg"> 微信</a> </p> <div class="qqBox"><img src="img/index/weibo_img1.jpg"></div> <div class="weiboBox"><img src="img/index/weibo_img1.jpg"></div> <div class="weixinBox"><img src="img/index/weibo_img1.jpg"></div> </div> </div> </div> </div> <div class="boardTitle"> <div class="boardTitle_logo"> <a href="#"><img src="img/index/logo_img.jpg"></a></div> <div class="boardTitle_hunt"> <p><input type="text" value=" 请输入搜索关键词" class="textInput"><input type="submit" value="" class="submiInput"/></p> </div> <div class="boardTitle_text"> <p class="boardTitle_text1">24小时咨询热线</p> <p class="boardTitle_text2">400-6300-966</p> </div> </div> <div class="navigationBar"> <div class="navigationBar_editor"> <a href="#" class="a1">首页</a> <a href="#" class="navigationBarSpeciala">留学国家</a> <a href="#" class="navigationBarSpeciala1">美国</a> <a href="#" class="navigationBarSpeciala1">英国</a> <a href="#" class="navigationBarSpeciala1">澳洲</a> <a href="#" class="navigationBarSpeciala1">加拿大</a> <a class="navigationBarSpeciala2">|</a> <a href="#" class="navigationBarSpeciala">留学学科</a> <a href="#" class="navigationBarSpeciala1">中学</a> <a href="#" class="navigationBarSpeciala1">本科</a> <a href="#" class="navigationBarSpeciala1">硕士</a> <a class="navigationBarSpeciala2">|</a> <a href="#" class="navigationBarSpeciala">留学资讯</a> <a href="#" class="navigationBarSpeciala">课程培训</a> <a href="#" class="navigationBarSpeciala">签证</a> <a href="#" class="navigationBarSpeciala">成功案例</a> <a href="#" class="navigationBarSpeciala">游学</a> </div> </div> <div class="loaction"> <a href="#"class="loaction_a1">首页 ></a><a href="#"class="loaction_a1">美国 ></a><a href="#"class="loaction_a2">华盛顿大学</a> </div> <div class="collogeName"> <div class="collogeName_left"> <img src="img/collogePage/college_img1.png"> </div> <div class="collogeName_middle"> <h5>华盛顿大学</h5> <a href="#">+关注</a> <p class="collogeName_middle_p1">University of Warwick</p> <p class="collogeName_middle_p1">所在城市:<span> England , Coventry</span></p> <p class="collogeName_middle_p2">罗素大学集团,商学院强势,全英最佳校园,入学要求高,教学方法独特,生活国际化,学校设施</p> </div> <div class="collogeName_right"> <a href="#">免费申请</a> </div> </div> <div class="schoolProfile"> <div class="schoolProfile_left"> <h5>学校介绍</h5> <div class="schoolProfile_left_ml"> <p class="schoolProfile_left_p1">学费:<span>15820-16660英镑/学年</span></p> <p class="schoolProfile_left_p1">生活费:<span>8205英镑/学年</span></p> <p class="schoolProfile_left_p1">就业率:<span>77.6% </span></p> <p class="schoolProfile_left_p1">师生比:<span>11.8</span></p> <p class="schoolProfile_left_p2">优势专业:<span>7航空和制造工程学 化学工程 土木工程 计算机科学 电气及电子工程 一般工程</span></p> </div> <h6>地理位置</h6> <p class="schoolContent">剑桥大学(University of Cambridge)位于英格兰的剑桥镇,是英国也是全世界最顶尖的大学之一。剑桥大学和牛津大学(University of Oxford)齐名为英国的两所最优秀的大学,被合称为“Oxbridge”。剑桥大学还是英国名校联盟“罗素集团”和欧洲的大学联盟科大学联大学联英布拉集团的成员。</p> <h6>院校特色</h6> <p class="schoolContent">桥是位于英格兰东部的一个城市,距伦敦以北50公里。剑桥的公路和铁路都十分健全,到伦敦主要机场也很近。市中心到处都是骑自行车的学生,距剑河不远就是英格兰的乡村。剑桥的火车站位于镇的南部,距市中心一英里,步行大约25分钟,坐公交5分钟。到伦敦国王十字车站的快速列车很稳定,大约45分钟可到达,有的停站时间长的列车可能要久一点。</p> <h6>强势专业</h6> <p class="schoolContent">剑桥是位于英格兰东部的一个城市,距伦敦以北50公里。剑桥的公路和铁路都十分健全,到伦敦主要机场也很近。市中心到处都是骑自行车的学生,距剑河不远就是英格兰的乡村。剑桥的火车站位于镇的南部,距市中心一英里,步行大约25分钟,坐公交5分钟。到伦敦国王十字车站的快速列车很稳定,大约45分钟可到达,有的停站时间长的列车可能要久一点。到伦敦国王十字车站的快速列车很稳定,大约45分钟可到达,有的停站时间长的列车可能要久一点。到伦敦国王十字车站的快速列车很稳定,大约45分钟可到达,有的停站时间长的列车可能要久一点。到伦敦国王十字车站的快速列车很稳定,大约45分钟可到达,有的停站时间长的列车可能要久一点。</p> <h6>就业介绍</h6> <p class="schoolContent">剑桥大学成立于1209年,最早是由一批为躲避殴斗而从牛津大学逃离出来的老师建立的。亨利三世国王在1231年授予剑桥教学垄断权。剑桥大学和牛津大学齐名为英国的两所最优秀的大学,被合称为“Oxbridge”,是世界十大名校之一,88位诺贝尔奖得主出自此校(实际来此校工作或执教过的人数超过100名,但剑桥大学官方的数据是根据学生或教师是否拥有学院的Membership/Fellowship而定,所以官方统计数目为88,拥有世界最多的诺贝尔奖)。相对于私立学校仍然比例过大的47%,剑桥大学在1999年还是成功地将国立学校的新生比例提高到了53%。它执行一种尽可能是精英阶层的入学政策,坚持既促进机会均等又不放弃要求成绩优异的原则。在2011年的美国新闻与世界报道和高等教育研究机构QS联合发布的USNEWS-QS世界大学排名中位列全球第1位。现任校长是乐思哲。剑桥大学的辍学率至今仍是全英国最低的(英国为1%,德国为50%左右)。</p> <div class="schoolProfile_left_bottom"> <h5>匹配 课程</h5> <ul> <li class="schoolProfile_left_li1"> <a href="#"><img src="img/collogePage/colloge_img6.png"></a> <p><a href="#">留学6.5分精品冲刺大班</a></p> </li> <li class="schoolProfile_left_li1"><a href="#"> <img src="img/collogePage/colloge_img7.png"></a> <p><a href="#">留学6.5分精品冲刺大</a>班</p> </li> <li class="schoolProfile_left_li1 li2"><a href="#"> <img src="img/collogePage/colloge_img8.png"></a> <p><a href="#">留学6.5分精品冲刺大班</a></p> </li> </ul> </div> </div> <div class="schoolProfile_right"> <h4>美国院校排名</h4> <div class="ul1Box"> <div class="li1Box"> <div class="imgBox"> <img src="img/index/ul_img1.png" class="png"></div> <div class="pBox"> <p class="ulp1">波士顿大学</p> <p class="ulp2">工科硕士</p> </div> <div class="checkBox"> <p><a href="#">查看</a></p> </div> </div> <div class="li1Box"> <div class="imgBox"> <img src="img/index/ul_img2.png" class="png"></div> <div class="pBox"> <p class="ulp1">波士顿大学</p> <p class="ulp2">工科硕士</p> </div> <div class="checkBox"> <p><a href="#">查看</a></p> </div> </div> <div class="li1Box"> <div class="imgBox"> <img src="img/index/ul_img3.png" class="png"></div> <div class="pBox"> <p class="ulp1">波士顿大学</p> <p class="ulp2">工科硕士</p> </div> <div class="checkBox"> <p><a href="#">查看</a></p> </div> </div> <div class="li1Box"> <div class="imgBox"> <img src="img/index/ul_img4.png" class="png"></div> <div class="pBox"> <p class="ulp1">波士顿大学</p> <p class="ulp2">工科硕士</p> </div> <div class="checkBox"> <p><a href="#">查看</a></p> </div> </div> <h5>课程推荐</h5> <div class="souseBox"> <div class="souseBox_left"> <img src="img/collogePage/colloge_img2.png"> </div> <div class="souseBox_right"> <h6><a href="#">留学6.5分精品大班</a></h6> <p><a href="#">招生对象大学英语四级成绩优者英期内需要雅思</a></p> </div> </div> <div class="souseBox"> <div class="souseBox_left"> <img src="img/collogePage/colloge_img3.png"> </div> <div class="souseBox_right"> <h6><a href="#">留学6.5分精品大班</a></h6> <p><a href="#">招生对象大学英语四级成绩优者英期内需要雅思</a></p> </div> </div> <div class="souseBox"> <div class="souseBox_left"> <img src="img/collogePage/colloge_img4.png"> </div> <div class="souseBox_right"> <h6><a href="#">留学6.5分精品大班</a></h6> <p><a href="#">招生对象大学英语四级成绩优者英期内需要雅思</a></p> </div> </div> <div class="souseBox box"> <div class="souseBox_left"> <img src="img/collogePage/colloge_img5.png"> </div> <div class="souseBox_right"> <h6><a href="#">留学6.5分精品大班</a></h6> <p><a href="#">招生对象大学英语四级成绩优者英期内需要雅思</a></p> </div> </div> <h5>风土人情</h5> <ul class="ul2"> <li><a href="#">克拉克大学排名院系专业设置留学申请求</a></li> <li><a href="#">贝勒大学专业留学设置 周环境 排名简介</a></li> <li><a href="#">美国大学地留学理环境 院业设置 排名</a></li> <li><a href="#">克拉克大学排名院系专业设置留学申请求</a></li> <li><a href="#">贝勒大学专业留学设置 周环境 排名简介</a></li> <li><a href="#">美国大学地留学理环境 院业设置 排名</a></li> <li><a href="#">克拉克大学排名院系专业设置留学申请求</a></li> <li><a href="#">克拉克大学排名院系专业设置留学申请求</a></li> </ul> </div> </div> </div> <div class="bottomPlace"> <div class="bottomEditor"> <div class="bottomEditor_left"> <dl> <dt>关于佳航</dt> <dd><a href="#">公司简介</a></dd> <dd><a href="#">联系我们</a></dd> <dd><a href="#">品牌优势</a></dd> <dd><a href="#">我们的服务</a></dd> </dl> <dl> <dt>我们的服务</dt> <dd><a href="#">留学在线咨询</a></dd> <dd><a href="#">专家团</a></dd> <dd><a href="#">咨询服务中心 </a></dd> <dd><a href="#">诚聘英才</a></dd> </dl> <dl> <dt>合作院校</dt> <dd><a href="#">留学在线咨询</a></dd> <dd><a href="#">专家团</a></dd> <dd><a href="#">咨询服务中心 </a></dd> <dd><a href="#">诚聘英才</a></dd> </dl> </div> <div class="bottomEditor_middle"> <div><img src="img/index/Qr_img1.png"><p>佳航国际服务号</p></div> <div><img src="img/index/Qr _img2.png"><p>佳航国际微博号</p></div> </div> <div class="bottomEditor_right"> <span><img src="img/index/phoneNumber.png"></span> <p>24小时咨询热线</p> <a href="#">免费咨询</a> </div> </div> </div> <div class="lastPlace"> <div class="lastEitor"> 京ICP备10218183号 京ICP证100808号 京公网安备 11010802020593号 出版物经营许可证新出发京批字第直130052号 </div> </div> </body> </html> <file_sep>// JavaScript Document window.onload=function(){ function doMove(obj,attr,dir,target,enFn){ clearInterval(obj.timer); var dir = parseInt(getStyle(obj,attr))>target?-dir:dir; obj.timer = setInterval(function(){ var speed = parseInt(getStyle(obj,attr))+ dir; if(speed>target && dir>0 || speed<target && dir<0){ speed = target; } obj.style[attr] = speed+'px'; if(speed == target){ clearInterval(obj.timer); enFn && enFn(); } },30); } function getStyle(obj,attr){ return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr]; } var btnPre=document.getElementById('btnPre'); var btnNext=document.getElementById('btnNext'); var mxul1=document.getElementById('mxul1'); var mxul2=document.getElementById('mxul2'); var mxali1=mxul1.getElementsByTagName('li'); var mxali2=mxul2.getElementsByTagName('li'); mxul1.innerHTML +=mxul1.innerHTML; mxul2.innerHTML +=mxul2.innerHTML; mxul1.style.width=mxali1[0].offsetWidth*(mxali1.length)+'px'; mxul2.style.width=mxali2[0].offsetWidth*(mxali2.length)+'px'; var num=0; var timer=null; function autopay(){ num++ if(num>mxali1.length/2){ mxul1.style.left=0; mxul2.style.left=0; num = 1; } doMove(mxul1,'left',mxali1[0].offsetWidth/40,-num*mxali1[0].offsetWidth) doMove(mxul2,'left',mxali2[0].offsetWidth/40,-num*mxali2[0].offsetWidth) } timer=setInterval(autopay,3000) btnPre.onclick=function(){ clearInterval(timer) autopay(); timer=setInterval(autopay,3000) } btnNext.onclick=function(){ clearInterval(timer) num--; if(num<0){ mxul1.style.left = -mxali1[0].offsetWidth*mxali1.length/2+'px'; mxul2.style.left = -mxali2[0].offsetWidth*mxali2.length/2+'px'; num = mxali1.length/2-1;} doMove(mxul1,'left',mxali1[0].offsetWidth/40,-num*mxali1[0].offsetWidth) doMove(mxul2,'left',mxali2[0].offsetWidth/40,-num*mxali2[0].offsetWidth) timer=setInterval(autopay,3000) } var btnPre1=document.getElementById('actorPre'); var btnNext1=document.getElementById('actorNext'); var actorul1=document.getElementById('actorul1'); var actorul2=document.getElementById('actorul2'); var actorul3=document.getElementById('actorul3'); var actorli1=actorul1.getElementsByTagName('li'); var actorli2=actorul2.getElementsByTagName('li'); var actorli3=actorul3.getElementsByTagName('li'); actorul1.innerHTML +=actorul1.innerHTML; actorul2.innerHTML +=actorul2.innerHTML; actorul3.innerHTML +=actorul3.innerHTML; actorul1.style.height=actorli1[0].offsetHeight*(actorli1.length)+'px'; actorul2.style.height=actorli2[0].offsetHeight*(actorli2.length)+'px'; actorul3.style.height=actorli3[0].offsetHeight*(actorli3.length)+'px'; var nun=0; var timer1=null; function actorPay(){ nun++ if(nun>actorli1.length/2){ actorul1.style.top=0; actorul2.style.top=0; actorul3.style.top=0; nun = 1; } doMove(actorul1,'top',actorli1[0].offsetHeight/40,-nun*actorli1[0].offsetHeight) doMove(actorul2,'top',actorli2[0].offsetHeight/40,-nun*actorli2[0].offsetHeight) doMove(actorul3,'top',actorli3[0].offsetHeight/40,-nun*actorli3[0].offsetHeight) } timer1=setInterval(actorPay,3000) btnPre1.onclick=function(){ clearInterval(timer1) actorPay(); timer1=setInterval(actorPay,3000) } btnNext1.onclick=function(){ clearInterval(timer1) nun--; if(nun<0){ actorul1.style.top = -actorli1[0].offsetHeight*(actorli1.length/2)+'px'; actorul2.style.top = -actorli2[0].offsetHeight*(actorli2.length/2)+'px'; actorul3.style.top = -actorli3[0].offsetHeight*(actorli3.length/2)+'px'; nun = actorli1.length/2-1;} doMove(actorul1,'top',actorli1[0].offsetHeight/40,-nun*actorli1[0].offsetHeight) doMove(actorul2,'top',actorli2[0].offsetHeight/40,-nun*actorli2[0].offsetHeight) doMove(actorul3,'top',actorli3[0].offsetHeight/40,-nun*actorli3[0].offsetHeight) timer1=setInterval(actorPay,3000) } var btnPre2=document.getElementById('actorPre1'); var btnNext2=document.getElementById('actorNext1'); var actorul4=document.getElementById('actorul4'); var actorul5=document.getElementById('actorul5'); var actorul6=document.getElementById('actorul6'); var actorli4=actorul4.getElementsByTagName('li'); var actorli5=actorul5.getElementsByTagName('li'); var actorli6=actorul6.getElementsByTagName('li'); actorul4.innerHTML +=actorul4.innerHTML; actorul5.innerHTML +=actorul5.innerHTML; actorul6.innerHTML +=actorul6.innerHTML; actorul4.style.height=actorli4[0].offsetHeight*(actorli4.length)+'px'; actorul5.style.height=actorli5[0].offsetHeight*(actorli5.length)+'px'; actorul6.style.height=actorli6[0].offsetHeight*(actorli6.length)+'px'; var nmn=0; var timer2=null; function actorPay1(){ nmn++ if(nmn>actorli4.length/2){ actorul4.style.top=0; actorul5.style.top=0; actorul6.style.top=0; nmn = 1; } doMove(actorul4,'top',actorli4[0].offsetHeight/40,-nmn*actorli4[0].offsetHeight) doMove(actorul5,'top',actorli5[0].offsetHeight/40,-nmn*actorli5[0].offsetHeight) doMove(actorul6,'top',actorli6[0].offsetHeight/40,-nmn*actorli6[0].offsetHeight) } timer2=setInterval(actorPay1,3000) btnPre2.onclick=function(){ clearInterval(timer2) actorPay1(); timer2=setInterval(actorPay1,3000) } btnNext2.onclick=function(){ clearInterval(timer2) nmn--; if(nmn<0){ actorul4.style.top = -actorli4[0].offsetHeight*(actorli4.length/2)+'px'; actorul5.style.top = -actorli5[0].offsetHeight*(actorli5.length/2)+'px'; actorul6.style.top = -actorli6[0].offsetHeight*(actorli6.length/2)+'px'; nmn = actorli4.length/2-1;} doMove(actorul4,'top',actorli4[0].offsetHeight/40,-nmn*actorli4[0].offsetHeight) doMove(actorul5,'top',actorli5[0].offsetHeight/40,-nmn*actorli5[0].offsetHeight) doMove(actorul6,'top',actorli6[0].offsetHeight/40,-nmn*actorli6[0].offsetHeight) timer2=setInterval(actorPay1,3000) } }<file_sep>// JavaScript Document $(function(){ $('.menueEditor').find('a').click(function(){ $('.menueEditor').find('a').attr('class','') $(this).attr('class','active'); }) $('.activePl_left').find('li').click(function(){ $('.activePl_left').find('li').attr('class','') $(this).attr('class','click'); }) $('.profile_left').find('li').click(function(){ $('.profile_left').find('li').attr('class','') $(this).attr('class','click1'); }) $('.picBox').find('.imgBox').hover(function(){ $('.picBox').find('.zhezhao').eq($(this).index()).css('display','block'); $('.picBox').find('.aXiqi').eq($(this).index()).css('display','block'); },function(){ $('.picBox').find('.zhezhao').eq($(this).index()).css('display','none'); $('.picBox').find('.aXiqi').eq($(this).index()).css('display','none'); }) $('.roomSty').click(function(){ if($('.roomSty').find('ul').css('display')=='block'){ $('.roomSty').find('ul').css('display','none'); }else{ $('.roomSty').find('ul').css('display','block');} }) $('.roomSty').find('ul').find('li').click(function(event){ $('.roomSty').find('ul').css('display','none'); $('.roomSty input').val($(this).html()) return false; }) $('#litAuo').get(0).innerHTML+=$('#litAuo').get(0).innerHTML; var ulWid=$('#litAuo').find('li').length*$('#litAuo').find('li').outerWidth(); var T=$('#litAuo').find('li').outerWidth(); var num=0; $('.proautoPay').html($('#litAuo').find('li').eq(num-2).html() ) $('#litAuo').css('width',ulWid) $('.nextBtn').click(function(){ num++ if(num>$('#litAuo').find('li').length/2){ num=1 $('#litAuo').css('left',0) } $('#litAuo').stop(true,true).animate( {left:-num*T},500 ) $('.proautoPay').html($('#litAuo').find('li').eq(num-2).html() ) }) $('.preBtn').click(function(){ num-- if(num<0){ num=$('#litAuo').find('li').length/2-1; $('#litAuo').css('left',-ulWid/2) } $('#litAuo').stop(true,true).animate( {left:-num*T},500 ) $('.proautoPay').html($('#litAuo').find('li').eq(num-2).html() ) }) }) <file_sep>// JavaScript Document window.onresize=function() { var windowWidth=document.documentElement.clientWidth; if(windowWidth>720) { windowWidth=720; } document.documentElement.style.fontSize=windowWidth/7.2+'px'; } window.onload=function() { var windowWidth=document.documentElement.clientWidth; if(windowWidth>720) { windowWidth=720; } document.documentElement.style.fontSize=windowWidth/7.2+'px'; }<file_sep>// JavaScript Document $(function() { //微信二维码 $(".wx").hover(function(){ $(".wx_hide").show(); },function(){ $(".wx_hide").hide(); }); //选课区 $(".xkq .title").css("marginLeft",-$(".xkq .title").width()/2); $('.kcxl').find('li').click(function() { $(this).addClass('kcxlactive').siblings().removeClass('kcxlactive'); }) $(".ms").hide(); $(".ms:first").show(); $(".skdd li").each(function(a) { $(this).click(function(){ $(this).addClass("xkactive").siblings().removeClass("xkactive"); $(".ms").hide(); $(".ms").eq(a).show(); $('.xzkc').hide(); $('.xzkc').eq(a).show(); }) }); //网校课程锚点链接 $(".wxkcmd").click(function(){ $("html,body").animate({scrollTop:($(".wxkc").offset().top)},500) }) //面授课程 //序号 $('.ms').each(function() { var xltitl = $(this).find('.xltitle strong'); for(var i=0;i<xltitl.length;i++){ if(i<10) { $(this).find('.xltitle strong:eq('+i+')').text('0'+(i+1)); }else { $(this).find('.xltitle strong:eq('+i+')').text((i+1)); } } }); if( $('.jybjs strong').html() == '' ) { $('.jybjs').css('display','none'); } //表格 $(".mscont tr").each(function(){ $('.mscont tr').find("td:odd").css("background","#f1f6ff"); }) //网校课程 $(".mscont tr").each(function(){ $('.mscont tr').find("td:odd").css("background","#f1f6ff"); $(this).find("td:last-child").css("background","#fff"); }) //教学环境 $('.environment .tabList').find('li').click(function() { $(this).addClass('enactive').siblings().removeClass('enactive'); $('.environment .cont').eq( $(this).index() ).addClass('contactive').siblings().removeClass('contactive'); if( $('.environment .tabList li:last-child').hasClass('enactive') ) { $('.environment .tabList li:last-child').prev().css('marginBottom','12px'); }else{ $('.environment .tabList li:last-child').prev().css('marginBottom',''); } }) //学校地址 $(".Address li").each(function(b) { $(this).click(function(){ $(this).addClass("add_active").siblings().removeClass("add_active"); $(".fb").hide(); $(".fb").eq(b).show(); }) }); $(".fb").find(".xxdz").hide(); $(".fb").find(".xxdz:first").show(); $(".tabFb li").hover(function(){ $(this).addClass('fb_active').siblings().removeClass('fb_active'); var index=$(this).parents(".fb").find(".tabFb li").index(this); $(this).parents(".fb").find(".xxdz").hide(); $(this).parents(".fb").find(".xxdz").eq(index).show(); }) //footer $('#now').html( ( new Date() ).getFullYear() ); //悬浮框 $(".xk").click(function(){ $("html,body").animate({scrollTop:($(".xkq").offset().top-25)},500) }) $(".xfk .top").click(function(){ $("html,body").animate({scrollTop:"0px"},500) }) //弹出层 var num = 0; var timer = null; function popUp() { $('.tkbox').show(); $('.bodyshade').show(); } timer=setInterval(popUp,20000); $('.tkclose,.tkzs').click(function() { $('.tkbox').hide(); $('.bodyshade').hide(); num = num+1; if(num >= 3) { clearInterval(timer); } }) }) <file_sep>// JavaScript Document $(function(){ $('.content ul li').click(function(){ $('.content ul li a').removeClass('li1'); $(this).find('a').addClass('li1'); $('.content .cont_R').removeClass('cont_R_show') $('.content .cont_R').eq($(this).index()).addClass('cont_R_show') }) })<file_sep> // JavaScript Document window.onload=function(){ //main2_bottom /* var m2bc=document.getElementById('m2bc'); var oinps=document.getElementById('inps'); var inps=m2bc.getElementsByTagName('input'); var op=m2bc.getElementsByTagName('p')[0]; var spans=op.getElementsByTagName('span'); var fonts=oinps.getElementsByTagName('font'); // alert( typeof fonts[0]) for(var i=0; i<inps.length;i++){ var sum=0; var num=0; inps[i].index=i; inps[i].onclick=function(){ if(inps[this.index].checked){ inps[this.index].checked==''; sum=sum+1 num=num+parseFloat(fonts[this.index].innerHTML); //alert(fonts[this.index].innerHTML); }else{ v inps[this.index].checked=='checked' sum=sum-1 num=num-parseFloat(fonts[this.index].innerHTML); //alert(num); } spans[0].innerHTML=sum; spans[2].innerHTML=num; }; };*/ ///////////////////////////////////////////////////////////// //////////////////////////////////// /////////////////////////////// //调用传惨 }<file_sep>// JavaScript Document $(function(){ window.onresize=function(){ if($(window).width()>1000){ $('.bannerIamg').css('width',$(window).width()) }else{ $('.bannerIamg').css('width',1000) } } $('#midlleUl').get(0).innerHTML+=$('#midlleUl').get(0).innerHTML; var midlleUl=$('#midlleUl').find('li').length*$('#midlleUl').find('li').outerWidth(); $('.bannerIamg').get(0).innerHTML=$('#midlleUl').find('li').eq(2).get(0).innerHTML; $('#midlleUl').find('li img').eq(2).css('border','2px solid #fff'); $('#midlleUl').find('li').click(function(){ $('#midlleUl').find('li img').css('border','none'); $(this).find('img').css('border','2px solid #fff'); $('.bannerIamg').get(0).innerHTML=$(this).get(0).innerHTML; $('.bannerIamg').find('img').css('border','none'); }) var T=$('#midlleUl').find('li').outerWidth(); var num=0; $('#neBtn').click(function(event){ num++ if(num>$('#midlleUl').find('li').length/2){ num=1 $('#midlleUl').css('left',0) } $('#midlleUl').stop(true,true).animate( {left:-num*T},500 ) $('#midlleUl').find('li img').css('border','none'); $('#midlleUl').find('li img').eq(2+num).css('border','2px solid #fff'); $('.bannerIamg').get(0).innerHTML=$('#midlleUl').find('li').eq(2+num).get(0).innerHTML; $('.bannerIamg').find('img').css('border','none'); return false; }) $('#prBtn').click(function(event){ num-- if(num<0){ num=$('#midlleUl').find('li').length/2-1; $('#midlleUl').css('left',-midlleUl/2) } $('#midlleUl').stop(true,true).animate( {left:-num*T},500 ) $('#midlleUl').find('li img').css('border','none'); $('#midlleUl').find('li img').eq(2+num).css('border','2px solid #fff'); $('.bannerIamg').get(0).innerHTML=$('#midlleUl').find('li').eq(2+num).get(0).innerHTML; $('.bannerIamg').find('img').css('border','none'); return false; }) $('.menueEditor').find('a').click(function(){ $('.menueEditor').find('a').attr('class','') $(this).attr('class','active'); }) $('.enviConte_left ul').find('li').click(function(){ $('.enviConte_left ul').find('li').attr('class','') $(this).attr('class','click1'); }) })<file_sep># MyProjects ## 如何预览 ### 方法 *  复制 htmlpreview.github.com/? 链接放入要预览页面地址栏的最前面 <file_sep>// JavaScript Document $(function(){ //////菜单选项/////////////////////////////////// $('.menuPl').find('a').click(function(){ $('.menuPl').find('a').removeClass('active') $(this).addClass('active'); }) //////轮播图/////////////////////////////////// $('.picInfo_left_ul1').get(0).innerHTML +=$('.picInfo_left_ul1').get(0).innerHTML; var T=$('.picInfo_left_ul1').find('li').outerWidth() var ul1Width=$('.picInfo_left_ul1').find('li').length*$('.picInfo_left_ul1').find('li').outerWidth() $('.picInfo_left_ul1').css('width',ul1Width) var num=0; var timer=null; for(var i=0;i<$('.picInfo_left_ul1').find('li').length/2;i++){ var ali=$('<li></li>') $('.picInfo_left_ul2').append(ali) } function auotoPay(){ if(num>$('.picInfo_left_ul1').find('li').length/2){ num=1; $('.picInfo_left_ul1').css('left',0) } $('.picInfo_left_ul2 li').removeClass('move') if(num>$('.picInfo_left_ul1').find('li').length/2-1){ $('.picInfo_left_ul2 li').eq(0).addClass('move') }else( $('.picInfo_left_ul2 li').eq(num).addClass('move') ) $('.picInfo_left_ul1').stop(true,true).animate( {left:-num*T},1000 ).delay(1000) num++ } auotoPay(num=0); timer=setInterval(auotoPay,2000) $('.picInfo_left_ul2 li').hover(function(){ num=$(this).index(); clearInterval(timer) $('.picInfo_left_ul2 li').removeClass('move') $(this).addClass('move') $('.picInfo_left_ul1').stop(true,true).animate( {left:-$(this).index()*T},1000 ).delay(1000) },function(){ timer=setInterval(auotoPay,2000) }) $('.picInfo_left_ul1 li img').hover(function(){ clearInterval(timer) },function(){ clearInterval(timer) timer=setInterval(auotoPay,2000) }) /////视屏播放///////////////////////// $('.videImg , .playVid').hover(function(){ $('.playVid').show(); },function(){ $('.playVid').hide() }) /////师资介绍轮播图////////////////// $('.autoUl').get(0).innerHTML+=$('.autoUl').get(0).innerHTML; var widthUl=$('.autoUl').find('li').length*$('.autoUl').find('li').outerWidth(); var dir=$('.autoUl').find('li').outerWidth(); var nnm=0; $('.autoUl').css('width',widthUl) $('.teachepeBtn').click(function(){ nnm++ if(nnm>$('.autoUl').find('li').length/2){ nnm=1 $('.autoUl').css('left',0) } $('.autoUl').animate( {left:-nnm*dir},500 ) }) $('.teacheneBtn').click(function(){ nnm-- if(nnm<0){ nnm=$('.autoUl').find('li').length/2-1; $('.autoUl').css('left',-widthUl/2) } $('.autoUl').animate( {left:-nnm*dir},500 ) }) })<file_sep>// JavaScript Document var oTopNav=document.querySelector('.topNav'); var oArrows=document.getElementById('arrows'); var oNav1=document.querySelector('#nav1'); var oShade1=document.getElementById('shade1'); var onOff1=true; oTopNav.onclick=function() { if(onOff1) { oArrows.src='images/iconUp.jpg'; oNav1.style.display='block'; oShade1.style.display='block'; onOff1=false; oShade1.onclick=function() { oArrows.src='images/iconDown.jpg'; oNav1.style.display='none'; oShade1.style.display='none'; onOff1=true; } }else { oArrows.src='images/iconDown.jpg'; oNav1.style.display='none'; oShade1.style.display='none'; onOff1=true; } } $('.icon span').click(function() { $(this).toggleClass('toggle'); }) $('#txt').keydown(function() { $('.qb').hide(); }); $('#txt').keyup(function() { if($('#txt').val()=='') { $('.qb').show(); } }); $('#btn').click(function() { if( $('#txt').val() == '' ) { alert('请输入具体内容!'); return; } var aLi = $('.detail li').eq(0).clone(); aLi.css('display','block'); aLi.insertBefore( $('.detail li').eq(0) ); var now=new Date(); var iMon=now.getMonth()+1; var iDay=now.getDate(); var iHour=now.getHours(); var iMin=now.getMinutes(); iMin=iMin>9?''+iMin:'0'+iMin; iHour=iHour>9?''+iHour:'0'+iHour; iDay=iDay>9?''+iDay:'0'+iDay; iMon=iMon>9?''+iMon:'0'+iMon; var str=iMon+'月'+iDay+'日'+' '+iHour+':'+iMin; aLi.find('.dateline').html('<em></em>'+str); $('.allCom h4').find('span').html( $('.detail li').length-1 ); $('.commentNum').find('i').html( $('.detail li').length-1 ); aLi.find('.detailCom').html( $('#txt').val() ); $('#txt').val(''); $('.qb').show(); aLi.find('.support').click(function() { if( $(this).find('em').attr('class')=='zan1' ) { $(this).find('em').attr('class','zan2'); $(this).find('i').html( parseInt($(this).find('i').html())+1 ); }else{ $(this).find('em').attr('class','zan1'); $(this).find('i').html( parseInt($(this).find('i').html())-1 ); } }); }) <file_sep>// JavaScript Document $(function() { //关闭遮罩 $('#close').click(function() { $('#shadeBox').css('display','none'); }); //锚点链接 $('#nav1').click(function() { $('html,body').animate({scrollTop:$('#title1').offset().top},1000); }); $('#nav2').click(function() { $('html,body').animate({scrollTop:$('#title2').offset().top},1000); }); $('#nav3').click(function() { $('html,body').animate({scrollTop:$('#title3').offset().top},1000); }); $('#nav4').click(function() { $('html,body').animate({scrollTop:$('#title4').offset().top},1000); }); $('.city').find('a').click(function() { $(this).attr('class','active').siblings().attr('class',''); $('.cityBox').find('.addList').eq( $(this).index() ).addClass('show').siblings().removeClass('show'); }); //返回顶部 $('.top').click(function() { $('html,body').animate({scrollTop:'0px'},1000); }); })<file_sep>// JavaScript Document // JavaScript Document /*by offcn_hsk time:2014-05-13*/ $(function(){ /*头部微博显示与隐藏*/ $(".offcn_header_wb").hover(function(){ $(".top_wb_con").show(); },function(){ $(".top_wb_con").hide(); }) $(".offcn_header_wx").hover(function(){ $(".top_wx_con").show(); },function(){ $(".top_wx_con").hide(); }) }) function show_wx(obj) { document.getElementById("wbxx"+obj).style.display=""; document.getElementById("weixb"+obj).className="wei"; } function close_wx(obj) { document.getElementById("wbxx"+obj).style.display="none"; document.getElementById("weixb"+obj).className="weixin"; } /*设为首页 加入收藏*/ function SetHome(obj,vrl){ try{ obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl); NavClickStat(1); } catch(e){ if(window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("抱歉!您的浏览器不支持直接设为首页。请在浏览器地址栏输入“about:config”并回车然后将[signed.applets.codebase_principal_support]设置为“true”,点击“加入收藏”后忽略安全提示,即可设置成功。"); } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage',vrl); } } } function AddFavorite(sURL, sTitle) { try { window.external.addFavorite(sURL, sTitle); } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, ""); } catch (e) { alert("加入收藏失败,请使用Ctrl+D进行添加"); } } }
db49b2547dba6a87fe5e5229c3bee50f98b855c9
[ "JavaScript", "HTML", "Markdown" ]
14
JavaScript
Juncheng210/MyProjects
0a074e279154da116279794ac8035aaeeccbe2d3
ef9ff0a9b8440699f14f4c89a1f24d91d5e944d5
refs/heads/master
<file_sep>import sounddevice as sd print(sd.query_devices())
b3a5c50a8174cf4f5181a729f626ba98c3245923
[ "Python" ]
1
Python
seanD111/FilterFiddler
278b2545b8f038fc5cebd1ed8445b82fd25d6267
14a49c15a3c0606ffd4c3a1fa077f98aad014272
refs/heads/master
<file_sep>#!/bin/bash export PYTHON_VERSION=$1 export PYVER=${1:0:1} export PYTHON_PIP_VERSION=$2 if [ "$PYVER" -eq "2" ]; then FLAGS='--enable-shared --enable-unicode=ucs4' else FLAGS='--enable-loadable-sqlite-extensions --enable-shared --enable-optimizations' fi set -ex \ && buildDeps='tcl-dev tk-dev' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ \ && wget -O python.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ && mkdir -p /usr/src/python \ && tar -xJC /usr/src/python --strip-components=1 -f python.tar.xz \ && rm python.tar.xz \ \ && cd /usr/src/python \ && ./configure --prefix=/usr $FLAGS \ && make -j$(nproc) \ && make install \ && ldconfig \ \ && if [ ! -e /usr/local/bin/pip$PYVER ]; then : \ && wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ && python$PYVER /tmp/get-pip.py "pip==$PYTHON_PIP_VERSION" \ && rm /tmp/get-pip.py \ ; fi \ && pip$PYVER install --no-cache-dir --upgrade --force-reinstall "pip==$PYTHON_PIP_VERSION" \ \ && find /usr/local -depth \ \( \ \( -type d -a -name test -o -name tests \) \ -o \ \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ \) -exec rm -rf '{}' + \ && apt-get purge -y --auto-remove $buildDeps \ && rm -rf /usr/src/python ~/.cache <file_sep>=========== FluidDevOps =========== |release| .. |release| image:: https://img.shields.io/pypi/v/fluiddevops.svg :target: https://pypi.python.org/pypi/fluiddevops/ :alt: Latest version FluidDevOps is a small package which provides some console scripts to make DevOps easier. See directory ``docker`` for more on running Docker containers. Installation ------------ :: python setup.py develop Features -------- - ``python -m fluiddevops.mirror`` or ``fluidmirror`` to setup hg to git mirroring for a group of packages and periodically check for updates :: usage: fluidmirror [-h] [-c CFG] {list,clone,set-remote,pull,push} ... positional arguments: {list,clone,set-remote,pull,push} sub-command list list all configured repositories clone clone all repositories based on config set-remote set remote path in hgrc of all configured repositories pull pull all configured repositories push push all configured repositories sync sync all configured repositories optional arguments: -h, --help show this help message and exit -c CFG, --cfg CFG config file <file_sep>#!/bin/bash crontab -l 2> _old.cron echo '#!/bin/bash' > _mirror.sh cat <<EOF >> _mirror.sh cd $PWD source $VIRTUAL_ENV/bin/activate `which fluidmirror` -c $PWD/mirror.cfg sync EOF chmod +x _mirror.sh echo "*/5 * * * * $PWD/_mirror.sh" > _new.cron cat _old.cron _new.cron | crontab - rm _old.crom _new.cron <file_sep># Building and running Docker containers This repository contains Dockerfiles for various FluidDyn containers. Dockerfiles are text files that contain the instructions for building a Docker image. ## Installation The containers were all built using Docker 1.13.x. Go to https://www.docker.com for information on how to install docker. ## Building and running containers To build a container, run: ```$ make build image=python3-stable``` To launch a container, run: ```$ make run image=python3-stable``` To launch Travis Ubuntu (precise) container for testing Python ```$ make run_travis``` See the Docker documentaion for information on the different docker commands that you can use. ## Docker hub Images of all the containers listed here are available on Docker Hub: https://hub.docker.com/u/fluiddyn. For example, running: ```$ docker pull fluiddyn/python3-stable``` will retrieve the Docker official python 3.6 installation along with extra libraries from Debian Jessie repos and python packages from PyPI required for FluidDyn. ```$ docker run -it fluiddyn/python3-stable /bin/bash``` And the image will be downloaded from Docker Hub if it is not already present on your machine and then run. ## Ingredients Note: Extra libraries (from official Debian Jessie repos) are not the most recent versions. see `apt_requirements.txt`, `requirements.txt` and `requirements_extra.txt` for the list of packages being pre-installed into the Docker images. <file_sep>libfftw3-dev libfftw3-mpi-dev libhdf5-openmpi-dev openmpi-bin libopenblas-dev gfortran emacs vim <file_sep>import argparse import os import sys from .config import read_config, get_repos from .vcs import clone, pull, push, set_remote, sync def _add_arg_repo(parser): parser.add_argument( '-r', '--repo', help='repository to act on, default: "all"', default='all') return parser def _add_arg_branch(parser): parser.add_argument( '-b', '--branch', help='branch to act on, default: "default"', default='default') return parser def get_parser(): parser = argparse.ArgumentParser( prog='fluidmirror', description=( 'works on a specific / all configured repositories (default)') ) parser.add_argument( '-c', '--cfg', help='config file', default='mirror.cfg') subparsers = parser.add_subparsers(help='sub-command') parser_list = subparsers.add_parser( 'list', help='list configuration') parser_list.set_defaults(func=_list) parser_clone = subparsers.add_parser( 'clone', help='hg clone') parser_clone.set_defaults(func=_clone_all) parser_setr = subparsers.add_parser( 'set-remote', help=('set remote (push) path in hgrc')) parser_setr.set_defaults(func=_setr_all) parser_pull = subparsers.add_parser( 'pull', help='hg pull -u') parser_pull.set_defaults(func=_pull_all) parser_push = subparsers.add_parser( 'push', help='hg bookmark && hg push git+...') parser_push.set_defaults(func=_push_all) parser_sync = subparsers.add_parser( 'sync', help='sync: pull and push ') parser_sync.set_defaults(func=_sync_all) for subparser in [parser_list, parser_clone, parser_setr, parser_pull, parser_push, parser_sync]: _add_arg_repo(subparser) for subparser in [parser_push, parser_sync]: _add_arg_branch(subparser) return parser def _list(args): read_config(args.cfg, output=True) def _config(args): config = read_config(args.cfg) dirname = os.path.dirname(args.cfg) if dirname == '': dirname = os.curdir os.chdir(dirname) if config['defaults']['ssh'] != '': hgopts = ' -e "{}" '.format( os.path.expandvars(config['defaults']['ssh'])) else: hgopts = '' return config, hgopts def _all(func, args, key='pull'): config, hgopts = _config(args) if hasattr(args, 'branch'): kwargs = {'branch': args.branch} else: kwargs = {} if args.repo == 'all': for repo in get_repos(config.sections()): func(config['repo:' + repo][key], repo, hgopts=hgopts, **kwargs) else: repo = args.repo func(config['repo:' + repo][key], repo, hgopts=hgopts, **kwargs) _clone_all = lambda args: _all(clone, args) _setr_all = lambda args: _all(set_remote, args, 'push') _pull_all = lambda args: _all(pull, args) _push_all = lambda args: _all(push, args, 'push') def _sync_all(args): config, hgopts = _config(args) if args.repo == 'all': for repo in get_repos(config.sections()): sync(repo, config['repo:' + repo]['pull'], config['repo:' + repo]['push'], hgopts=hgopts, branch=args.branch) else: repo = args.repo sync(repo, config['repo:' + repo]['pull'], config['repo:' + repo]['push'], hgopts=hgopts, branch=args.branch) def main(*args): parser = get_parser() args = parser.parse_args(*args) args.func(args) if __name__ == '__main__': sys.exit(main()) <file_sep>from __future__ import print_function import configparser import sys from os.path import join, exists def get_repos(sections): return [r.split(':')[1] for r in sections if r.startswith('repo')] def read_config(path, output=False): config = configparser.ConfigParser() if not exists(path): raise OSError(path + ' not found') config.read(path) pull_base = config['defaults']['pull_base'] push_base = config['defaults']['push_base'] repos = get_repos(config.sections()) for repo in repos: if output: print('\nrepo:', repo) key = 'repo:' + repo pull = config[key]['pull'] if pull == '': pull = join(pull_base, repo) config.set(key, 'pull', pull) push = config['repo:' + repo]['push'] if push == '': push = join(push_base, repo) config.set(key, 'push', push) if output: print('pull:', pull) print('push:', push) return config if __name__ == '__main__': read_config(sys.argv[1]) <file_sep>FROM ${image} MAINTAINER <NAME> <<EMAIL>> RUN apt-get update RUN apt-get install -y --no-install-recommends libfftw3-mpi-dev RUN apt-get install -y --no-install-recommends libhdf5-openmpi-dev RUN apt-get install -y --no-install-recommends openmpi-bin RUN apt-get install -y --no-install-recommends libopenblas-dev RUN apt-get install -y --no-install-recommends gfortran RUN apt-get install -y --no-install-recommends emacs vim RUN apt-get install -y --no-install-recommends libfftw3-dev RUN rm -rf /var/lib/apt/lists/* RUN groupadd -g 999 appuser && useradd -m -r -u 999 -g appuser -s /bin/bash appuser -s /bin/bash USER appuser ARG HOME=/home/appuser RUN mkdir -p $HOME/opt WORKDIR $HOME/opt RUN echo $USER $HOME $PWD && whoami RUN mkdir -p $HOME/.local/include RUN mkdir -p $HOME/.local/lib RUN ln -s /usr/include/fftw* $HOME/.local/include RUN ln -s /usr/lib/x86_64-linux-gnu/libfftw3* $HOME/.local/lib RUN wget https://bitbucket.org/fluiddyn/fluidfft/raw/default/doc/install/install_p3dfft.sh -O ./install_p3dfft.sh RUN wget https://bitbucket.org/fluiddyn/fluidfft/raw/default/doc/install/install_pfft.sh -O ./install_pfft.sh RUN wget https://bitbucket.org/fluiddyn/fluidfft/raw/default/site.cfg.files/site.cfg.docker -O ~/.fluidfft-site.cfg RUN chmod +x install_p3dfft.sh install_pfft.sh RUN ./install_p3dfft.sh RUN ./install_pfft.sh COPY requirements.txt $PWD RUN ${pip} install --no-cache-dir --user -U -r requirements.txt COPY requirements_extra.txt $PWD RUN ${pip} install --no-cache-dir --user -U -r requirements_extra.txt RUN mkdir -p $HOME/.config/matplotlib RUN echo 'backend : agg' > $HOME/.config/matplotlib/matplotlibrc ENV LD_LIBRARY_PATH=$HOME/.local/lib ENV PATH=$PATH:$HOME/.local/bin ENV CPATH=$CPATH:$HOME/.local/include <file_sep>image ?= python3-stable tag := $(shell date -I'date'| tr -d "[:punct:]") start: systemctl start docker dockermako: python make_files_with_mako.py cleanmako: python -c 'from make_files_with_mako import clean; clean()' build: dockermako docker build -f $(image).Dockerfile -t fluiddyn/$(image) . docker tag fluiddyn/$(image) fluiddyn/$(image):$(tag) build_nocache: dockermako docker build -f $(image).Dockerfile -t fluiddyn/$(image) . --no-cache docker tag fluiddyn/$(image) fluiddyn/$(image):$(tag) onbuild: dockermako docker build -f $(image).onbuild.Dockerfile -t fluiddyn/$(image):onbuild . push: docker push fluiddyn/$(image) run: docker run --restart=always -it fluiddyn/$(image) bash run_travis: docker run -it travisci/ci-python bash -c "su - travis" run_travis_old: docker run -it quay.io/travisci/travis-python bash -c "su - travis" cleancontainers: for cont in $$(docker ps -a | awk 'NR>1{print $$1}'); do docker rm $$cont; done cleanimages: docker rmi -f $$(docker images -qf "dangling=true") cleanall: cleanmako cleancontainers cleanimages <file_sep>from __future__ import print_function import os import subprocess import shlex import configparser def _run(cmd, output=False): print(cmd) cmd = shlex.split(cmd) if output: return subprocess.check_output(cmd).decode('utf8') else: subprocess.call(cmd) def clone(src, dest=None, hgopts=None): if dest is not None and os.path.exists(dest): print('Skipping', dest, ': directory exists!') return _run('hg clone {} {} {}'.format(src, dest, hgopts)) def set_remote(dest, src, hgopts=None): path = os.path.join(src, '.hg', 'hgrc') config = configparser.ConfigParser() config.read(path) if 'git' in dest: dest = 'git+' + dest config.set('paths', 'github', dest) if not config.has_section('extensions'): config.add_section('extensions') config.set('extensions', 'hgext.bookmarks', '') config.set('extensions', 'hggit', '') with open(path, 'w') as configfile: config.write(configfile) os.chdir(src) subprocess.call(['hg', 'paths']) os.chdir('..') def pull(src, dest, update=True, output=False, hgopts=None): os.chdir(dest) cmd = 'hg pull ' + src + hgopts if update: cmd += ' -u' output = _run(cmd, output) os.chdir('..') return output def push(dest, src, hgopts=None, branch='default'): os.chdir(src) print(src) if branch == 'default': _run('hg bookmark -r default master') else: output = _run('hg branches', output=True) if branch in output: output = _run('hg bookmark -r ' + branch + ' branch-' + branch) else: print('Branch', branch, 'is closed or does not exist.') os.chdir('..') return _run('hg push git+' + dest + hgopts) os.chdir('..') def sync(src, pull_repo, push_repo, hgopts=None, branch='default'): output = pull(pull_repo, src, output=True, hgopts=hgopts) if all([string not in output for string in ['no changes', 'abort']]): push(push_repo, src, hgopts=hgopts, branch=branch) <file_sep>import os from os.path import join from datetime import datetime from mako.template import Template here = os.path.abspath(os.path.dirname(__file__)) files = { join(here, 'python2-stable.Dockerfile'): dict( pip='pip2', image='python:2.7'), join(here, 'python3-stable.Dockerfile'): dict( pip='pip3', image='python:3.6-stretch'), } def modification_date(filename): mtime = os.path.getmtime(filename) return datetime.fromtimestamp(mtime) def make_file(template, filepath, **kwargs): if not os.path.exists(filepath): hastomake = True else: if modification_date(filepath) < modification_date(template): hastomake = True else: hastomake = False if hastomake: print(template, '->', filepath) with open(filepath, 'w') as f: template_mako = Template(filename=template) f.write(template_mako.render(**kwargs)) def clean(): for filepath in files: os.remove(filepath) if __name__ == '__main__': template = join(here, 'template_mako.Dockerfile') for filepath, kwargs in files.items(): make_file(template, filepath, **kwargs) <file_sep>from setuptools import setup, find_packages from runpy import run_path import os here = os.path.abspath(os.path.dirname(__file__)) d = run_path('fluiddevops/_version.py') __version__ = d['__version__'] # Get the long description from the relevant file with open(os.path.join(here, 'README.rst')) as f: long_description = f.read() lines = long_description.splitlines(True) long_description = ''.join(lines[10:]) # Get the development status from the version string if 'a' in __version__: devstatus = 'Development Status :: 3 - Alpha' elif 'b' in __version__: devstatus = 'Development Status :: 4 - Beta' else: devstatus = 'Development Status :: 5 - Production/Stable' setup( name="fluiddevops", version=__version__, packages=find_packages(exclude=['docker', 'examples']), install_requires=['configparser', 'fluiddyn', 'py-cpuinfo'], extras_requires={ 'hg': ['mercurial', 'hg-git'], # 'mirror_bb': open( # 'fluiddevops/mirror_bb/webhook-listener/REQUIREMENTS.txt').read().splitlines()}, }, entry_points={ 'console_scripts': ['fluidmirror = fluiddevops.mirror:main', ]}, author='<NAME>', author_email='<EMAIL>', description="Console scripts to make DevOps easier.", long_description=long_description, license="CeCILL", keywords='DevOps, continuous integration, testing', url="http://bitbucket.org/gfdyn/fluiddevops", classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable devstatus, 'Intended Audience :: Science/Research', 'Intended Audience :: Education', 'Topic :: Scientific/Engineering', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', # actually CeCILL License (GPL compatible license for French laws) # # Specify the Python versions you support here. In particular, # ensure that you indicate whether you support Python 2, # Python 3 or both. 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3'], ) <file_sep>#!/bin/bash fluidmirror clone fluidmirror set-remote <file_sep> help: @echo "targets: develop and install" develop: python setup.py develop install: python setup.py install <file_sep>future tox pyfftw mpi4py h5py h5netcdf ipython pillow scikit-image mako imageio pandas <file_sep>FROM python:2.7 MAINTAINER <NAME> <<EMAIL>> RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY apt_requirements.txt /usr/src/app/ RUN apt-get update RUN apt-get install -y --no-install-recommends $(grep -vE "^\s*#" apt_requirements.txt | tr "\n" " ") # RUN apt-get install -y --no-install-recommends python python-pip python-dev # RUN ./install_python.sh 3.6.0 9.0.1 ENV PYTHON_VERSION 3.6.0 ENV PYVER 3 ENV PYTHON_PIP_VERSION 9.0.1 RUN set -ex \ && if [ "$PYVER" -eq "2" ]; then \ FLAGS='--enable-shared --enable-unicode=ucs4' \ ; else \ FLAGS='--enable-loadable-sqlite-extensions --enable-shared --enable-optimizations' \ ; fi \ && buildDeps='tcl-dev tk-dev' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ \ && wget -O python.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ && mkdir -p /usr/src/python \ && tar -xJC /usr/src/python --strip-components=1 -f python.tar.xz \ && rm python.tar.xz \ \ && cd /usr/src/python \ && ./configure --prefix=/usr $FLAGS \ && make -j$(nproc) \ && make install \ && ldconfig \ \ && if [ ! -e /usr/local/bin/pip$PYVER ]; then : \ && wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ && python$PYVER /tmp/get-pip.py "pip==$PYTHON_PIP_VERSION" \ && rm /tmp/get-pip.py \ ; fi \ && pip$PYVER install --no-cache-dir --upgrade --force-reinstall "pip==$PYTHON_PIP_VERSION" \ \ && find /usr/local -depth \ \( \ \( -type d -a -name test -o -name tests \) \ -o \ \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ \) -exec rm -rf '{}' + \ && apt-get purge -y --auto-remove $buildDeps \ && rm -rf /usr/src/python ~/.cache RUN rm -rf /var/lib/apt/lists/* COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -U -r requirements.txt RUN pip3 install --no-cache-dir -U -r requirements.txt COPY requirements_extra.txt /usr/src/app/ RUN pip install --no-cache-dir -U -r requirements_extra.txt RUN pip3 install --no-cache-dir -U -r requirements_extra.txt COPY . /usr/src/app RUN mkdir -p /root/.config/matplotlib \ && echo 'backend : agg' > /root/.config/matplotlib/matplotlibrc <file_sep>#!/usr/bin/env python '''Python script to run `fluidmirror sync` intermittently Usage ----- nohup python -u mirror_launch.py > ~/.fluiddyn/mirror.log 2>&1 & ''' from __future__ import print_function import sched import time from datetime import datetime from random import random from fluiddevops.mirror import main s = sched.scheduler(time.time, time.sleep) every = 3 * 60 * 60 # seconds def job(): rnd_max = every * 0.1 rnd_delay = 2 * (random() - 0.5) * rnd_max print( 'fluidmirror sync run once in {} and run every {} +/- {} seconds'.format( rnd_delay, every, rnd_max)) s.enter(rnd_delay * 1, 1, main, [['sync']]) s.enter(rnd_delay * 2, 1, main, [['sync', '-b', 'dev']]) while True: print('Time: ', datetime.fromtimestamp(time.time())) rnd_delay = 2 * (random() - 0.5) * rnd_max s.enter(every + rnd_delay * 1, 1, main, [['sync']]) s.enter(every + rnd_delay * 2, 1, main, [['sync', '-b', 'dev']]) s.run() if __name__ == '__main__': job() <file_sep>numpy matplotlib scipy psutil <file_sep>__version__ = '0.0.0b3'
385c11666db7f2d9560cfd5625d9edb89817a7b1
[ "reStructuredText", "Markdown", "Makefile", "Python", "Text", "Dockerfile", "Shell" ]
19
Shell
fluiddyn/fluiddevops
4708c5d9088c7fdc0f6356e7dc5a5c5f28fa69ee
e72db8d47d89e5987e7d2fa25074807dbf9fffbb
refs/heads/master
<repo_name>sripathyfication/cricls<file_sep>/CricShell.py from prettytable import PrettyTable from cricli import * import datetime import sys, cmd, os class CricShell(cmd.Cmd): intro = "\n Welcome to CricShell. (Command line tool for cricket scores. Type ? or help for commands) \n" prompt = 'cricShell >' main_header = " CricShell - Cricket on the command line, 2017" def create_cric_instance(self): self.cric_inst = Cricket() def do_list(self,arg): ''' Fetch the current ongoing international matches ''' current_matches = self.cric_inst.get_ongoing_matches() print "\n\t " + self.main_header table = PrettyTable(["Match-Id","Date","Team-1","Team-2"]) table.align = "l" for match in current_matches: date = datetime.datetime.strptime(match['date'],"%Y-%m-%dT%H:%M:%S.%fZ") date_new = date.strftime("%d-%m-%Y") table.add_row([match['unique_id'],date_new,match['team-1'],match['team-2']]) print table def do_watch(self,arg): ''' Watch for updates on a match continuously unless interrupted Usage: watch <match-id> ''' print "Not supported" def do_score(self,arg): '''Get scores for match id : Usage: score <match-id> ''' score = self.cric_inst.get_score(int(arg)) if score['matchStarted'] is True: print "\n\t\t " + self.main_header table = PrettyTable(["Match-Id","Score","Team-1","Team-2","State"]) table.align = "l" table.add_row([int(arg),score['score'],score['team-1'],score['team-2'],score['stat']]) print table elif score['matchStarted'] is False and score['score']: print "\n\t\t " + self.main_header table = PrettyTable(["Match-Id","Score","Team-1","Team-2","State"]) table.align = "l" table.add_row([int(arg),score['score'],score['team-1'],score['team-2'],score['stat']]) print table else: print "\n\t" + self.main_header table = PrettyTable(["Match-Id","Team-1","Team-2","State"]) table.add_row([int(arg),score['team-1'],score['team-2'],'Match not started yet.']) print table def do_stop(self, arg): ''' Stop watching for updates to match-id ''' print "Not supported" def do_help(self, arg): print "\n\t\t ==== CricShell Help Menu ==== " print "\tlist --- List all ongoing international cricket matches" print "\tscore --- Fetch the score for match <match-id>" print "\twatch --- Watch for updates to match <match-id>" print "\tstop --- Stop watching for updates to match <match-id>" print "\tclear --- Clear screen." print "\texit --- Exit cricShell. Are you sure you want to go to espncricinfo? " def do_clear(self,arg): os.system('clear') def do_exit(self,arg): ''' Quit CricShell ''' print " Thanks for using CricShell" sys.exit(0) if __name__ == '__main__': cri = CricShell() cri.create_cric_instance() cri.cmdloop() <file_sep>/cricli.py #!/usr/local/bin/python import requests import json import argparse import pprint import datetime from time import sleep from collections import defaultdict # Fetches class Cricket(): def __init__(self): self.api_key = {'apikey':'<KEY>'} self.score_data = {} self.list_of_matches = [] # a list of dictionaries self.match_url = 'http://cricapi.com/api/matches/' self.score_url = 'http://cricapi.com/api/cricketScore/' self.collect_matches() def store_matches(self,match_data): ''' Store match information for retrieval later on ''' index = 0 # match_data is a dictionary of dictionaries for key,matches in match_data.iteritems(): if key == 'matches': # extract each match and put it in a list_of_matches for match in matches: self.list_of_matches.append(match) # Creates a list of matches keyed. def collect_matches(self): r = requests.post(self.match_url,self.api_key) matches = r.json() self.store_matches(matches) # Creates a dictionary of match scores keyed on match id.. def get_score(self,match_id): data = {} data['unique_id'] = match_id data['apikey'] = self.api_key['apikey'] r = requests.post(self.score_url,data) score_data = r.json() return score_data def get_total_matches(self): return len(self.list_of_matches) def get_total_ongoing_matches(self): # For each match in list_of_matches # If the squad field is true, then count that # against total ongoing matches. _ongoing_match_count = 0 for match in self.list_of_matches: for key,value in match.iteritems(): if key == 'squad': if value == True: _ongoing_match_count = _ongoing_match_count +1 return _ongoing_match_count def get_ongoing_matches(self): ongoing_matches = [] for match in self.list_of_matches: for key, value in match.iteritems(): if key == 'squad': if value == True: ongoing_matches.append(match) return ongoing_matches def dump_all(self): for match in self.list_of_matches: print match #Test Driver if __name__=='__main__': #spawn_workers_and_do_work() crick = Cricket() crick.dump_all() print "Total cricket matches: " +str(crick.get_total_matches()) print "Total ongoing cricket matches: " +str(crick.get_total_ongoing_matches())
1058607b27b6a7ba477d87fd225d589870917b2c
[ "Python" ]
2
Python
sripathyfication/cricls
2bb9347a17f6d3d0475a8839d029e19c748c95ef
7025d4a5341dedab2c652f9d43c0a80db524b98e
refs/heads/master
<repo_name>Khon123/lht<file_sep>/app/Http/Controllers/frontend/SendMailController.php <?php namespace App\Http\Controllers\frontend; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class SendMailController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Send email to gmail. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function sendMail(Request $request) { $datas = array( 'email' => $request->email, 'phone' => $request->phone, 'name' => $request->name, 'bodyMessage' => $request->message, ); Mail::send('Email.contact', $datas, function($message) use ($datas){ $message->to('<EMAIL>'); $message->from($datas['email']); }); // check for can not be send. if(Mail::failures()){ return redirect('/contact')->with('message', 'Your Mail can not send, please try again!')->with('type', 'danger'); } return redirect('/contact')->with('message', 'Your Mail sent Successfully!')->with('type', 'success'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Http/Controllers/backend/AboutController.php <?php namespace App\Http\Controllers\backend; use App\About; use App\Article; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AboutController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'About'; Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['abouts'] = About::where('lang', '=', $lang)->orderBy('created_at', 'desc')->get(); return view('backpack::abouts.about', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($id) { $about = About::find($id); return Response()->json($about); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $home = About::find($id); $home->title = $request->title; if($request->detial == null){ return redirect(config('backpack.base.route_prefix', 'admin').'/about')->with('message', 'detial can not be blank!')->with('type', 'danger'); } $home->detial = $request->detial; $home->status = $request->status; $home->updated_by = auth::id(); $home->save(); return redirect(config('backpack.base.route_prefix', 'admin').'/about'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/routes/web.php <?php use App\User; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Input; /* |-------------------------------------------------------------------------- | 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('/', function () { // return view('welcome'); // }); //Route article Route::group(['prefix' => '/admin/menu'], function () { Route::get('/', 'backend\ArticleController@index'); Route::get('/{id?}', 'backend\ArticleController@get'); Route::post('/{id?}', 'backend\ArticleController@update'); }); //Route Home Route::group(['prefix' => '/admin/home'], function(){ Route::get('/', 'backend\HomeController@view'); Route::get('/{id?}', 'backend\HomeController@get'); Route::post('/{id?}', 'backend\HomeController@update'); }); //Route About Route::group(['prefix' => '/admin/about'], function(){ Route::get('/', 'backend\AboutController@view'); Route::get('/{id?}', 'backend\AboutController@get'); Route::post('/{id?}', 'backend\AboutController@update'); }); //Route slider Route::group(['prefix' => '/admin/slide'], function () { Route::get('/', 'backend\SliderController@view'); Route::get('/{slide_id?}', 'backend\SliderController@get'); Route::post('/', 'backend\SliderController@store'); Route::post('/{slide_id?}', 'backend\SliderController@update'); Route::delete('/{slide_id?}', 'backend\SliderController@destroy'); }); //Route company Route::group(['prefix' => '/admin/company'], function () { Route::get('/', 'backend\CompanyController@view'); Route::get('/{id?}', 'backend\CompanyController@get'); Route::post('/', 'backend\CompanyController@store'); Route::post('/{id?}', 'backend\CompanyController@update'); Route::delete('/{id?}', 'backend\CompanyController@destroy'); }); //Route sub company Route::group(['prefix' => '/admin/subcompany'], function(){ Route::get('/', 'backend\SubCompanyController@view'); Route::get('/{id?}', 'backend\SubCompanyController@get'); Route::post('/{id?}', 'backend\SubCompanyController@update'); }); // Route team Route::group(['prefix' => '/admin/team'], function () { Route::get('/', 'backend\EmployeeController@view'); Route::get('/{employee_id?}', 'backend\EmployeeController@get'); Route::post('/', 'backend\EmployeeController@store'); Route::post('/{employee_id?}', 'backend\EmployeeController@update'); Route::delete('/{employee_id?}', 'backend\EmployeeController@destroy'); }); //Route Event Route::group(['prefix' => '/admin/event'], function(){ Route::get('/', 'backend\EventController@view'); Route::get('/{event_id?}', 'backend\EventController@edit'); Route::post('/', 'backend\EventController@store'); Route::post('/{event_id?}', 'backend\EventController@update'); Route::delete('/{event_id?}', 'backend\EventController@destroy'); }); // Route Trading Route::group(['prefix' => '/admin/trading'], function(){ Route::get('/', 'backend\TradingController@view'); Route::get('/{id?}', 'backend\TradingController@get'); Route::post('/{id?}', 'backend\TradingController@update'); }); // Route career Route::group(['prefix' => '/admin/career'], function(){ Route::get('/', 'backend\CareerController@view'); Route::get('/{career_id?}', 'backend\CareerController@edit'); Route::post('/', 'backend\CareerController@store'); Route::post('/{career_id?}', 'backend\CareerController@update'); Route::delete('/{career_id?}', 'backend\CareerController@destroy'); }); // Route user Route::group(['prefix' => '/admin/user'], function(){ Route::get('/', 'backend\UserController@view'); Route::get('/{id?}', 'backend\UserController@edit'); Route::post('/{id?}', 'backend\UserController@update'); }); Route::post('/admin/change-password', 'backend\ChangePasswordController@changePassword'); // ======================================================================== // Route FrontEnd // Route Home Route::get('/', 'frontend\HomeController@getIndex'); // Route About Route::get('/about', 'frontend\AboutController@getIndex'); // Route Company Route::group(['prefix' => '/group-company'], function(){ Route::get('/', 'frontend\GroupCompanyController@getIndex'); // Route Sub Company Route::get('/sub-company/{id?}', 'frontend\GroupCompanyController@getSubCompany'); }); // Route Team Route::get('/team', 'frontend\TeamController@getIndex'); Route::get('/team/{id?}', 'frontend\TeamController@showTeam'); // Route Event Route::get('/event', 'frontend\EventFrontendController@getIndex'); Route::get('/event/{id?}', 'frontend\EventFrontendController@showEvent'); // Route Trading Route::get('/trading', 'frontend\TradingController@getIndex'); // Route Career Route::get('/career', 'frontend\CareerFrontendController@getIndex'); Route::get('/career/{id?}', 'frontend\CareerFrontendController@showCareer'); // Route Contact Us Route::get('/contact', 'frontend\ContactController@getIndex'); Route::post('/contact', 'frontend\SendMailController@sendMail'); <file_sep>/app/Http/Controllers/backend/HomeController.php <?php namespace App\Http\Controllers\backend; use App\Home; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Database\Eloquent\paginate; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Validator; use Intervention\Image\Facades\Image; class HomeController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Home'; //set title page Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['homes'] = Home::where('lang', '=', $lang)->orderBy('created_at', 'desc')->get(); return view('backpack::homes.home', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($id) { $home = Home::find($id); return Response()->json($home); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $home = Home::find($id); $home->title = $request->title; $home->titleDetial = $request->titleDetial; if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $home->image = $filename; } } $home->titleImage = $request->titleImage; $home->imageDetial = $request->imageDetial; $home->status = $request->status; $home->updated_by = auth::id(); $home->save(); return redirect(config('backpack.base.route_prefix', 'admin').'/home'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/database/seeds/ArticlesTableSeeder.php <?php use Carbon\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class ArticlesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $articles = array( array( 'name' => 'Home', 'alias' => 'home', 'id_table' => '1', 'lang' => 'en', ), array( 'name' => 'ទំព័រដើម', 'alias' => 'home', 'id_table' => '1', 'lang' => 'kh', ), array( 'name' => 'About Us', 'alias' => 'about', 'id_table' => '2', 'lang' => 'en', ), array( 'name' => 'អំពីយើងខ្ញុំ', 'alias' => 'about', 'id_table' => '2', 'lang' => 'kh', ), array( 'name' => 'Group Company', 'alias' => 'group-company', 'id_table' => '3', 'lang' => 'en', ), array( 'name' => 'ក្រុមហ៊ុនជាដៃគូ', 'alias' => 'group-company', 'id_table' => '3', 'lang' => 'kh', ), array( 'name' => 'Our Team', 'alias' => 'team', 'id_table' => '4', 'lang' => 'en', ), array( 'name' => 'ក្រុមការងាររបស់យើង', 'alias' => 'team', 'id_table' => '4', 'lang' => 'kh', ), array( 'name' => 'Event', 'alias' => 'event', 'id_table' => '5', 'lang' => 'en', ), array( 'name' => 'ព្រឹតិការណ៏', 'alias' => 'event', 'id_table' => '5', 'lang' => 'kh', ), array( 'name' => 'Trading', 'alias' => 'trading', 'id_table' => '6', 'lang' => 'en', ), array( 'name' => 'ពាណិជ្ជកម្ម', 'alias' => 'trading', 'id_table' => '6', 'lang' => 'kh', ), array( 'name' => 'Career', 'alias' => 'career', 'id_table' => '7', 'lang' => 'en', ), array( 'name' => 'កាងារ', 'alias' => 'career', 'id_table' => '7', 'lang' => 'kh', ), array( 'name' => 'Contact Us', 'alias' => 'contact', 'id_table' => '8', 'lang' => 'en', ), array( 'name' => 'ទំនាក់ទំនង', 'alias' => 'contact', 'id_table' => '8', 'lang' => 'kh', ), ); foreach ($articles as $key => $article) { DB::table('articles')->insert([ 'id_table' => $article['id_table'], 'name' => $article['name'], 'alias' => $article['alias'], 'lang' => $article['lang'], 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]); } } } <file_sep>/app/Http/Controllers/backend/CompanyController.php <?php namespace App\Http\Controllers\backend; use App\Company; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Validator; class CompanyController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Company'; // check Language Language::checkLang($request->lang); // get Language $lang = Language::getTitleLang(); $this->datas['datas'] = Company::where('lang', '=', $lang)->orderBy('created_at', 'desc')->paginate(10); return view('backpack::company.company', $this->datas); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { /*validation image*/ $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $listLang = config('app.locales'); $id_table = Company::max('id_table')+1; $filename = ''; foreach ($listLang as $key => $value) { $company = new Company(); if($key =='kh'){ $company->image = $filename; } if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $company->image = $filename; } } $company->id_table = $id_table; $company->company_name = $request->company_name; $company->url = $request->url; $company->description = $request->description; $company->status = $request->status; $company->lang = $key; $company->created_by = auth::id(); $company->updated_by = auth::id(); $company->save(); } return redirect(config('backpack.base.route_prefix', 'admin').'/company'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($id) { $company = Company::find($id); return Response()->json($company); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $company = Company::find($id); $company->company_name = $request->company_name; $company->url = $request->url; if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $company->image = $filename; } } $company->description = $request->description; $company->status = $request->status; $company->updated_by = auth::id(); $company->save(); return redirect(config('backpack.base.route_prefix', 'admin').'/company'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($company_id) { $company = Company::where('id_table', '=', $company_id)->delete(); return response()->json($company); } } <file_sep>/app/Http/Controllers/backend/TradingController.php <?php namespace App\Http\Controllers\backend; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use App\Trading; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class TradingController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Trading'; Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['tradings'] = Trading::where('lang', '=', $lang)->get(); return view('backpack::tradings.trading', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($id) { $trading = Trading::find($id); return Response()->json($trading); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $trading = Trading::find($id); $trading->title = $request->title; if($request->description == null){ return redirect(url(config('backpack.base.route_prefix', 'admin').'/trading'))->with('message', 'Caption can not be blank!')->with('type', 'danger'); } $trading->description = $request->description; $trading->status = $request->status; $trading->updated_by = auth::id(); $trading->save(); return redirect(url(config('backpack.base.route_prefix', 'admin').'/trading')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/database/seeds/SubCompanyContentTableSeeder.php <?php use Carbon\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class SubCompanyContentTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $subCompanies = array( array( 'id_table' => '1', 'name' => 'Carolee', 'alias' => 'carolee', 'image' => 'spasalon.jpg', 'url' => 'www.Carolee.com', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'lang' => 'en', ), array( 'id_table' => '1', 'name' => 'Carolee', 'alias' => 'carolee', 'image' => 'spasalon.jpg', 'url' => 'www.Carolee.com', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'lang' => 'kh', ), array( 'id_table' => '2', 'name' => 'Tsubaki', 'alias' => 'tsubaki', 'image' => 'spasalon.jpg', 'url' => 'www.Tsubaki.com', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'lang' => 'en', ), array( 'id_table' => '2', 'name' => 'Tsubaki', 'alias' => 'tsubaki', 'image' => 'spasalon.jpg', 'url' => 'www.Tsubaki.com', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'lang' => 'kh', ), array( 'id_table' => '3', 'name' => 'Aqualabal', 'alias' => 'aqualabal', 'image' => 'spasalon.jpg', 'url' => 'www.Aqualabal.com', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'lang' => 'en', ), array( 'id_table' => '3', 'name' => 'Aqualabal', 'alias' => 'aqualabal', 'image' => 'spasalon.jpg', 'url' => 'www.Aqualabal.com', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'lang' => 'kh', ), ); foreach ($subCompanies as $key => $row) { DB::table('sub_companies')->insert([ 'id_table' => $row['id_table'], 'name' => $row['name'], 'alias' => $row['alias'], 'image' => $row['image'], 'url' => $row['url'], 'detial' => $row['detial'], 'lang' => $row['lang'], 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]); } } } <file_sep>/app/Http/Controllers/backend/CareerController.php <?php namespace App\Http\Controllers\backend; use App\Career; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Validator; use Intervention\Image\Facades\Image; class CareerController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Career'; Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['datas'] = Career::where('lang', '=', $lang)->orderBy('created_at', 'desc')->paginate(10); return view('backpack::careers.career', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { /*validation image*/ $validator = Validator::make($request->all(), [ 'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $listLang = config('app.locales'); $id_table = Career::max('id_table')+1; $filename = ''; foreach ($listLang as $key => $value) { $career = new Career(); /*check has file and validation image */ if($validator->passes()){ if($request->hasFile("image")){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $career->image = $filename; } } if($key =='kh'){ $career->image = $filename; } $career->id_table = $id_table; if($request->job_title == null){ return redirect(url(config('backpack.base.route_prefix', 'admin').'/career'))->with('message', 'Job title can not be blank!, please try again')->with('type', 'danger'); } $career->job_title = $request->job_title; $career->job_description = $request->job_description; $career->job_requirement = $request->job_requirement; $career->post_date = $request->post_date; $career->close_date = $request->close_date; $career->status = $request->status; $career->lang = $key; $career->created_by = auth::id(); $career->updated_by = auth::id(); $career->save(); } return redirect(url(config('backpack.base.route_prefix', 'admin').'/career')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($career_id) { $career = Career::find($career_id); return Response()->json($career); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $career = Career::find($id); /*validation image*/ $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); /*check has file and validation image */ if($request->hasFile("image")){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $career->image = $filename; } } $career->job_title = $request->job_title; $career->job_description = $request->job_description; $career->job_requirement = $request->job_requirement; $career->post_date = $request->post_date; $career->close_date = $request->close_date; $career->status = $request->status; $career->updated_by = auth::id(); $career->save(); return redirect(url(config('backpack.base.route_prefix', 'admin').'/career')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($career_id) { $career = Career::where('id_table', '=', $career_id)->delete(); return response()->json($career); } } <file_sep>/app/Http/Controllers/backend/EventController.php <?php namespace App\Http\Controllers\backend; use App\Event; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Validator; use Intervention\Image\Facades\Image; class EventController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Event'; // check Language Language::checkLang($request->lang); // get language $lang = Language::getTitleLang(); $this->datas['datas'] = Event::where('lang', '=', $lang)->orderBy('created_at', 'desc')->paginate(10); return view('backpack::events.event', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { /*validation image*/ $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $listLang = config('app.locales'); $id_table = Event::max('id_table')+1; $filename = ''; foreach ($listLang as $key => $value) { $event = new Event(); /*check has file and validation image */ if($key =='kh'){ $event->image = $filename; } if($request->hasFile("image")){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $event->image = $filename; } } $event->id_table = $id_table; $event->title = $request->title; $event->event_date = $request->event_date; $event->description = $request->description; $event->status = $request->status; $event->lang = $key; $event->created_by = Auth::id(); $event->updated_by = Auth::id(); $event->save(); } return redirect(url(config('backpack.base.route_prefix', 'admin').'/event')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($event_id) { $event = Event::find($event_id); return Response()->Json($event); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $event_id) { $event = Event::find($event_id); /*validation image*/ $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); /*check has file and validation image */ if($request->hasFile("image")){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $event->image = $filename; } } $event->title = $request->title; $event->event_date = $request->event_date; $event->description = $request->description; $event->status = $request->status; $event->updated_by = Auth::id(); $event->save(); return redirect(url(config('backpack.base.route_prefix', 'admin').'/event')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($event_id) { $event = Event::where('id_table', '=', $event_id)->delete(); return Response()->Json($event); } } <file_sep>/app/Http/Controllers/backend/ArticleController.php <?php namespace App\Http\Controllers\backend; use App\Article; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class ArticleController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $this->datas['title'] = 'Menu'; // set the page title // check language Language::checkLang($request->lang); // get title lang $lang = Language::getTitleLang(); $article = new Article(); $this->datas['menus'] = $article->where('lang', '=', $lang)->get(); return view('backpack::articles.article', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($id) { $article = Article::find($id); return Response()->json($article); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $article = Article::find($id); $article->name = $request->name; $article->description = $request->description; $article->status = $request->status; $article->updated_by = auth::id(); $article->save(); return redirect(config('backpack.base.route_prefix', 'admin').'/menu'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Http/Controllers/backend/SliderController.php <?php namespace App\Http\Controllers\backend; use App\Article; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use App\Slider; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Image; use Validator; class SliderController extends Controller { /** *The information we send to the view *@var array */ protected $datas = []; /** /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Slider'; $slide = new Slider(); $article = new Article(); // check Language Language::checkLang($request->lang); // get Language $lang = Language::getTitleLang(); $this->datas['datas'] = $slide->where('lang', '=', $lang)->orderBy('created_at', 'desc')->paginate(10); $this->datas['articles']=$article->whereIn('id_table', [1,2,6])->where('lang', '=', 'en')->get(); return view('backpack::slides.slide', $this->datas ); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { /* validation image; */ $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $listLang = config('app.locales'); $id_table = Slider::max('id_table')+1; $filename = ''; foreach ($listLang as $key => $value) { $slide = new Slider(); $slide->id_table = $id_table; $slide->article_id = $request->article_id; if($key =='kh'){ $slide->image = $filename; } if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $slide->image = $filename; } } $slide->detial = $request->detial; $slide->status = $request->status; $slide->lang = $key; $slide->created_by = auth::id(); $slide->updated_by = auth::id(); $slide->save(); } return redirect(url(config('backpack.base.route_prefix', 'admin').'/slide')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($slide_id) { $slide = Slider::find($slide_id); return Response()->json($slide); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $slide_id) { $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $slide = Slider::find($slide_id); if( Language::getTitleLang()== 'en' ){ $slide->article_id = $request->article_id; } if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $slide->image = $filename; } } $slide->detial = $request->detial; $slide->status = $request->status; $slide->updated_by = auth::id(); $slide->save(); $update = ['article_id' => $request->article_id]; DB::table('sliders')->where('id' ,'=', $slide_id+1)->update($update); return redirect(url(config('backpack.base.route_prefix', 'admin').'/slide')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($slide_id) { $slide = Slider::where('id_table', '=', $slide_id)->delete(); return response()->json($slide); } } <file_sep>/app/Http/Controllers/frontend/GroupCompanyController.php <?php namespace App\Http\Controllers\frontend; use App\Article; use App\Company; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use App\SubCompany; use Illuminate\Http\Request; class GroupCompanyController extends Controller { protected $datas = []; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getIndex(Request $request) { Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['menu'] = Article::where('lang', '=', $lang)->get();//get menu to page group company; $this->datas['subCompanies'] = SubCompany::where([['lang', '=', $lang], ['status', '=', 'Enabled']])->get();//get sub company to page group company; $this->datas['companys'] = Company::where([['lang', '=', $lang], ['status', '=', 'Enabled']])->get();//get company to page group company; return view('FrontEnd.pages.company', $this->datas); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function getSubCompany(Request $request, $id) { Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['menu'] = Article::where('lang', '=', $lang)->get();//get menu to page group company; $this->datas['subCompanies'] = SubCompany::where([['lang', '=', $lang], ['status', '=', 'Enabled']])->get();//get sub company to page sub company; $subCompany = SubCompany::find($id); return view('FrontEnd.pages.sub-company', compact('subCompany'))->with($this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Http/Controllers/frontend/TradingController.php <?php namespace App\Http\Controllers\frontend; use App\Article; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use App\Slider; use App\Trading; use Illuminate\Http\Request; class TradingController extends Controller { protected $datas = []; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getIndex(Request $request) { Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['slides'] = Slider::where([['lang', '=', $lang], ['article_id', '=', 11]])->orderBy('id', 'desc')->take(3)->get();//get slide to page trading; $this->datas['tradings'] = Trading::where('lang', '=', $lang)->get();//get content trading; frontend $this->datas['menu'] = Article::where('lang', '=', $lang)->get();//get menu in page trading frontend; return view('FrontEnd.pages.trading', $this->datas);//return view trading; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/database/seeds/AboutContentTableSeeder.php <?php use Carbon\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class AboutContentTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $aboutContents = array( array( 'title' => 'LHT Capital', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'id_table' => '1', 'lang' => 'en', ), array( 'title' => 'LHT Capital', 'detial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'id_table' => '1', 'lang' => 'kh', ), ); foreach ($aboutContents as $key => $row) { DB::table('abouts')->insert([ 'id_table' => $row['id_table'], 'title' => $row['title'], 'detial' => $row['detial'], 'lang' => $row['lang'], 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]); } } } <file_sep>/app/Http/Controllers/frontend/TeamController.php <?php namespace App\Http\Controllers\frontend; use App\Article; use App\Employee; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; class TeamController extends Controller { protected $datas = []; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getIndex(Request $request) { Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['teams'] = Employee::where([['lang', '=', $lang], ['status', '=', 'Enabled']])->paginate(20); $this->datas['menu'] = Article::where('lang', '=', $lang)->get(); return view('FrontEnd.pages.team', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function showTeam(Request $request, $id) { Language::checkLang($request->lang); $lang = Language::getTitleLang(); $decryptId = Crypt::decrypt($id); $this->datas['team'] = Employee::find($decryptId); $this->datas['menu'] = Article::where('lang', '=', $lang)->get(); return view('FrontEnd.pages.team-detial', $this->datas); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Http/Controllers/backend/EmployeeController.php <?php namespace App\Http\Controllers\backend; use App\Employee; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Database\Eloquent\Relations\paginate; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\validate; use Image; class EmployeeController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'Team'; // check language Language::checkLang($request->lang); // get language $lang = Language::getTitleLang(); $this->datas['datas'] = Employee::where('lang', '=', $lang)->orderBy('created_at', 'desc')->paginate(10); return view('backpack::employees.employee', $this->datas ); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { /*validation image*/ $validator = Validator::make($request->all(), [ // 'firstName' => 'required|min:2|max:35|alpha', // 'lastName' => 'required|min:2|max:35|alpha', 'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048', // 'gender' => 'required', // 'phone' => 'min:9|max:20|numeric', // 'email' => 'email|unique:users', // 'address' => 'string|min:2', // 'description' => 'required', ]); $listLeng = config('app.locales'); $id_table = Employee::max('id_table')+1; $filename = ''; foreach ($listLeng as $key => $value) { $employee = new Employee(); $employee->id_table = $id_table; $employee->firstName = $request->firstName; $employee->lastName = $request->lastName; $employee->gender = $request->gender; if($key == 'kh'){ $employee->image = $filename; } if($validator->passes()){ if($request->hasFile('image')){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $employee->image = $filename; } } $employee->phone = $request->phone; $employee->email = $request->email; $employee->address = $request->address; $employee->detial = $request->detial; $employee->status = $request->status; $employee->lang = $key; $employee->created_by = auth::id(); $employee->updated_by = auth::id(); $employee->save(); } return redirect(url(config('backpack.base.route_prefix', 'admin').'/team')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($employee_id) { $employee = Employee::find($employee_id); return Response()->json($employee); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $employee_id) { $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $employee = Employee::find($employee_id); $employee->firstName = $request->firstName; $employee->lastName = $request->lastName; $employee->gender = $request->gender; if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $employee->image = $filename; } } $employee->phone = $request->phone; $employee->email = $request->email; $employee->address = $request->address; $employee->detial = $request->detial; $employee->status = $request->status; $employee->updated_by = auth::id(); $employee->save(); return redirect(url(config('backpack.base.route_prefix', 'admin').'/team')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($employee_id) { // $employee = Employee::destroy($employee_id); $employee = new Employee(); $response = $employee->where('id_table', '=', $employee_id)->delete(); return response()->json($response); } } <file_sep>/app/Http/Controllers/frontend/ContactController.php <?php namespace App\Http\Controllers\frontend; use App\Article; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class ContactController extends Controller { protected $datas = []; /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getIndex(Request $request) { Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['menu'] = Article::where('lang', '=', $lang)->get(); return view('FrontEnd.pages.contact', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function sendEmail(Request $request) { $datas = array( 'email' => $request->email, 'phone' => $request->phone, 'name' => $request->name, 'message' => $request->message, ); dd($datas); Mail::send('Email.contact', $datas, function($message) use ($datas){ $message->from($datas['email']); $message->to('<EMAIL>'); }); redirect('/contact'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/database/seeds/HomeContentTableSeeder.php <?php use Carbon\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class HomeContentTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $homeContents = array( array ( 'title' => 'LHT Capital', 'titleDetial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'image' => 'ddd.jpg', 'titleImage' => 'LHT Capital', 'imageDetial' => 'Welcome to lht beauty.Our Clients and Customers bdndfit from intergrated', 'id_table' => '1', 'lang' => 'en', ), array ( 'title' => 'LHT Capital', 'titleDetial' => 'LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, seles; distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated and tailor-made services along the entire value chain, offter any combination of sourcing, marketing, seles;distribution and after-sal support services. LHT is the leading Market Expansion Services in cambodia. Our Ckients and Customers bdndfit from intergrated', 'image' => 'ddd.jpg', 'titleImage' => 'LHT Capital', 'imageDetial' => 'Welcome to lht beauty.Our Clients and Customers bdndfit from intergrated', 'id_table' => '1', 'lang' => 'kh', ) ); foreach ($homeContents as $key => $row) { DB::table('homes')->insert([ 'id_table' => $row['id_table'], 'title' => $row['title'], 'titleDetial' => $row['titleDetial'], 'image' => $row['image'], 'titleImage' => $row['titleImage'], 'imageDetial' => $row['imageDetial'], 'lang' => $row['lang'], 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]); } } } <file_sep>/app/Http/Controllers/backend/SubCompanyController.php <?php namespace App\Http\Controllers\backend; use App\Http\Controllers\Controller; use App\Http\Controllers\Helpers\Language; use App\SubCompany; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; use Intervention\Image\Facades\Image; class SubCompanyController extends Controller { protected $datas = []; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function view(Request $request) { $this->datas['title'] = 'SubCompany'; Language::checkLang($request->lang); $lang = Language::getTitleLang(); $this->datas['subCompanies'] = SubCompany::where('lang', '=', $lang)->get(); return view('backpack::sub-companies.sub-company', $this->datas); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function get($id) { $subCompany = SubCompany::find($id); return Response()->json($subCompany); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $subCompany = SubCompany::find($id); $subCompany->name = $request->name; $subCompany->url = $request->url; if($request->hasFile('image')){ if($validator->passes()){ $image = $request->file('image'); $filename = time() . '.' . $image->getClientOriginalExtension(); $image->move(public_path('/uploads/images/') , $filename ); $subCompany->image = $filename; } } $subCompany->detial = $request->detial; $subCompany->status = $request->status; $subCompany->updated_by = auth::id(); $subCompany->save(); return redirect(url(config('backpack.base.route_prefix', 'admin').'/subcompany')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Employee.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\App; use Session; class Employee extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'firstName', 'lastName', 'gender', 'image','phone','email','status' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'created_by','updated_by' ]; }
c81ea9164bd52a72a4ee7bbac29de075efe1af9b
[ "PHP" ]
21
PHP
Khon123/lht
aabde67c2dad70acc93bf1e610cdbcc4a5bff237
ec29aa5d17d0082a6c3f1d1ab28593ae11806603
refs/heads/master
<repo_name>Zaquan1/FYP<file_sep>/TrainingFeature.py import pickle from Feature import Feature import itertools import numpy as np import csv import time from pandas import read_csv def get_directory(): with open('music.pkl', 'rb') as f: music_dir = pickle.load(f) return music_dir def get_labels(): arousal = read_csv("resource/music_label/arousal.csv", header=0) valence = read_csv("resource/music_label/valence.csv", header=0) return arousal, valence def get_feature_name(name, total_round=1): i = 0 new_name = [] if total_round == 1: new_name.append(name) else: while i < total_round: new_name.append(name + "_" + str(i)) i += 1 return new_name # get directory for all the music musicDir = get_directory() # get labels for the music arousal, valence = get_labels() # get all features' header all_feature_name = [] all_feature_name.append(get_feature_name("mfcc", 13)) all_feature_name.append(get_feature_name("mfcc_delta", 13)) all_feature_name.append(get_feature_name("mfcc_delta2", 13)) all_feature_name.append(get_feature_name("spectral_flux")) all_feature_name.append(get_feature_name("zero_crossing_rate")) all_feature_name.append(get_feature_name("rolloff95")) all_feature_name.append(get_feature_name("rolloff85")) all_feature_name.append(get_feature_name("spectral contrast", 7)) all_feature_name.append(get_feature_name("spectral_centroid")) all_feature_name.append(get_feature_name("chroma", 12)) all_feature_name.append(get_feature_name("tonnetz", 6)) all_feature_name.append(get_feature_name("rmse")) all_feature_name.append(get_feature_name("energy_novelty")) all_feature_name.append(get_feature_name("loudness")) all_feature_name.append(get_feature_name("dtempo")) all_feature_name = list(itertools.chain.from_iterable(all_feature_name)) all_feature_name_mean = [(x + '_mean') for x in all_feature_name] all_feature_name_std = [(x + '_std') for x in all_feature_name] features_header = [] features_header.append(all_feature_name_mean) features_header.append(all_feature_name_std) features_header.append(get_feature_name("arousal")) features_header.append(get_feature_name("valence")) features_header = list(itertools.chain.from_iterable(features_header)) i = 0 for music in musicDir: start = time.time() # extract all features features = Feature(music, 15) print("Extracting music feature: ", features.filename, "...") print("extracting timbre...") features.extract_timbre_features() print("extracting melody...") features.extract_melody_features() print("extracting energy...") features.extract_energy_features() print("extracting rhythm...") features.extract_rhythm_features() all_features = features.get_all_features() # get current feature labels row_arousal_label = arousal.loc[arousal['song_id'] == int(features.filename)].index[0] row_valence_label = valence.loc[valence['song_id'] == int(features.filename)].index[0] curr_arousal_label = arousal.values[row_arousal_label, 1:] curr_valence_label = valence.values[row_valence_label, 1:] # remove nan from list curr_arousal_label = curr_arousal_label[~np.isnan(curr_arousal_label)] curr_valence_label = curr_valence_label[~np.isnan(curr_valence_label)] # removing excess label/timestamps min_music_length = min(len(curr_arousal_label), len(curr_valence_label)) all_features = all_features[:, :min_music_length] curr_arousal_label = curr_arousal_label[:min_music_length] curr_valence_label = curr_valence_label[:min_music_length] # append label to the data all_features = np.vstack([all_features, curr_arousal_label, curr_valence_label]) # save feature to csv with open("resource/features/" + features.filename + ".csv", "w+", newline='') as my_csv: csvWriter = csv.writer(my_csv, delimiter=',') csvWriter.writerow(features_header) # invert feature to be (timestamp x feature) format csvWriter.writerows(np.transpose(all_features)) end = time.time() i += 1 print(features.filename, " done, total left: ", i, "/", len(musicDir)) print("Runtime: ", end-start, " seconds") <file_sep>/UserInterface.py import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from plotly import tools from Feature import Feature from keras.models import load_model import base64 import os import numpy as np import miscellaneous as misc app = dash.Dash() stop = True music = { 'name': None, 'filepath': None, 'duration': None, 'energy_feature': [], 'timbre_feature': [], 'rhythm_feature': [], 'melody_feature': [], 'arousal_predict': [], 'valance_predict': [], 'binary': None } model = load_model("resource/model/LSTM.h5") model._make_predict_function() app.css.config.serve_locally = True app.scripts.config.serve_locally = True app.layout = html.Div(children=[ html.H1('Music Emotion Recognition', style={'textAlign': 'center'}), html.Hr(), dcc.Upload( id='upload-audio', children=html.Div([ 'Drag and Drop or ', html.A('Select Files'), ]), style={ 'width': '98%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, multiple=False, accept='.mp3' ), html.Div( id='features-graph-container' ), ]) def generate_graph_id(value): return '{}_graph'.format(value) DYNAMIC_GRAPH = { 'Valance-arousal': dcc.Graph( id=generate_graph_id('Valance-arousal'), figure={} ), 'Features': dcc.Graph( id=generate_graph_id('Features'), figure={} ) } def generate_interval_id(value): return '{}_interval'.format(value) @app.callback( Output('features-graph-container', 'children'), [Input('upload-audio', 'contents'), Input('upload-audio', 'filename')]) def display_controls(contents, filename): print("hi there") if contents is not None: get_audio_contents(contents, filename) return html.Div([ html.Div([ DYNAMIC_GRAPH['Valance-arousal'] ], style={'width': '50%', 'display': 'inline-block'}), html.Div([ DYNAMIC_GRAPH['Features'] ], style={'width': '50%', 'display': 'inline-block'}), html.Audio(src=contents, id='music-audio', autoPlay='audio'), dcc.Interval( id=generate_interval_id('interval'), interval=1*500, n_intervals=0 ), ]) def get_audio_contents(c, filename): if c is not None: ctype, cstring = str(c).split(',') decoded = base64.b64decode(cstring) music['filepath'] = os.path.dirname(os.path.realpath(__file__)) + "/resource/temp/" + filename try: file = open(music.get('filepath'), 'wb') file.write(decoded) file.close() except: print("something went wrong") # record all necessary information into dictionary music['name'] = filename music['binary'] = c music_feature = Feature(music['filepath']) # get all extracted feature music['energy_feature'] = (Feature.sync_frames(music_feature, music_feature.extract_energy_features())).mean( axis=0) music['timbre_feature'] = (Feature.sync_frames(music_feature, music_feature.extract_timbre_features())).mean( axis=0) music['melody_feature'] = (Feature.sync_frames(music_feature, music_feature.extract_melody_features())).mean( axis=0) music['rhythm_feature'] = (Feature.sync_frames(music_feature, music_feature.extract_rhythm_features()))[:-3] # data preparation for prediction data = misc.series_to_supervised(np.transpose(music_feature.get_all_features()), 3, 1) data = data.values.reshape(data.values.shape[0], 4, 146) predict = model.predict(data) # save prediction into dictionary music['arousal_predict'] = predict[:, 0] music['valance_predict'] = predict[:, 1] music['duration'] = [i for i in misc.frange(0.5, len(music['timbre_feature']) * 0.5, 0.5)] '''['%d:%2.1f' % (int((i + 1.5) / 60), (i + 1.5) % 60) for i in frange(0.5, len(predict) * 0.5, 0.5)]''' def generate_output_callback(key): def output_callback(n_interval): # This function can display different outputs depending on # the values of the dynamic controls if key == 'Features': trace_rhythm = go.Scatter( x=music['duration'][:n_interval], y=music['rhythm_feature'][:n_interval] ) trace_timbre = go.Scatter( x=music['duration'][:n_interval], y=music['timbre_feature'][:n_interval] ) trace_energy = go.Scatter( x=music['duration'][:n_interval], y=music['energy_feature'][:n_interval] ) trace_melody = go.Scatter( x=music['duration'][:n_interval], y=music['melody_feature'][:n_interval] ) fig = tools.make_subplots(4, 1, subplot_titles=('Timbre Feature', 'energy Feature', 'melody Feature', 'rhythm Feature')) fig.append_trace(trace_timbre, 1, 1) fig.append_trace(trace_energy, 2, 1) fig.append_trace(trace_melody, 3, 1) fig.append_trace(trace_rhythm, 4, 1) fig['layout']['xaxis4'].update(title='Duration') else: trace = go.Scatter( x=music['valance_predict'][misc.negative_to_zero(n_interval-4):misc.negative_to_zero(n_interval-3)], y=music['arousal_predict'][misc.negative_to_zero(n_interval-4):misc.negative_to_zero(n_interval-3)], mode='markers+text', text=music['duration'][n_interval-1:n_interval], textposition='bottom' ) fig = tools.make_subplots(1, 1) fig.append_trace(trace, 1, 1) fig['layout'].update(title='Arousal Valance Graph') fig['layout']['xaxis1'].update(title='Valance', range=[-1, 1]) fig['layout']['yaxis1'].update(title='Arousal', range=[-1, 1]) return fig return output_callback def generate_interval_callback(): def interval_callback(n_interval): if n_interval >= len(music['duration']): return 60*60*1000 else: return 1*500 return interval_callback app.config.supress_callback_exceptions = True for key in DYNAMIC_GRAPH: print('all callback created: ', key) app.callback( Output(generate_graph_id(key), 'figure'), [Input(generate_interval_id('interval'), 'n_intervals')])( generate_output_callback(key) ) app.callback( Output(generate_interval_id('interval'), 'interval'), [Input(generate_interval_id('interval'), 'n_intervals')] )(generate_interval_callback()) if __name__ == '__main__': app.run_server(debug=False)<file_sep>/ModelTraining.py from matplotlib import pyplot import os from pandas import read_csv from pandas import DataFrame from pandas import concat from keras.models import Sequential from keras.layers import Dense, Dropout from keras.layers import LSTM from keras.models import load_model import time from math import sqrt from sklearn.metrics import mean_squared_error import numpy as np import miscellaneous as misc # split the data into features and label def split_features_and_y(data, time_stamp, features_number): split_data = [] for i in range(time_stamp+1): if i == 0: split_data = data[:, :((i + 1)*features_number)-2] else: split_data = np.hstack([split_data, data[:, i*features_number:((i + 1)*features_number)-2]]) y_label = data[:, -2:] return split_data, y_label # create the model def get_model(): model = Sequential() model.add(LSTM(512, input_shape=(4, 146), return_sequences=True)) model.add(Dropout(0.1)) model.add(LSTM(256)) model.add(Dropout(0.1)) model.add(Dense(256)) model.add(Dropout(0.1)) model.add(Dense(1, activation='tanh')) model.compile(loss='mean_squared_error', metrics=['mse'], optimizer='adam') return model # get the features from the csv file def get_extracted_features(): i = 1 features_data = [] dirpath = os.path.dirname(os.path.realpath(__file__)) + "/resource/features" print("getting feature....") for filename in os.listdir(dirpath): dataset = read_csv("resource/features/" + filename, header=0) values = dataset.values data = misc.series_to_supervised(values, timesteps, 1) if i == 1: features_data = data else: features_data = np.vstack([features_data, data]) print(i, '/', 1802) i += 1 return features_data timesteps = 3 # number of total features including 2 of the labels, arousal and valance n_features = 148 # get all the features from csv file features_data = get_extracted_features() # separate the data into train, validation and test train = features_data[:int(len(features_data)/2), :] val = features_data[int(len(features_data)/2):int(len(features_data)/1.2), :] test = features_data[int(len(features_data)/1.2):, :] # split the data into features and labels train_X, train_y = split_features_and_y(train, timesteps, n_features) val_X, val_y = split_features_and_y(val, timesteps, n_features) test_X, test_y = split_features_and_y(test, timesteps, n_features) # reshape the data that is suitable for the model train_X = train_X.reshape(train_X.shape[0], timesteps+1, n_features-2) val_X = val_X.reshape(val_X.shape[0], timesteps+1, n_features-2) test_X = test_X.reshape(test_X.shape[0], timesteps+1, n_features-2) # create the model for arousal model_arousal = get_model() print(train_y.shape) # train the model for arousal historyArousal = model_arousal.fit(train_X, train_y[:, 0], epochs=200, batch_size=100, validation_data=(val_X, val_y[:, 0]), verbose=2, shuffle=False) print("saving model..") # save the model model_arousal.save(os.path.dirname(os.path.realpath(__file__)) + "/resource/model/LSTMArousal.h5") # display the training progress pyplot.plot(historyArousal.history['loss'], label='train_arousal') pyplot.plot(historyArousal.history['val_loss'], label='test_arousal') pyplot.legend() # create the model for valance model_valance = get_model() # train model for valance historyValance = model_valance.fit(train_X, train_y[:, 1], epochs=200, batch_size=100, validation_data=(val_X, val_y[:, 1]), verbose=2, shuffle=False) print("saving model..") # save the model model_valance.save(os.path.dirname(os.path.realpath(__file__)) + "/resource/model/LSTMValance.h5") # display the training progress pyplot.plot(historyValance.history['loss'], label='train_valance') pyplot.plot(historyValance.history['val_loss'], label='test_valance') pyplot.legend() # make the prediction for calculating RMSE prediction_arousal = model_arousal.predict(test_X) prediction_valance = model_valance.predict(test_X) print("calculating RMSE...") rmse_arousal = sqrt(mean_squared_error(prediction_arousal, test_y[:, 0])) rmse_valance = sqrt(mean_squared_error(prediction_valance, test_y[:, 1])) print("RMSE arousal: ", rmse_arousal, "RMSE valance: ", rmse_valance) pyplot.show()<file_sep>/Feature.py import pickle import librosa import matplotlib.pyplot as plt import IPython.display import librosa.display import itertools import numpy as np import csv import os from pandas import read_csv class Feature: hop_length = 512 def __init__(self, filepath, offset=0.0): self.filepath = filepath self.filename = os.path.basename(os.path.normpath(filepath)).split(".")[0] self.y, self.sr = librosa.load(path=filepath, sr=22050, offset=offset) self.frames = self.duration_to_frame() self.timbre_features = [] self.melody_features = [] self.energy_features = [] self.rhythm_features = [] def extract_timbre_features(self): print("extract timbre...") y_harmonic = librosa.effects.harmonic(self.y, margin=4) # get mfcc mfcc = librosa.feature.mfcc(y=y_harmonic, sr=self.sr, hop_length=self.hop_length, n_mfcc=13) # get dmfcc mfcc_delta = librosa.feature.delta(mfcc) # get ddmfcc mfcc_delta2 = librosa.feature.delta(mfcc, order=2) # get spectral flux spectral_flux = librosa.onset.onset_strength(y=self.y, sr=self.sr) spectral_flux = spectral_flux / spectral_flux.max() # get zero crossing rate zc = librosa.feature.zero_crossing_rate(y=self.y) # get rolloff of 95% and 85% rolloff95 = librosa.feature.spectral_rolloff(y=self.y, sr=self.sr, roll_percent=0.95) rolloff85 = librosa.feature.spectral_rolloff(y=self.y, sr=self.sr, roll_percent=0.85) # get spectral contrast spectral_contrast = librosa.feature.spectral_contrast(self.y, sr=self.sr) # get spectral centroid spectral_centroid = librosa.feature.spectral_centroid(self.y, sr=self.sr) self.timbre_features = np.vstack([mfcc, mfcc_delta, mfcc_delta2, spectral_flux, zc, rolloff95, rolloff85, spectral_contrast, spectral_centroid]) ''' # plot for rolloff plt.figure() plt.subplot(4,1,1) plt.semilogy(rolloff85.T) plt.xticks([]) plt.xlim([0, rolloff85.shape[-1]]) plt.subplot(4, 1, 2) plt.semilogy(rolloff95.T) plt.subplot(4, 1, 3) plt.semilogy((sync_frames(rolloff95, duration_to_frame(y))).T) plt.subplot(4, 1, 4) plt.semilogy((sync_frames(rolloff95, duration_to_frame(y), np.std)).T) #plot for mfcc plt.figure(1, figsize=(12, 6)) plt.subplot(2, 1, 1) librosa.display.specshow(mfcc) plt.ylabel('MFCC') plt.colorbar() plt.subplot(2, 1, 2) librosa.display.specshow(mfcc_delta) plt.ylabel('MFCC-$\Delta$') plt.colorbar() #plot for flux plt.figure(2) plt.subplot(4,1,1) plt.plot(2 + spectral_flux, alpha=0.8, label='Mean (mel)') plt.subplot(4, 1, 2) plt.plot(2 + spectral_flux2, alpha=0.8, label='Mean (mel)') plt.subplot(4,1,3) plt.plot(2 + spectral_flux/spectral_flux.max(), alpha=0.8, label='Mean (mel)') plt.subplot(4, 1, 4) plt.plot(2 + spectral_flux2/spectral_flux2.max(), alpha=0.8, label='Mean (mel)') ''' return self.timbre_features def extract_melody_features(self): print("extract melody...") y_harmonic = librosa.effects.harmonic(self.y, margin=4) chromagram = librosa.feature.chroma_cqt(y=y_harmonic, sr=self.sr, hop_length=self.hop_length, bins_per_octave=12 * 3) # get tonal centroid tonnets = librosa.feature.tonnetz(y_harmonic, sr=self.sr) self.melody_features = np.vstack([chromagram, tonnets]) return self.melody_features def extract_energy_features(self): print("extract energy...") y_stft = librosa.stft(y=self.y, hop_length=self.hop_length) S, phase = librosa.magphase(y_stft) rms = librosa.feature.rmse(S=S).flatten() rms_diff = np.zeros_like(rms) rms_diff[1:] = np.diff(rms) energy_novelty = np.max([np.zeros_like(rms_diff), rms_diff], axis=0) # get loudness power = np.abs(S)**2 p_mean = np.sum(power, axis=0, keepdims=True) p_ref = np.max(power) loudness = librosa.power_to_db(p_mean, ref=p_ref) self.energy_features = np.vstack([rms, energy_novelty, loudness]) ''''' plt.figure() plt.subplot(2,1,1) librosa.display.specshow(tonnets) plt.colorbar() plt.title('tonnetzz') plt.subplot(2, 1, 2) librosa.display.specshow(chromagram) plt.colorbar() plt.title('Chroma') plt.tight_layout() ''' return self.energy_features def extract_rhythm_features(self): print("extract rhythm...") onset = librosa.onset.onset_strength(self.y, sr=self.sr) dynamic_tempo = librosa.beat.tempo(onset_envelope=onset, sr=self.sr, aggregate=None) self.rhythm_features = dynamic_tempo ''' plt.figure() plt.subplot(3,1,1) plt.plot(dynamic_tempo, linewidth=1.5, label='tempo estimate') plt.legend(frameon=True, framealpha=0.75) plt.subplot(3,1,2) plt.plot(sync_frames(dynamic_tempo, duration_to_frame(y)), linewidth=1.5, label='tempo estimate') plt.legend(frameon=True, framealpha=0.75) plt.subplot(3,1,3) plt.plot(sync_frames(dynamic_tempo, duration_to_frame(y), np.std), linewidth=1.5, label='tempo estimate') plt.legend(frameon=True, framealpha=0.75) ''' return self.rhythm_features # get the frame for every sec_inc seconds def duration_to_frame(self, sec_inc=0.5): duration = librosa.get_duration(y=self.y, sr=self.sr, hop_length=self.hop_length) time_stamp = sec_inc time = [] while time_stamp <= duration: time.append(time_stamp) time_stamp += sec_inc return librosa.time_to_frames(time, hop_length=self.hop_length, sr=self.sr) # sync all the frames based on duration_to_frame def sync_frames(self, features, aggregate=np.mean): sync_feature = librosa.util.sync(features, self.frames, aggregate=aggregate) return sync_feature def get_all_features(self): all_features = np.vstack([self.timbre_features, self.melody_features, self.energy_features, self.rhythm_features]) return np.vstack([self.sync_frames(all_features), self.sync_frames(all_features, aggregate=np.std)])
4b0f817a57747f03e15e199a8d6d6c7217a7a1c5
[ "Python" ]
4
Python
Zaquan1/FYP
deaec21cb57429305e7399d9496024db5dfc20eb
ce99d8f3dfcc4d2fc0a649dc77839ecfebf7e078
refs/heads/master
<file_sep>const express = require('express') const router = express.Router() var knex = require('../db/knex') function User(){ return knex('app_user') } // CREATE router.post('/', function (req, res){ User().insert({ email: req.body.email, username: req.body.username }) .then(function(){ res.sendStatus(201) }) }) // READ router.get('/', function (req, res){ User().select().then(function (result){ res.send(result) }) }) router.get('/:email', function (req, res){ User().where('email', req.params.email).first().then(function (result){ res.send(result) }) }) // UPDATE router.put('/:email', function (req, res){ User().where('email', req.params.email) .update({ username: req.body.username },'email').then(function(result){ res.send('user'+ result + 'was updated') }).catch(err => { console.log(err) }) }) // DELETE router.delete('/:email', function (req, res){ User().where('email', req.params.email).del() .then(function (result){ res.send(201); }).catch(err => { console.log(err) }) }) module.exports = router <file_sep>require('dotenv').config(); // const path = require('path'); const bodyParser = require('body-parser'); const logger = require('morgan'); const helmet = require('helmet'); const express = require('express'); const cors = require('cors'); const expressSession = require('express-session'); const passport = require('./passport'); const cookieParser = require('cookie-parser'); // Route files const user = require('./routes/user'); const song = require('./routes/song'); const playlist = require('./routes/playlist'); const facebook = require('./routes/facebook'); const playlistSong = require('./routes/playlist_song'); //const playlistUser = require('./routes/playlist_user') const role = require('./routes/role'); const comment = require('./routes/comments'); const PORT = process.env.PORT || 3000; const app = express(); // Middleware app.use(cors()); app.use(logger('dev')); app.use(helmet()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(expressSession({ secret: 'mouse dog', saveUninitialized: true, resave: false })); app.use(passport.initialize()); app.use(passport.session()); // Routes app.use('/facebook', facebook); app.use('/playlist', playlist); app.use('/playlist_song', playlistSong); app.use('/song', song); app.use('/role', role); app.use('/user', user); app.use('/comment', comment) // Listening port app.listen(PORT, () => { // eslint-disable-next-line console.log(`Listening on port: ${PORT}`); }); <file_sep>const router = require('express').Router(); const knex = require('../db/knex'); // Get all songs router.get('/', (req, res) => { knex('song') .then((songs) => { res.json(songs); }); }); // Get one song router.get('/:id', (req, res) => { knex('song') .where('id', req.params.id) .first() .then((song) => { res.json(song) }) }); // Post new song router.post('/', (req, res) => { knex('song') .insert(req.body) .returning('*') .then(function (data) { res.json(data) }) }); // Update song router.put('/:id', (req, res) => { const song = req.body; const id = req.params.id; knex('song') .where('id', id) .update(song, '*') .then((updatedSong) => { res.json(updatedSong); }); }); // Delete song router.delete('/:id', (req, res) => { const id = req.params.id; knex('song') .where('id', id) .del() .then(() => { res.status(204).send(); }); }); module.exports = router; <file_sep>const express = require('express') const router = express.Router() var knex = require('../db/knex') function play(){ return knex('playlist') } // CREATE router.post('/', function (req, res){ play().insert({ name: req.body.name }) .then(function(result){ res.json(result) }) }) // READ router.get('/', function (req, res){ play().select().then(function (result){ res.send(result) }) }) router.get('/:id', function (req, res){ play().where('id', req.params.id).first().then(function (result){ res.send(result) }) }) // UPDATE router.put('/:id', function (req, res){ play().where('id', req.params.id) .update({ name: req.body.name },'id').then(function(result){ res.send('playlist'+ result + 'was updated') }).catch(err => { console.log(err) }) }) // DELETE router.delete('/:id', function (req, res){ play().where('id', req.params.id).del() .then(function (result){ res.send(201); }).catch(err => { console.log(err) }) }) module.exports = router <file_sep>const passport = require('passport'); const express = require('express'); const Strategy = require('passport-facebook').Strategy; passport.use(new Strategy({ clientID: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, callbackURL: 'http://localhost:3000/login/facebook/return' }, function(accessToken, refreshToken, profile, cb) { // In this example, the user's Facebook profile is supplied as the user // record. In a production-quality application, the Facebook profile should // be associated with a user record in the application's database, which // allows for account linking and authentication with other identity // providers. return cb(null, profile); })); passport.serializeUser(function(user, cb) { cb(null, user); }); passport.deserializeUser(function(obj, cb) { cb(null, obj); }); module.exports = passport <file_sep>const router = require('express').Router() const knex = require('../db/knex') //Queries function getAllRoles() { return knex('playlist_user') } function getPlaylistByUser(id) { return knex('playlist_user') .leftJoin('playlist', 'playlist_user.p_id', 'playlist.id') .where('u_id', id) .select( 'playlist.name as title', 'playlist_user.role as role', 'playlist.id as id' ) } function getUsersForPlaylist(id) { return knex('playlist_user').where('p_id', id) } function createNewPlaylistUser(newUserObj) { return knex('playlist_user').insert(newUserObj).returning('*') } function updateUserForPlaylist(id, updateObj) { return knex('playlist_user').where('id', id).update(updateObj, '*') } function deleteUserForPlaylist(id) { return knex('playlist_user').where('id', id).del() } //routes //get all roles router.get('/', (req, res) => { getAllRoles().then(result => { res.json(result) }) }) //get all playlists for a specific user router.get('/:id', (req, res) => { const id = req.params.id getPlaylistByUser(id).then(result => { res.json(result) }) .catch(err => { console.log(err) res.status(503).send(err.message) }) }) //get all users for a specific playlist router.get('/playlist/:id', (req, res) => { const id = Number(req.params.id) getUsersForPlaylist(id).then(result => { res.json(result) }) .catch(err => { console.log(err) res.status(503).send(err.message) }) }) //add user to a playlist router.post('/', (req, res) => { createNewPlaylistUser(req.body).then(newUser => { res.json(newUser) }) .catch(err => { console.log(err) res.status(503).send(err.message) }) }) //update user in a playlist router.put('/:id', (req, res) => { const id = Number(req.params.id) updateUserForPlaylist(id, req.body).then(updatedUser => { res.json(updatedUser) }) .catch(err => { console.log(err) res.status(503).send(err.message) }) }) //delete user from playlist router.delete('/:id', (req, res) => { const id = req.params.id deleteUserForPlaylist(id).then(() => { res.status(204).send() }) .catch(err => { console.log(err) res.status(503).send(err.message) }) }) module.exports = router
619ce062233d134cbe6266a6b80efbf579220978
[ "JavaScript" ]
6
JavaScript
tcatsl/weDJ-backend
e97fa4eeb0787f7542a6f512cce91c67f192ee0d
af3b150beba1c5078465b5a28bce14e9e30fd9c6