text
stringlengths 184
4.48M
|
---|
<?php
namespace Oro\Bundle\SaleBundle\Tests\Unit\Quote\Shipping\Context\LineItem\Factory;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Oro\Bundle\CurrencyBundle\Entity\Price;
use Oro\Bundle\ProductBundle\Entity\Product;
use Oro\Bundle\ProductBundle\Entity\ProductUnit;
use Oro\Bundle\ProductBundle\Model\ProductLineItemInterface;
use Oro\Bundle\ProductBundle\Tests\Unit\Stub\ProductStub;
use Oro\Bundle\SaleBundle\Entity\QuoteDemand;
use Oro\Bundle\SaleBundle\Entity\QuoteProduct;
use Oro\Bundle\SaleBundle\Entity\QuoteProductDemand;
use Oro\Bundle\SaleBundle\Entity\QuoteProductOffer;
use Oro\Bundle\SaleBundle\Quote\Shipping\Context\LineItem\Factory\ShippingLineItemFromQuoteProductDemandFactory;
use Oro\Bundle\ShippingBundle\Context\LineItem\Factory\ShippingKitItemLineItemFromProductKitItemLineItemFactory;
use Oro\Bundle\ShippingBundle\Context\LineItem\Factory\ShippingLineItemFromProductLineItemFactory;
use Oro\Bundle\ShippingBundle\Context\ShippingLineItem;
use Oro\Bundle\ShippingBundle\Entity\LengthUnit;
use Oro\Bundle\ShippingBundle\Entity\ProductShippingOptions;
use Oro\Bundle\ShippingBundle\Entity\Repository\ProductShippingOptionsRepository;
use Oro\Bundle\ShippingBundle\Entity\WeightUnit;
use Oro\Bundle\ShippingBundle\Model\Dimensions;
use Oro\Bundle\ShippingBundle\Model\Weight;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class ShippingLineItemFromQuoteProductDemandFactoryTest extends TestCase
{
private const TEST_QUANTITY = 15;
private ProductUnit|MockObject $productUnit;
private ProductShippingOptionsRepository|MockObject $repository;
private ShippingLineItemFromProductLineItemFactory $factory;
protected function setUp(): void
{
$this->productUnit = $this->createMock(ProductUnit::class);
$this->productUnit->method('getCode')->willReturn('someCode');
$this->repository = $this->createMock(ProductShippingOptionsRepository::class);
$managerRegistry = $this->createMock(ManagerRegistry::class);
$managerRegistry
->expects(self::any())
->method('getRepository')
->with(ProductShippingOptions::class)
->willReturn($this->repository);
$entityManager = $this->createMock(EntityManagerInterface::class);
$managerRegistry
->expects(self::any())
->method('getManagerForClass')
->withConsecutive([WeightUnit::class], [LengthUnit::class])
->willReturn($entityManager);
$entityManager
->expects(self::any())
->method('getReference')
->willReturnCallback(
static function (string $className, ?string $unitCode) {
$unit = new $className();
$unit->setCode($unitCode);
return $unit;
}
);
$this->factory = new ShippingLineItemFromQuoteProductDemandFactory(
$managerRegistry,
new ShippingKitItemLineItemFromProductKitItemLineItemFactory()
);
}
public function testCreateByProductLineItemInterfaceOnly(): void
{
$quoteProductDemand = $this->createMock(ProductLineItemInterface::class);
$this->expectExceptionObject(
new \InvalidArgumentException(sprintf(
'"%s" expected, "%s" given',
QuoteProductDemand::class,
get_debug_type($quoteProductDemand)
))
);
$this->repository->expects(self::never())
->method('findIndexedByProductsAndUnits')
->withAnyParameters();
$this->factory->create($quoteProductDemand);
}
public function testCreate(): void
{
$product = $this->getProduct(1001);
$quoteProduct = (new QuoteProduct())
->setProduct($product);
$quoteProductOffer = $this->createQuoteProductOffer(
self::TEST_QUANTITY,
$this->productUnit,
Price::create(99.9, 'USD'),
$quoteProduct
);
$quoteProductDemand = new QuoteProductDemand(new QuoteDemand(), $quoteProductOffer, self::TEST_QUANTITY);
$this->repository->expects(self::once())
->method('findIndexedByProductsAndUnits')
->willReturn(
[
$product->getId() => [
'someCode' => [
'dimensionsHeight' => 3.0,
'dimensionsLength' => 1.0,
'dimensionsWidth' => 2.0,
'dimensionsUnit' => 'in',
'weightUnit' => 'kilo',
'weightValue' => 42.0,
]
],
]
);
$expectedShippingLineItem = $this->createShippingLineItem(
$quoteProductOffer->getQuantity(),
$quoteProductOffer->getProductUnit(),
$quoteProductOffer->getProductUnitCode(),
$quoteProductOffer,
$quoteProductOffer->getPrice(),
$quoteProductOffer->getProduct(),
Dimensions::create(1, 2, 3, (new LengthUnit())->setCode('in')),
Weight::create(42, (new WeightUnit())->setCode('kilo'))
);
self::assertEquals(
$expectedShippingLineItem,
$this->factory->create($quoteProductDemand)
);
}
public function testCreateCollectionByProductLineItemInterfaceOnly(): void
{
$quoteProductDemand = $this->createMock(ProductLineItemInterface::class);
$this->expectExceptionObject(
new \InvalidArgumentException(sprintf(
'"%s" expected, "%s" given',
QuoteProductDemand::class,
get_debug_type($quoteProductDemand)
))
);
$this->repository->expects(self::never())
->method('findIndexedByProductsAndUnits')
->withAnyParameters();
$this->factory->createCollection([$quoteProductDemand]);
}
public function testCreateCollection(): void
{
$product1 = $this->getProduct(1001);
$product2 = $this->getProduct(2002);
$quoteProduct1 = (new QuoteProduct())
->setProduct($product1);
$quoteProduct2 = (new QuoteProduct())
->setProduct($product2);
$quoteProductOffer1 = $this->createQuoteProductOffer(
1,
$this->productUnit,
Price::create(99.9, 'USD'),
$quoteProduct1
);
$quoteProductOffer2 = $this->createQuoteProductOffer(
2,
$this->productUnit,
Price::create(199.9, 'USD'),
$quoteProduct2
);
$quoteProductDemand1 = new QuoteProductDemand(new QuoteDemand(), $quoteProductOffer1, 100);
$quoteProductDemand2 = new QuoteProductDemand(new QuoteDemand(), $quoteProductOffer2, 200);
$quoteProductDemands = [$quoteProductDemand1, $quoteProductDemand2];
$expectedShippingLineItem1 = $this->createShippingLineItem(
$quoteProductDemand1->getQuantity(),
$quoteProductOffer1->getProductUnit(),
$quoteProductOffer1->getProductUnitCode(),
$quoteProductOffer1,
$quoteProductOffer1->getPrice(),
$quoteProductOffer1->getProduct(),
Dimensions::create(1, 2, 3, (new LengthUnit())->setCode('in')),
Weight::create(42, (new WeightUnit())->setCode('kilo')),
);
$expectedShippingLineItem2 = $this->createShippingLineItem(
$quoteProductDemand2->getQuantity(),
$quoteProductOffer2->getProductUnit(),
$quoteProductOffer2->getProductUnitCode(),
$quoteProductOffer2,
$quoteProductOffer2->getPrice(),
$quoteProductOffer2->getProduct(),
Dimensions::create(11, 12, 13, (new LengthUnit())->setCode('meter')),
Weight::create(142, (new WeightUnit())->setCode('lbs')),
);
$this->repository
->expects(self::once())
->method('findIndexedByProductsAndUnits')
->willReturn(
[
$product1->getId() => [
'someCode' => [
'dimensionsHeight' => 3.0,
'dimensionsLength' => 1.0,
'dimensionsWidth' => 2.0,
'dimensionsUnit' => 'in',
'weightUnit' => 'kilo',
'weightValue' => 42.0,
]
],
$product2->getId() => [
'someCode' => [
'dimensionsHeight' => 13.0,
'dimensionsLength' => 11.0,
'dimensionsWidth' => 12.0,
'dimensionsUnit' => 'meter',
'weightUnit' => 'lbs',
'weightValue' => 142.0,
]
]
]
);
self::assertEquals(
new ArrayCollection([$expectedShippingLineItem1, $expectedShippingLineItem2]),
$this->factory->createCollection($quoteProductDemands)
);
}
public function testCreateCollectionEmpty(): void
{
$this->repository
->method('findIndexedByProductsAndUnits')
->willReturn([]);
self::assertEquals(new ArrayCollection([]), $this->factory->createCollection([]));
}
private function createQuoteProductOffer(
float|int $quantity,
?ProductUnit $productUnit,
?Price $price,
QuoteProduct $quoteProduct
): QuoteProductOffer {
$quoteProductOffer = new QuoteProductOffer();
$quoteProductOffer->setQuantity($quantity);
$quoteProductOffer->setProductUnit($productUnit);
$quoteProductOffer->setQuoteProduct($quoteProduct);
$quoteProductOffer->setPrice($price);
$quoteProductOffer->setProductUnitCode($productUnit->getCode());
return $quoteProductOffer;
}
private function getProduct(int $id): Product
{
return (new ProductStub())
->setId($id);
}
private function createShippingLineItem(
float|int $quantity,
?ProductUnit $productUnit,
string $unitCode,
ProductLineItemInterface $productHolder,
?Price $price,
?Product $product,
?Dimensions $dimensions,
?Weight $weight
): ShippingLineItem {
$shippingLineItem = (new ShippingLineItem(
$productUnit,
$quantity,
$productHolder
))
->setProductUnitCode($unitCode)
->setProduct($product)
->setProductSku($product->getSku());
if ($price) {
$shippingLineItem->setPrice($price);
}
if ($dimensions) {
$shippingLineItem->setDimensions($dimensions);
}
if ($weight) {
$shippingLineItem->setWeight($weight);
}
return $shippingLineItem;
}
}
|
# Week 5
## React. Next.JS/SSR/SSG
### Disclaimer:
In this task you going to use Next.js Pages API instead of brand-new APP dir API. The main motivation of it is stability and wide community around this solution. Pages API still supportable by Next.JS team. This decision will help you avoid unnecessary problems and questions regarding server-side components. Anyway, if you are interested in deep dive into APP API you can read about it [here](https://nextjs.org/docs/app/building-your-application/routing) and [here](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md).
### What should be done:
1. Create a separate branch for this task from the previous branch task.
2. Migrate the app to the Next.JS retaining the functionality.
- You must enable server-side rendering for all the pages.
3. Switch from react-router to Next.JS router (react-router lib must be removed).
4. Update tests to make it work with Next.JS.
5. You must use **Pages API** instead of **new APP API**.
### Questions
You should be using Discord as the main mean of the communication.
Also, we will try to collect your questions regarding the 5th Module using special form, which will be provided via the Discord with the 6th Module start. Questions will be collected in Module 06 section of the same spreadsheet. Please, check answers carefully before posting the question, may be your question has been answered already.
We will try to conduct a session for each module providing answers for some questions.
Please **check the answers carefully before posting** a question, as your question might have already been answered. We will strive to hold a session for each module, providing answers to some of the questions.
### Score
The task will be checked during cross-check and cross-code-review.
#### Cross-code-review process
1. Clone the repository you are going to review
2. Install all the required dependencies
3. Run linting using special command in package.json file, output should not produce any errors or warnings
4. Run tests using special command in package.json file, all tests should pass, test coverage should be shown after running all the tests
5. Review the code. Pay attention at the following "code smells": props drilling; large, complex components aka "god" components; direct DOM manipulation, etc.
When reviewing the code try pay attention at the following principles:
* Write code as simply as possible: KISS
* Avoid unnecessary repetition: DRY
* Delete what is not needed: YAGNI
We also need to mention the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) and other [SOLID](https://en.wikipedia.org/wiki/SOLID) principles
Please, check [this article](https://dmitripavlutin.com/7-architectural-attributes-of-a-reliable-react-component/) for reference
Last, but not least - check the presence of the comments. Ideally there shouldn't be any comments at all. Sometimes people just comment code which is not needed. So why not to remove it entirely? In case you will need to restore this code, you can always refer to the git history. And more - [comments are lies](https://blog.devgenius.io/code-should-be-the-one-version-of-the-truth-dont-add-comments-b0bcd8631a9a)
#### Cross-check process
Run app and check that the functionality is working (cross-check)
#### Points
##### Student can get 100 points:
- The app migrated to the Next.JS - **25 points**
- All retaining functionality works as expected from previous tasks - **25 points**
- Pages API has been used for all pages - **20 points**
- All pages with state receive it via getServerSideProps - **10 points**
- Tests had been modified to work with SSR - **20 points**
##### Penalties:
- TypeScript isn't used: **-95 points**
- Usage of *any*: **-20 points per each**
- Usage of *ts-ignore*: **-20 points per each**
- Direct DOM manipulations inside the React components: **-50 points per each**
- Presence of *code-smells* (God-object, chunks of duplicate code), commented code sections: **-10 points per each**
- Usage of component libraries, e.g. Material UI, Ant Design: **-100 points**
- Test coverage is less than 80%: **-30 points**
- React hooks are used to get access to either state, or to the component lifecycle: **-70 points**
- Next.js isn't used: **-100 points**
- Usage of client state on page: **-20 points** per each
- Pages API isn't used: **-50 points**
- Commits after the deadline: **-40 points**
### Repository requirements
* the task should be done in **your personal private repository**
* in the repository create a branch from the **previous task** branch with the name of the task and work in the created branch
* the commits history should reflect the process of app creating [Commits requirements](https://docs.rs.school/#/git-convention?id=%D0%A2%D1%80%D0%B5%D0%B1%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D0%BA-%D0%B8%D0%BC%D0%B5%D0%BD%D0%B0%D0%BC-%D0%BA%D0%BE%D0%BC%D0%BC%D0%B8%D1%82%D0%BE%D0%B2) [RU]
* after finishing development it’s necessary to make Pull Request from app’s branch to `main` branch [Pull Request requirements](https://docs.rs.school/#/pull-request-review-process?id=%D0%A2%D1%80%D0%B5%D0%B1%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D0%BA-pull-request-pr) [RU]
* after completing the module, private repository should be exposed for cross-checks and cross-code-reviews for the duration of the next module (one week), after this week will end, repository should be made private again
**Do not merge Pull Request from the development branch to the `main` branch**
### Theory
- [SSR vs SSG](https://vercel.com/blog/nextjs-server-side-rendering-vs-static-generation)
- [Next.JS](https://nextjs.org/)
- [Pages API](https://nextjs.org/docs/pages)
- [RTK with server side rendering](https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering)
- [RTK Query + Next.JS example](https://github.com/phryneas/ssr-experiments/tree/main/nextjs-blog)
|
RAM struktura
00h _______________________ 80h
|___BANK0___|___BANK1___|
| INDF |
| TMR0 | OPTION |
| PLC |
| STATUS |
| FSR |
| PORTA | TRISA |
| PORTB | TRISB |
| |
| EEDATA | EECON1 |
| EEADR | EECON2 |
| PCLATH |
|________INTCON_________|
| |
| 68 bajtova |
| GPR - zajednički |
| za obe banke |
|_______________________|
STATUS registar
_______________________________________________
| | | | | | | | |
| IRP | RP1 | RP0 | TO- | PD- | Z | DC | C |
|_____|_____|_____|_____|_____|_____|_____|_____|
- Bitovi:
7: IRP => ne koristi se
6,5: (RP1, RP0) => koriste se za selekciju banke, s tim što PIC16F84A ima samo dve banke, pa RP1 nema uticaj i ne koristi se
4: TO- (timeout):
- 1 => Nakon dovođenja napajanja/CLRWDT/SLEEP
- 0 => Dogodio se timeout reset od WDT
3: PD- (power down):
- 1 => Nakon dovođenja napajanja ili CLRWDT
- 0 => Nakon SLEEP naredbe
2: Z (zero):
- 1 => Rezultat aritmetičke ili logičke operacije je bio 0
- 0 => Rezultat nije bio 0
1: DC (digit carry):
- 1 => Došlo je do prenosa iz niže u višu tetradu
- 0 => Nije došlo do prenosa iz niže u višu tetradu
0: C (carry/borrow):
- Sabiranje:
- 1 => Dogodio se prenos bita najviše pozicije
- 0 => Nije se dogodio prenos bita najviše pozicije
- Oduzimanje:
- 1 => Nije se pozajmio bit najviše pozicije
- 0 => Pozajmio se bit najviše pozicije
INTCON registar
_______________________________________________________
| | | | | | | | |
| GIE | EEIE | T0IE | INTE | RBIE | T0IF | INTF | RBIF |
|______|______|______|______|______|______|______|______|
- Bitovi:
7: GIE => Bit globalne dozvole prekida
- 1 => Svi prekidi su omogućeni
- 0 => Svi prekidi su onemogućeni
6: EEIE => Dozvoljava prekid usled završetka upisa u EEPROM
- 1 => Omogućen prekida
- 0 => Onemogućen prekid
5: T0IE => Dozvoljava prekid usled prekoračenja TMR0:
- 1 => Omogućen
- 0 => Onemogućen
4: INTE => Dozvoljava prekid na RB0/INT priključku:
- 1 => Omogućen
- 0 => Onemogućen
3: RBIE => Dozvoljava prekid po promeni RB4-RB7:
- 1 => Omogućen
- 0 => Onemogućen
2: T0IF => Indikator (fleg) prekida TMR0:
- 1 => Došlo je do ove vrste prekida
- 0 => Nije došlo do ove vrste prekida
1: INTF => Indikator prekida RB0/INT:
- 1 => Došlo je do ove vrste prekida
- 0 => Nije došlo do ove vrste prekida
0: RBIF => Indikator prekida RB4-RB7:
- 1 => Došlo je do ove vrste prekida
- 0 => Nije došlo do ove vrste prekida
OPTION registar
___________________________________________________________________
| | | | | | | | |
| RBPU- | INTEDG | T0CS | T0SE | PSA | PS2 | PS1 | PS0 |
|________|________|________|________|_______|_______|_______|_______|
Bitovi:
7: Not RBPU => Bit Pull-up otpornika PORTB:
- 1 => PORTB otpornici su isključeni
- 0 => PORTB otpornici su uključeni
6: INTEDG => Ivica za spoljašnji prekid RB0:
- 1 => Rastuća
- 0 => Opadajuća
5: T0CS => Izbor takta za TMR0:
- 1 => Spoljašnji (RA4)
- 0 => Interni CLK
4: T0SE => Izbor ivice za TMR0 kada radi sa spoljnim taktom (na RA4):
- 1 => Opadajuća ivica (1 => 0) inkrementira TMR0
- 0 => Rastuća ivica (0 => 1) inkrementira TMR0
3: PSA => Dodela preskalera:
- 1 => WDT tajmeru
- 0 => TMR0 tajmeru
2: PS2 \
1: PS1 > Bivoti za izbor odnosa deljenja preskalera
0: PS0 /
EECON1 registar
______________________________________________________
| | | | | | | | |
| - | - | - | EEIF | WREERR | WREN | WR | RD |
|_____|_____|_____|______|________|______|______|______|
Bitovi:
4: EEIF => Interrupt fleg za detekciju prekida nakon upisa u EEPROM
3: WRERR => Greška pri prenosu
2: WREN => Omogućiti upis
1: WR => Izvršiti upis
0: RD => Izvršiti čitanje
CONFIGURATION WORD
_________________________________________________________
| | | | | | | | |
| CP | ... | ... | CP | PWRTE- | WDTE | FOSC1 | FOSC0 |
|______|_____|_____|______|________|______|_______|_______|
Bitovi:
13-4: CP (Code Protection):
- 1 => Zaštita isključena
- 0 => Programska memorija zaštićena
3: PWRTE- => Power-Up timer
- 1 => Isključen Power-Up timer
- 0 => Uključen Power-Up timer
2:
1-0: FOSC1, FOSC0 => Selekcija tipa oscilatora
- 00 => RC
- 01 => HS
- 10 => XT
- 11 => LP
|
import React, { Component } from 'react';
import Table from './common/table';
import Like from "./common/like";
import {Link} from "react-router-dom";
class MoviesTable extends Component {
columns = [
{
path: 'title',
lable: 'Title',
content: movie => <Link to={`/movies/${movie._id}`}>{movie.title}</Link> },
{ path: 'genre.name', lable: 'Genre' },
{ path: 'numberInStock', lable: 'Stock' },
{ path: 'dailyRentalRate', lable: 'Rate' },
{ key: 'like',
content: movie => (
<Like liked={movie.liked}
onClick={ ()=> this.props.onLike(movie)}
/> )},
{ key: 'delete',
content: movie =>
(<button onClick={ ()=> this.props.onDelete(movie)}
className="btn btn-danger btn-sm">
Delete
</button>) }
];
render() {
const { movies, onSort, sortColumn } = this.props;
return (
<Table columns={this.columns}
data={movies}
sortColumn={sortColumn}
onSort={onSort}
/>
);
}
}
export default MoviesTable;
|
/* Chapter 21 */
-- 1
SELECT Color
,SUM(CASE WHEN YEAR(SaleDate) = 2015 THEN SD.SalePrice
ELSE NULL END) AS '2015'
,SUM(CASE WHEN YEAR(SaleDate) = 2016 THEN SD.SalePrice
ELSE NULL END) AS '2016'
,SUM(CASE WHEN YEAR(SaleDate) = 2017 THEN SD.SalePrice
ELSE NULL END) AS '2017'
,SUM(CASE WHEN YEAR(SaleDate) = 2018 THEN SD.SalePrice
ELSE NULL END) AS '2018'
FROM stock ST
JOIN salesdetails SD
ON ST.StockCode = SD.StockID
JOIN sales SA
ON SA.SalesID = SD.SalesID
GROUP BY Color;
-- 2
WITH PivotDataSource_CTE (Make, Model, Color)
AS
(
SELECT MK.MakeName, MD.ModelName, ST.Color
FROM make MK
JOIN model MD ON MK.MakeID = MD.MakeID
JOIN stock ST ON ST.ModelID = MD.ModelID
)
SELECT make, model
,COUNT(CASE WHEN Color = 'Black' THEN Color
ELSE NULL END)
AS 'Black'
,COUNT(CASE WHEN Color = 'Blue' THEN Color
ELSE NULL END)
AS 'Blue'
,COUNT(CASE WHEN Color = 'British Racing Green'
THEN Color ELSE NULL END) AS 'British Racing Green'
,COUNT(CASE WHEN Color = 'Canary Yellow' THEN Color
ELSE NULL END) AS 'Canary Yellow'
,COUNT(CASE WHEN Color = 'Dark Purple' THEN Color
ELSE NULL END) AS 'Dark Purple'
,COUNT(CASE WHEN Color = 'Green' THEN Color
ELSE NULL END) AS 'Green'
,COUNT(CASE WHEN Color = 'Night Blue' THEN Color
ELSE NULL END) AS 'Night Blue'
,COUNT(CASE WHEN Color = 'Pink' THEN Color
ELSE NULL END)
AS 'Pink'
,COUNT(CASE WHEN Color = 'Red' THEN Color
ELSE NULL END) AS 'Red'
,COUNT(CASE WHEN Color = 'Silver' THEN Color
ELSE NULL END) AS 'Silver'
FROM PivotDataSource_CTE
GROUP BY Make, Model;
-- 3
SELECT Color, YearOfSale
,CASE CJ.YearOfSale
WHEN '2015' THEN '2015'
WHEN '2016' THEN '2016'
WHEN '2017' THEN '2017'
WHEN '2018' THEN '2018'
END AS SalesValue
FROM pivottable
CROSS JOIN
(
SELECT '2015' AS YearOfSale
UNION
SELECT '2016' AS YearOfSale
UNION
SELECT '2017' AS YearOfSale
UNION
SELECT '2018' AS YearOfSale
) CJ
ORDER BY Color, YearOfSale;
-- 4
SELECT MakeName, Color, SUM(Cost) AS Cost
FROM make MK
JOIN model MD ON MK.MakeID = MD.MakeID
JOIN stock ST ON ST.ModelID = MD.ModelID
GROUP BY MakeName, Color WITH ROLLUP;
-- 5
WITH GroupedSource_CTE
AS
(
SELECT
MakeName
,Color
,Count(*) AS NumberOfCarsBought
FROM make MK
JOIN model MD ON MK.MakeID = MD.MakeID
JOIN stock ST ON ST.ModelID = MD.ModelID
WHERE MakeName IS NOT NULL OR Color IS NOT NULL
GROUP BY MakeName, Color WITH ROLLUP
)
SELECT AggregationType
,Category
,NumberOfCarsBought
FROM
(
SELECT 'GrandTotal' AS AggregationType, NULL AS Category
,NumberOfCarsBought, 1 AS SortOrder
FROM GroupedSource_CTE
WHERE MakeName IS NULL and Color IS NULL
UNION
SELECT 'make Subtotals', MakeName, NumberOfCarsBought , 2
FROM GroupedSource_CTE
WHERE MakeName IS NOT NULL and Color IS NULL
) SQ
ORDER BY SortOrder, NumberOfCarsBought DESC;
-- 6
WITH RECURSIVE HierarchyList_CTE
AS
(
SELECT StaffID, StaffName, Department, ManagerID, 1 AS StaffLevel
FROM staff
WHERE ManagerID IS NULL
UNION ALL
SELECT ST.StaffID, ST.StaffName
,ST.Department, ST.ManagerID, StaffLevel + 1
FROM staff ST
JOIN HierarchyList_CTE CTE
ON ST.ManagerID = CTE.StaffID
)
SELECT STF.Department
,STF.StaffName
,CTE.StaffName AS ManagerName
,CTE.StaffLevel
FROM HierarchyList_CTE CTE
JOIN staff STF
ON STF.ManagerID = CTE.StaffID;
-- 7
WITH RECURSIVE HierarchyList_CTE
AS
(
SELECT StaffID, StaffName, Department, ManagerID, 1 AS StaffLevel
FROM staff
WHERE ManagerID IS NULL
UNION ALL
SELECT ST.StaffID, ST.StaffName
,ST.Department, ST.ManagerID, StaffLevel + 1
FROM staff ST
JOIN HierarchyList_CTE CTE
ON ST.ManagerID = CTE.StaffID
)
SELECT STF.Department
,CONCAT(SPACE(StaffLevel * 2)
,STF.StaffName)
AS StaffMember
,CTE.StaffName AS ManagerName
,CTE.StaffLevel
FROM HierarchyList_CTE CTE
JOIN staff STF
ON STF.ManagerID = CTE.StaffID
ORDER BY Department, StaffLevel, CTE.StaffName;
-- 8
SELECT REPLACE(CustomerName, 'Ltd', 'Limited')
AS NoAcronymName
FROM customer
WHERE LOWER(CustomerName) LIKE '%ltd%';
-- 9
SELECT
INSERT(StockCode,1,23,'PrestigeCars-') AS NewStockCode
,Cost
,RepairsCost
,PartsCost
,TransportInCost
FROM stock;
-- 10
WITH ConcatenateSource_CTE (MakeModel, Color)
AS
(
SELECT DISTINCT CONCAT(MakeName, ' ', ModelName), Color
FROM make MK
JOIN model AS MD USING(MakeID)
JOIN stock AS ST USING(ModelID)
JOIN salesdetails SD ON SD.SalesDetailsID = ST.StockCode)
SELECT MakeModel, GROUP_CONCAT(DISTINCT Color) AS ColorList
FROM ConcatenateSource_CTE
GROUP BY MakeModel;
-- 11
SELECT MK.MakeName, MD.ModelName
,TRUNCATE(ST.Cost, 0), DATE(SA.SaleDate)
INTO OUTFILE 'C:\\MariaDBQueriesSampleData\\SalesList.txt'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
FROM make AS MK
JOIN model AS MD USING(MakeID)
JOIN stock AS ST USING(ModelID)
JOIN salesdetails SD ON ST.StockCode = SD.StockID
JOIN sales AS SA USING(SalesID)
ORDER BY MK.MakeName, MD.ModelName;
-- 12
SELECT 'MakeName', 'ModelName', 'Cost', 'SaleDate'
UNION ALL
SELECT MK.MakeName, MD.ModelName
,TRUNCATE(ST.Cost, 0), DATE(SA.SaleDate)
INTO OUTFILE 'C:\\MariaDBQueriesSampleData\\SalesList.txt'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
FROM make AS MK
JOIN model AS MD USING(MakeID)
JOIN stock AS ST USING(ModelID)
JOIN salesdetails SD ON ST.StockCode = SD.StockID
JOIN sales AS SA USING(SalesID)
WHERE MK.MakeName = 'Bentley';
-- 13
SELECT RPAD('MakeName', 35, ' ')
,RPAD('ModelName', 35, ' ')
,RPAD('Cost', 15, ' ')
,RPAD('SaleDate', 15, ' ')
UNION ALL
SELECT RPAD(MK.MakeName, 35, ' ')
,RPAD(MD.ModelName, 35, ' ')
,LPAD(TRUNCATE(ST.Cost, 0), 15, ' ')
,LPAD(DATE(SA.SaleDate), 15, ' ')
INTO OUTFILE 'C:\\MariaDBQueriesSampleData\\SalesListFixed.txt'
LINES TERMINATED BY '\r\n'
FROM make AS MK
JOIN model AS MD USING(MakeID)
JOIN stock AS ST USING(ModelID)
JOIN salesdetails SD ON ST.StockCode = SD.StockID
JOIN Sales AS SA USING(SalesID);
-- 14
SELECT TRIM(MK.MakeName), TRIM(MD.ModelName)
,TRIM(TRUNCATE(ST.Cost, 0)), TRIM(DATE(SA.SaleDate))
INTO OUTFILE 'C:\\MariaDBQueriesSampleData\\SalesList.txt'
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
FROM make AS MK
JOIN model AS MD USING(MakeID)
JOIN stock AS ST USING(ModelID)
JOIN salesdetails SD ON ST.StockCode = SD.StockID
JOIN sales AS SA USING(SalesID)
ORDER BY MK.MakeName, MD.ModelName;
|
// filename : guest.h
#include <iostream>
#include <algorithm>
#include "date.h"
using namespace std;
#ifndef GUEST_H
#define GUEST_H
class Guest {
public:
/**
* 构造函数
* @param id_card 身份证
* @param chick_in_date 入住时间
* @param name 名称
* @param gender 性别(男性为0, 女性为1)
*/
Guest (string id_card,
Date &chick_in_date,
string name,
string gender = "man")
: id_card(id_card),
name(name){
this->chick_in_date = chick_in_date;
if(gender == "female" || "woman" || "girl"){
this->gender = 1;
}
};
/**
* 显示成员信息
*/
void show() {
cout << (gender ? "Her" : "His") << " name is: "
<< name << "\nID_card: " << id_card
<< "\ncheck in date: " << chick_in_date << endl;
}
void check_in() {
cout << "Guset room check in" << endl;
}
void check_out() {
cout << "Guest room check out" << endl;
}
friend ofstream &operator<<(ofstream & out, Guest &a) {
out << a.id_card << "," << a.chick_in_date << ","
<< a.name << "," << (a.gender ? "woman": "man") << endl;
return out;
}
string get_id_card(){
return id_card;
}
string get_check_in_date(){
return chick_in_date.get_date();
}
string get_name(){
return name;
}
string get_gender(){
return (gender ? "female" : "male");
}
private:
string id_card;
Date chick_in_date;
string name;
bool gender = 0; // 默认为男性
};
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using Cells;
using Cells.Components;
using UnityEngine;
namespace GameGrid
{
public static class GridShiftExtensions
{
public static Direction GetTurnDirection(this Grid grid, Cell cell)
{
var indexOfA = grid.IndexOf(grid.Hero);
var indexOfB = grid.IndexOf(cell);
return VectorToDirection(indexOfB - indexOfA);
}
/// <summary>
/// Only work for vertical and horizontal movements
/// </summary>
public static Direction GetTurnDirection(this Grid grid, Cell a, Cell b)
{
var indexOfA = grid.IndexOf(a);
var indexOfB = grid.IndexOf(b);
return VectorToDirection(indexOfB - indexOfA);
}
public static Direction GetShiftDirection(this Grid grid, Cell a, Cell b)
{
var turnDirection = grid.GetTurnDirection(a, b);
var shiftDirection = turnDirection.NextDirectionClockwise();
return shiftDirection;
}
/// <summary>
/// Get shift details based on a current turn direction, shift direction is random, cells in a direction never contains Hero.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="index">Index of a cell that was removed and need to be filled by shifting.</param>
/// <param name="turnDirection">Direction of a current turn.</param>
/// <returns>Shift details.</returns>
public static CellShiftDetails GetRandomShiftDetails(this Grid grid, Vector2Int index, Direction turnDirection)
{
var direction = turnDirection;
var shiftNoneOrHero = true;
CellShiftDetails shiftDetails = null;
while (shiftNoneOrHero)
{
shiftDetails = GetCellsFromDirection(grid, index, direction);
shiftNoneOrHero = !shiftDetails.Cells.Any() || shiftDetails.Cells.Any(x => x.HasCellComponent<Hero>());
direction = direction.NextDirectionClockwise();
}
return shiftDetails;
}
public static CellShiftDetails GetShiftDetails(this Grid grid, Cell cell, Direction turnDirection)
{
var cellIndex = grid.IndexOf(cell);
return grid.GetShiftDetails(cellIndex, turnDirection);
}
/// <summary>
/// Get shift details based on a current turn direction, shift from first available direction clockwise.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="cellIndex">Index of a cell that was removed and need to be filled by shifting.</param>
/// <param name="turnDirection">Direction of a current turn.</param>
/// <returns>Shift details.</returns>
public static CellShiftDetails GetShiftDetails(this Grid grid, Vector2Int cellIndex, Direction turnDirection)
{
var cellShiftDetails = new List<CellShiftDetails>();
for (int i = 1; i < 4; i++)
{
var currentShiftFromDirection = turnDirection.NextDirectionClockwise(i);
cellShiftDetails.Add(grid.GetCellsFromDirection(cellIndex, currentShiftFromDirection));
}
var maxCellsCount = cellShiftDetails.Select(x => x.Cells.Count).Max();
return cellShiftDetails.First(x => x.Cells.Count == maxCellsCount);
}
private static CellShiftDetails GetCellsFromDirection(this Grid grid, Vector2Int startIndex, Direction direction)
{
var shiftFromIndex = ToIndex(direction);
var cellShiftDetails = new CellShiftDetails
{
ShiftFrom = direction.ToIndex()
};
var index = startIndex + shiftFromIndex;
while (grid.IsIndexInBounds(index))
{
cellShiftDetails.Cells.Add(grid.GetCell(index));
cellShiftDetails.LastCellIndex = index;
index += shiftFromIndex;
}
return cellShiftDetails;
}
public static Direction VectorToDirection(Vector2Int vector)
{
if (vector == Vector2Int.up)
{
return Direction.Up;
}
if (vector == Vector2Int.right)
{
return Direction.Right;
}
if (vector == Vector2Int.down)
{
return Direction.Down;
}
if (vector == Vector2Int.left)
{
return Direction.Left;
}
throw new ArgumentOutOfRangeException();
}
public static Direction NextDirectionClockwise(this Direction direction, int offset = 1)
{
return (Direction)(((int)direction + offset) % 4);
}
public static Vector2Int ToIndex(this Direction direction)
{
return direction switch
{
Direction.Up => Vector2Int.up,
Direction.Right => Vector2Int.right,
Direction.Down => Vector2Int.down,
Direction.Left => Vector2Int.left,
_ => throw new ArgumentOutOfRangeException()
};
}
}
// this is just for readability
// for actual usage Vector2 looks more usable
public enum Direction
{
Up = 0,
Right = 1,
Down = 2,
Left = 3
}
}
|
package memberservice.member.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Aspect // <- AOP
@Component // -> 컴포넌트 스캔을 통해 스프링 빈을 자동 등록
public class TimeTraceAop {
// @Around("execution(* memberservice.member.service..*(..))")
// @Around("execution(* memberservice.member.repository..*(..))")
// @Around("execution(* memberservice.member.controller..*(..))")
@Around("execution(* memberservice.member..*(..))") // -> AOP targeting : 해당 패키지의 하위 전부를 타케팅
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
System.out.println("START : " + joinPoint.toString());
try {
return joinPoint.proceed();
} finally {
long finish = System.currentTimeMillis();
long timeMs = finish - start;
System.out.println("END : " + joinPoint.toString() + " " + timeMs + " ms");
}
}
}
|
/*
-----------CONSIGNA PRIMER PARCIAL----------------------------------
Crear un algoritmo que represente un contador binario,
el primer led(que se encuentra a la izq) es el mas significativo
los valores van de 0 a 15.
---------------------------------------------------------------------
*/
#define B3 12
#define B2 11
#define B1 10
#define B0 9
#define TIEMPO 1000
void PrenderLed(int encenderLed);
void EncenderBinario(int estado3, int estado2,int estado1,int estado0);
void setup()
{
pinMode(B3, OUTPUT);
pinMode(B2, OUTPUT);
pinMode(B1, OUTPUT);
pinMode(B0, OUTPUT);
Serial.begin(9600);
}
int contador=0;
void loop()
{
contador++;
if(contador>15)
{
contador=0;
}
PrenderLed(contador);
delay(TIEMPO);
}
//muestra el numero binario
void PrenderLed(int encenderLed)
{
Serial.println(encenderLed);
switch(encenderLed)
{
case 0:
EncenderBinario(LOW,LOW,LOW,LOW);
break;
//Dato 0001
case 1:
EncenderBinario(LOW,LOW,LOW,HIGH);
break;
//Dato 0010
case 2:
EncenderBinario(LOW,LOW,HIGH,LOW);
break;
//Dato 0011
case 3:
EncenderBinario(LOW,LOW,HIGH,HIGH);
break;
//Dato 0100
case 4:
EncenderBinario(LOW,HIGH,LOW,LOW);
break;
//Dato 0101
case 5:
EncenderBinario(LOW,HIGH,LOW,HIGH);
break;
//Dato 0110
case 6:
EncenderBinario(LOW,HIGH,HIGH,LOW);
break;
//Dato 0111
case 7:
EncenderBinario(LOW,HIGH,HIGH,HIGH);
break;
//Dato 1000
case 8:
EncenderBinario(HIGH,LOW,LOW,LOW);
break;
//Dato 1001
case 9:
EncenderBinario(HIGH,LOW,LOW,HIGH);
break;
//Dato 1010
case 10:
EncenderBinario(HIGH,LOW,HIGH,LOW);
break;
//Dato 1011
case 11:
EncenderBinario(HIGH,LOW,HIGH,HIGH);
break;
//Dato 1100
case 12:
EncenderBinario(HIGH,HIGH,LOW,LOW);
break;
//Dato 1101
case 13:
EncenderBinario(HIGH,HIGH,LOW,HIGH);
break;
//Dato 1110
case 14:
EncenderBinario(HIGH,HIGH,HIGH,LOW);
break;
//Dato 1111
case 15:
EncenderBinario(HIGH,HIGH,HIGH,HIGH);
break;
}
}
//Enciende cada led dependiendo el estado que recibe
void EncenderBinario(int estado3, int estado2,int estado1,int estado0)
{
digitalWrite(B3,estado3);
digitalWrite(B2,estado2);
digitalWrite(B1,estado1);
digitalWrite(B0,estado0);
}
|
import React from 'react';
import { Typography, type TypographyProps } from '@mui/material';
import { type Variant } from '@mui/material/styles/createTypography';
export type VariantType =
| 'heading1'
| 'heading2'
| 'heading3'
| 'heading4'
| 'heading5'
| 'heading6'
| 'bodyCopyXLHeavy'
| 'bodyCopyLHeavy'
| 'bodyCopyLBold'
| 'bodyCopyMHeavy'
| 'bodyCopyMBold'
| 'bodyCopyMMedium'
| 'bodyCopyMRegular'
| 'bodyCopySHeavy'
| 'bodyCopySBold'
| 'bodyCopySMedium'
| 'bodyCopySRegular'
| 'bodyCopyXSBold'
| 'bodyCopyXSMedium'
| 'bodyCopyTMedium'
| 'bodyCopyTBold';
type Props = {
children: React.ReactNode;
variant: VariantType;
component?: React.ElementType;
} & Omit<TypographyProps, 'variant'>;
const variantMapping = {
heading1: 'heading1',
heading2: 'heading2',
heading3: 'heading3',
heading4: 'heading4',
heading5: 'heading5',
heading6: 'heading6',
bodyCopyXLHeavy: 'bodyCopyXL',
bodyCopyLHeavy: 'bodyCopyL',
bodyCopyLBold: 'bodyCopyL',
bodyCopyMHeavy: 'bodyCopyM',
bodyCopyMBold: 'bodyCopyM',
bodyCopyMMedium: 'bodyCopyM',
bodyCopyMRegular: 'bodyCopyM',
bodyCopySHeavy: 'bodyCopyS',
bodyCopySBold: 'bodyCopyS',
bodyCopySMedium: 'bodyCopyS',
bodyCopySRegular: 'bodyCopyS',
bodyCopyXSBold: 'bodyCopyXS',
bodyCopyXSMedium: 'bodyCopyXS',
bodyCopyTMedium: 'bodyCopyT',
bodyCopyTBold: 'bodyCopyT',
};
const weightMapping = {
heading1: '900',
heading2: '900',
heading3: '900',
heading4: '700',
heading5: '700',
heading6: '700',
bodyCopyXLHeavy: '700',
bodyCopyLHeavy: '700',
bodyCopyLBold: '600',
bodyCopyMHeavy: '700',
bodyCopyMBold: '600',
bodyCopyMMedium: '500',
bodyCopyMRegular: '400',
bodyCopySHeavy: '700',
bodyCopySBold: '600',
bodyCopySMedium: '500',
bodyCopySRegular: '400',
bodyCopyXSBold: '600',
bodyCopyXSMedium: '500',
bodyCopyTMedium: '500',
bodyCopyTBold: '700',
};
export const TypoText = ({ variant, children, component = 'span', ...props }: Props) => (
<Typography
variant={variantMapping[variant] as Variant}
style={{ fontWeight: weightMapping[variant] }}
{...props}
component={component}
>
{children}
</Typography>
);
|
import React from 'react';
import { useDarkMode } from '../../context/DarkModeContext';
import styles from './Header.module.css';
import { MdDarkMode, MdOutlineLightMode } from 'react-icons/md';
export default function Header({ filters, filter, onFilterChange }) {
const { darkMode, toggleDarkMode } = useDarkMode();
return (
<header className={styles.header}>
<button className={styles.toggle} onClick={toggleDarkMode}>
{!darkMode && <MdDarkMode />}
{darkMode && <MdOutlineLightMode />}
</button>
<ul className={styles.filters}>
{filters.map((value, index) => (
<li key={index}>
<button
className={`${styles.filter} ${
value === filter && styles.selected
}`}
onClick={() => onFilterChange(value)}
>
{value}
</button>
</li>
))}
</ul>
</header>
);
}
|
package com.icss.etc.Service;
import com.icss.etc.pojo.CommonResult;
import com.icss.etc.pojo.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* value:指定要调用的远程服务的名称。该属性是必须的,用于唯一标识要调用的远程服务。
*
* configuration:指定Feign客户端的配置类。该属性是可选的,如果不指定,则使用默认的配置类。可以传递一个或多个@Configuration类型的Bean定义,用于配置Feign客户端的行为。
*
* name:指定Feign客户端的名称。等同于value
*
* fallback:指定Feign客户端的回退类。该属性是可选的,用于指定在调用远程服务失败时使用的备用实现类。
*
* decode404:指定是否对404错误进行解码。该属性是可选的,默认为false,表示不解码。如果设置为true,当调用远程服务返回404错误时,Feign会将其解码为相应的错误信息。
*
* encoder:指定Feign请求和响应的编码器。该属性是可选的,用于指定请求和响应的编码方式。可以使用自定义的编码器来处理特定的数据类型。
*
* contract:指定Feign客户端的契约类。该属性是可选的,用于指定Feign客户端的契约类,用于定义和约束远程服务的方法签名。
*
* path:指定Feign客户端的路径。该属性是可选的,用于指定Feign客户端的请求路径前缀。
*
* scopes:指定Feign客户端的作用域。该属性是可选的,用于指定Feign客户端的作用域,可以是RequestScope、SessionScope或GlobalScope。
*/
/**
* @FeignClient:这是Feign库提供的注解,用于声明一个Feign客户端
* 解释:调用名为"cloud-payment-service8001"的远程服务
*/
@Component
@FeignClient(value = "provider-payment8001")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
/**
* 调用是根据 @GetMapping(value = "/payment/testFeign666")路径来匹配远程接口的。
* 当使用@FeignClient注解声明一个Feign客户端时,可以通过value属性指定要调用的远程服务的名称。
* 在上述代码中,@FeignClient(value = "provider-payment8001")指定了要调用名为"provider-payment8001"的远程服务。
*
* 当调用PaymentFeignService接口中的testFeign()方法时,OpenFeign会根据接口上的@GetMapping注解
* 以及指定的路径/payment/testFeign666来查找远程服务的接口定义。
* 它会扫描类路径下的所有组件,查找带有@GetMapping注解的类,并解析出对应的URL路径。
* 然后,OpenFeign会将这些信息与远程服务的名称进行匹配,找到对应的接口定义。
*
* 如果找到了匹配的接口定义,OpenFeign就会将请求转发给相应的服务实现类,
* 并返回结果。在这个例子中,testFeign()方法被调用时,
* OpenFeign会将请求转发给名为"provider-payment8001"的远程服务的/payment/testFeign666接口定义,并返回结果。
*
*/
@GetMapping(value = "/payment/testFeign666")
public String testFeign();
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();
}
|
/*
* This file is part of the Robot Learning Lab SDK
*
* Copyright (C) 2020 Mark Weinreuter <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <rll_move/grasp_util.h>
#include <eigen_conversions/eigen_msg.h>
#include <fcl/collision.h>
#include <fcl/math/vec_3f.h>
#include <fcl/shape/geometric_shapes.h>
#include <tf/tf.h>
// for mesh objects
#include <geometric_shapes/shape_operations.h>
#include <geometric_shapes/shapes.h>
#define ALLOWED_ROTATION_DEVIATION (.01)
CollisionObjectBuilder& CollisionObjectBuilder::setPose(geometry_msgs::Pose pose)
{
pose_ = pose;
return *this;
}
// TODO(mark): rename reset or provide beginPrimitive/beginMesh?
CollisionObjectBuilder& CollisionObjectBuilder::begin()
{
object_ = moveit_msgs::CollisionObject();
pose_ = geometry_msgs::Pose();
pose_.orientation.w = 1; // minimum required pose TODO(mark): point up
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::addMesh(const std::string& file_path, double scale)
{
// Path where the .dae or .stl object is located
shapes::Mesh* m = shapes::createMeshFromResource(file_path, { scale, scale, scale });
if (m == nullptr)
{
ROS_FATAL("Your mesh '%s' failed to loaded", file_path.c_str());
return *this;
}
shape_msgs::Mesh mesh;
shapes::ShapeMsg mesh_msg;
shapes::constructMsgFromShape(m, mesh_msg); // TODO(mark): who owns this pointer?! should I delete it?
mesh = boost::get<shape_msgs::Mesh>(mesh_msg);
// TODO(mark): isn't it super expensive to always copy the mesh around?
object_.meshes.push_back(mesh);
is_primitive_ = false;
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::addCylinder(double radius, double height)
{
shape_msgs::SolidPrimitive primitive;
primitive.type = shape_msgs::SolidPrimitive::CYLINDER;
primitive.dimensions.resize(2);
primitive.dimensions[0] = height;
primitive.dimensions[1] = radius;
object_.primitives.push_back(primitive);
is_primitive_ = true;
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::positionBottomAtZ(double height, double collision_offset)
{
pose_.position.z += height / 2 + collision_offset;
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::setPosition(const geometry_msgs::Point& point)
{
pose_.position = point;
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::translate(double x, double y, double z)
{
pose_.position.x += x;
pose_.position.y += y;
pose_.position.z += z;
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::rotateRPY(double r, double p, double y)
{
static tf2::Quaternion quaternion;
quaternion.setRPY(r, p, y);
pose_.orientation.x = quaternion.x();
pose_.orientation.y = quaternion.y();
pose_.orientation.z = quaternion.z();
pose_.orientation.w = quaternion.w();
return *this;
}
CollisionObjectBuilder& CollisionObjectBuilder::addBox(double w, double h, double d)
{
shape_msgs::SolidPrimitive primitive;
primitive.type = shape_msgs::SolidPrimitive::BOX;
primitive.dimensions.resize(3);
primitive.dimensions[0] = w;
primitive.dimensions[1] = h;
primitive.dimensions[2] = d;
is_primitive_ = true;
object_.primitives.push_back(primitive);
return *this;
}
moveit_msgs::CollisionObject CollisionObjectBuilder::build(const std::string& id, const std::string& frame_id)
{
object_.operation = moveit_msgs::CollisionObject::ADD;
object_.id = id;
object_.header.frame_id = frame_id;
if (is_primitive_)
{
object_.primitive_poses.push_back(pose_);
}
else
{
object_.mesh_poses.push_back(pose_);
}
return std::move(object_); // TODO(mark): want to mark as invalid, but move on return is bad? (see effective c++)
}
|
import 'package:flutter/material.dart';
class CustomSliderWidget extends StatefulWidget {
final double height;
final double width;
const CustomSliderWidget({super.key,this.height=300,this.width=90});
@override
State<CustomSliderWidget> createState() => _CustomSliderWidgetState();
}
class _CustomSliderWidgetState extends State<CustomSliderWidget> {
/// Global Key to Recognize the widget
final GlobalKey _key=LabeledGlobalKey("main_slider");
/// initial values
bool _showPercent=false;
double _dragPosition=0;
double _dragPercent=0.5;
/// When Drag Starts
void _onDragStart(DragStartDetails details){
/// check the currentContext
if(_key.currentContext==null)return;
/// Initializing the renderBox using _key
final renderBox=_key.currentContext!.findRenderObject() as RenderBox;
/// Getting position and converting the into Offset
final offSet=renderBox.globalToLocal(details.globalPosition);
/// Calling the _onDrag to Update values and state
_onDrag(offSet);
}
/// When Drag Update
void _onDragUpdate(DragUpdateDetails details){
/// check the currentContext
if(_key.currentContext==null)return;
/// Initializing the renderBox using _key
final renderBox=_key.currentContext!.findRenderObject() as RenderBox;
/// Getting position and converting the into Offset
final offSet=renderBox.globalToLocal(details.globalPosition);
/// Calling the _onDrag to Update values and state
_onDrag(offSet);
}
/// When Drag End
void _onDraEnd( DragEndDetails details){
/// Setting _showPercent to false to hide the top Percentage
setState(() {
_showPercent=false;
});
}
/// ONDrag Method
void _onDrag(Offset offset){
/// Creating the tempDragPosition variable and assgin value as 0;
double tempDragPosition=0;
/// Checking the drag Height is less than 0
if(offset.dy<=0){
tempDragPosition=0;
/// Checking the drag Height is greater than actual container height
}else if(offset.dy>=widget.height){
tempDragPosition=widget.height;
/// else setting the tempDragPosition offset.dy (means drag height)
}else{
tempDragPosition=offset.dy;
}
/// Updating the value
setState(() {
_dragPosition=tempDragPosition;
_dragPercent=_dragPosition/widget.height;
if(!_showPercent)_showPercent=true;
});
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
//// Percentage Line ///////
Container(
height: widget.height,
margin:const EdgeInsets.fromLTRB(0, 20, 8,4),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.generate(11, (index) => Text("${100-(index*10)}",style: const TextStyle(color: Colors.white),))
),
),
Column(
mainAxisSize: MainAxisSize.min,
children: [
//// Percent indicator
AnimatedOpacity(
opacity: _showPercent?1:0, duration: const Duration(milliseconds: 100),
child: Text("${(_dragPercent*100).floor()}%",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
),
const SizedBox(height: 8,),
/////// Slider with Border /////
Container(
decoration: BoxDecoration(
border: Border.all(
width: 8,
color: Colors.white),
borderRadius: BorderRadius.circular(16)
),
child: GestureDetector(
onVerticalDragStart: _onDragStart,
onVerticalDragUpdate: _onDragUpdate,
onVerticalDragEnd: _onDraEnd,
child: RotatedBox(
quarterTurns: 2,
child: Container(
key: _key,
height: widget.height,
width: widget.width,
child: AbsorbPointer(
child: ClipPath(
clipper: PercentagePainter(percetage: _dragPercent),
child: Container(
height: widget.height,
width: widget.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
gradient:const LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Color(0xFFDEAC6A),
Color(0xFFFA2323)])
),
),
),
),
),
),
),
)
],
)
],
);
}
}
class PercentagePainter extends CustomClipper<Path>{
final double percetage;
PercentagePainter({ required this.percetage});
@override
Path getClip(Size size) {
final path =Path();
path.moveTo(0, size.height*percetage);
path.lineTo(0,0);
path.lineTo(size.width, 0);
path.lineTo(size.width, size.height*percetage);
path.close();
return path;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
// TODO: implement shouldReclip
return true;
}
}
|
<?php
namespace SergiX44\Nutgram\Handlers\Listeners;
use InvalidArgumentException;
use SergiX44\Nutgram\Exception\ApiException;
use SergiX44\Nutgram\Handlers\CollectHandlers;
use SergiX44\Nutgram\Handlers\Handler;
use SergiX44\Nutgram\Telegram\Properties\UpdateType;
/**
* @mixin CollectHandlers
*/
trait SpecialListeners
{
protected const FALLBACK = 'FALLBACK';
protected const EXCEPTION = 'EXCEPTION';
protected const BEFORE_API_REQUEST = 'BEFORE_API_REQUEST';
protected const AFTER_API_REQUEST = 'AFTER_API_REQUEST';
protected const API_ERROR = 'API_ERROR';
/**
* @param $callable
* @return Handler
*/
public function fallback($callable): Handler
{
return $this->{$this->target}[self::FALLBACK][] = new Handler($callable);
}
/**
* @param UpdateType $type
* @param $callable
* @return Handler
*/
public function fallbackOn(UpdateType $type, $callable): Handler
{
$this->checkFinalized();
return $this->{$this->target}[self::FALLBACK][$type->value] = new Handler($callable, $type->value);
}
/**
* @param callable|string $callableOrException
* @param callable|null $callable
* @return Handler
*/
public function onException($callableOrException, $callable = null): Handler
{
$this->checkFinalized();
return $this->registerErrorHandlerFor(self::EXCEPTION, $callableOrException, $callable);
}
/**
* @param callable|string $callableOrPattern
* @param callable|null $callable
* @return Handler
*/
public function onApiError($callableOrPattern, $callable = null): Handler
{
$this->checkFinalized();
return $this->registerErrorHandlerFor(self::API_ERROR, $callableOrPattern, $callable);
}
/**
* @param string $exceptionClass
* @return Handler
*/
public function registerApiException(string $exceptionClass): Handler
{
$this->checkFinalized();
if (!is_subclass_of($exceptionClass, ApiException::class)) {
throw new InvalidArgumentException(
sprintf('The provided exception must be a subclass of %s.', ApiException::class)
);
}
if ($exceptionClass::$pattern === null) {
throw new InvalidArgumentException(
sprintf('The $pattern must be defined on the class %s.', $exceptionClass)
);
}
return $this->registerErrorHandlerFor(self::API_ERROR, $exceptionClass::$pattern, $exceptionClass);
}
/**
* @param $callable
* @return Handler
*/
public function beforeApiRequest($callable): Handler
{
$this->checkFinalized();
return $this->{$this->target}[self::BEFORE_API_REQUEST] = (new Handler($callable))->skipGlobalMiddlewares();
}
/**
* @param $callable
* @return Handler
*/
public function afterApiRequest($callable): Handler
{
$this->checkFinalized();
return $this->{$this->target}[self::AFTER_API_REQUEST] = (new Handler($callable))->skipGlobalMiddlewares();
}
}
|
import 'package:cloud_firestore/cloud_firestore.dart';
class UserRecord {
final String uid;
final String username;
final String gender;
final String photoUrl;
UserRecord({
required this.uid,
required this.username,
required this.gender,
this.photoUrl = '',
});
Map<String, dynamic> toJson() {
return {
'uid': uid,
'username': username,
'gender': gender,
'photoUrl': photoUrl,
};
}
static UserRecord userFromSnapshot(DocumentSnapshot snapshot) {
return UserRecord(
uid: snapshot['uid'],
username: snapshot['username'],
gender: snapshot['gender'],
photoUrl: snapshot['photoUrl'],
);
}
}
|
import { useEffect, useRef } from "react";
const useClickOutSide = (callBack) => {
const ref = useRef();
useEffect(() => {
console.log(ref);
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
callBack();
}
};
document.addEventListener("click", handleClick, true);
return () => document.removeEventListener("click", handleClick, true);
}, []);
return ref;
};
export default useClickOutSide;
|
import { View, Text, StyleSheet, Pressable, TouchableOpacity } from 'react-native';
import React, { useState, useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../config';
import { FlashList } from '@shopify/flash-list';
import { Entypo } from '@expo/vector-icons';
import { MaterialIcons } from '@expo/vector-icons';
const Home = () => {
const [notes, setNotes] = useState([]);
const navigation = useNavigation();
useEffect(() => {
const unsubscribe = firebase.firestore()
.collection('notes')
.onSnapshot((querySnapshot) => {
const newNotes = [];
querySnapshot.forEach((doc) => {
const { note, title } = doc.data();
newNotes.push({ note, title, id: doc.id });
});
setNotes(newNotes);
});
return () => {
unsubscribe();
};
}, []);
const handleLogout = () => {
firebase.auth().signOut()
.then(() => {
// Successfully logged out, navigate to the Login screen
navigation.navigate('Login');
})
.catch(error => {
alert(error.message);
});
};
return (
<View style={styles.container}>
{notes.length === 0 ? (
<View style={styles.createNotesContainer}>
<Text style={styles.createNotesText}>Create New Notes</Text>
</View>
) : (
<FlashList
data={notes}
numColumns={2}
estimatedItemSize={100}
renderItem={({ item }) => (
<View style={styles.noteView}>
<Pressable
onPress={() => navigation.navigate('Detail', { item })}
>
<Text style={styles.noteTitle}>
{item.title}
</Text>
<Text style={styles.noteDescription}>
{item.note}
</Text>
</Pressable>
</View>
)}
/>
)}
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('NoteAdd')}
>
<Entypo name='plus' size={45} color='black' />
</TouchableOpacity>
<TouchableOpacity
style={styles.logoutButton}
onPress={handleLogout}
>
<MaterialIcons name="logout" size={45} color="black" />
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#BCA37F',
},
noteView: {
flex: 1,
backgroundColor: '#FAEED1',
margin: 10,
padding: 10,
borderRadius: 10,
shadowColor: 'black',
shadowOffset: { width: 0, height: 0 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 7,
alignItems: 'center',
},
noteTitle: {
fontSize: 20,
fontWeight: 'bold',
},
noteDescription: {
fontSize: 16,
marginTop: 5,
},
button: {
position: 'absolute',
bottom: 60,
right: 30,
backgroundColor: '#FAEED1',
borderRadius: 50,
padding: 10,
elevation: 7,
},
logoutButton: {
position: 'absolute',
bottom:150,
right: 30,
backgroundColor: '#FAEED1',
borderRadius: 50,
padding: 10,
elevation: 7,
},
logoutButtonText: {
color: 'black',
fontSize: 16,
fontWeight: 'bold',
},
createNotesContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
createNotesText: {
fontSize: 24,
fontWeight: 'bold',
color: '#000',
},
});
export default Home;
|
import express, {Application} from 'express';
import cors from "cors";
import userRoutes from "../routes/usuario";
import db from '../db/connection';
class Server {
private app: Application;
private port: String;
private apiPaths = {
usuarios: '/api/usuarios'
}
constructor(){
this.app = express();
this.port = process.env.PORT || '8000';
//Definir middlewares
this.middlewares();
//Definir mis rutas
this.routes();
//Definir BBDD
this.dbConnection();
}
async dbConnection(){
try {
await db.authenticate();
console.log('Base de datos Online');
} catch (error) {
throw new Error('Error al conectar la BD');
}
}
middlewares(){
//cors
this.app.use( cors());
//lectura del body
this.app.use(express.json());
//carpeta pública
this.app.use(express.static('public'));
}
routes(){
this.app.use(this.apiPaths.usuarios, userRoutes);
}
listen(){
this.app.listen( this.port, () =>{
console.log('Servidor corriendo en el puerto:', this.port);
})
}
}
export default Server;
|
/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrien Kirjak – initial implementation
*
** @version 0.0.1
** @purpose 1:16.1.2, Ensure that the IUT recognizes predefined functions and correctly evaluates them (as specified by Annex C)
** @verdict pass accept, ttcn3verdict:pass
***************************************************/
module Sem_160102_predefined_functions_012 {
type enumerated EnumeratedType {e_black, e_white};
type enumerated EnumeratedTypeWithLabels1 {e_black (-1), e_red (1), e_white(0) , e_yellow }; //e_yellow is 2
type component GeneralComp {
}
testcase TC_Sem_160102_predefined_functions_012 () runs on GeneralComp {
var EnumeratedType vl_enum_black := e_black;
var EnumeratedType vl_enum_white := e_white;
var EnumeratedTypeWithLabels1 vl_enum1_red := e_white;
var EnumeratedTypeWithLabels1 vl_enum1_yellow := e_black;
const EnumeratedType c_enum_black := e_black;
const EnumeratedType c_enum_white := e_white;
const EnumeratedTypeWithLabels1 c_enum1_red := e_red;
const EnumeratedTypeWithLabels1 c_enum1_yellow := e_yellow;
int2enum(1,vl_enum1_red);
int2enum(2,vl_enum1_yellow);
setverdict(pass);
if (vl_enum1_red != c_enum1_red) {
setverdict(fail, "cannot decode e_red");
}
if (vl_enum1_yellow != c_enum1_yellow) {
setverdict(fail, "cannot decode e_yellow");
}
}
control{
execute(TC_Sem_160102_predefined_functions_012());
}
}
|
from prophet import Prophet
from pyspark.sql.functions import *
from pyspark.sql.types import *
import pandas as pd
from sklearn.metrics import mean_squared_error, mean_absolute_error
from math import sqrt
class DBUForecaster():
"""
Class for DBU Forecasting
"""
def __init__(self, forecast_periods=7, interval_width=0.85, forecast_frequency='d', include_history=True):
"""
Initilization function
:param forecast_periods: Periods to forecast. Default is 7.
:param interval_width: confidence level of min/max thresholds. Default is 0.85
:param forecast_frequency: frequency of the ds column. Default is daily i.e. 'd'
:param include_history: whether or not to include history in the output dataframe. Default is True.
"""
self.forecast_periods=forecast_periods
self.forecast_frequency=forecast_frequency
self.include_history=include_history
self.interval_width=interval_width
# Training output schema
self.forecast_result_schema = StructType([
StructField('ds',DateType()),
# StructField('workspace_id', StringType()),
StructField('sku',StringType()),
StructField('y',FloatType()),
StructField('yhat',FloatType()),
StructField('yhat_upper',FloatType()),
StructField('yhat_lower',FloatType())
])
# Evaluation output schema
self.eval_schema =StructType([
StructField('training_date', DateType()),
# StructField('workspace_id', StringType()),
StructField('sku', StringType()),
StructField('mae', FloatType()),
StructField('mse', FloatType()),
StructField('rmse', FloatType())
])
# Evaluation output schema
def generate_forecast(self, history_pd):
"""
Function to generate forecasts
"""
# remove missing values (more likely at day-store-item level)
history_pd = history_pd.dropna()
# train and configure the model
model = Prophet( interval_width=self.interval_width )
model.fit( history_pd )
# make predictions
future_pd = model.make_future_dataframe(
periods=self.forecast_periods,
freq=self.forecast_frequency,
include_history=self.include_history
)
forecast_pd = model.predict( future_pd )
# ASSEMBLE EXPECTED RESULT SET
# --------------------------------------
# get relevant fields from forecast
f_pd = forecast_pd[ ['ds','yhat', 'yhat_upper', 'yhat_lower'] ].set_index('ds')
# get relevant fields from history
# h_pd = history_pd[['ds','workspace_id','sku','y']].set_index('ds')
h_pd = history_pd[['ds','sku','y']].set_index('ds')
# join history and forecast
results_pd = f_pd.join( h_pd, how='left' )
results_pd.reset_index(level=0, inplace=True)
# get sku & workspace id from incoming data set
results_pd['sku'] = history_pd['sku'].iloc[0]
# results_pd['workspace_id'] = history_pd['workspace_id'].iloc[0]
# return results_pd[ ['ds', 'workspace_id', 'sku', 'y', 'yhat', 'yhat_upper', 'yhat_lower'] ]
return results_pd[ ['ds', 'sku', 'y', 'yhat', 'yhat_upper', 'yhat_lower'] ]
def evaluate_forecast(self, evaluation_pd):
"""
Forecast evaluation function. Generates MAE, RMSE, MSE metrics.
"""
evaluation_pd = evaluation_pd[evaluation_pd['y'].notnull()]
# get sku in incoming data set
training_date = evaluation_pd['training_date'].iloc[0]
sku = evaluation_pd['sku'].iloc[0]
# workspace_id = evaluation_pd['workspace_id'].iloc[0]
# calulate evaluation metrics
mae = mean_absolute_error( evaluation_pd['y'], evaluation_pd['yhat'] )
mse = mean_squared_error( evaluation_pd['y'], evaluation_pd['yhat'] )
rmse = sqrt( mse )
# assemble result set
# results = {'training_date':[training_date], 'workspace_id':[workspace_id], 'sku':[sku], 'mae':[mae], 'mse':[mse], 'rmse':[rmse]}
results = {'training_date':[training_date], 'sku':[sku], 'mae':[mae], 'mse':[mse], 'rmse':[rmse]}
return pd.DataFrame.from_dict( results )
class ForecastHelper():
def apply_forecast(forecast_client):
def apply(df):
return forecast_client.generate_forecast(df)
return apply
def score_forecasts(df, forecast_client):
group_cols = [x for x in list(df.columns) if x not in ['ds','y']]
print(f"Grouping By the following columns: {group_cols}")
return (df.groupBy(*group_cols)
.applyInPandas(ForecastHelper.apply_forecast(forecast_client), schema=forecast_client.forecast_result_schema)
.withColumn('training_date', current_timestamp() )
)
def apply_forecast_eval(forecast_client):
def apply_eval(df):
return forecast_client.evaluate_forecast(df)
return apply_eval
def eval_forecasts(df, forecast_client):
group_cols = [x for x in list(df.columns) if x not in ['ds', 'y', 'yhat', 'yhat_upper', 'yhat_lower'] ]
return (df.groupBy(*group_cols)
.applyInPandas(ForecastHelper.apply_forecast_eval(forecast_client), schema=forecast_client.eval_schema)
)
|
# 设计模式
## 1 类与类之间的关系
* 关联关系(单向关联、双向关联、自关联):是对象之间的一种引用关系,用于表示一类对象与另一类对象之间的联系
* 例如老师和学生、师傅和徒弟
* 带箭头的实线
* 聚合关系:强关联关系,整体和部分之间的关系,但是成员对象可以脱离整体对象而独立存在
* 例如学校与老师的关系,学校包含老师,但是学校停办了,老师依然存在
* 带空心菱形的实线,菱形指向整体
* 组合关系:更强烈的聚合关系,整体对象控制部分对象的生命周期,部分对象不能脱离整体对象而存在
* 例如头和嘴的关系,没有了头,嘴也就不存在了
* 带实心菱形的实线,菱形指向整体
* 依赖关系:使用关系,是对象之间耦合度最弱的一种关联方式
* 某个类的方法通过局部变量、方法的参数或者对静态方法的调用来访问另一个类(被依赖类)中的某些方法来完成一些职责
* 带箭头的虚线,箭头从使用类指向被依赖的类
* 继承关系:对象之间耦合度最大的一种关系
* 空芯三角箭头的实线,箭头从子类指向父类
* 实现关系:接口与实现类之间的关系
* 空心三角箭头的虚线,箭头从实现类指向接口
## 2 软件设计原则
### (1)开闭原则
* 对扩展开放,对修改关闭
* 在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。
### (2)里氏代换原则
* 任何父类可以出现的地方,子类一定可以出现
* 子类可以扩展父类的功能,但不能改变父类原有的功能
### (3)依赖倒转原则
* 高层模块不应该依赖低层模块,两者都应该依赖其抽象;抽象不应该依赖细节,细节应该依赖抽象
* 简单地说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模块间的耦合
### (4)接口隔离原则
* 客户端不应该被迫依赖于它不使用的方法,一个类对应一个类的依赖应该建立在最小的接口上
### (5)迪米特法则
* 只和你的直接朋友交谈,不跟“陌生人”说话
* 如果两个软件实体无序直接通信,那么久不应当发生直接的相互调用,可以通过第三方转发该调用。其目的是降低类之间的耦合度,提高模块的相对独立性
### (6)合成复用原则
* 尽量先使用组合或聚合等关联关系来实现,其次才考虑使用继承关系来实现
## 3 创建者模式
* 创建者模式的主要关注点是“怎样创建对象?”,它的主要特点是“将对象的创建与使用分离”
* 这样可以降低系统的耦合度,使用者不需要关注对象的创建细节
### (1)单例设计模式
* 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。
* 这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
#### a 单例模式的实现
* 饿汉式
* 类加载时就会导致该单例对象被创建
* 懒汉式
* 类加载时不会导致该单例对象被创建,而是首次使用该对象时才会创建
### (2)工厂方法模式
### (3)抽象工程模式
### (4)原型模式
### (5)建造者模式
|
import Color from 'color';
import { Sprite, Texture } from 'pixi.js';
import { IHistoryTarget } from './History';
export default class Layer implements IHistoryTarget {
canvas: HTMLCanvasElement;
texture: Texture;
sprite: Sprite;
ctx: CanvasRenderingContext2D;
destroyed = false;
width: number = 0;
height: number = 0;
name: string = 'New Layer';
constructor({ width, height }) {
this.canvas = document.createElement('canvas');
this.texture = Texture.from(this.canvas);
this.ctx = this.canvas.getContext('2d');
this.sprite = Sprite.from(this.texture);
this.resize(width, height);
}
addImageData(data, dx, dy, subtract = false) {
const imageData = this.ctx.getImageData(
dx,
dy,
data.width,
data.height
);
for (let j = 0; j < data.height; j++) {
for (let i = 0; i < data.width; i++) {
const index = (i + j * data.width) * 4;
if (subtract) {
imageData.data[index + 0] -= data.data[index + 0];
imageData.data[index + 1] -= data.data[index + 1];
imageData.data[index + 2] -= data.data[index + 2];
imageData.data[index + 3] -= data.data[index + 3];
} else {
imageData.data[index + 0] += data.data[index + 0];
imageData.data[index + 1] += data.data[index + 1];
imageData.data[index + 2] += data.data[index + 2];
imageData.data[index + 3] += data.data[index + 3];
}
}
}
this.ctx.putImageData(imageData, dx, dy);
this.update();
}
undo(delta: any) {
this.addImageData(delta, delta.dx, delta.dy, true);
}
redo(delta: any) {
this.addImageData(delta, delta.dx, delta.dy);
}
resize(width: number, height: number) {
this.width = width;
this.height = height;
this.canvas.width = width;
this.canvas.height = height;
this.sprite.width = width;
this.sprite.height = height;
return this;
}
drawImage(image: HTMLImageElement, dx = 0, dy = 0) {
this.ctx.drawImage(image, dx, dy);
this.update();
return this;
}
destroy() {
this.texture.destroy();
this.canvas = null;
this.destroyed = true;
}
update() {
this.texture.update();
// update sprite dimensions after texture update
this.sprite.width = this.width;
this.sprite.height = this.height;
return this;
}
// utility call that is chainable and calls update at the end
render(renderCallback: (ctx: CanvasRenderingContext2D) => void) {
renderCallback(this.ctx);
this.update();
return this;
}
// not optimized for mass calls, instead use ctx#getImageData
getPixelColor(x: number, y: number) {
const clr = this.ctx.getImageData(x, y, 1, 1).data;
return new Color({
red: clr[0],
green: clr[1],
blue: clr[2],
alpha: clr[3],
});
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS Clear</title>
<style>
.div1 {
float: left;
padding: 10px;
background-color: green;
}
.div2 {
padding: 10px;
border: 3px solid red;
}
.div3 {
float: left;
padding: 10px;
background-color: green;
}
.div4 {
padding: 10px;
border: 3px solid red;
clear: left;
}
</style>
</head>
<body>
<h2>Without clear</h2>
<div class="div1">div1</div>
<div class="div2">
div2 - Notice that div2 is after div1 in the HTML code. However, since
div1 floats to the left, the text in div2 flows around div1.
</div>
<br /><br />
<h2>With clear</h2>
<div class="div3">div3</div>
<div class="div4">
div4 - Here, clear: left; moves div4 down below the floating div3. The
value "left" clears elements floated to the left. You can also clear
"right" and "both".
</div>
</body>
</html>
|
<script setup lang="ts">
import { getData } from '@/firebase/firestore';
import type { ExpenseGroup } from '@/types';
import { getFirestore, updateDoc } from 'firebase/firestore';
import { onBeforeMount, ref, defineProps, defineEmits } from 'vue';
import { NButton } from 'naive-ui'
import type { User } from 'firebase/auth';
const db = getFirestore();
const props = defineProps<{
user: User
}>();
const emit = defineEmits(['invitesChange']);
const invitedGroups = ref<ExpenseGroup[]>([]);
async function syncInvites() {
invitedGroups.value = await getData<ExpenseGroup[]>(db, 'ExpenseGroup', 'invitedPeople', 'array-contains', props.user.email as string) as ExpenseGroup[];
}
onBeforeMount(async () => {
await syncInvites();
});
function accepts(invite: ExpenseGroup) {
const newCollaborator = {
name: props.user.displayName,
email: props.user.email,
uid: props.user.uid,
photoUrl: props.user.photoURL,
};
updateDoc(invite.ref, {
invitedPeople: [...invite.invitedPeople.filter(mail => mail !== props.user.email)],
collaboratorsData: [...invite.collaboratorsData, newCollaborator],
collaborators: [...invite.collaborators, props.user.uid]
})
emit('invitesChange');
syncInvites();
}
function reject(invite: ExpenseGroup) {
updateDoc(invite.ref, {
invitedPeople: [...invite.invitedPeople.filter(mail => mail !== props.user.email)]
})
syncInvites();
}
</script>
<template>
<div v-if="invitedGroups.length > 0">
<h3>Convites</h3>
<div v-for="(invite, index) in invitedGroups" v-bind:key="index" class="invite display-flex direction-column">
<span>Grupo: {{ invite.groupName }}</span>
<span>Dono(a): {{ invite.collaboratorsData.filter(col => col.uid === invite.ownerUid)[0].email }}</span>
<div class="display-flex justify-evenly" style="margin-top: 1rem;">
<n-button round type="error" @click="reject(invite)">
Recusar
</n-button>
<n-button round type="success" @click="accepts(invite)">
Aceitar
</n-button>
</div>
</div>
</div>
</template>
<style scoped>
.invite {
background: #f9eaff;
border-radius: 5px;
padding: 10px;
margin: 1rem 0;
}
</style>
|
/******************************************************************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#ifndef QWT_ABSTRACT_SCALE_DRAW_H
#define QWT_ABSTRACT_SCALE_DRAW_H
#include "qwt_global.h"
#include "qwt_scale_div.h"
class QwtText;
class QPalette;
class QPainter;
class QFont;
class QwtTransform;
class QwtScaleMap;
/*!
\brief A abstract base class for drawing scales
QwtAbstractScaleDraw can be used to draw linear or logarithmic scales.
After a scale division has been specified as a QwtScaleDiv object
using setScaleDiv(), the scale can be drawn with the draw() member.
*/
class QWT_EXPORT QwtAbstractScaleDraw
{
public:
/*!
Components of a scale
\sa enableComponent(), hasComponent
*/
enum ScaleComponent
{
//! Backbone = the line where the ticks are located
Backbone = 0x01,
//! Ticks
Ticks = 0x02,
//! Labels
Labels = 0x04
};
Q_DECLARE_FLAGS(ScaleComponents, ScaleComponent)
QwtAbstractScaleDraw();
virtual ~QwtAbstractScaleDraw();
void setScaleDiv(const QwtScaleDiv &);
const QwtScaleDiv &scaleDiv() const;
void setTransformation(QwtTransform *);
const QwtScaleMap &scaleMap() const;
QwtScaleMap &scaleMap();
void enableComponent(ScaleComponent, bool enable = true);
bool hasComponent(ScaleComponent) const;
void setTickLength(QwtScaleDiv::TickType, double length);
double tickLength(QwtScaleDiv::TickType) const;
double maxTickLength() const;
void setSpacing(double);
double spacing() const;
void setPenWidthF(qreal width);
qreal penWidthF() const;
virtual void draw(QPainter *, const QPalette &) const;
virtual QwtText label(double) const;
/*!
Calculate the extent
The extent is the distance from the baseline to the outermost
pixel of the scale draw in opposite to its orientation.
It is at least minimumExtent() pixels.
\param font Font used for drawing the tick labels
\return Number of pixels
\sa setMinimumExtent(), minimumExtent()
*/
virtual double extent(const QFont &font) const = 0;
void setMinimumExtent(double);
double minimumExtent() const;
void invalidateCache();
protected:
/*!
Draw a tick
\param painter Painter
\param value Value of the tick
\param len Length of the tick
\sa drawBackbone(), drawLabel()
*/
virtual void drawTick(QPainter *painter, double value, double len) const = 0;
/*!
Draws the baseline of the scale
\param painter Painter
\sa drawTick(), drawLabel()
*/
virtual void drawBackbone(QPainter *painter) const = 0;
/*!
Draws the label for a major scale tick
\param painter Painter
\param value Value
\sa drawTick(), drawBackbone()
*/
virtual void drawLabel(QPainter *painter, double value) const = 0;
const QwtText &tickLabel(const QFont &, double value) const;
private:
Q_DISABLE_COPY(QwtAbstractScaleDraw)
class PrivateData;
PrivateData *m_data;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QwtAbstractScaleDraw::ScaleComponents)
#endif
|
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:kistler/core/app_utils/app_utils.dart';
import 'package:kistler/core/image_constant/images.dart';
import 'package:kistler/generated/locale_keys.g.dart';
import 'package:kistler/presentaion/bottom_nav_screen/view/bottom_nav_screen.dart';
import 'package:kistler/presentaion/get_started_screen/view/get_started_screen.dart';
import 'package:kistler/presentaion/no_internet_screen/view/no_internet_screen.dart';
import 'package:kistler/presentaion/splash_Screen/controller/common_controller.dart';
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
await context.setLocale(Locale('de'));
});
super.initState();
Future.delayed(Duration(seconds: 3), () async {
if (await AppUtils.isOnline()) {
final String? savedToken = await AppUtils.getAccessKey();
if (savedToken != null && savedToken.isNotEmpty) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => BottomNavScreen()),
);
} else {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => GetStartedScreen()),
);
}
} else {
if (mounted) {
await AppUtils.oneTimeSnackBar(LocaleKeys.No_internet_connection.tr(),
context: CommonController.navigatorState.currentContext!);
}
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => NoInternetScreen()),
(route) => false);
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 100,
width: 100,
child: Image.asset(
ImageConstant.smallLogo,
fit: BoxFit.cover,
)),
),
);
}
}
|
syntax = "proto3";
import "google/protobuf/timestamp.proto";
option java_multiple_files = true;
option java_package = "cs236351.transactionManager";
package cs236351.transactionManager;
enum ResponseEnum {
SUCCESS = 0;
FAILURE = 1;
}
message Response {
ResponseEnum type = 1;
string message = 2;
}
message AddressRequest {
string address = 1;
int32 limit = 2;
}
message Transfer {
string srcAddress = 1;
string dstAddress = 2;
uint64 coins = 3;
string txId = 4;
}
message UTxO {
string txId = 1;
string address = 2;
}
message UTxOList {
repeated UTxO utxoList = 1;
}
message Transaction {
string txId = 1;
repeated UTxO inputs = 2;
repeated Transfer outputs = 3;
}
message TimedTransaction {
Transaction transaction = 1;
google.protobuf.Timestamp timestamp = 2;
}
message TransactionList {
repeated Transaction transactions = 1;
}
message TimedTransactionList {
repeated TimedTransaction transactionList = 1;
}
message ConsensusMessage {
bytes message = 1;
}
|
const axios = require('axios');
const bd = require('./database/models');
async function chargeData(){
try {
const response = await axios.get('https://restcountries.com/v3.1/all');
const countries = response.data;
for (const country of countries) {
if (country && typeof country === 'object') {
const { name, capital, population, flags, continents, languages, currencies } = country;
let continentName="No information";
if (continents){
continentName = continents.length > 0 ? continents[0] : 'No information';
}
const [continent] = await bd.Continent.findOrCreate({
where: { name: continentName },
});
let capitalName="No information";
if (capital){
capitalName = capital.length > 0 ? capital[0] : 'No information';
}
let flagImage="No information";
if (flags){
flagImage = flags.png? flags.png : 'No information';
}
const [dbCountry, created] = await bd.Country.findOrCreate({
where: { name: name.common },
defaults: {
capital: capitalName,
population: population.toString(),
flagImage: flagImage,
Continent_id: continent.id
},
});
if (languages && typeof languages === 'object') {
const languageEntries = Object.entries(languages);
if (languageEntries){
for (const [code, name] of languageEntries) {
if (name){
const [dbLanguage] = await bd.Language.findOrCreate({
where: { name },
});
await dbCountry.addLanguage(dbLanguage);
}
}
}
}
if (currencies && typeof currencies === 'object') {
for (const [code, currencyData] of Object.entries(currencies)) {
if (currencyData){
const name = currencyData.name? currencyData.name : 'No information';
const symbol = currencyData.symbol? currencyData.symbol : 'No information';
const [dbCoin] = await bd.Coin.findOrCreate({
where: { name, symbol },
});
await dbCountry.addCoin(dbCoin);
}
}
}
}
}
console.log('Data charged');
} catch (error) {
console.error('Api error:', error.message);
}
}
module.exports = {chargeData}
|
/*******************************************************************************
* Copyright (c) 2010, 2016 EclipseSource and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* EclipseSource - initial API and implementation
******************************************************************************/
package org.eclipse.swt.internal.widgets.canvaskit;
import static org.eclipse.rap.rwt.testfixture.internal.TestUtil.createImage;
import static org.eclipse.swt.internal.widgets.canvaskit.GCOperationWriter.getGcId;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.eclipse.rap.json.JsonArray;
import org.eclipse.rap.json.JsonObject;
import org.eclipse.rap.rwt.internal.lifecycle.WidgetUtil;
import org.eclipse.rap.rwt.internal.protocol.Operation.CallOperation;
import org.eclipse.rap.rwt.testfixture.internal.Fixture;
import org.eclipse.rap.rwt.testfixture.internal.TestMessage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.internal.graphics.GCAdapter;
import org.eclipse.swt.internal.graphics.GCOperation;
import org.eclipse.swt.internal.graphics.ImageFactory;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class GCOperationWriter_Test {
private Display display;
private Canvas canvas;
private GC gc;
@Before
public void setUp() {
Fixture.setUp();
Fixture.fakeResponseWriter();
display = new Display();
Shell control = new Shell( display );
canvas = new Canvas( control, SWT.NONE );
canvas.setSize( 100, 200 );
gc = new GC( canvas );
}
@After
public void tearDown() {
Fixture.tearDown();
}
@Test
public void testInit() {
canvas.setForeground( new Color( display, 1, 2, 3 ) );
canvas.setBackground( new Color( display, 4, 5, 6 ) );
canvas.setFont( new Font( display, "Arial", 12, SWT.BOLD ) );
GCOperationWriter operationWriter = new GCOperationWriter( canvas );
operationWriter.initialize();
TestMessage message = Fixture.getProtocolMessage();
CallOperation init = message.findCallOperation( getGcId( canvas ), "init" );
JsonObject parameters = init.getParameters();
assertEquals( 0, parameters.get( "x" ).asInt() );
assertEquals( 0, parameters.get( "y" ).asInt() );
assertEquals( 100, parameters.get( "width" ).asInt() );
assertEquals( 200, parameters.get( "height" ).asInt() );
assertEquals( "[[\"Arial\"],12,true,false]", parameters.get( "font" ).asArray().toString() );
assertEquals( "[1,2,3,255]", parameters.get( "strokeStyle" ).asArray().toString() );
assertEquals( "[4,5,6,255]", parameters.get( "fillStyle" ).asArray().toString() );
}
@Test
public void testSetLineWidth() {
gc.setLineWidth( 13 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineWidth\",13]", getOperation( 0, ops ) );
}
@Test
public void testSetLineWidthZero() {
gc.setLineWidth( 10 );
gc.setLineWidth( 0 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineWidth\",10]", getOperation( 0, ops ) );
assertEquals( "[\"lineWidth\",1]", getOperation( 1, ops ) );
}
@Test
public void testForeground() {
gc.setForeground( new Color( display, 155, 11, 24 ) );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"strokeStyle\",[155,11,24,255]]", getOperation( 0, ops ) );
}
@Test
public void testBackground() {
gc.setBackground( new Color( display, 155, 11, 24 ) );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"fillStyle\",[155,11,24,255]]", getOperation( 0, ops ) );
}
@Test
public void testAlpha() {
gc.setAlpha( 100 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"globalAlpha\",0.39]", getOperation( 0, ops ) );
}
@Test
public void testLineCapFlat() {
gc.setLineCap( SWT.CAP_ROUND );
gc.setLineCap( SWT.CAP_FLAT );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineCap\",\"butt\"]", getOperation( 1, ops ) );
}
@Test
public void testLineCapRound() {
gc.setLineCap( SWT.CAP_ROUND );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineCap\",\"round\"]", getOperation( 0, ops ) );
}
@Test
public void testLineCapSquare() {
gc.setLineCap( SWT.CAP_SQUARE );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineCap\",\"square\"]", getOperation( 0, ops ) );
}
@Test
public void testLineJoinBevel() {
gc.setLineJoin( SWT.JOIN_BEVEL );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineJoin\",\"bevel\"]", getOperation( 0, ops ) );
}
@Test
public void testLineJoinMiter() {
gc.setLineJoin( SWT.JOIN_ROUND );
gc.setLineJoin( SWT.JOIN_MITER );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineJoin\",\"miter\"]", getOperation( 1, ops ) );
}
@Test
public void testLineJoinRound() {
gc.setLineJoin( SWT.JOIN_ROUND );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"lineJoin\",\"round\"]", getOperation( 0, ops ) );
}
@Test
public void testFont() {
gc.setFont( new Font( display, "Arial", 12, SWT.BOLD ) );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"font\",[[\"Arial\"],12,true,false]]", getOperation( 0, ops ) );
}
@Test
public void testDrawLine() {
gc.setLineWidth( 2 );
gc.drawLine( 10, 11, 20, 21 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10,11]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",20,21]", getOperation( 3, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 4, ops ) );
}
@Test
public void testDrawLineOffset() {
gc.drawLine( 10, 11, 20, 21 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 0, ops ) );
assertEquals( "[\"moveTo\",10.5,11.5]", getOperation( 1, ops ) );
assertEquals( "[\"lineTo\",20.5,21.5]", getOperation( 2, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 3, ops ) );
}
@Test
public void testDrawPoint() {
gc.setForeground( new Color( display, 255, 0, 7 ) );
gc.drawPoint( 27, 44 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"strokeStyle\",[255,0,7,255]]", getOperation( 0, ops ) );
assertEquals( "[\"save\"]", getOperation( 1, ops ) );
assertEquals( "[\"fillStyle\",[255,0,7,255]]", getOperation( 2, ops ) );
assertEquals( "[\"lineWidth\",1]", getOperation( 3, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 4, ops ) );
assertEquals( "[\"rect\",27,44,1,1]", getOperation( 5, ops ) );
assertEquals( "[\"fill\"]", getOperation( 6, ops ) );
assertEquals( "[\"restore\"]", getOperation( 7, ops ) );
}
@Test
public void testDrawRectangle() {
gc.setLineWidth( 2 );
gc.drawRectangle( 10, 20, 55, 56 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"rect\",10,20,55,56]", getOperation( 2, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 3, ops ) );
}
@Test
public void testFillRectangle() {
gc.setLineWidth( 2 );
gc.fillRectangle( 10, 20, 55, 56 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"rect\",10,20,55,56]", getOperation( 2, ops ) );
assertEquals( "[\"fill\"]", getOperation( 3, ops ) );
}
@Test
public void testDrawRectangleOffset() {
gc.setLineWidth( 1 );
gc.drawRectangle( 10, 20, 55, 56 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"rect\",10.5,20.5,55,56]", getOperation( 2, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 3, ops ) );
}
@Test
public void testDrawPolyLine() {
gc.setLineWidth( 2 );
gc.drawPolyline( new int[]{ 10, 20, 30, 40, 50, 60, 90, 100 } );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10,20]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",30,40]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",50,60]", getOperation( 4, ops ) );
assertEquals( "[\"lineTo\",90,100]", getOperation( 5, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 6, ops ) );
}
@Test
public void testDrawPolygon() {
gc.setLineWidth( 2 );
gc.drawPolygon( new int[]{ 10, 20, 30, 40, 50, 60, 90, 100 } );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10,20]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",30,40]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",50,60]", getOperation( 4, ops ) );
assertEquals( "[\"lineTo\",90,100]", getOperation( 5, ops ) );
assertEquals( "[\"lineTo\",10,20]", getOperation( 6, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 7, ops ) );
}
@Test
public void testFillPolygon() {
gc.setLineWidth( 2 );
gc.fillPolygon( new int[]{ 10, 20, 30, 40, 50, 60, 90, 100 } );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10,20]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",30,40]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",50,60]", getOperation( 4, ops ) );
assertEquals( "[\"lineTo\",90,100]", getOperation( 5, ops ) );
assertEquals( "[\"lineTo\",10,20]", getOperation( 6, ops ) );
assertEquals( "[\"fill\"]", getOperation( 7, ops ) );
}
@Test
public void testDrawPolyLineOffset() {
gc.drawPolyline( new int[]{ 10, 20, 30, 40, 50, 60, 90, 100 } );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 0, ops ) );
assertEquals( "[\"moveTo\",10.5,20.5]", getOperation( 1, ops ) );
assertEquals( "[\"lineTo\",30.5,40.5]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",50.5,60.5]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",90.5,100.5]", getOperation( 4, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 5, ops ) );
}
@Test
public void testDrawRoundRect() {
gc.setLineWidth( 2 );
gc.drawRoundRectangle( 10, 20, 100, 200, 1, 3 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10,22.5]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",10,217.5]", getOperation( 3, ops ) );
assertEquals( "[\"quadraticCurveTo\",10,220,11.5,220]", getOperation( 4, ops ) );
assertEquals( "[\"lineTo\",108.5,220]", getOperation( 5, ops ) );
assertEquals( "[\"quadraticCurveTo\",110,220,110,217.5]", getOperation( 6, ops ) );
assertEquals( "[\"lineTo\",110,22.5]", getOperation( 7, ops ) );
assertEquals( "[\"quadraticCurveTo\",110,20,108.5,20]", getOperation( 8, ops ) );
assertEquals( "[\"lineTo\",11.5,20]", getOperation( 9, ops ) );
assertEquals( "[\"quadraticCurveTo\",10,20,10,22.5]", getOperation( 10, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 11, ops ) );
}
@Test
public void testDrawRoundRectOffset() {
gc.setLineWidth( 1 );
gc.drawRoundRectangle( 10, 20, 100, 200, 1, 3 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10.5,23]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",10.5,218]", getOperation( 3, ops ) );
assertEquals( "[\"quadraticCurveTo\",10.5,220.5,12,220.5]", getOperation( 4, ops ) );
assertEquals( "[\"lineTo\",109,220.5]", getOperation( 5, ops ) );
assertEquals( "[\"quadraticCurveTo\",110.5,220.5,110.5,218]", getOperation( 6, ops ) );
assertEquals( "[\"lineTo\",110.5,23]", getOperation( 7, ops ) );
assertEquals( "[\"quadraticCurveTo\",110.5,20.5,109,20.5]", getOperation( 8, ops ) );
assertEquals( "[\"lineTo\",12,20.5]", getOperation( 9, ops ) );
assertEquals( "[\"quadraticCurveTo\",10.5,20.5,10.5,23]", getOperation( 10, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 11, ops ) );
}
@Test
public void testFillRoundRect() {
gc.setLineWidth( 2 );
gc.fillRoundRectangle( 10, 20, 100, 200, 1, 3 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",10,22.5]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",10,217.5]", getOperation( 3, ops ) );
assertEquals( "[\"quadraticCurveTo\",10,220,11.5,220]", getOperation( 4, ops ) );
assertEquals( "[\"lineTo\",108.5,220]", getOperation( 5, ops ) );
assertEquals( "[\"quadraticCurveTo\",110,220,110,217.5]", getOperation( 6, ops ) );
assertEquals( "[\"lineTo\",110,22.5]", getOperation( 7, ops ) );
assertEquals( "[\"quadraticCurveTo\",110,20,108.5,20]", getOperation( 8, ops ) );
assertEquals( "[\"lineTo\",11.5,20]", getOperation( 9, ops ) );
assertEquals( "[\"quadraticCurveTo\",10,20,10,22.5]", getOperation( 10, ops ) );
assertEquals( "[\"fill\"]", getOperation( 11, ops ) );
}
@Test
public void testFillGradientRectangleVertical() {
gc.setLineWidth( 2 );
gc.setForeground( new Color( display, new RGB( 0, 10, 20 ) ) );
gc.setBackground( new Color( display, new RGB( 30, 40, 50 ) ) );
gc.fillGradientRectangle( 10, 20, 100, 200, true );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 3, ops ) );
assertEquals( "[\"createLinearGradient\",10,20,10,220]", getOperation( 4, ops ) );
assertEquals( "[\"addColorStop\",0,[0,10,20,255]]", getOperation( 5, ops ) );
assertEquals( "[\"addColorStop\",1,[30,40,50,255]]", getOperation( 6, ops ) );
assertEquals( "[\"fillStyle\",\"linearGradient\"]", getOperation( 7, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 8, ops ) );
assertEquals( "[\"rect\",10,20,100,200]", getOperation( 9, ops ) );
assertEquals( "[\"fill\"]", getOperation( 10, ops ) );
assertEquals( "[\"restore\"]", getOperation( 11, ops ) );
}
@Test
public void testFillGradientRectangleHorizontal() {
gc.setLineWidth( 2 );
gc.setForeground( new Color( display, new RGB( 0, 10, 20 ) ) );
gc.setBackground( new Color( display, new RGB( 30, 40, 50 ) ) );
gc.fillGradientRectangle( 10, 20, 100, 200, false );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 3, ops ) );
assertEquals( "[\"createLinearGradient\",10,20,110,20]", getOperation( 4, ops ) );
assertEquals( "[\"addColorStop\",0,[0,10,20,255]]", getOperation( 5, ops ) );
assertEquals( "[\"addColorStop\",1,[30,40,50,255]]", getOperation( 6, ops ) );
assertEquals( "[\"fillStyle\",\"linearGradient\"]", getOperation( 7, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 8, ops ) );
assertEquals( "[\"rect\",10,20,100,200]", getOperation( 9, ops ) );
assertEquals( "[\"fill\"]", getOperation( 10, ops ) );
assertEquals( "[\"restore\"]", getOperation( 11, ops ) );
}
@Test
public void testFillGradientRectangleVerticalSwapped() {
gc.setLineWidth( 2 );
gc.setForeground( new Color( display, new RGB( 0, 10, 20 ) ) );
gc.setBackground( new Color( display, new RGB( 30, 40, 50 ) ) );
gc.fillGradientRectangle( 100, 200, -10, -20, true );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 3, ops ) );
assertEquals( "[\"createLinearGradient\",90,180,90,200]", getOperation( 4, ops ) );
assertEquals( "[\"addColorStop\",0,[30,40,50,255]]", getOperation( 5, ops ) );
assertEquals( "[\"addColorStop\",1,[0,10,20,255]]", getOperation( 6, ops ) );
assertEquals( "[\"fillStyle\",\"linearGradient\"]", getOperation( 7, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 8, ops ) );
assertEquals( "[\"rect\",90,180,-10,-20]", getOperation( 9, ops ) );
assertEquals( "[\"fill\"]", getOperation( 10, ops ) );
assertEquals( "[\"restore\"]", getOperation( 11, ops ) );
}
@Test
public void testFillGradientRectangleHorizontalSwapped() {
gc.setLineWidth( 2 );
gc.setForeground( new Color( display, new RGB( 0, 10, 20 ) ) );
gc.setBackground( new Color( display, new RGB( 30, 40, 50 ) ) );
gc.fillGradientRectangle( 100, 200, -10, -20, false );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 3, ops ) );
assertEquals( "[\"createLinearGradient\",90,180,100,180]", getOperation( 4, ops ) );
assertEquals( "[\"addColorStop\",0,[30,40,50,255]]", getOperation( 5, ops ) );
assertEquals( "[\"addColorStop\",1,[0,10,20,255]]", getOperation( 6, ops ) );
assertEquals( "[\"fillStyle\",\"linearGradient\"]", getOperation( 7, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 8, ops ) );
assertEquals( "[\"rect\",90,180,-10,-20]", getOperation( 9, ops ) );
assertEquals( "[\"fill\"]", getOperation( 10, ops ) );
assertEquals( "[\"restore\"]", getOperation( 11, ops ) );
}
@Test
public void testDrawArc() {
gc.setLineWidth( 2 );
gc.drawArc( 10, 20, 100, 200, 50, 100 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 1, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 2, ops ) );
assertEquals( "[\"ellipse\",60,120,50,100,0,-0.8727,-2.618,true]", getOperation( 3, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 4, ops ) );
assertEquals( "[\"restore\"]", getOperation( 5, ops ) );
}
@Test
public void testDrawArcOffset() {
gc.setLineWidth( 1 );
gc.drawArc( 10, 20, 100, 200, 50, 100 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 1, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 2, ops ) );
assertEquals( "[\"ellipse\",60.5,120.5,50,100,0,-0.8727,-2.618,true]", getOperation( 3, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 4, ops ) );
assertEquals( "[\"restore\"]", getOperation( 5, ops ) );
}
@Test
public void testFillArc() {
gc.setLineWidth( 2 );
gc.fillArc( 10, 20, 100, 200, 50, 100 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 1, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 2, ops ) );
assertEquals( "[\"ellipse\",60,120,50,100,0,-0.8727,-2.618,true]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",0,0]", getOperation( 4, ops ) );
assertEquals( "[\"closePath\"]", getOperation( 5, ops ) );
assertEquals( "[\"fill\"]", getOperation( 6, ops ) );
assertEquals( "[\"restore\"]", getOperation( 7, ops ) );
}
@Test
public void testFillArcClockwise() {
gc.setLineWidth( 2 );
gc.fillArc( 10, 20, 100, 200, 50, -100 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 1, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 2, ops ) );
assertEquals( "[\"ellipse\",60,120,50,100,0,-0.8727,0.8726001,false]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",0,0]", getOperation( 4, ops ) );
assertEquals( "[\"closePath\"]", getOperation( 5, ops ) );
assertEquals( "[\"fill\"]", getOperation( 6, ops ) );
assertEquals( "[\"restore\"]", getOperation( 7, ops ) );
}
@Test
public void testDrawImage() throws IOException {
Image image = createImage( display, Fixture.IMAGE_50x100 );
String imageLocation = ImageFactory.getImagePath( image );
gc.drawImage( image, 10, 50 );
JsonArray ops = getGCOperations( canvas );
String expected = "[\"drawImage\",\"" + imageLocation + "\",10,50]";
assertEquals( expected, getOperation( 0, ops ) );
}
@Test
public void testDrawImagePart() throws IOException {
Image image = createImage( display,( Fixture.IMAGE_50x100 ) );
String imageLocation = ImageFactory.getImagePath( image );
gc.drawImage( image, 10, 20, 30, 40, 100, 110, 400, 500 );
JsonArray ops = getGCOperations( canvas );
String expected = "[\"drawImage\",\"" + imageLocation + "\",10,20,30,40,100,110,400,500]";
assertEquals( expected, getOperation( 0, ops ) );
}
@Test
public void testDrawText() {
gc.drawText( "foo", 30, 34, true );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"strokeText\",\"foo\",false,true,true,30,34]", getOperation( 0, ops ) );
}
@Test
public void testDrawTextWithMenmonic() {
gc.drawText( "foo", 30, 34, SWT.DRAW_MNEMONIC );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"fillText\",\"foo\",true,false,false,30,34]", getOperation( 0, ops ) );
}
@Test
public void testDrawTextWithDelimiter() {
gc.drawText( "foo", 30, 34, SWT.DRAW_DELIMITER );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"fillText\",\"foo\",false,true,false,30,34]", getOperation( 0, ops ) );
}
@Test
public void testDrawTextWithTab() {
gc.drawText( "foo", 30, 34, SWT.DRAW_TAB );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"fillText\",\"foo\",false,false,true,30,34]", getOperation( 0, ops ) );
}
@Test
public void testFillText() {
gc.drawText( "foo", 30, 34 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"fillText\",\"foo\",false,true,true,30,34]", getOperation( 0, ops ) );
}
// bug 351216: [GC] Throws unexpected "Graphic is diposed" exception
@Test
public void testWriteColorOperationWithDisposedColor() {
Color color = new Color( canvas.getDisplay(), 1, 2, 3 );
gc.setForeground( color );
color.dispose();
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"strokeStyle\",[1,2,3,255]]", getOperation( 0, ops ) );
}
// bug 351216: [GC] Throws unexpected "Graphic is diposed" exception
@Test
public void testWriteFontOperationWithDisposedFont() {
Font font = new Font( canvas.getDisplay(), "font-name", 1, SWT.NORMAL );
gc.setFont( font );
font.dispose();
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"font\",[[\"font-name\"],1,false,false]]", getOperation( 0, ops ) );
}
// bug 351216: [GC] Throws unexpected "Graphic is disposed" exception
@Test
public void testWriteImageOperationWithDisposedImage() {
Image image = new Image( canvas.getDisplay(), 100, 100 );
gc.drawImage( image, 0, 0 );
image.dispose();
writeGCOperations( canvas );
JsonArray ops = getGCOperations( canvas );
assertTrue( getOperation( 0, ops ).contains( "drawImage" ) );
}
@Test
public void testDrawPath() {
Path path = new Path( display );
path.lineTo( 10, 10 );
path.moveTo( 20, 20 );
path.quadTo( 25, 25, 30, 20 );
path.cubicTo( 55, 55, 65, 55, 70, 40 );
path.close();
gc.drawPath( path );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 0, ops ) );
assertEquals( "[\"moveTo\",0,0]", getOperation( 1, ops ) );
assertEquals( "[\"lineTo\",10,10]", getOperation( 2, ops ) );
assertEquals( "[\"moveTo\",20,20]", getOperation( 3, ops ) );
assertEquals( "[\"quadraticCurveTo\",25,25,30,20]", getOperation( 4, ops ) );
assertEquals( "[\"bezierCurveTo\",55,55,65,55,70,40]", getOperation( 5, ops ) );
assertEquals( "[\"closePath\"]", getOperation( 6, ops ) );
assertEquals( "[\"stroke\"]", getOperation( 7, ops ) );
}
@Test
public void testFillPath() {
Path path = new Path( display );
path.lineTo( 10, 10 );
path.moveTo( 20, 20 );
path.quadTo( 25, 25, 30, 20 );
path.cubicTo( 55, 55, 65, 55, 70, 40 );
path.close();
gc.fillPath( path );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"beginPath\"]", getOperation( 0, ops ) );
assertEquals( "[\"moveTo\",0,0]", getOperation( 1, ops ) );
assertEquals( "[\"lineTo\",10,10]", getOperation( 2, ops ) );
assertEquals( "[\"moveTo\",20,20]", getOperation( 3, ops ) );
assertEquals( "[\"quadraticCurveTo\",25,25,30,20]", getOperation( 4, ops ) );
assertEquals( "[\"bezierCurveTo\",55,55,65,55,70,40]", getOperation( 5, ops ) );
assertEquals( "[\"closePath\"]", getOperation( 6, ops ) );
assertEquals( "[\"fill\"]", getOperation( 7, ops ) );
}
@Test
public void testSetClipping_withRectangle() {
gc.setClipping( 1, 2, 3, 4 );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 0, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"rect\",1,2,3,4]", getOperation( 2, ops ) );
assertEquals( "[\"clip\"]", getOperation( 3, ops ) );
}
@Test
public void testSetClipping_withPath() {
Path path = new Path( display );
path.moveTo( 20, 20 );
path.lineTo( 30, 30 );
path.lineTo( 10, 40 );
path.close();
gc.setClipping( path );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"save\"]", getOperation( 0, ops ) );
assertEquals( "[\"beginPath\"]", getOperation( 1, ops ) );
assertEquals( "[\"moveTo\",20,20]", getOperation( 2, ops ) );
assertEquals( "[\"lineTo\",30,30]", getOperation( 3, ops ) );
assertEquals( "[\"lineTo\",10,40]", getOperation( 4, ops ) );
assertEquals( "[\"closePath\"]", getOperation( 5, ops ) );
assertEquals( "[\"clip\"]", getOperation( 6, ops ) );
}
@Test
public void testSetClipping_reset() {
gc.setClipping( 1, 2, 3, 4 );
getGCAdapter( canvas ).clearGCOperations();
gc.setClipping( ( Rectangle )null );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"resetClip\"]", getOperation( 0, ops ) );
}
@Test
public void testGetGcId() {
String gcId = GCOperationWriter.getGcId( canvas );
assertEquals( WidgetUtil.getId( canvas ) + ".gc", gcId );
}
@Test
public void testSetTransform() {
gc.setTransform( new Transform( display, 1, 2, 3, 4, 5, 6 ) );
JsonArray ops = getGCOperations( canvas );
assertEquals( "[\"setTransform\",1,2,3,4,5,6]", getOperation( 0, ops ) );
}
private static JsonArray getGCOperations( Canvas canvas ) {
writeGCOperations( canvas );
TestMessage message = Fixture.getProtocolMessage();
CallOperation draw = message.findCallOperation( getGcId( canvas ), "draw" );
return draw.getParameters().get( "operations" ).asArray();
}
private static String getOperation( int i, JsonArray operations ) {
String result = null;
try {
result = operations.get( i ).asArray().toString();
} catch( Exception e ) {
fail();
}
return result;
}
private static void writeGCOperations( Canvas canvas ) {
GCOperation[] operations = getGCAdapter( canvas ).getGCOperations();
GCOperationWriter operationWriter = new GCOperationWriter( canvas );
for( GCOperation operation : operations ) {
operationWriter.write( operation );
}
operationWriter.render();
}
private static GCAdapter getGCAdapter( Canvas canvas ) {
return canvas.getAdapter( GCAdapter.class );
}
}
|
#
# (C) Tenable Network Security, Inc.
#
# The descriptive text and package checks in this plugin were
# extracted from Debian Security Advisory DLA-200-1. The text
# itself is copyright (C) Software in the Public Interest, Inc.
#
include("compat.inc");
if (description)
{
script_id(82805);
script_version("$Revision: 1.6 $");
script_cvs_date("$Date: 2017/05/03 13:42:51 $");
script_cve_id("CVE-2014-4975", "CVE-2014-8080", "CVE-2014-8090");
script_bugtraq_id(68474, 70935, 71230);
script_osvdb_id(108971, 113747, 114641);
script_name(english:"Debian DLA-200-1 : ruby1.9.1 security update");
script_summary(english:"Checks dpkg output for the updated packages.");
script_set_attribute(
attribute:"synopsis",
value:"The remote Debian host is missing a security update."
);
script_set_attribute(
attribute:"description",
value:
"CVE-2014-4975
The encodes() function in pack.c had an off-by-one error that could
lead to a stack-based buffer overflow. This could allow remote
attackers to cause a denial of service (crash) or arbitrary code
execution.
CVE-2014-8080, CVE-2014-8090
The REXML parser could be coerced into allocating large string objects
that could consume all available memory on the system. This could
allow remote attackers to cause a denial of service (crash).
NOTE: Tenable Network Security has extracted the preceding description
block directly from the DLA security advisory. Tenable has attempted
to automatically clean and format it as much as possible without
introducing additional issues."
);
script_set_attribute(
attribute:"see_also",
value:"https://lists.debian.org/debian-lts-announce/2015/04/msg00013.html"
);
script_set_attribute(
attribute:"see_also",
value:"https://packages.debian.org/source/squeeze-lts/ruby1.9.1"
);
script_set_attribute(attribute:"solution", value:"Upgrade the affected packages.");
script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:P/I:N/A:N");
script_set_cvss_temporal_vector("CVSS2#E:ND/RL:OF/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available");
script_set_attribute(attribute:"exploit_available", value:"false");
script_set_attribute(attribute:"plugin_type", value:"local");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:libruby1.9.1");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:libruby1.9.1-dbg");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:libtcltk-ruby1.9.1");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:ri1.9.1");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:ruby1.9.1");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:ruby1.9.1-dev");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:ruby1.9.1-elisp");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:ruby1.9.1-examples");
script_set_attribute(attribute:"cpe", value:"p-cpe:/a:debian:debian_linux:ruby1.9.1-full");
script_set_attribute(attribute:"cpe", value:"cpe:/o:debian:debian_linux:6.0");
script_set_attribute(attribute:"patch_publication_date", value:"2015/04/15");
script_set_attribute(attribute:"plugin_publication_date", value:"2015/04/16");
script_end_attributes();
script_category(ACT_GATHER_INFO);
script_copyright(english:"This script is Copyright (C) 2015-2017 Tenable Network Security, Inc.");
script_family(english:"Debian Local Security Checks");
script_dependencies("ssh_get_info.nasl");
script_require_keys("Host/local_checks_enabled", "Host/Debian/release", "Host/Debian/dpkg-l");
exit(0);
}
include("audit.inc");
include("debian_package.inc");
if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED);
if (!get_kb_item("Host/Debian/release")) audit(AUDIT_OS_NOT, "Debian");
if (!get_kb_item("Host/Debian/dpkg-l")) audit(AUDIT_PACKAGE_LIST_MISSING);
flag = 0;
if (deb_check(release:"6.0", prefix:"libruby1.9.1", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"libruby1.9.1-dbg", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"libtcltk-ruby1.9.1", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"ri1.9.1", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"ruby1.9.1", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"ruby1.9.1-dev", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"ruby1.9.1-elisp", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"ruby1.9.1-examples", reference:"1.9.2.0-2+deb6u3")) flag++;
if (deb_check(release:"6.0", prefix:"ruby1.9.1-full", reference:"1.9.2.0-2+deb6u3")) flag++;
if (flag)
{
if (report_verbosity > 0) security_warning(port:0, extra:deb_report_get());
else security_warning(0);
exit(0);
}
else audit(AUDIT_HOST_NOT, "affected");
|
import { useState } from "react";
import PropTypes from "prop-types"; // typechecking of proptypes
const containerStyle = {
display: "flex",
alignItems: "center",
gap: "20px",
};
const starsContainerStyle = { display: "flex" };
StarsRating.propTypes = {
maxRating: PropTypes.number,
colorStar: PropTypes.string,
sizeStar: PropTypes.number,
className: PropTypes.string,
message: PropTypes.array,
defaulRating: PropTypes.number,
onSetExternalRating: PropTypes.func,
};
export default function StarsRating({ maxRating = 3, colorStar = "gold", sizeStar = 20, className = "", message = [], defaulRating = 0, onSetExternalRating }) {
const [rating, setRating] = useState(defaulRating);
const [hoverRating, setHoverRating] = useState(0);
function handleClickRating(rate) {
setRating(rate);
if (onSetExternalRating) onSetExternalRating(rate); // get state variable rating outside component StarsRating
}
return (
<div style={containerStyle} className={className}>
<div style={starsContainerStyle}>
{Array.from({ length: maxRating }, (_, i) => (
<StarIcon key={i + 1} sizeStar={sizeStar} onClickRating={() => handleClickRating(i + 1)} color={(hoverRating ? hoverRating : rating) >= i + 1 ? colorStar : "lightgray"} onEnterRating={() => setHoverRating(i + 1)} onLeaveRating={() => setHoverRating(0)} />
))}
</div>
{message.length === maxRating && <b style={{ color: colorStar }}>{message[hoverRating - 1] || message[rating - 1]}</b>}
{(message.length === 0 || message.length !== maxRating) && <b style={{ color: colorStar }}>{hoverRating || rating || ""}</b>}
</div>
);
}
function StarIcon({ onClickRating, color, onEnterRating, onLeaveRating, sizeStar }) {
const starIconStyle = { height: `${sizeStar}px`, width: `${sizeStar}px`, cursor: "pointer", display: "block" };
return (
<span style={starIconStyle} role="button" onClick={onClickRating} onMouseEnter={onEnterRating} onMouseLeave={onLeaveRating}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill={color}>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
</span>
);
}
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import sympy as sp
import numpy as np
from scipy.integrate import odeint
from scipy.integrate import solve_ivp
from torch.utils.data import Dataset, DataLoader
from torch.optim.optimizer import Optimizer
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
class ManifoldEmbedding(nn.Module):
def __init__(self, input_dim):
super(ManifoldEmbedding, self).__init__()
# Define symbols for space-time coordinates
self.t, self.x, self.y, self.z = sp.symbols('t x y z')
self.input_dim = input_dim
def christoffel_symbols(self, g, g_inv):
""" Calculate Christoffel symbols for a given metric tensor, g """
dim = g.shape[0]
Gamma = sp.zeros(dim, dim, dim)
for k in range(dim):
for i in range(dim):
for j in range(dim):
for l in range(dim):
Gamma[k, i, j] += 0.5 * g_inv[k, l] * (sp.diff(g[j, l], (self.t, self.x, self.y, self.z)[i]) +
sp.diff(g[i, l], (self.t, self.x, self.y, self.z)[j]) -
sp.diff(g[i, j], (self.t, self.x, self.y, self.z)[l]))
return Gamma
def geodesic_equations(self, t, y, Gamma):
""" Define the geodesic differential equations using the Christoffel symbols """
dim = int(len(y) / 2)
dydt = np.zeros(2 * dim)
for i in range(dim):
dydt[i] = y[dim + i]
dydt[dim + i] = -sum(Gamma[i, j, k] * y[dim + j] * y[dim + k] for j in range(dim) for k in range(dim))
return dydt
def calculate_metric(self, data):
""" Calculate the metric tensor from observed wave geodesics """
positions = data[:, :4] # t, x, y, z
velocities = data[:, 4:] # dt, dx, dy, dz
# Initial guess of the metric tensor
g = sp.Matrix([
[-1 + self.t**2 * 0.1, 0, 0, 0],
[0, 1 + self.x**2 * 0.1, 0, 0],
[0, 0, 1 + self.y**2 * 0.1, 0],
[0, 0, 0, 1 + self.z**2 * 0.1]
])
g_inv = g.inv()
# Calculate Christoffel symbols from the current metric tensor
Gamma = self.christoffel_symbols(g, g_inv)
# Numerically integrate geodesics
for i in range(positions.shape[0]):
initial_conditions = np.concatenate([positions[i].numpy(), velocities[i].numpy()])
sol = solve_ivp(self.geodesic_equations, [0, 1], initial_conditions, args=(Gamma,), dense_output=True)
# This step involves updating g based on how closely sol matches the expected geodesic
# This might involve an optimization step that minimizes the difference between predicted and observed paths
return g
def forward(self, x):
# Calculate the metric tensor based on input data geodesics
metric_tensor = self.calculate_metric(x)
return metric_tensor
class RicciCurvature:
def __init__(self, metric_tensor):
self.metric = torch.tensor(metric_tensor.detach().numpy()) # Convert to PyTorch tensor
self.dim = self.metric.shape[0]
self.symbols = sp.symbols(f'x0:{self.dim}')
self.christoffel_symbols = self.compute_christoffel_symbols()
self.riemann_tensor = self.compute_riemann_tensor() # Compute and store the Riemann tensor
def compute_christoffel_symbols(self):
christoffel = torch.zeros((self.dim, self.dim, self.dim), dtype=torch.float32)
metric_inv = torch.inverse(self.metric) # Compute the inverse of the metric tensor
for k in range(self.dim):
for i in range(self.dim):
for j in range(self.dim):
term = 0
for l in range(self.dim):
term += metric_inv[k, l] * (self.diff(self.metric[j, l], self.symbols[i], order=1) +
self.diff(self.metric[i, l], self.symbols[j], order=1) -
self.diff(self.metric[i, j], self.symbols[l], order=1))
christoffel[k][i][j] = term / 2
return christoffel
def diff(self, expr, symbol, order=1):
expr = sp.sympify(expr) # Ensure expr is a SymPy expression
return torch.tensor(float(sp.diff(expr, symbol, int(order))), dtype=torch.float32) # Ensure conversion to float
def compute_riemann_tensor(self):
riemann = [[[sp.zeros(self.dim) for _ in range(self.dim)] for _ in range(self.dim)] for _ in range(self.dim)]
for k in range(self.dim):
for l in range(self.dim):
for i in range(self.dim):
for j in range(self.dim):
# Convert tensor to SymPy expression
christoffel_symbol = sp.Float(self.christoffel_symbols[k][l][j].item())
# Differentiate
term1 = sp.diff(christoffel_symbol, self.symbols[i], 1)
term2 = sp.diff(christoffel_symbol, self.symbols[j], 1)
riemann[k][l][i][j] = term1 - term2
for m in range(self.dim):
term3 = christoffel_symbol * christoffel_symbol
term4 = christoffel_symbol * christoffel_symbol
riemann[k][l][i][j] += term3 - term4
riemann[k][l][i][j] = sp.simplify(riemann[k][l][i][j])
self.riemann_tensor = riemann
return riemann
def compute_ricci_tensor(self):
ricci = sp.MutableDenseMatrix(sp.zeros(self.dim, self.dim))
for i in range(self.dim):
for j in range(self.dim):
for k in range(self.dim):
ricci[i, j] += self.riemann_tensor[k][i][k][j]
ricci[i, j] = sp.simplify(ricci[i, j])
return ricci
class GeodesicLoss(nn.Module):
def __init__(self, num_steps=10):
super().__init__()
self.num_steps = num_steps
def forward(self, outputs, targets, christoffel_symbols):
x0, x1 = outputs, targets
# Convert MutableDenseMatrix to a tensor and ensure it has 3 dimensions
if isinstance(christoffel_symbols, sp.MutableDenseMatrix):
gamma = torch.tensor(np.array(christoffel_symbols.tolist()).astype(np.float32), device=outputs.device)
else:
gamma = christoffel_symbols
if gamma.dim() == 2:
gamma = gamma.unsqueeze(0)
trajectory = x0
velocity = torch.zeros_like(x0)
dt = 1.0 / self.num_steps
for _ in range(self.num_steps):
acceleration = -torch.einsum('ijk,bj,bk->bi', gamma, velocity, velocity)
velocity += acceleration * dt
trajectory += velocity * dt
geodesic_distance = torch.norm(trajectory - x1, dim=1)
return torch.mean(geodesic_distance)
class CovariantDescent(Optimizer):
def __init__(self, params, lr=0.01, curvature_func=None):
if lr <= 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if curvature_func and not callable(curvature_func):
raise ValueError("curvature_func must be callable")
defaults = dict(lr=lr, curvature_func=curvature_func)
super().__init__(params, defaults)
def step(self, closure=None):
loss = closure() if closure else None
for group in self.param_groups:
curvature_func = group['curvature_func']
for p in group['params']:
if p.grad is not None:
grad = p.grad.data
if curvature_func:
curvature = curvature_func(p)
adjusted_grad = grad - curvature @ grad
else:
adjusted_grad = grad
p.data -= group['lr'] * adjusted_grad
return loss
class RicciFlow:
def __init__(self, model, optimizer, num_iterations=10, lr=0.01, epsilon=1e-5):
self.model = model
self.optimizer = optimizer
self.num_iterations = num_iterations
self.lr = lr
self.epsilon = epsilon # Small value for finite difference
def flow_step(self, inputs, labels):
for _ in range(self.num_iterations):
self.optimizer.zero_grad()
outputs = self.model(inputs)
metric = self.model.embedding.get_metric()
ricci_curvature = RicciCurvature(metric)
ricci_tensor = ricci_curvature.compute_ricci_tensor()
loss = criterion(outputs, labels, ricci_tensor)
loss.backward()
self.optimizer.step()
self.update_metric()
def update_metric(self):
with torch.no_grad():
for p in self.model.embedding.parameters():
# Copy the current metric tensor
metric = p.data.clone()
# Initialize a tensor to store the updated metric tensor
updated_metric = torch.zeros_like(metric)
# Iterate over each component of the metric tensor
for i in range(metric.shape[0]):
for j in range(metric.shape[1]):
# Perturb the (i, j)-th component of the metric tensor
metric[i, j] += self.epsilon
# Compute the loss with the perturbed metric tensor
self.model.embedding.metric.data = metric
outputs = self.model(inputs)
ricci_curvature = RicciCurvature(self.model.embedding.get_metric())
ricci_tensor = ricci_curvature.compute_ricci_tensor()
loss = criterion(outputs, labels, ricci_tensor)
# Compute the gradient of the loss with respect to the perturbed metric component
gradient = (loss - criterion(outputs, labels, ricci_tensor)) / self.epsilon
# Update the (i, j)-th component of the metric tensor
updated_metric[i, j] = metric[i, j] - self.lr * gradient
# Reset the metric tensor
metric[i, j] -= self.epsilon
# Update the metric tensor
p.data = updated_metric
class Model(nn.Module):
def __init__(self, input_dim, embedding_dim):
super(Model, self).__init__()
self.embedding = ManifoldEmbedding(input_dim, embedding_dim)
def forward(self, x):
return self.embedding(x)
input_dim = 55
embedding_dim = 5
model = Model(input_dim, embedding_dim)
optimizer = CovariantDescent(model.parameters(), lr=0.01, curvature_func=lambda p: 0.01 * torch.eye(p.size(0)))
criterion = GeodesicLoss()
inputs = torch.randn(100, input_dim)
labels = torch.randn(100, embedding_dim)
for epoch in range(5):
for inputs, labels in dataloader:
optimizer.zero_grad()
outputs = model(inputs)
metric = model.embedding.get_metric()
ricci_curvature = RicciCurvature(metric)
ricci_tensor = ricci_curvature.compute_ricci_tensor()
loss = criterion(outputs, labels, ricci_tensor)
loss.backward()
optimizer.step()
print(f'Epoch {epoch+1}, Loss: {loss.item()}')
|
import React, { useState, useRef, useEffect } from "react";
import {
Button,
Checkbox,
Divider,
FormControlLabel,
Grid,
InputLabel,
OutlinedInput,
Stack,
Typography,
Container,
} from "@mui/material";
const Webcam = ({ onCapture }) => {
const [stream, setStream] = useState(null);
const videoRef = useRef(null);
const [showCamera, setShowCamera] = useState(true);
useEffect(() => {
const getMedia = async () => {
const constraints = { audio: false, video: true };
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
setStream(stream);
videoRef.current.srcObject = stream;
} catch (err) {
console.error(err);
}
};
getMedia();
return () => {
if (stream) {
stream.getTracks().forEach((track) => track.stop());
}
};
}, []);
const captureImage = () => {
const canvas = document.createElement("canvas");
canvas.width = videoRef.current.videoWidth;
canvas.height = videoRef.current.videoHeight;
canvas.getContext("2d").drawImage(videoRef.current, 0, 0);
const imageUrl = canvas.toDataURL();
setShowCamera(false);
onCapture(imageUrl);
};
return (
<div>
{showCamera ? (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<video
ref={videoRef}
autoPlay
playsInline
muted
width="400"
height="320"
/>
<Button
style={{ bottom: "0" }}
size="large"
type="submit"
variant="contained"
color="primary"
onClick={captureImage}
>
Capture Image
</Button>
</div>
) : null}
</div>
);
};
export default Webcam;
|
---
layout: post
title: "Logistic Regression"
date: 2021-07-06 2:14:54 +0700
categories: MachineLearning
---
# TOC
- [Definition](#define)
- [Maximum likelihood](#maxili)
- [Stochastic gradient descent ](#sgrad)
- [Code example](#code)
# Definition <a name="define"></a>
Remind us a bit about linear regression:
$$ \hat{y}=h_{\theta}(x) = \theta \cdot x $$
Where $$ h_{\theta} $$ is the hypothesis function with parameter vector $$ \theta $$. $$ h_{\theta} $$ is supposed to turn input x into output y. Now, to make it more interesting, we would examine a non-linear relationship by wrapping the y hat in the logistic function. Here is the logistic function (also called sigmoid which means s-shape):
$$ \sigma(z) = \frac{1}{1+e^{-z}} \in (0,1) $$
<img src='https://images.viblo.asia/36d15a7f-4d7d-4b4c-8bde-72b3fbaf842c.png'>
<p style="font-size:9px">Source:https://viblo.asia/p/logistic-regression-bai-toan-co-ban-trong-machine-learning-924lJ4rzKPM</p>
Let $$ z = \hat{y} = \theta \cdot x $$, we have a new hypothesis function:
$$ h_{\theta}(x)=\sigma(\theta^{\top}x)=\frac{1}{1+e^{-\theta^{\top}x}} $$
There is one reason for us to support the logistic function: its derivative is pretty straightforward:
$$ \sigma'(z)=\frac{\partial}{\partial x}\frac{1}{1+e^{-z}}=\frac{1}{(1+e^{-z})^{2}}e^{-z}=\frac{1}{1+e^{-z}}(1-\frac{1}{1+e^{-z}})=\sigma(z)(1-\sigma(z)) $$
Let’s go back to discuss the characteristics of the logistic function. As we know, linear regression outputs a value without bounds. The logistic function, on the other hand, outputs only between 0 and 1. Since that character makes output of the logistic function looks very similar to a probability, let us consider a classification problem with n classes: with input x, we have a probability of $$ \sigma(\hat{y}(x^{(i)})) $$ that the output y would belong to class i.
To make it simple, we start with n = 2, in this case, we call our problem a binary classification. Since there are only 2 classes, we denote one class to be 0 (y = 0 in this case), the other class to be 1 (y = 1). The probability of y equal 1, depending on input x and parameter , would be the linear combination of x and $$ \theta $$, just like in a linear regression but with an extra transformation of going through the sigmoid function. The probability of y equal 0 would simply be the residual of 1 minus the probability of y equal 1. In mathematical notation:
$$ P(y=1|x;\theta) = h_{\theta}(x) $$
$$ P(y=0|x;\theta) = 1 - h_{\theta}(x) $$
The above two definition can be written equivalently as in the following equation:
$$ \Leftrightarrow p(y|x;\theta) = (h_{\theta}(x))^{y}(1-h_{\theta}(x))^{1-y} $$
Let’s check: with y = 0, the first factor equals 1 since a number to the power of 0 equals 1. The second factor has the power 1 - 0 = 1, hence it is itself $$ 1-h_{\theta}(x) $$, this gives us the probability of y equal 0, exactly as above. Similarly, with y = 1, the second factor has a power of 0 hence its value is 1. The first factor equals itself $$ h_{\theta}(x) $$ hence the probability of y = 1, exactly as above.
# Maximum likelihood <a name="maxili"></a>
Remember the maximum likelihood: given training set X and target vector y, we want to find parameters such that the joint probability of all output y to be maximum. In other words, we find so that the probability that the entire target vector y happens is the highest possible. With this in mind, the problem becomes:
$$ max_{\theta} P(y|X;\theta) $$
$$ \Leftrightarrow \theta = arg max_{\theta}P(y|X;\theta) $$
Assume i.i.d (data is independently and identically distributed), here is the likelihood:
$$ P(y|X;\theta)=\prod_{i=1}^{n}P(y^{(i)}|x^{(i)};\theta)=\prod_{i=1}^{n}(h_{\theta}(x^{(i)}))^{y^{(i)}}(1-h_{\theta}(x^{(i)}))^{1-y^{(i)}} $$
To make it simpler, we use the log likelihood as a substitute for the likelihood:
$$ l(\theta)=logP(y|X;\theta)=\sum_{i=1}^{n}y^{(i)}log h(x^{(i)})+(1-y^{(i)})log(1-h(x^{(i)})) $$
Applying gradient descent, just like in the case of linear regression, we have the update rule for parameters: $$ \theta \leftarrow \theta + \alpha \nabla_{\theta}l(\theta) $$ with plus for maximization instead of minus for minimization.
# Stochastic gradient descent <a name="sgrad"></a>
As mentioned in the linear regression post, a full batch gradient descent utilizes the entire training set for calculation, a mini-batch gradient descent uses only a part of the training data at a time. By that, the stochastic gradient descent uses only one training instance for the calculation of the loss function. To take it from the previous section, we would use the log likelihood function for our purpose, and instead of gradient descent, we would use gradient ascent to maximize the log likelihood. Let’s take the derivative of the log likelihood function (we ascent one dimension/one parameter at a time):
$$ \frac{\partial}{\partial \theta_{j}}l(\theta) = (\frac{y}{h(x)}-\frac{1-y}{1-h(x)})\frac{\partial}{\partial \theta_{j}}h(x) $$
Since h(x) is the logistic function, we apply the neat derivative of logistic h(x) to be
$$ \frac{\partial}{\partial_{j}} h(x) = h(x)(1-h(x)) $$
The above (bigger) derivative becomes:
$$ \frac{\partial}{\partial \theta_{i}}l(\theta) = (\frac{y}{h(x)}-\frac{1-y}{1-h(x)})h(x)(1-h(x))\frac{\partial}{\partial_{j}}\theta^{\top}x $$
$$ = (y(1-h(x))-(1-y)h(x))x_{j} $$
$$ =(y-y.h(x)-h(x)+y.h(x))x_{j}=(y-h(x))x_{j} $$
This is the stochastic gradient ascent rule:
$$ \theta_{j} \leftarrow \theta_{j}+\alpha(y^{(i)}-h_{\theta}(x^{(i)}))x^{(i)}_{j} $$
Notice that $$ y - h(x) $$ is the difference between the true value and the predicted value, so the general idea holds that we guide our step on the landscape by measuring how right we are when we make small steps on the landscape. You would come to the same conclusion if you define a loss function and minimize it.
For binary classification, apart from using the logistic function in the hypothesis function, we can apply this versatile function to the loss function. For example, we can define a loss function to be:
$$ Loss(x,y,\theta) = log(1+e^{-(\theta x)y}) $$
If x is the confidence in predicting positive y, we call the $$ (\theta x)y = \hat{y}.y $$ the margin (how correct we are). Notice that the margin (correctness) uses both true y and predicted y and they multiply with each other.
# Code example <a name="code"></a>
Let’s take a simple example for healthcare: given an array of breast tumor sizes, and an array of targets in which y = 1 means it is a cancerous tumor and y = 0 means it is a benign tumor. We can train a logistic regression on this small dataset and make use of sklearn’s predict and predict_proba method. Predict gives hard classification (the results are forced into 0 and 1) while predict_proba gives soft classification (the results are probability of belonging into positive prediction)
```python
import numpy
from sklearn import linear_model
import matplotlib.pyplot as plt
X = numpy.array([3.78, 2.44, 2.09, 0.14, 1.72, 1.65, 4.92, 4.37, 4.96, 4.52, 3.69, 5.88]).reshape(-1,1)
y = numpy.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
logr = linear_model.LogisticRegression()
logr.fit(X,y)
y_pred=logr.predict(X)
print(y_pred)
y_pred_soft=logr.predict_proba(X)
print(y_pred_soft)
```
[1 0 0 0 0 0 1 1 1 1 1 1]
[[0.39250045 0.60749955]
[0.80731124 0.19268876]
[0.87224114 0.12775886]
[0.99044779 0.00955221]
[0.91961384 0.08038616]
[0.92654363 0.07345637]
[0.11637257 0.88362743]
[0.22098622 0.77901378]
[0.11075591 0.88924409]
[0.18706503 0.81293497]
[0.42280871 0.57719129]
[0.03335757 0.96664243]]
The first observation is incorrectly classified as a dangerous case in the hard classification algorithm. In the soft version (probabilistic), the propensity of having cancer is only 61%, the graph below shows how soft the prediction becomes using the logistic function:
```python
colors=[]
y_max=[]
for i in y_pred_soft:
y_max.append(i[1])
if i[0]>i[1]:
colors.append('b')
else:
colors.append('r')
```
```python
plt.scatter(X,y,alpha=0.2,color=['b','b','b','b','b','b','r','r','r','r','r','r'])
plt.scatter(X,y_pred,marker='^',alpha=0.2,color=['r','b','b','b','b','b','r','r','r','r','r','r'])
plt.scatter(X,y_max,marker='s',alpha=0.5,color=colors)
```
<matplotlib.collections.PathCollection at 0x7fc1b03d6490>


Another example uses a fish data set. We have a dataset that classified fish into 7 categories. We preprocess data by using a scaler and encode the label into numbers. Then we split the data into a train and a test set, for the sake of validating.
```python
dataset_url = "https://raw.githubusercontent.com/harika-bonthu/02-linear-regression-fish/master/datasets_229906_491820_Fish.csv"
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
fish = pd.read_csv(dataset_url, error_bad_lines=False)
X = fish.iloc[:, 1:]
y = fish.loc[:, 'Species']
scaler = MinMaxScaler()
scaler.fit(X)
X_scaled = scaler.transform(X)
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y)
X_train, X_test, y_train, y_test= train_test_split(X_scaled, y, test_size=0.2, random_state=42)
```
/var/folders/kf/5_ggvsz93vxdbx_h0tvy66xh0000gn/T/ipykernel_3145/1694655126.py:15: FutureWarning: The error_bad_lines argument has been deprecated and will be removed in a future version. Use on_bad_lines in the future.
fish = pd.read_csv(dataset_url, error_bad_lines=False)
When we plot the scatters of the train and test set, we see a similar distribution. This is a good sign, since we would like our training set to be close to the test set, this would reduce error.
```python
plt.figure(figsize = (20, 6))
plt.subplot(1, 2, 1)
plt.scatter(X_train[:,5], X_train[:,4], c = y_train)
plt.xlabel('Height')
plt.ylabel('Length3')
plt.title('Training Set Scatter Plot')
plt.subplot(1, 2, 2)
plt.scatter(X_test[:,5], X_test[:,4], c = y_test)
plt.xlabel('Height')
plt.ylabel('Length3')
plt.title('Test Set Scatter Plot')
plt.show()
```


Then we run the logistic regression estimator from sklearn. The accuracy is 81.25% and we plot the confusion matrix. The confusion matrix is a visual representation to check how correct we are at our prediction. For example, number 3 in the bottom row of the matrix means that there are 3 predictions for the input in class number 2 but the real targets turn out to belong to class number 6. Then we retrieve the importance of each feature, the “Height” attribute/feature is the most important one, contributing 77% of the prediction information. Then comes the Length3.
```python
# training the model
clf = LogisticRegression()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: {:.2f}%".format(accuracy * 100))
cf = confusion_matrix(y_test, y_pred)
plt.figure()
sns.heatmap(cf, annot=True)
plt.xlabel('Prediction')
plt.ylabel('Target')
plt.title('Confusion Matrix')
```
Accuracy: 81.25%
Text(0.5, 1.0, 'Confusion Matrix')


```python
clf.coef_[0]
```
array([ 0.34202933, -0.0568451 , 0.04333105, 0.60957822, 3.81719467,
0.18893405])
```python
X.columns
```
Index(['Weight', 'Length1', 'Length2', 'Length3', 'Height', 'Width'], dtype='object')
|
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.core.paginator import Paginator
from .models import User, Post
# Index shows all posts
def index(request):
return render(request, "network/index.html")
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "network/login.html")
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "network/register.html", {
"message": "Passwords must match."
})
# Ensure that username "anonimno" can't be used, as it's used
# in templates for passing non regisetered user to js
if username == "anonimno":
return render(request, "network/register.html", {
"message": "Invalid username."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "network/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "network/register.html")
# View posts for following link
def following(request):
return render(request, "network/following.html")
# View profile
def profile(request, username):
profile_user = User.objects.get(username=username)
logged_user = User.objects.get(username=request.user.username)
# Follow or Unfollow logic
# First check if it's profile page of the logged in user and then check if
# profile user is in the following list of the logged in user
if profile_user == logged_user:
able_to_follow = "unabled"
elif profile_user in logged_user.following.filter(username=profile_user.username):
able_to_follow = "no"
else:
able_to_follow = "yes"
# https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/
return render(request, "network/profile.html", context={
"profile_username": username,
"able_to_follow": able_to_follow,
# http://www.learningaboutelectronics.com/Articles/How-to-count-the-number-of-objects-in-a-ManyToManyField-in-Django.php
"following_number": profile_user.following.all().count(),
# https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ManyToManyField.symmetrical
"followers_number": profile_user.followed_by.all().count(),
})
@login_required
def compose(request):
# Composing a new post must be via POST
if request.method != "POST":
return JsonResponse({"error": "POST request required."}, status=400)
data = json.loads(request.body)
username = data.get("author", "")
text = data.get("text", "")
if text == "":
return JsonResponse({"error": "You must type something."}, status=400)
post = Post(
author = User.objects.get(username=username),
text = text
)
post.save()
return JsonResponse({"message": "Success."}, status=201)
# Return JSON with posts - posts API route
def posts(request, type, page_no):
if type == "all":
posts = Post.objects.all()
elif type == "following":
if request.user.is_authenticated:
# https://docs.djangoproject.com/en/3.0/ref/models/querysets/#in
posts = Post.objects.filter(author__in=request.user.following.all())
else:
return JsonResponse({"error": "You must be logged in."}, status=400)
else:
# Return profile posts
if User.objects.filter(username=type).exists():
profile_username_id = User.objects.get(username=type)
posts = Post.objects.filter(author=profile_username_id)
else:
return JsonResponse({"error": "Invalid profile."}, status=400)
posts = posts.order_by("-timestamp").all()
paginator = Paginator(posts, 10)
page_obj = paginator.get_page(page_no)
page_obj.number = page_no
logged = request.user if request.user.is_authenticated else None
data = [page_obj.serialize(logged=logged) for page_obj in page_obj]
# https://realpython.com/django-pagination/#responding-with-paginated-data
payload = {
"page": {
"current": page_obj.number,
"has_next": page_obj.has_next(),
"has_previous": page_obj.has_previous(),
"total_pages": page_obj.paginator.num_pages
},
"data": data
}
return JsonResponse(payload)
def edit(request):
# Editing a post must be via PUT request method
if request.method != "PUT":
return JsonResponse({"error": "PUT request required."}, status=400)
data = json.loads(request.body)
id = data.get("id", "")
text = data.get("text", "")
update_post = Post.objects.get(id=id)
if update_post.author.id != request.user.id:
return JsonResponse({"error": "Only author of the post can edit it."}, status=400)
update_post.text = text
update_post.save()
return JsonResponse({"message": "Success."}, status=201)
def follow(request):
# Changing User following field post must be via POST
if request.method != "PUT":
return JsonResponse({"error": "PUT request required."}, status=400)
data = json.loads(request.body)
user_username = data.get("user_username", "")
profile_username = data.get("profile_username", "")
logged_user = User.objects.get(username=user_username)
follow_user = User.objects.get(username=profile_username)
# Prevent editing if not logged in
if logged_user.id != request.user.id:
return JsonResponse({"error": "You must be logged in."}, status=400)
# Prevent users from following themselves
if logged_user.id == follow_user.id:
return JsonResponse({"error": "You can't follow yourself"}, status=400)
# Follow / Unfollow
if logged_user in User.objects.filter(following=follow_user):
logged_user.following.remove(follow_user)
else:
logged_user.following.add(follow_user)
return JsonResponse({"message": "Success."}, status=201)
def like(request):
# Editing post field must be via PUT request method
if request.method != "PUT":
return JsonResponse({"error": "PUT request required."}, status=400)
data = json.loads(request.body)
id = data.get("id", "")
like_post = Post.objects.get(id=id)
liked_post_likers = like_post.likers.all()
# Like / Unlike
if request.user in liked_post_likers:
like_post.likers.remove(request.user)
else:
like_post.likers.add(request.user)
return JsonResponse({"message": "Success."}, status=201)
|
import { z } from "zod";
import {
createTRPCRouter,
protectedProcedure,
publicProcedure,
} from "~/server/api/trpc";
export const postRouter = createTRPCRouter({
/*
This fetches the latest 20 posts from the database. The posts are sorted by
the latest post date. This is used to display the home feed. See the Home
component for more details. We sort by chronological order so the Home
feed is purely to catch up on the latest posts of mutuals.
*/
getLatestPosts: publicProcedure.query(async ({ ctx }) => {
const postsCount = await ctx.db.post.count();
const skip = Math.floor(Math.random() * postsCount);
return ctx.db.post.findMany({
orderBy: { createdAt: "desc" },
take: 20,
skip: skip,
include: {
createdBy: {
select: {
username: true,
avatarUrl: true,
},
},
comments: {
include: {
createdBy: true,
},
},
},
});
}),
getSecretMessage: protectedProcedure.query(() => {
return "you can now see this secret message!";
}),
/*
This allows the user to add or remove interest. When a user is interested in a post,
it will affect their recommended feeds. Future work would include a more sophisticated
ranking system that would rank feeds based on the user's mutuals and their mutuals' feeds.
Could be less of a binary interested or not interested and more of a ranking system.
*/
addInterest: protectedProcedure
.input(z.object({ postId: z.number(), profileId: z.string()}))
.mutation(({ ctx, input }) => {
return ctx.db.post.update({
where: { id: input.postId },
data: {
interestedProfiles: {
connect: {
id: input.profileId,
},
},
},
});
}),
removeInterest: protectedProcedure
.input(z.object({ postId: z.number(), profileId: z.string()}))
.mutation(({ ctx, input }) => {
return ctx.db.post.update({
where: { id: input.postId },
data: {
interestedProfiles: {
disconnect: {
id: input.profileId,
},
},
},
});
}),
// Fetch the posts for a given profile
getPostsByProfileId: protectedProcedure
.input(z.string())
.query(async ({ ctx, input }) => {
return ctx.db.post.findMany({
where: {
createdBy: {
id: input,
},
},
orderBy: {
createdAt: "desc",
},
});
}),
getPost: protectedProcedure
.input(z.number())
.query(async ({ ctx, input }) => {
return ctx.db.post.findFirst({
where: {
id: input,
},
include: {
interestedProfiles: true,
}
});
}),
});
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.baremaps.workflow.tasks;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.apache.baremaps.collection.*;
import org.apache.baremaps.collection.memory.MemoryMappedFile;
import org.apache.baremaps.collection.type.LonLatDataType;
import org.apache.baremaps.collection.type.LongDataType;
import org.apache.baremaps.collection.type.LongListDataType;
import org.apache.baremaps.collection.type.PairDataType;
import org.apache.baremaps.collection.utils.FileUtils;
import org.apache.baremaps.database.BlockImporter;
import org.apache.baremaps.database.repository.*;
import org.apache.baremaps.openstreetmap.model.Node;
import org.apache.baremaps.openstreetmap.model.Relation;
import org.apache.baremaps.openstreetmap.model.Way;
import org.apache.baremaps.openstreetmap.pbf.PbfBlockReader;
import org.apache.baremaps.stream.StreamUtils;
import org.apache.baremaps.workflow.Task;
import org.apache.baremaps.workflow.WorkflowContext;
import org.locationtech.jts.geom.Coordinate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public record ImportOpenStreetMap(Path file, String database, Integer databaseSrid)
implements
Task {
private static final Logger logger = LoggerFactory.getLogger(ImportOpenStreetMap.class);
@Override
public void execute(WorkflowContext context) throws Exception {
logger.info("Importing {} into {}", file, database);
var dataSource = context.getDataSource(database);
var path = file.toAbsolutePath();
var headerRepository = new PostgresHeaderRepository(dataSource);
var nodeRepository = new PostgresNodeRepository(dataSource);
var wayRepository = new PostgresWayRepository(dataSource);
var relationRepository = new PostgresRelationRepository(dataSource);
headerRepository.drop();
nodeRepository.drop();
wayRepository.drop();
relationRepository.drop();
headerRepository.create();
nodeRepository.create();
wayRepository.create();
relationRepository.create();
var cacheDir = Files.createTempDirectory(Paths.get("."), "cache_");
DataMap<Coordinate> coordinateMap;
if (Files.size(path) > 1 << 30) {
var coordinatesFile = Files.createFile(cacheDir.resolve("coordinates"));
coordinateMap = new MemoryAlignedDataMap<>(
new LonLatDataType(),
new MemoryMappedFile(coordinatesFile));
} else {
var coordinatesKeysFile = Files.createFile(cacheDir.resolve("coordinates_keys"));
var coordinatesValsFile = Files.createFile(cacheDir.resolve("coordinates_vals"));
coordinateMap =
new MonotonicDataMap<>(
new MemoryAlignedDataList<>(
new PairDataType<>(new LongDataType(), new LongDataType()),
new MemoryMappedFile(coordinatesKeysFile)),
new AppendOnlyBuffer<>(
new LonLatDataType(),
new MemoryMappedFile(coordinatesValsFile)));
}
var referencesKeysDir = Files.createFile(cacheDir.resolve("references_keys"));
var referencesValuesDir = Files.createFile(cacheDir.resolve("references_vals"));
var referenceMap =
new MonotonicDataMap<>(
new MemoryAlignedDataList<>(
new PairDataType<>(new LongDataType(), new LongDataType()),
new MemoryMappedFile(referencesKeysDir)),
new AppendOnlyBuffer<>(
new LongListDataType(),
new MemoryMappedFile(referencesValuesDir)));
execute(
path,
coordinateMap,
referenceMap,
headerRepository,
nodeRepository,
wayRepository,
relationRepository,
databaseSrid);
FileUtils.deleteRecursively(cacheDir);
logger.info("Finished importing {} into {}", file, database);
}
public static void execute(
Path path,
DataMap<Coordinate> coordinateMap,
DataMap<List<Long>> referenceMap,
HeaderRepository headerRepository,
Repository<Long, Node> nodeRepository,
Repository<Long, Way> wayRepository,
Repository<Long, Relation> relationRepository,
Integer databaseSrid) throws IOException {
// configure the block reader
var reader = new PbfBlockReader()
.geometries(true)
.projection(databaseSrid)
.coordinateMap(coordinateMap)
.referenceMap(referenceMap);
// configure the block importer
var importer = new BlockImporter(
headerRepository,
nodeRepository,
wayRepository,
relationRepository);
// Stream and process the blocks
try (var input = Files.newInputStream(path)) {
StreamUtils.batch(reader.stream(input)).forEach(importer);
}
}
}
|
class Shape {
protected String name;
public Shape next; // Linked list인가 보다...
public Shape() {next = null;} // 생성자 ==> 필드 초기화
public void paint() {
draw();
}
public void draw() {
System.out.println(name);
}
}
class Line extends Shape {
@Override
public void draw() {
System.out.println("Line");
}
}
class Rect extends Shape {
@Override
public void draw() {
System.out.println("Rect");
}
}
class Circle extends Shape {
protected String name;
@Override
public void draw() {
name = "Circle";
super.name = "Shape"; // 정적바인딩 ==> super 이용
super.draw();
System.out.println(name);
// System.out.println("Circle");
}
}
public class MethodOverridingEx {
static void paint(Shape p) {
p.draw();
}
public static void main(String[] args) {
// todo. Linked List 메서드 오버라이딩
Shape start, last, obj;
// Linked List 로 도형 생성하여 연결
start = new Line();
last = start;
obj = new Rect();
last.next = obj;
last= obj;
obj = new Line();
last.next = obj;
last = obj;
obj = new Circle();
last.next = obj;
last = obj;
Shape p = start;
while (p != null) {
p.draw();
p = p.next;
}
// // 정적바인딩 ==> super 키워드 이용
// Shape b = new Circle(); // 업캐스팅
// b.paint();
// //원래는 동적바인딩에 의해서 Circle만 나올텐데, super.name 으로 Shape 집어넣고 super.draw()로 부모클래스의 메서드 사용
}
}
|
import { useState } from 'react';
export const useFilters = () => {
const [filters, setFilters] = useState([
{ label: 'All', param: 'all', active: true },
{ label: 'Active', param: 'active', active: false },
{ label: 'Completed', param: 'completed', active: false },
]);
const selectFilter = (filterID: string) => {
const newFilters = filters.map((filter) => ({
...filter,
active: filter.param === filterID,
}));
setFilters(newFilters);
};
return [filters, selectFilter];
};
|
package sync
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"github.com/google/uuid"
"github.com/humanbeeng/lepo/server/internal/git"
"github.com/humanbeeng/lepo/server/internal/sync/extract"
"github.com/humanbeeng/lepo/server/internal/sync/extract/golang"
"github.com/humanbeeng/lepo/server/internal/sync/extract/java"
"github.com/weaviate/weaviate-go-client/v4/weaviate"
"github.com/weaviate/weaviate/entities/models"
"go.uber.org/zap"
)
type GitSyncer struct {
languageToExtractor map[string]extract.Extractor
ExcludedFolderPatterns []string
cloner *git.GitCloner
weaviate *weaviate.Client
logger *zap.Logger
}
type GitSyncerOpts struct {
URL string
}
func NewGitSyncer(cloner *git.GitCloner, weaviate *weaviate.Client, logger *zap.Logger) *GitSyncer {
return &GitSyncer{
languageToExtractor: buildSupportedLanguagesMap(logger),
ExcludedFolderPatterns: make([]string, 0),
cloner: cloner,
weaviate: weaviate,
logger: logger,
}
}
func (s *GitSyncer) Sync(url string) error {
// TODO: Introduce goroutines and pass chunks as batch through channel to improve performance
syncId := uuid.New()
targetPath := filepath.Join("../temp/repo", syncId.String())
s.logger.Info("Sync job requested", zap.String("url", url))
// Clone repository
req := git.GitCloneRequest{
URL: url,
TargetPath: targetPath,
}
err := s.cloner.Clone(req)
if err != nil {
s.logger.Error("Clone failed", zap.Error(err))
return err
}
info, err := os.Stat(targetPath)
if os.IsNotExist(err) {
return fmt.Errorf("error: %v does not exists\n", url)
}
if !info.IsDir() {
return fmt.Errorf("error: %v is not a directory\n", url)
}
defer s.cleanup(targetPath)
var extractFailedFiles []string
var dirChunks []extract.Chunk
err = filepath.Walk(targetPath,
// TODO: Exclude fileChunks
func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error: %v\n", err)
}
if !info.IsDir() {
if extractor, ok := s.languageToExtractor[filepath.Ext(info.Name())]; ok {
s.logger.Info("Starting extraction", zap.String("path", path))
fileChunks, err := extractor.Extract(path)
if err != nil {
extractFailedFiles = append(extractFailedFiles, info.Name())
}
dirChunks = append(dirChunks, fileChunks...)
}
}
return nil
})
if err != nil {
s.logger.Error("Error while walking", zap.Error(err))
}
s.logger.Info("Number of files chunked", zap.Int("chunked", len(dirChunks)))
s.logger.Info("Number of files failed", zap.Int("failed", len(extractFailedFiles)))
if len(dirChunks) == 0 {
s.logger.Warn("No files found to chunk. Exiting")
return nil
}
// Move this to embed package
objects := make([]*models.Object, 0)
for _, chunk := range dirChunks {
objects = append(objects, &models.Object{
Class: "CodeSnippets",
Properties: map[string]any{
"file": chunk.File,
"code": chunk.Content,
"language": chunk.Language,
"codeType": chunk.Type,
"module": chunk.Module,
},
})
}
s.logger.Info("Pushing to weaviate", zap.Int("objects", len(objects)))
batchRes, err := s.weaviate.Batch().
ObjectsBatcher().
WithObjects(objects...).
Do(context.Background())
if err != nil {
panic(err)
}
for _, res := range batchRes {
if res.Result.Errors != nil {
s.logger.Warn("Error while pushing", zap.Any("errors", res.Result.Errors))
}
}
s.logger.Info("Sync completed", zap.String("syncId", syncId.String()))
return nil
}
func (s *GitSyncer) Desync() error {
return s.weaviate.Schema().AllDeleter().Do(context.Background())
}
func buildSupportedLanguagesMap(logger *zap.Logger) map[string]extract.Extractor {
supportedLanguages := make(map[string]extract.Extractor)
supportedLanguages[".go"] = golang.NewGoExtractor()
supportedLanguages[".java"] = java.NewJavaExtractor(logger)
return supportedLanguages
}
func (s *GitSyncer) cleanup(targetPath string) {
err := os.RemoveAll(targetPath)
s.logger.Info("Cleaning up", zap.String("targetPath", targetPath))
if err != nil {
log.Println("warn: Unable to cleanup cloned repo", targetPath)
}
}
|
/***************************************************************************
Parameter.h - description
-------------------
* A parameter - a named value (or array of values) with a type and
* (optional) units.
* A parameter's type may be set explicitly or by by setting its value(s).
* A parameter value set as one type may be got as another type, provided
* that the implied conversion is supported. For example, any float may be
* converted to a String, but only some Strings may be converted to floats.
* Getting a parameter value never changes the intrinsic parameter type.
* A ParameterConvertException is thrown when a conversion fails.
copyright : (C) 2012 Fraunhofer ITWM
This file is part of jseisIO.
jseisIO is free software: you can redistribute it and/or modify
it under the terms of the Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jseisIO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Lesser General Public License for more details.
You should have received a copy of the Lesser General Public License
along with jseisIO. If not, see <http://www.gnu.org/licenses/>.
***************************************************************************/
#ifndef PARAMETER_H
#define PARAMETER_H
#include <iostream>
#include <map>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include "stringfuncs.h"
#include "jsDefs.h"
namespace jsIO {
class Parameter {
public:
~Parameter();
/** No descriptions */
Parameter();
int Init(std::string &_name, std::string &_units, std::string &_values, int _type);
int Init(std::string &_name, std::string &_values, int _type);
int Init(std::string &_name, std::string &_values, std::string _stype);
std::string getName() const {
return name;
}
void setName(std::string _name) {
name = _name;
}
;
int getType() const {
return type;
}
;
int getNValues() const {
return N_values;
}
;
bool setValues(std::string &_values, int _type);
bool valuesAsBooleans(bool*) const;
bool valuesAsInts(int*) const;
bool valuesAsLongs(long*) const;
bool valuesAsFloats(float*) const;
bool valuesAsDoubles(double*) const;
bool valuesAsStrings(std::string*) const;
std::string getValuesAsString() const;
std::string getTypeAsString() const;
std::string saveAsXML() const;
public:
static const int UNDEFINED = 0;
static const int BOOLEAN = 1;
static const int INT = 2;
static const int LONG = 3;
static const int FLOAT = 4;
static const int DOUBLE = 5;
static const int STRING = 6;
private:
std::string name;
std::string units;
int type;
int N_values;
bool *bvalues;
int *ivalues;
long *lvalues;
float *fvalues;
double *dvalues;
std::string *svalues;
private:
void setTypeAsString(std::string stype);
};
}
#endif
|
import React from "react";
import ReactDOM from "react-dom";
import {
property,
BrickWrapper,
UpdatingElement,
method,
} from "@next-core/brick-kit";
/**
* @id basic-bricks.general-timer
* @name basic-bricks.general-timer
* @docKind brick
* @description 启动一个定时发出指定事件的定时器
* @author cyril
* @slots
* @history
* 1.67.2:新增构件 `basic-bricks.general-timer`
* @memo
* @noInheritDoc
*/
export class GeneralTimerElement extends UpdatingElement {
/**
* @kind string
* @required false
* @default general-timer.timing-event
* @description 定时抛出的事件
* @group basic
*/
@property()
eventName: string;
/**
* @kind number
* @required false
* @default 60000
* @description 定时间隔(单位:ms)
* @group basic
*/
@property()
interval: number;
/**
* @default true
* @required
* @description 是否开启定时间隔
*/
@property({
attribute: false,
})
isInterval = true;
/**
* @kind any
* @required false
* @default -
* @description 抛出事件的数据
* @group basic
*/
@property()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
dataSource: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _intervalId: any = null;
private defaultEventName = "general-timer.timing-event";
private defaultInterval = 60000;
/**
*
* @description 停止timer
*/
@method() stopTimer(): void {
if (this._intervalId) {
clearInterval(this._intervalId);
}
}
/**
*
* @description 重启timer
*/
@method() reStartTimer(): void {
this.stopTimer();
this.startTimeout();
}
connectedCallback(): void {
// Don't override user's style settings.
// istanbul ignore else
if (!this.style.display) {
this.style.display = "block";
}
this.startTimeout();
this._render();
}
disconnectedCallback(): void {
if (this._intervalId) {
clearInterval(this._intervalId);
}
ReactDOM.unmountComponentAtNode(this);
}
private startTimeout(): void {
this._intervalId = setTimeout(() => {
if (this.dataSource) {
this.dispatchEvent(
new CustomEvent(this.eventName || this.defaultEventName, {
detail: this.dataSource,
})
);
} else {
this.dispatchEvent(
new CustomEvent(this.eventName || this.defaultEventName)
);
}
if (this.isInterval) {
this.startTimeout();
}
}, this.interval || this.defaultInterval);
}
protected _render(): void {
// istanbul ignore else
if (this.isConnected) {
ReactDOM.render(
<BrickWrapper>
<></>
</BrickWrapper>,
this
);
}
}
}
customElements.define("basic-bricks.general-timer", GeneralTimerElement);
|
// Returns the natural logarithm of a number.
// @param {Number} $x
// @example
// log(2) // 0.69315
// log(10) // 2.30259
@function log ($x) {
@if $x <= 0 {
@return 0 / 0;
}
$k: nth(frexp($x / $SQRT2), 2);
$x: $x / ldexp(1, $k);
$x: ($x - 1) / ($x + 1);
$x2: $x * $x;
$i: 1;
$s: $x;
$sp: null;
@while $sp != $s {
$x: $x * $x2;
$i: $i + 2;
$sp: $s;
$s: $s + $x / $i;
}
@return $LN2 * $k + 2 * $s;
}
|
package com.mplayer.musicplayer.mp3player.playsongs.offlineonlineaudio.app.adapter.song;
import android.view.View;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.mplayer.musicplayer.mp3player.playsongs.offlineonlineaudio.app.AdsIntegration.AdsBaseActivity;
import com.mplayer.musicplayer.mp3player.playsongs.offlineonlineaudio.app.glide.SongGlideRequest;
import com.mplayer.musicplayer.mp3player.playsongs.offlineonlineaudio.app.interfaces.CabHolder;
import com.mplayer.musicplayer.mp3player.playsongs.offlineonlineaudio.app.model.Song;
import com.mplayer.musicplayer.mp3player.playsongs.offlineonlineaudio.app.util.MusicUtil;
import java.util.List;
public class AlbumSongAdapter extends SongAdapter {
AppCompatActivity activity;
public AlbumSongAdapter(AdsBaseActivity activity, List<Song> dataSet, @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder) {
super(activity, dataSet, itemLayoutRes, usePalette, cabHolder);
this.activity = activity;
}
@Override
protected SongAdapter.ViewHolder createViewHolder(View view) {
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull SongAdapter.ViewHolder holder, int position) {
super.onBindViewHolder(holder, position);
final Song song = dataSet.get(position);
if (holder.imageText != null) {
final int trackNumber = MusicUtil.getFixedTrackNumber(song.trackNumber);
final String trackNumberString = trackNumber > 0 ? String.valueOf(trackNumber) : "-";
holder.imageText.setText(trackNumberString);
}
if (holder.imageText != null) {
holder.imageText.setText(String.valueOf(position + 1));
}
}
@Override
protected String getSongText(Song song) {
return MusicUtil.getReadableDurationString(song.duration);
}
public class ViewHolder extends SongAdapter.ViewHolder {
public ViewHolder(@NonNull View itemView) {
super(itemView);
if (imageText != null) {
imageText.setVisibility(View.VISIBLE);
}
// if (image != null) {
// image.setVisibility(View.GONE);
// }
}
}
@Override
protected void loadAlbumCover(Song song, SongAdapter.ViewHolder holder) {
// We don't want to load it in this adapter
SongGlideRequest.Builder.from(Glide.with(activity), song)
.checkIgnoreMediaStore(activity).build()
.into(holder.image);
}
}
|
// Project 4
// CS 2413 Data Structures
// Spring 2023
#include <iostream>
#include <vector> // for array of transactions and array of blockChains
#include <list> // for array of blocks
using namespace std;
// this class is simple data type of class
//just complete the structure of a transaction object
class transaction
{
int tID; // transaction id----------------------------------> given input
int fromID; // source ID --------------------------------------> given input
int fromValue; // P4: how much funds does the source ID person have? If first time, then initialize with 100 coins
int toID; // target ID ---------------------------------------> given input
int toValue; // P4: how much funds does the source ID person have? If first time, then initialize with 100 coins
int tAmount; // how much is being transfered
string timeStamp; // time of the transaction read from the input file
public:
transaction() : tID(0), fromID(0), toID(0), tAmount(0), timeStamp("") {} // default constructor
transaction(int temptID, int tempfromID, int temptoID, int temptAmount, string temptimeStamp) {
tID = temptID;
fromID = tempfromID;
fromValue = 100;
toID = temptoID;
toValue = 100;
tAmount = temptAmount;
timeStamp = temptimeStamp;
}
transaction(int temptID, int tempfromID, int tempfromValue, int temptoID, int tempToValue, int temptAmount, string temptimeStamp) {
tID = temptID;
fromID = tempfromID;
fromValue = tempfromValue;
toID = temptoID;
toValue = tempToValue;
tAmount = temptAmount;
timeStamp = temptimeStamp;
}
// all setters and getters
int getTID() const { return tID; }
void setTID(int id) { tID = id; }
int getFromID() const { return fromID; }
void setFromID(int id) { fromID = id; }
int getFromValue() const { return fromValue; }
void setFromValue(int value) { fromValue = value; }
int getToID() const { return toID; }
void setToID(int id) { toID = id; }
int getToValue() const { return toValue; }
void setToValue(int value) { toValue = value; }
int getTAmount() const { return tAmount; }
void setTAmount(int amount) { tAmount = amount; }
string getTimeStamp() const { return timeStamp; }
void setTimeStamp(string time) { timeStamp = time; }
// this diplay method will be called in block class's display method
//while iterating though the loop
void displayTransaction() {
cout << tID << " " << fromID << " " << fromValue << " " << toID << " " << toValue << " " <<
tAmount << " " << timeStamp << endl;
}
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Some comments for output
//Each time a transaction is add to a new block this line should be printed->
// "Adding block #1"
// After this as each transaction is added to block 1 -> "Inserting Transaction to block #1"
// this class will have vector of transactions
class block
{
int blockNumber; // block number of the current block
int currentNumTransactions; // how many transactions are currently in the block
int maxNumTransactions; // how many maximum transactions can be in the block
vector<transaction> bTransactions; // vector of transaction objects
public:
block() {} // default constructor
// non default constructor
block(int bNumber, int maxTransactions) {
this->blockNumber = bNumber;
this->currentNumTransactions = 0;
this->maxNumTransactions = maxTransactions;
this->bTransactions.resize(maxTransactions);
}
int searchIDGetValue(int ID) { // this will return the from value
int tempFromId;
int tempToId;
int calculatedFromValue = -1;
for (int i = currentNumTransactions - 1; i >= 0; i--) {
tempFromId = bTransactions[i].getFromID();
tempToId = bTransactions[i].getToID();
if (tempFromId == ID || tempToId == ID) {
if (tempFromId == ID) {
calculatedFromValue = bTransactions[i].getFromValue() - bTransactions[i].getTAmount();
return calculatedFromValue;
}
else if (tempToId == ID) {
calculatedFromValue = bTransactions[i].getToValue() + bTransactions[i].getTAmount();
return calculatedFromValue;
}
}
}
return calculatedFromValue;
}
// insert method to insert a new transaction
void insertTransaction(int numNode, transaction t)
{
cout << "Inserting transaction to block #" << blockNumber << " in node " << numNode << endl;
bTransactions[currentNumTransactions] = t;
currentNumTransactions++;
return;
}
// setters and getters as needed
int getBlockNumber() { return blockNumber; }
void setBlockNumber(int num) { blockNumber = num; }
int getCurrentNumTransactions() { return currentNumTransactions; }
void setCurrentNumTransactions(int num) { currentNumTransactions = num; }
int getMaxNumTransactions() { return maxNumTransactions; }
void setMaxNumTransactions(int num) { maxNumTransactions = num; }
vector<transaction> getBTransactions() { return bTransactions; }
void setBTransactions(vector<transaction> transactions) { bTransactions = transactions; }
//display method which will be called from the blockchain class
void displayBlock() {
cout << "Block Number: " << blockNumber << " -- Number of Transaction: " << currentNumTransactions << endl;
for (int i = 0; i < currentNumTransactions; i++) {
// calling display method of transaction class
bTransactions[i].displayTransaction(); // display method will be called for each transaction object stored int the vector
}
}
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// this class will have linked list of blocks
class blockChain
{
int currentNumBlocks; // maintain the size of the list/block chain list
list<block> bChain; // blockchain as a linked list
int numTransactionsPerBlock; // max transactions per block
public:
//default
blockChain() {
this->currentNumBlocks = 0;
this->numTransactionsPerBlock = 0;
}
// non default
blockChain(int transPerBlock) {
this->currentNumBlocks = 0;
this->numTransactionsPerBlock = transPerBlock;
}
// insert method to insert new transaction into the block chain - add new block if existing block is full
void insertTransaction(int numNode, transaction t)
{
if (bChain.empty() || bChain.back().getCurrentNumTransactions() == numTransactionsPerBlock)
{
block newBlock(currentNumBlocks + 1, numTransactionsPerBlock);
newBlock.insertTransaction(numNode, t);
bChain.push_back(newBlock);
currentNumBlocks++;
}
else
{
bChain.back().insertTransaction(numNode, t);
}
}
// P4: search for an ID across all blocks in bChain
int searchIDGetValue(int ID) {
int tempValue = -1;
for (std::list<block>::reverse_iterator it = bChain.rbegin(); it != bChain.rend(); ++it) {
tempValue = it->searchIDGetValue(ID);
if (tempValue != -1) {
return tempValue;
}
}
return tempValue;
}
// setters and getters as needed
int getCurrentNumBlocks() { return currentNumBlocks; }
void setCurrentNumBlocks(int num) { currentNumBlocks = num; }
list<block> getBChain() { return bChain; }
void setBChain(list<block> chain) { bChain = chain; }
int getNumTransactionsPerBlock() { return numTransactionsPerBlock; }
void setNumTransactionsPerBlock(int num) { numTransactionsPerBlock = num; }
//display method which will be called in the main method
void displayData() {
for (std::list<block>::iterator it = bChain.begin(); it != bChain.end(); ++it) {
it->displayBlock(); //calling diplay method from the block class
}
}
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class blockNetwork
{
int numNodes; // maintain the number of nodes in the network
vector<blockChain> allNodes; // vector of all the blockChains in the network
vector<int> u; // edge list u node
vector<int> v; // edge list v node
int tPerBlock;
public:
blockNetwork() {
this->numNodes = 0; // default constructor
}
blockNetwork(int numberOfNodes, int numEdges, int transPerBlock) { // non default constructor
this->numNodes = numberOfNodes;
this->allNodes.resize(numberOfNodes);
for (int i = 0; i < numberOfNodes; i++) {
allNodes[i].setNumTransactionsPerBlock(transPerBlock);
}
this->u.resize(numEdges);
this->v.resize(numEdges);
this->tPerBlock = transPerBlock;
}
//insert method to insert new transaction into the block chain in a specific node - there will be a block chain existent in each node (allNodes vector)
void insertTransaction(int nodeNum, transaction t)
{
int tempFromValue;
tempFromValue = allNodes[nodeNum].searchIDGetValue(t.getFromID());
int tempToValue;
tempToValue = allNodes[nodeNum].searchIDGetValue(t.getToID());
if (tempFromValue != -1 && tempToValue != -1) {
transaction tempTransaction(t.getTID(), t.getFromID(),tempFromValue, t.getToID(), tempToValue, t.getTAmount(), t.getTimeStamp());
allNodes[nodeNum].insertTransaction(nodeNum, tempTransaction);
}
else if (tempFromValue != -1 && tempToValue == -1) {
transaction tempTransaction(t.getTID(), t.getFromID(), tempFromValue, t.getToID(), 100, t.getTAmount(), t.getTimeStamp());
allNodes[nodeNum].insertTransaction(nodeNum, tempTransaction);
}
else if (tempFromValue == -1 && tempToValue != -1) {
transaction tempTransaction(t.getTID(), t.getFromID(), 100, t.getToID(), tempToValue, t.getTAmount(), t.getTimeStamp());
allNodes[nodeNum].insertTransaction(nodeNum, tempTransaction);
}
else if (tempFromValue == -1 && tempToValue == -1) {
transaction tempTransaction(t.getTID(), t.getFromID(), 100, t.getToID(), 100, t.getTAmount(), t.getTimeStamp());
allNodes[nodeNum].insertTransaction(nodeNum, tempTransaction);
}
else {
transaction tempTransaction(t.getTID(), t.getFromID(), 100, t.getToID(), 100, t.getTAmount(), t.getTimeStamp());
allNodes[nodeNum].insertTransaction(nodeNum, tempTransaction);
}
}
// setters and getters as needed
vector<int> getU() { return u; }
void setU(vector<int> tempU) { u = tempU; }
vector<int> getV() { return v; }
void setV(vector<int> tempV) { u = tempV; }
// other methods as needed
//TODO: Display method
void displayBlockNetwork() {
for (int i = 0; i < numNodes; i++) {
cout << "~~~ Node " << i << ": " << endl;
cout << "Current number of blocks: " << allNodes[i].getCurrentNumBlocks() << endl;
allNodes[i].displayData();
}
}
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main() {
int numNodesInNetwork; // number of nodes in the network
cin >> numNodesInNetwork;//---------------------------------------------------------------------------> 4
cout << "Number of nodes: " << numNodesInNetwork << endl;
int numTransactionsPerBlock; // max transactions per block
cin >> numTransactionsPerBlock; //---------------------------------------------------------------------> 10
cout << "Number of transactions per block: " << numTransactionsPerBlock << endl;
int totalNumTransactions; // total transactions to be read from the input file
cin >> totalNumTransactions; //---------------------------------------------------------------------> 27
cout << "Total number of transactions: " << totalNumTransactions << endl;
int numEdges;
cin >> numEdges;
// object of block network
blockNetwork* n1 = new blockNetwork(numNodesInNetwork, numEdges, numTransactionsPerBlock);
//set U and V
vector<int> tempU = n1->getU();
vector<int> tempV = n1->getV();
for (int i = 0; i < numEdges; i++) {
cin >> tempU[i] >> tempV[i];
}
n1->setU(tempU);
n1->setV(tempV);
for (int i = 0; i < totalNumTransactions; i++) {
int numNode, tID, fromID, toID, tAmount;
string timeStamp;
cin >> numNode >> tID >> fromID >> toID >> tAmount >> timeStamp;
transaction t(tID, fromID, toID, tAmount, timeStamp);
n1->insertTransaction(numNode, t);
}
//TODO: Display the information
n1->displayBlockNetwork();
delete n1;
return 0;
}
//Problems- 1) With the insertion method adding blockchains
// problem- 2) with the pointers and null pointers in the search method
|
# **DNS Proxy**
## What is The DNSProxy?
A DNS proxy, also known as a DNS forwarder or a DNS resolver, is an intermediary server that sits between client devices and DNS servers. Its primary function is to handle DNS queries and forward them to appropriate DNS servers for resolution.
When a client device sends a DNS query to a DNS proxy, the proxy examines the request and acts as a middleman between the client and the DNS server. The DNS proxy checks its cache to see if it already has the resolved IP address for the requested domain. If the information is available in its cache, the proxy can respond directly to the client without sending a query to an external DNS server. This caching mechanism helps to improve the response time and reduce the load on DNS servers.
## ***Introduction***
"A UDP connection is established on port `53`. Whenever a request is made on this connection, the data is buffered, and then passed to the parser module. The parser module handles DNS requests, which are identified by a 12-byte header. Using this module, we separate the nameserver from the query, and check the query type (e.g., AAAA, A, etc.). If the query type is incorrect, a DNS error is returned. Otherwise, we check all the keys using the name server. If a key with the specified name server exists and is already cached, we retrieve it. Otherwise, a UDP connection is established with the DNS server. We send the request and receive the response, which is then stored in the UDP connection proxy to be displayed in the command line (cmd)."

"As it is clear from the diagram, with the increase in the percentage of proxy use, the utilization time ratio decreases."
> The traffic volume saved by this proxy, considering a daily count of 2000 user request, is maximum of
> `(2000 * 0.5)* 100 /1024 = 97.65 KB`.
## ***Requirment***
To run this project, you will need:
- Golang
- Redis
## ***Installation***
1. Using Docker
```sh
docker-compose up
```
2. Build from scratch
3. downloads the modules needed to build and test a package
```sh
go mod download
```
and then using binary
```sh
go bulid
./nsproxy proxy
```
## ***Development***
Open your favorite Terminal and run these commands.
- **First**: run the redis server
- **Second**: Set the Redis host and port in config
- **Third**: DNS Proxy server is listening on localhost `(127.0.0.1:53)`
```sh
go run main.go proxy
```
- **Forth**: Requesting the domain and getting the desired IP from the proxy server in cmd or anything.
```sh
nslookup `[Domain name]` 127.0.0.1
```
For example:
> input => nslookup snapp.ir 127.0.0.1
> output

## ***Configuration***
The `config.json` file will load the program's script settings,
including cache-expiration, external-dns-server, server port, server host, redis port and redis host in json format when the program is run.
- `cache-expiration-time` : The duration which a domain and it's response set in cache.
- `external-dns-server` : A list of external DNS server IPs to request and update in the cache
- `redis-port` : redis up on the port 6379
- `server-port` : UDP connnection on the port 53
|
package com.littleye233.days.compose.home
import android.annotation.SuppressLint
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.littleye233.days.compose.util.DayCard
import com.littleye233.days.compose.util.TopDateCard
import com.littleye233.days.db.DaysDb
import com.littleye233.days.db.DaysDbContent
import com.littleye233.days.ui.theme.DaysTheme
import kotlinx.datetime.toJavaInstant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Period
import java.util.TimeZone
data class HomeScreenCallback(
val onAddClick: () -> Unit,
val onDayCardClick: (dayId: Int) -> Unit
)
@ExperimentalMaterial3Api
@Composable
fun HomeScreen(
db: MutableState<DaysDbContent>,
snackbarHostState: SnackbarHostState,
callback: HomeScreenCallback
) {
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.surface
),
title = {
Text(
text = "Days",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
scrollBehavior = scrollBehavior
)
},
floatingActionButton = {
FloatingActionButton(onClick = callback.onAddClick) {
Icon(Icons.Filled.Add, contentDescription = "Add Day")
}
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
) {
HomeScreenContent(it, db, callback)
}
}
@Composable
fun HomeScreenContent(
innerPadding: PaddingValues,
db: MutableState<DaysDbContent>,
callback: HomeScreenCallback
) {
val nowDt = LocalDate.now()
Column(
modifier = Modifier
.padding(innerPadding)
.padding(horizontal = 15.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Spacer(modifier = Modifier.height(4.dp))
TopDateCard()
Text(
text = "Your Days",
style = MaterialTheme.typography.titleSmall
)
Column(
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
db.value.days.forEachIndexed { index, dayItem ->
val dt = LocalDateTime.ofInstant(
dayItem.instant.toJavaInstant(),
TimeZone.getDefault().toZoneId()
).toLocalDate()
val period = Period.between(dt, nowDt)
DayCard(
title = dayItem.name,
date = dt,
days = period.days,
modifier = Modifier
.clickable(onClick = { callback.onDayCardClick(index) })
)
}
}
}
}
@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun HomeScreenPreview() {
DaysTheme {
Surface {
HomeScreen(
mutableStateOf(DaysDb.DB_DEFAULT),
SnackbarHostState(),
HomeScreenCallback({}, {})
)
}
}
}
|
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>HTML5 WebGL粒子爆炸动画DEMO演示</title>
<style>
body{
margin:0px;
overflow: hidden;
}
canvas{
margin:0px;
position:absolute;
}
</style>
</head>
<body>
<canvas id="c"></canvas>
//片段着色器
<script id="shader-fs" type="x-shader/x-fragment">
#ifdef GL_ES
precision highp float;
#endif
uniform float u_Width;
uniform float u_Height;
uniform vec4 u_FragColor;
varying vec2 pp;
void main(void) {
gl_FragColor = vec4(pp, 1.0, 1.0);
}
</script>
//顶点着色器
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec4 a_Position;
uniform mat4 u_ModelMatrix;
varying vec2 pp;
void main(void) {
pp = a_Position.xy * 0.5 + 0.5;
gl_Position = a_Position;
}
</script>
<script>
var canvas, gl;
canvas = document.getElementById("c");
gl = canvas.getContext("experimental-webgl");
cw = window.innerWidth;
ch = window.innerHeight;
canvas.width = window.innerWidth;
canvas.height = ch;
gl.viewport(0, 0, canvas.width, canvas.height);
var vertexShaderScript = document.getElementById("shader-vs");
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderScript.text);
gl.compileShader(vertexShader);
var fragmentShaderScript = document.getElementById("shader-fs");
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderScript.text);
gl.compileShader(fragmentShader);
gl.program = gl.createProgram();
gl.attachShader(gl.program, vertexShader);
gl.attachShader(gl.program, fragmentShader);
gl.linkProgram(gl.program);
gl.useProgram(gl.program);
var vertices = new Float32Array([
-1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0
]);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, -1, 1, 1, 1, 1, -1]), gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 0, 2, 3]), gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
</script>
</body>
</html>
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:weather_sample_app/features/weather/Screens/home_screen.dart';
import 'package:weather_sample_app/features/weather/Screens/hourly_screen.dart';
import 'package:weather_sample_app/features/weather/Screens/weekly_screen.dart';
import 'package:weather_sample_app/features/weather/api/weather_api.dart';
import 'package:weather_sample_app/features/weather/location/location_manger.dart';
import 'package:weather_sample_app/features/weather/provider/weather_provider.dart';
void main() {
runApp(
const MyApp(),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => WeatherProvider(WeatherApi(), LocationManager()),
child: MaterialApp(
title: 'Flutter Weather',
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
iconTheme: IconThemeData(
color: Colors.blue,
),
elevation: 0,
),
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
colorScheme:
ColorScheme.fromSwatch().copyWith(secondary: Colors.white),
),
home: const HomeScreen(),
routes: {
WeeklyScreen.routeName: (context) => const WeeklyScreen(),
HourlyScreen.routeName: (context) => const HourlyScreen(),
},
),
);
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using MediatR;
using ValidationException = Ordering.Application.Exceptions.ValidationException;
namespace Ordering.Application.Behaviors
{
public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
RequestHandlerDelegate<TResponse> next)
{
if (_validators.Any())
{
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(
_validators.Select(v => v.ValidateAsync(context, cancellationToken))
);
var failures = validationResults
.Where(r => r.Errors.Any())
.SelectMany(r => r.Errors)
.ToList();
if (failures.Any())
throw new ValidationException(validationFailures: failures);
}
return await next();
}
}
}
|
import { ApiProperty } from '@nestjs/swagger';
import { Expose, Transform, Type } from 'class-transformer';
import { LineString } from 'geojson';
import { SettlementSerializer } from 'src/modules/settlements/serializers/settlement.serializer';
import { RideEntity } from '../db/ride.entity';
export class RideSerializer {
@ApiProperty()
@Expose()
id: string;
@ApiProperty()
@Expose()
driverId: string;
@ApiProperty()
@Expose()
departureSettlementId: string;
@ApiProperty()
@Expose()
arrivalSettlementId: string;
@ApiProperty({
type: 'array',
items: {
type: 'array',
items: { type: 'number', minLength: 2, maxLength: 2 },
},
})
@Transform(({ obj }: { obj: RideEntity }) => obj.routeCurve.coordinates)
@Expose()
routeCurve: number[][];
@ApiProperty()
@Expose()
status: string;
@ApiProperty()
@Expose()
estDepartureTime: Date;
@ApiProperty()
@Expose()
estArrivalTime: Date;
@ApiProperty()
@Type(() => SettlementSerializer)
@Expose()
departureSettlement: SettlementSerializer;
@ApiProperty()
@Type(() => SettlementSerializer)
@Expose()
arrivalSettlement: SettlementSerializer;
}
|
const fs = require('fs-extra')
const archiver = require('archiver')
const outputZipPath = './out/archive.zip' // Specify the 'out' directory
async function zipFiles() {
try {
// Create the 'out' directory if it doesn't exist
await fs.ensureDir('./out')
// Create a new zip archive
const archive = archiver('zip', {
zlib: { level: 9 }, // Maximum compression level
})
// Create a write stream to save the archive
const output = fs.createWriteStream(outputZipPath)
// Pipe the archive data to the write stream
archive.pipe(output)
// Add the contents of the 'dist' directory to the archive
archive.directory('./dist', false)
// Add the 'node_modules' directory to the archive
archive.directory('./node_modules', 'node_modules')
// Finalize the archive
await archive.finalize()
console.log(`Files zipped successfully. Output path: ${outputZipPath}`)
} catch (err) {
console.error('Error zipping files:', err)
}
}
zipFiles()
|
/** @format */
/**
* External dependencies
*/
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Gridicon from 'gridicons';
import { localize } from 'i18n-calypso';
import { flowRight, get } from 'lodash';
import { connect } from 'react-redux';
/**
* Internal dependencies
*/
import Tooltip from 'components/tooltip';
import getSiteStatsQueryDate from 'state/selectors/get-site-stats-query-date';
import { getSelectedSiteId } from 'state/ui/selectors';
import { isRequestingSiteStatsForQuery } from 'state/stats/lists/selectors';
import { isAutoRefreshAllowedForQuery } from 'state/stats/lists/utils';
class StatsDatePicker extends Component {
static propTypes = {
date: PropTypes.oneOfType( [ PropTypes.object.isRequired, PropTypes.string.isRequired ] ),
period: PropTypes.string.isRequired,
summary: PropTypes.bool,
query: PropTypes.object,
statType: PropTypes.string,
isActivity: PropTypes.bool,
showQueryDate: PropTypes.bool,
};
static defaultProps = {
showQueryDate: false,
isActivity: false,
};
state = {
isTooltipVisible: false,
};
showTooltip = () => {
this.setState( { isTooltipVisible: true } );
};
hideTooltip = () => {
this.setState( { isTooltipVisible: false } );
};
dateForSummarize() {
const { query, moment, translate } = this.props;
const localizedDate = moment();
switch ( query.num ) {
case '-1':
return translate( 'All Time' );
default:
return translate( '%(number)s days ending %(endDate)s (Summarized)', {
context: 'Date range for which stats are being displayed',
args: {
// LL is a date localized by momentjs
number: parseInt( query.num ),
endDate: localizedDate.format( 'LL' ),
},
} );
}
}
dateForDisplay() {
const { date, moment, period, translate } = this.props;
// Ensure we have a moment instance here to work with.
const momentDate = moment.isMoment( date ) ? date : moment( date );
const localizedDate = moment( momentDate.format( 'YYYY-MM-DD' ) );
let formattedDate;
switch ( period ) {
case 'week':
formattedDate = translate( '%(startDate)s - %(endDate)s', {
context: 'Date range for which stats are being displayed',
args: {
// LL is a date localized by momentjs
startDate: localizedDate
.startOf( 'week' )
.add( 1, 'd' )
.format( 'LL' ),
endDate: localizedDate
.endOf( 'week' )
.add( 1, 'd' )
.format( 'LL' ),
},
} );
break;
case 'month':
formattedDate = localizedDate.format( 'MMMM YYYY' );
break;
case 'year':
formattedDate = localizedDate.format( 'YYYY' );
break;
default:
// LL is a date localized by momentjs
formattedDate = localizedDate.format( 'LL' );
}
return formattedDate;
}
renderQueryDate() {
const { queryDate, moment, translate } = this.props;
if ( ! queryDate ) {
return null;
}
const today = moment();
const date = moment( queryDate );
const isToday = today.isSame( date, 'day' );
return (
<span>
{ translate( 'Last update: %(time)s', {
args: { time: isToday ? date.format( 'LT' ) : date.fromNow() },
} ) }
<Gridicon icon="info-outline" size={ 18 } />
</span>
);
}
bindStatusIndicator = ref => {
this.statusIndicator = ref;
};
render() {
const { summary, translate, query, showQueryDate, isActivity } = this.props;
const isSummarizeQuery = get( query, 'summarize' );
const sectionTitle = isActivity
? translate( 'Activity for {{period/}}', {
components: {
period: (
<span className="period">
<span className="date">
{ isSummarizeQuery ? this.dateForSummarize() : this.dateForDisplay() }
</span>
</span>
),
},
comment: 'Example: "Activity for December 2017"',
} )
: translate( 'Stats for {{period/}}', {
components: {
period: (
<span className="period">
<span className="date">
{ isSummarizeQuery ? this.dateForSummarize() : this.dateForDisplay() }
</span>
</span>
),
},
context: 'Stats: Main stats page heading',
comment:
'Example: "Stats for December 7", "Stats for December 8 - December 14", "Stats for December", "Stats for 2014"',
} );
return (
<div>
{ summary ? (
<span>{ sectionTitle }</span>
) : (
<div className="stats-section-title">
<h3>{ sectionTitle }</h3>
{ showQueryDate &&
isAutoRefreshAllowedForQuery( query ) && (
<div
className="stats-date-picker__refresh-status"
ref={ this.bindStatusIndicator }
onMouseEnter={ this.showTooltip }
onMouseLeave={ this.hideTooltip }
>
<span className="stats-date-picker__update-date">
{ this.renderQueryDate() }
<Tooltip
isVisible={ this.state.isTooltipVisible }
onClose={ this.hideTooltip }
position="bottom"
context={ this.statusIndicator }
>
{ translate( 'Auto-refreshing every 30 minutes' ) }
</Tooltip>
</span>
</div>
) }
</div>
) }
</div>
);
}
}
const connectComponent = connect( ( state, { query, statsType, showQueryDate } ) => {
const siteId = getSelectedSiteId( state );
return {
queryDate: showQueryDate ? getSiteStatsQueryDate( state, siteId, statsType, query ) : null,
requesting: showQueryDate
? isRequestingSiteStatsForQuery( state, siteId, statsType, query )
: false,
};
} );
export default flowRight(
connectComponent,
localize
)( StatsDatePicker );
|
package dev.jason.harmony.slashcommands.music;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import com.jagrosh.jlyrics.LyricsClient;
import com.jason.harmony.Bot;
import com.jason.harmony.audio.AudioHandler;
import dev.jason.harmony.slashcommands.MusicCommand;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.ArrayList;
import java.util.List;
public class ParolesCmd extends MusicCommand {
private final LyricsClient lClient = new LyricsClient();
public ParolesCmd(Bot bot) {
super(bot);
this.name = "paroles";
this.arguments = "[titre de la chanson]";
this.help = "Afficher les paroles des chansons";
this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS};
this.aliases = bot.getConfig().getAliases(this.name);
this.bePlaying = true;
List<OptionData> options = new ArrayList<>();
options.add(new OptionData(OptionType.STRING, "name", "nom de la chanson", false));
this.options = options;
}
@Override
public void doCommand(SlashCommandEvent event) {
event.getChannel().sendTyping().queue();
String title;
if (event.getOption("name").getAsString().isEmpty()) {
AudioHandler sendingHandler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
if (sendingHandler.isMusicPlaying(event.getJDA()))
title = sendingHandler.getPlayer().getPlayingTrack().getInfo().title;
else {
event.reply(event.getClient().getError() + "Impossible d'utiliser cette commande car aucune chanson n'est en cours de lecture.").queue();
return;
}
} else
title = event.getOption("name").getAsString();
lClient.getLyrics(title).thenAccept(lyrics ->
{
if (lyrics == null) {
event.reply(event.getClient().getError() + "`" + title + "` : Paroles introuvables" + (event.getOption("name").getAsString().isEmpty() ? ". Essayez d'entrer le nom de la chanson manuellement (`/lyrics [nom de la chanson]`)." : ".")).queue();
return;
}
EmbedBuilder eb = new EmbedBuilder()
.setAuthor(lyrics.getAuthor())
.setColor(event.getMember().getColor())
.setTitle(lyrics.getTitle(), lyrics.getURL());
if (lyrics.getContent().length() > 15000) {
event.reply(event.getClient().getWarning() + " Chanson trouvée avec des paroles pour `" + title + "`, mais elles peuvent être incorrectes : " + lyrics.getURL()).queue();
} else if (lyrics.getContent().length() > 2000) {
String content = lyrics.getContent().trim();
while (content.length() > 2000) {
int index = content.lastIndexOf("\n\n", 2000);
if (index == -1)
index = content.lastIndexOf("\n", 2000);
if (index == -1)
index = content.lastIndexOf(" ", 2000);
if (index == -1)
index = 2000;
event.replyEmbeds(eb.setDescription(content.substring(0, index).trim()).build()).queue();
content = content.substring(index).trim();
eb.setAuthor(null).setTitle(null, null);
}
event.replyEmbeds(eb.setDescription(content).build()).queue();
} else
event.replyEmbeds(eb.setDescription(lyrics.getContent()).build()).queue();
});
}
@Override
public void doCommand(CommandEvent event) {
event.getChannel().sendTyping().queue();
String title;
if (event.getArgs().isEmpty()) {
AudioHandler sendingHandler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler();
if (sendingHandler.isMusicPlaying(event.getJDA()))
title = sendingHandler.getPlayer().getPlayingTrack().getInfo().title;
else {
event.replyError("Impossible d'utiliser cette commande car aucune chanson n'est en cours de lecture.");
return;
}
} else
title = event.getArgs();
lClient.getLyrics(title).thenAccept(lyrics ->
{
if (lyrics == null) {
event.replyError("`" + title + "` : Paroles introuvables" + (event.getArgs().isEmpty() ? ". Essayez d'entrer le titre de la chanson manuellement (`/lyrics [nom de la chanson]`)." : "."));
return;
}
EmbedBuilder eb = new EmbedBuilder()
.setAuthor(lyrics.getAuthor())
.setColor(event.getSelfMember().getColor())
.setTitle(lyrics.getTitle(), lyrics.getURL());
if (lyrics.getContent().length() > 15000) {
event.replyWarning("Chanson trouvée avec des paroles pour `" + title + "`, mais elles peuvent être incorrectes : " + lyrics.getURL());
} else if (lyrics.getContent().length() > 2000) {
String content = lyrics.getContent().trim();
while (content.length() > 2000) {
int index = content.lastIndexOf("\n\n", 2000);
if (index == -1)
index = content.lastIndexOf("\n", 2000);
if (index == -1)
index = content.lastIndexOf(" ", 2000);
if (index == -1)
index = 2000;
event.reply(eb.setDescription(content.substring(0, index).trim()).build());
content = content.substring(index).trim();
eb.setAuthor(null).setTitle(null, null);
}
event.reply(eb.setDescription(content).build());
} else
event.reply(eb.setDescription(lyrics.getContent()).build());
});
}
}
|
import React, {useState} from 'react'
import { Link } from "react-router-dom";
import menu from "../public/menuicon.png"
function Navbar() {
const [visible, setVisible] = useState("right-[100%]");
console.log(visible);
function menuClick() {
if (visible) {
setVisible("");
} else if (visible === "") {
setVisible("right-[100%]");
}
}
return (
<>
<nav className="bg-gray-300 w-full sticky top-0 z-50">
<div className="mx-auto px-6">
<div className="flex justify-between">
<div className="flex w-full justify-between ">
{/* logo */}
<div className="flex">
<Link to="/" className="flex items-center py-5 px-1">
<img className="w-10 rounded-full ml-4 cursor-pointer" src="" alt="logo" />
</Link>
<Link to="/" className="flex items-center py-5 px-1">
<h1 className=' text-lg font-bold'>Name</h1>
</Link>
</div>
{/* primary nav */}
<div className="hidden lg:flex items-center space-x-2 text-lg">
<Link to="/" className="py-5 px-2 hover:font-semibold hover:underline hover:underline-offset-2">
Home
</Link>
<Link to="/aboutus" className="py-5 px-2 hover:font-semibold hover:underline hover:underline-offset-2">
About Us
</Link>
<Link to="/contactus" className="py-5 px-2 hover:font-semibold hover:underline hover:underline-offset-2">
Contact Us
</Link>
{/* <Link to="/admin" className="py-5 px-3 text-gray-700 hover:text-black hover:underline hover:underline-offset-2">
Admin
</Link> */}
</div>
{/* secondary nav */}
<div className="hidden lg:flex my-4 rounded-full bg-gray-500 hover:bg-gray-400 items-center text-lg">
<Link to="/signin" className="py-1 px-3 rounded transition duration-300">
Log in
</Link>
</div>
</div>
{/* mobile button goes here */}
<div className="lg:hidden flex items-center">
<button className="mobile-menu-button" onClick={menuClick}>
<img className="w-6 fill-yellow-500 cursor-pointer" src={menu} alt="menu" />
</button>
</div>
</div>
</div>
{/* mobile menu */}
<div className={`mobile-menu flex flex-col ${visible} font-semibold bg-gray-500 w-full h-[100vh] items-center absolute lg:hidden`}>
<Link to="/" className="block py-2 px-4 my-1 text-sm">
Home
</Link>
<hr className="w-[50%]" />
<Link to="/About" className="block py-2 px-4 my-1 text-sm">
About Us
</Link>
<hr className="w-[50%]" />
<Link to="/contactus" className="block py-2 px-4 my-1 text-sm">
Contact Us
</Link>
<hr className="w-[50%]" />
<Link to="/signin" className="block py-2 px-4 my-1 text-sm">
Log in
</Link>
</div>
</nav>
</>
)
}
export default Navbar
|
/* fira code font family */
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;500&display=swap');
/*
Variables
*/
:root {
--primaryColor: #f15025;
--mainBlack: #222;
--mainWhite: #fff;
--offWhite: #f7f7f7;
--darkGrey: #afafaf;
--mainTransition: all 0.3s linear;
--mainSpacing: 0.2rem;
}
/*
Global Styles
*/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Fira Code", monospace;
color: var(--mainBlack);
background: var(--mainWhite);
line-height: 1.5;
}
a {
text-decoration: none;
}
img {
width: 100%;
display: block;
}
h1,
h2,
h3 {
text-transform: capitalize;
letter-spacing: var(--mainSpacing);
margin-bottom: 1.25rem;
}
h1 {
font-size: 3rem;
}
h2 {
margin-bottom: 0;
}
p {
font-weight: 300;
font-size: 0.7rem;
line-height: 2;
}
/* button */
.btn {
display: inline-block;
padding: 0.75rem 1.25rem;
text-transform: capitalize;
border: 3px solid var(--primaryColor);
color: var(--primaryColor);
margin: 3rem;
transition: var(--mainTransition);
background: var(--mainWhite);
font-size: 1rem;
word-spacing: 0.5rem;
}
.btn:hover {
background: var(--primaryColor);
color: var(--mainWhite);
}
/*
End of Global Styles
*/
/*
Cards Styles
*/
.cards-section-title{
width:90vw;
margin: 0 auto;
margin-top: 4rem;
}
.cards-section-title h1{
font-weight: 500;
text-align: center;
}
.cards{
width: 90vw;
max-width: 1170px;
margin: 0 auto;
/* different layouts code is at last */
}
.card{
border: 1px solid var(--darkGrey);
margin-bottom: 2rem;
}
/* if paragraph has more data then cards paragraph then they don't look like as of now, so */
.card{
display: grid;
grid-template-columns: 1fr;
/* first auto is for img container , take as much value as it want. second 1fr is for paragraph take as much as it can and the third is for the footer. after setting all cards are stretched according to greatest paragraph data */
grid-template-rows: auto 1fr auto;
}
.card .img-container img{
height: 300px;
}
.card-text{
padding: 1rem 1rem;
}
.card-footer{
display: grid;
grid-template-columns: repeat(4,1fr);
grid-template-rows: 2.5rem ;
align-items: center;
justify-items: center;
background:var(--darkGrey);
color: var(--primaryColor);
}
/*
@media screen and (min-width: 768px){
.cards{
display: grid;
grid-template-columns: repeat(2, 1fr);
column-gap: 2rem;
}
.card .img-container img{
height: 300px;
}
}
@media screen and (min-width: 992px){
.cards{
grid-template-columns: repeat(3, 1fr);
}
} */
/* USING AUTOFIT AND AUTOFILL
To use autofill and autofit find out three things
1. max-width of the container in which we want to create columns.
2. find out the total gap of all columns in a row.
3. decide how many columns you want in a row when screen size is
equal to max-width.
sizeof oneColumn : (max-width - totalGap)/totalColumns;
Now ,
grid-template-columns: repeat(autofill/autofit, minmax(oneColumn, 1fr)
so now when screen size is max it only creates no. of columns that you decided and below that screen size all columns take 1 fr of screen size.
And in minmax we pass the minimum column size at max screen size which we finded using formula and another parameter show what to do when screen is not max-width.
*/
/* create different columns layout for different size without any media query
max-width = 1170px
columns = 3
gap = 2
2 gap in three column 1 gap equal to 2 rem so total 64px
(1170 - 64)/3 = 368px */
.cards{
display: grid;
column-gap: 2rem;
/* if there's space remains then auto-fit share that space to the present card
But in auto-fill present card not take the empty space. They only acquire their alloted space */
grid-template-columns: repeat(auto-fill, minmax(368px, 1fr));
}
/*
End of Cards Styles
*/
|
using API_Webshop_MSPR.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
namespace API_Webshop_MSPR
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Webshop", Version = "v1" });
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddTransient<IJwtAuthenticationService, JwtAuthenticationService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api Webshop v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
import { Block, BlockNoteEditor, PartialBlock } from '@blocknote/core';
import '@blocknote/core/fonts/inter.css';
import { BlockNoteView } from '@blocknote/react';
import '@blocknote/react/style.css';
import { saveAs } from 'file-saver';
import htmlToPdf from 'html-to-pdf';
import { useEffect, useMemo, useState } from 'react';
async function saveToStorage(jsonBlocks: Block[]) {
// Save contents to local storage. You might want to debounce this or replace
// with a call to your API / database.
localStorage.setItem('editorContent', JSON.stringify(jsonBlocks));
}
async function loadFromStorage() {
// Gets the previously stored editor contents.
const storageString = localStorage.getItem('editorContent');
return storageString
? (JSON.parse(storageString) as PartialBlock[])
: undefined;
}
export default function App() {
const [initialContent, setInitialContent] = useState<
PartialBlock[] | undefined | 'loading'
>('loading');
const [markdown, setMarkdown] = useState<string>('');
const [pdf, setPdf] = useState<Blob | null>(null);
// Loads the previously stored editor contents.
useEffect(() => {
loadFromStorage().then((content) => {
setInitialContent(content);
});
}, []);
// Creates a new editor instance.
// We use useMemo + createBlockNoteEditor instead of useCreateBlockNote so we
// can delay the creation of the editor until the initial content is loaded.
const editor = useMemo(() => {
if (initialContent === 'loading') {
return undefined;
}
return BlockNoteEditor.create({ initialContent });
}, [initialContent]);
if (editor === undefined) {
return 'Loading content...';
}
const onChange = async () => {
saveToStorage(editor.document);
const markdown = await editor.blocksToMarkdownLossy(editor.document);
const pdfHtml = await editor.blocksToHTMLLossy(editor.document);
setMarkdown(markdown);
// Convert HTML to PDF
htmlToPdf()
.set({ html: pdfHtml })
.toPdf((generatedPdf: any) => {
const pdfBlob = generatedPdf.output('blob');
setPdf(pdfBlob);
});
};
const handleDownloadMarkdown = () => {
if (markdown.trim() !== '') {
const blob = new Blob([markdown], { type: 'text/markdown' });
saveAs(blob, 'blocknote_document.md');
}
};
const handleDownloadPdf = () => {
if (pdf) {
saveAs(pdf, 'blocknote_document.pdf'); // Download the PDF using saveAs
}
};
// Renders the editor instance.
return (
<div>
<BlockNoteView editor={editor} onChange={onChange} />
<button onClick={handleDownloadMarkdown}>Download Markdown</button>
<button onClick={handleDownloadPdf}>Download PDF</button>
<div>
<pre>{markdown}</pre>
</div>
</div>
);
}
|
import 'package:e_commerce/book/constant.dart';
import 'package:e_commerce/book/models/product.dart';
import 'package:e_commerce/book/screens/home/components/item_card.dart';
import 'package:flutter/material.dart';
class Body extends StatelessWidget {
const Body({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// return Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Padding(
// padding: const EdgeInsets.symmetric(horizontal: cDefaultPadding),
// child: Text(
// "Books",
// style: Theme.of(context)
// .textTheme
// .headline5!
// .copyWith(fontWeight: FontWeight.bold),
// ),
// ),
// Categories(),
return Container(
margin: EdgeInsets.only(top: 7, bottom: 5),
child: Column(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: cDefaultPadding),
child: GridView.builder(
itemCount: products.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.75,
mainAxisSpacing: cDefaultPadding,
crossAxisSpacing: cDefaultPadding,
),
itemBuilder: (context, index) => ItemCard(
product: products[index],
// press: () => Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => DetailsScreen(
// product: products[id],
// ),
),
),
),
),
],
),
);
}
}
|
import React, { Dispatch, SetStateAction, useState } from 'react';
export type AppState = {
theme?: 'dark' | 'light';
setTheme?: Dispatch<SetStateAction<'dark' | 'light'>>;
};
export const useAppState = (): AppState => {
const [theme, setTheme] = useState<'light' | 'dark'>('dark');
return {
theme,
setTheme,
};
};
export default React.createContext<AppState>({
theme: 'dark',
});
|
<script setup xmlns="http://www.w3.org/1999/html">
import SymphonyLayout from "@/Layouts/SymphonyLayout.vue";
import {Link, useForm} from "@inertiajs/vue3";
import {Icon} from "@iconify/vue";
import Post from "@/Components/Symphony/Post/Post.vue";
import {ref} from "vue";
import MainModal from "@/Components/Symphony/Modal/MainModal.vue";
import {useClipboard} from "@vueuse/core";
import ShareButton from "@/Components/Symphony/Button/ShareButton.vue";
import CounterMessage from "@/Components/Symphony/CounterMessage.vue";
import UserInfo from "@/Components/Symphony/Post/UserInfo.vue";
import UserCommentInfo from "@/Components/Symphony/UserCommentInfo.vue";
import Tooltip from "@/Components/Symphony/Tooltip.vue";
defineProps({
posts: Object,
user: Object,
nbPosts: Number,
likedPosts: Object,
followers: Object,
followings: Object,
trendingUsers: Array,
});
const source = ref('')
const {text, copy, copied, isSupported} = useClipboard({source})
const formComment = useForm({
content: "",
post_id: null,
});
const formFollow = useForm({
following_id: null,
});
const submitComment = (postId) => {
formComment.post_id = postId;
formComment.post(route('comments.store'), {
preserveScroll: true,
onSuccess: () => {
formComment.reset('content');
}
});
};
const dateFormater = (date) => {
return new Date(date).toLocaleDateString('fr-FR', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
};
const showFilter = ref('post');
const ManageShowFilter = (filter) => {
showFilter.value = filter;
};
// Fonction pour suivre/désabonner avec formulaire
const toggleFollowing = (trendingUser) => {
formFollow.following_id = trendingUser.id;
formFollow.post(route('user.follow'), {
preserveScroll: true,
onSuccess: () => {
}
})
};
const toggleUnFollow = (trendingUser) => {
formFollow.following_id = trendingUser.id;
formFollow.delete(route('user.unfollow', {user: trendingUser.id}), {
preserveScroll: true,
onSuccess: () => {
}
})
};
</script>
<template>
<SymphonyLayout>
<template #trendingUsers>
<div v-for="trendingUser in trendingUsers" :key="trendingUser.id"
class="flex w-full flex-row mb-4 items-center gap-4 justify-between">
<div class="flex flex-row items-center gap-4 w-3/4">
<img alt="user profile image" :src="trendingUser.profile_photo_url" class="w-12 h-12 rounded">
<div class="flex-col flex">
<Tooltip>
<template #button>
<UserInfo :name="trendingUser.name" :username="trendingUser.username" :user-id="trendingUser.id"
class="overflow-hidden w-32"/>
</template>
<template #content>
<UserInfo :name="trendingUser.name" :username="trendingUser.username" :user-id="trendingUser.id"/>
</template>
</Tooltip>
</div>
</div>
<div class="flex flex-row items-center gap-4">
<!-- Bouton qui change en fonction de l'état de suivi -->
<form
@submit.prevent="trendingUser.isFollowed ? toggleUnFollow(trendingUser) : toggleFollowing(trendingUser)">
<button class="bg-symph-500 text-white rounded-full p-1 aspect-square">
<Icon v-if="trendingUser.isFollowed"
class="w-6 h-6" icon="material-symbols:check-indeterminate-small-rounded"/>
<Icon v-else class="w-6 h-6" icon="jam:plus"/>
</button>
</form>
</div>
</div>
</template>
<template #postForm>
<div>
<div
class="w-full bg-symph-700 flex gap-8 border-b pb-8 border-symph-500 sm:flex-row flex-col rounded-t-2xl border-x border-t px-8 pt-8">
<img alt="user profile image" :src="user.profile_photo_url"
class="shadow-symph-500 aspect-square self-center sm:min-w-48 min-w-20 max-w-48 h-max rounded">
<div class="justify-between w-full flex flex-col text-gray-500 mr-8">
<div class="flex flex-col">
<div class="flex flex-row gap-5 items-center justify-between">
<div class="">
<p class="font-bold text-lg">{{ user.name }}</p>
<p class="text-sm">@{{ user.username }}</p>
</div>
<div v-if="user.id !== $page.props.auth.user.id">
<form v-if="user.isFollowed" @submit.prevent="toggleUnFollow(user)">
<button class="bg-red-900/70 hover:bg-red-900/40 text-symph-100 border border-red-500 rounded-lg p-2"
type="submit">
<Icon class="text-2xl" icon="line-md:person-off-twotone"></Icon>
</button>
</form>
<form v-else @submit.prevent="toggleFollowing(user)">
<button class="bg-secondary-900/70 hover:bg-secondary-900/40 text-symph-100 border border-secondary rounded-lg p-2"
type="submit">
<Icon class="text-2xl" icon="line-md:person-add-twotone"></Icon>
</button>
</form>
</div>
</div>
<div class="pt-6 break-all ">
<div class="text-sm">{{ user.description }}</div>
</div>
</div>
<div class="flex sm:flex-row gap-2 flex-col sm:gap-10 gap-2 items-center-5 pt-6">
<div class="flex flex-row items-center gap-2">
<Icon class="w-6 h-6" icon="material-symbols-light:post-add"/>
<p class="text-sm font-light text-gray-700">{{ nbPosts }} Posts</p>
</div>
<div class="flex flex-row gap-2 items-center">
<Icon class="min-w-6 h-6" icon="iconoir:calendar"/>
<p class="text-sm font-light text-gray-700">A rejoint <span
class="font-bold text-secondary">Symphony</span> le {{
dateFormater(user.created_at)
}}</p>
</div>
</div>
</div>
</div>
<div
class="flex text-symph-400 bg-symph-700 flex-row justify-around items-center rounded-b-2xl border-symph-500 border-x border-b">
<button :class="showFilter === 'post' ? 'text-secondary' : ''" class="hover:bg-gray-900 rounded-bl-2xl font-black border-r border-gray-900 text-center basis-1/2 h-full p-5"
@click="ManageShowFilter('post')">
<div class="flex flex-row gap-2 items-center justify-center">
<Icon class="w-6 h-6" icon="material-symbols-light:post-outline-rounded"/>
<h1 class="text-md hidden sm:block font-bold">Posts</h1>
</div>
</button>
<button :class="showFilter === 'like' ? 'text-secondary' : ''" class="hover:bg-gray-900 font-black border-r border-gray-900 text-center basis-1/2 h-full p-5"
@click="ManageShowFilter('like')">
<div class="flex flex-row gap-2 items-center justify-center">
<Icon class="w-6 h-6" icon="icon-park-twotone:like"/>
<h1 class="text-md hidden sm:block font-bold">J'aime</h1>
</div>
</button>
<button :class="showFilter === 'followers' ? 'text-secondary' : ''"
class="hover:bg-gray-900 font-black border-r border-gray-900 text-center basis-1/2 h-full p-5"
@click="ManageShowFilter('followers')">
<div class="flex flex-row gap-2 items-center justify-center">
<Icon class="w-6 h-6" icon="solar:user-circle-bold-duotone"/>
<h1 class="text-md hidden sm:block font-bold">Followers</h1>
</div>
</button>
<button :class="showFilter === 'followings' ? 'text-secondary' : ''"
class="hover:bg-gray-900 rounded-br-2xl font-black text-center basis-1/2 h-full p-5"
@click="ManageShowFilter('followings')">
<div class="flex flex-row gap-2 items-center justify-center">
<Icon class="w-6 h-6" icon="solar:user-circle-bold-duotone"/>
<h1 class="text-md hidden sm:block font-bold">Followings</h1>
</div>
</button>
</div>
</div>
</template>
<div v-if="showFilter === 'post'">
<div v-for="(post, index) in posts" v-if="nbPosts !== 0" :key="post.id">
<Post
:is-last="index === posts.length - 1"
:connectLine="false"
:createdAt="post.created_at"
:post="post"
:src="post.user.profile_photo_url"
:user-id="post.user.id">
<template #likeButton>
<Link :href="route('posts.show', {id: post.id})">
<div class="flex flex-row gap-2 items-center text-gray-300 hover:text-secondary">
<Icon class="w-5 h-5" icon="icon-park-twotone:more-three"/>
<h1 class="text-md font-bold w-max">voir plus</h1>
</div>
</Link>
<div class="flex flex-row gap-2 items-center">
<Link :href="post.isLiked ? route('posts.unlike', { post: post }) : route('posts.like', { post: post })"
method="post">
<Icon :class="[ post.isLiked ? 'text-secondary-500' : 'text-gray-300']"
class="w-5 h-5 transition hover:scale-110 hover:rotate-6 ease-in-out"
icon="uil:heart"/>
</Link>
<h1 class="text-md text-symph-200 font-bold">{{ post.nbLikes }}</h1>
</div>
<div class="flex flex-row gap-2 items-center">
<MainModal @submit="submitComment(post.id)">
<template #button>
<Icon class="w-5 h-5 transition hover:scale-110 ease-in-out text-gray-300"
icon="uil:comment"/>
</template>
<template #modalTitle>
Ajouter un commentaire
</template>
<template #content>
<div class="flex flex-col gap-2">
<UserCommentInfo :content="post.content" :created_at="post.created_at"
:name="post.user.name" :profile_src="post.user.profile_photo_url"
:username="post.user.username"/>
</div>
<div class="flex flex-row items-start gap-4 mt-8">
<img alt="user profile image" :src="$page.props.auth.user.profile_photo_url" class="w-12 h-12 rounded">
<div class="w-full">
<textarea v-model="formComment.content" class="w-full text-symph-200 h-48 rounded-lg bg-symph-800 border-symph-500 resize-none" maxlength="255"
placeholder="Ecrit ton commentaire"
required></textarea>
<CounterMessage :max-characters="255"
:message="formComment.content" class="text-symph-100 w-full text-end"/>
</div>
</div>
<button
class="bg-secondary/20 hover:bg-secondary/40 border border-secondary text-white rounded-md px-4 py-2 mt-3">
Envoyer
</button>
</template>
</MainModal>
<h1 class="text-md text-symph-200 font-bold">{{ post.nbComments }}</h1>
</div>
<!-- Share button -->
<div class="flex flex-row gap-2 items-center">
<ShareButton :copy-text="route('posts.show', {id: post.id})"></ShareButton>
</div>
</template>
</Post>
</div>
<div v-else>
<div class="flex flex-col text-symph-300 items-center justify-center py-20">
<Icon class="w-48 h-48" icon="line-md:cancel-twotone"/>
<h1 class="text-3xl text-center font-bold">Aucun post pour le moment</h1>
</div>
</div>
</div>
<div v-else-if="showFilter === 'like'">
<div v-for="(post, index) in likedPosts" v-if="likedPosts.length !== 0 && likedPosts" :key="post.id">
<Post
:is-last="index === likedPosts.length - 1"
:connectLine="false"
:createdAt="post.created_at"
:post="post"
:src="post.user.profile_photo_url"
:user-id="post.user.id">
<template #likeButton>
<Link :href="route('posts.show', {id: post.id})">
<div class="flex flex-row gap-2 items-center text-gray-300 hover:text-secondary">
<Icon class="w-5 h-5" icon="icon-park-twotone:more-three"/>
<h1 class="text-md font-bold w-max">voir plus</h1>
</div>
</Link>
<div class="flex flex-row gap-2 items-center">
<Link :href="post.isLiked ? route('posts.unlike', { post: post }) : route('posts.like', { post: post })"
method="post">
<Icon :class="[ post.isLiked ? 'text-secondary-500' : 'text-gray-300']"
class="w-5 h-5 transition hover:scale-110 hover:rotate-6 ease-in-out"
icon="uil:heart"/>
</Link>
<h1 class="text-md text-symph-200 font-bold">{{ post.nbLikes }}</h1>
</div>
<div class="flex flex-row gap-2 items-center">
<MainModal @submit="submitComment(post.id)">
<template #button>
<Icon class="w-5 h-5 transition hover:scale-110 ease-in-out text-gray-300"
icon="uil:comment"/>
</template>
<template #modalTitle>
Ajouter un commentaire
</template>
<template #content>
<div class="flex flex-col gap-2">
<UserCommentInfo :content="post.content" :created_at="post.created_at"
:name="post.user.name" :profile_src="post.user.profile_photo_url"
:username="post.user.username"/>
</div>
<div class="flex flex-row items-start gap-4 mt-8">
<img alt="user profile image" :src="$page.props.auth.user.profile_photo_url" class="w-12 h-12 rounded">
<div class="w-full">
<textarea v-model="formComment.content" class="w-full text-symph-200 h-48 rounded-lg bg-symph-800 border-symph-500 resize-none" maxlength="255"
placeholder="Ecrit ton commentaire"
required></textarea>
<CounterMessage :max-characters="255"
:message="formComment.content" class="text-symph-100 w-full text-end"/>
</div>
</div>
<button
class="bg-secondary/20 hover:bg-secondary/40 border border-secondary text-white rounded-md px-4 py-2 mt-3">
Envoyer
</button>
</template>
</MainModal>
<h1 class="text-md text-symph-200 font-bold">{{ post.nbComments }}</h1>
</div>
<!-- Share button -->
<div class="flex flex-row gap-2 items-center">
<ShareButton :copy-text="route('posts.show', {id: post.id})"></ShareButton>
</div>
</template>
</Post>
</div>
<div v-else>
<div class="flex flex-col text-symph-300 items-center justify-center py-20">
<Icon class="w-48 h-48" icon="line-md:person-off-twotone-loop"/>
<h1 class="text-3xl text-center font-bold">Aucun post liké pour le moment</h1>
</div>
</div>
</div>
<div v-else-if="showFilter === 'followers'" class="flex-col flex gap-2">
<div v-if="followers.length !== 0" class="w-full">
<div v-for="user in followers" class="hover:bg-symph-600 py-3 px-8">
<Link :href="route('profileUser.show', {id: user.id})">
<div class="flex flex-row gap-4 items-center">
<img alt="user profile image" :src="user.profile_photo_url" class="aspect-square rounded h-10">
<div class="flex flex-col">
<h1 class="text-gray-600 truncate text-nowrap">{{ user.name }}</h1>
<p class="text-gray-500 text-sm">@{{ user.username }}</p>
</div>
</div>
</Link>
</div>
</div>
<div v-else class="flex flex-col items-center py-20">
<Icon class="w-48 h-48 text-gray-500" icon="line-md:alert-circle-twotone-loop"/>
<h1 class="text-gray-600 text-3xl text-center font-bold truncate text-nowrap">Aucun résultat</h1>
</div>
</div>
<div v-else-if="showFilter === 'followings'" class="flex-col flex gap-2">
<div v-if="followings.length !== 0" class="w-full">
<div v-for="user in followings" class="hover:bg-symph-600 py-3 px-8">
<Link :href="route('profileUser.show', {id: user.id})">
<div class="flex flex-row gap-4 items-center">
<img alt="user profile image" :src="user.profile_photo_url" class="aspect-square rounded h-10">
<div class="flex flex-col">
<h1 class="text-gray-600 truncate text-nowrap">{{ user.name }}</h1>
<p class="text-gray-500 text-sm">@{{ user.username }}</p>
</div>
</div>
</Link>
</div>
</div>
<div v-else class="flex flex-col items-center py-20">
<Icon class="w-48 h-48 text-gray-500" icon="line-md:alert-circle-twotone-loop"/>
<h1 class="text-gray-600 text-3xl text-center font-bold truncate text-nowrap">Aucun résultat</h1>
</div>
</div>
</SymphonyLayout>
</template>
<style scoped>
</style>
|
<template>
<div>
<v-container>
<v-row>
<v-col cols="12" md="9" class="mt-8">
<v-card>
<v-card-title>
Editar Usuario
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Buscar Solicitudes"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table :search="search" :headers="headers" :items="users">
<template v-slot:item.actions="{ item }">
<v-icon @click="editUser(item)" class="mr-2" style="color:green">mdi-pencil</v-icon>
<v-icon @click="deleteUser(item)" style="color:red;">mdi-delete</v-icon>
</template>
</v-data-table>
</v-card>
</v-col>
</v-row>
</v-container>
<v-dialog v-model="editScreen" max-width="850" persistent>
<v-card>
<v-app-bar dark color="primary">
<v-toolbar-title class="title font-weight-light">
<v-avatar size="50">
<v-icon>mdi-pencil</v-icon>
</v-avatar>
<span style="font-size: 22px"> Editar Usuario</span>
</v-toolbar-title>
</v-app-bar>
<v-card-text>
<v-container>
<v-list>
<v-row justify-md="center">
<v-col cols="12" md="4">
<v-list-item-content>
<v-list-item-subtitle>
<v-text-field
v-model="user.name"
:rules="nameRules"
required
class="mt-2"
label="Nombre del Usuario"
outlined
>
</v-text-field>
</v-list-item-subtitle>
</v-list-item-content>
</v-col>
<v-col cols="12" md="4">
<v-list-item-content>
<v-list-item-subtitle>
<v-text-field
v-model="user.lastname"
:rules="lastnameRules"
required
class="mt-2"
label="Apellido(s)"
outlined
>
</v-text-field>
</v-list-item-subtitle>
</v-list-item-content>
</v-col>
<v-col cols="12" md="4">
<v-list-item-content>
<v-list-item-subtitle>
<v-text-field
v-model="user.email"
:rules="emailRules"
required
class="mt-2"
label="Email"
outlined
>
</v-text-field>
</v-list-item-subtitle>
</v-list-item-content>
</v-col>
<v-col cols="12" md="4">
<v-list-item-content>
<v-list-item-subtitle class="body-1" style="color: black">
<span class="body-1 font-weight-bold" style="color: black;">Sexo</span>
<br/>
<v-btn-toggle
v-model="user.gender"
rounded
color="primary"
dense
>
<v-btn value="1">
<v-icon left>mdi-human-male</v-icon>
Hombre
</v-btn>
<v-btn value="2">
<v-icon left>mdi-human-female</v-icon>
Mujer
</v-btn>
</v-btn-toggle>
</v-list-item-subtitle>
</v-list-item-content>
</v-col>
<v-col cols="12" md="4">
<v-list-item-content>
<v-list-item-subtitle class="body-1" style="color: black">
<v-text-field
v-model="user.age"
:rules="ageRules"
required
class="mt-2"
label="Edad"
outlined
type="number"
></v-text-field>
</v-list-item-subtitle>
</v-list-item-content>
</v-col>
<v-col cols="12" md="4">
<v-list-item-content>
<v-list-item-subtitle class="body-1" style="color: black">
<v-text-field
v-model="user.password"
:rules="passwordRules"
required
class="mt-2"
label="Contraseña"
outlined
type="password"
></v-text-field>
</v-list-item-subtitle>
</v-list-item-content>
</v-col>
</v-row>
</v-list>
</v-container>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn text color="primary" @click="editScreen = false">Cancelar</v-btn>
<v-btn color="primary" @click="edit(user)">Enviar</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-model="deleteScreen" max-width="550" persistent>
<v-card>
<v-app-bar dark color="primary">
<v-toolbar-title class="title font-weight-light">
<v-avatar size="50">
<v-icon style="color:red">mdi-delete</v-icon>
</v-avatar>
<span style="font-size: 22px">Eliminar Usuario</span>
</v-toolbar-title>
</v-app-bar>
<v-card-text>
<v-container>
<v-row justify-md="center">
<v-col cols="12" md="12">
<span class="text-h5" style="color:black;">¿Deseas eliminar el usuario de {{ userDelete.name }}?</span>
</v-col>
</v-row>
</v-container>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn text color="primary" @click="deleteScreen = false">Cancelar</v-btn>
<v-btn color="primary" @click="deleteBack(userDelete)">Si,Eliminar</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-row justify="center">
<v-col cols="12" md="6">
<v-snackbar v-model="successSnackbar" color="success" bottom>
<span class="text-h3">Operación exitosa!</span>
<v-btn text @click="successSnackbar = false">Cerrar</v-btn>
</v-snackbar>
</v-col>
</v-row>
<v-row justify="center">
<v-col cols="12" md="6">
<v-snackbar v-model="errorSnackbar" color="success" bottom>
<span class="text-h3">Operación Erronea!</span>
<v-btn text @click="errorSnackbar = false">Cerrar</v-btn>
</v-snackbar>
</v-col>
</v-row>
</div>
</template>
<script>
export default {
name: "editUsers",
data: () => ({
search: "",
users: [],
successSnackbar: false,
errorSnackbar: false,
editScreen: false,
user: [],
deleteScreen: false,
userDelete: [],
headers: [
{
text: "#",
align: "center",
value: "id",
class: "white--text primary",
divider: false,
},
{
text: "Nombre",
value: "name",
align: "center",
class: "white--text primary",
divider: false,
},
{
text: "Apellido(s)",
value: "lastname",
align: "center",
class: "white--text primary",
divider: false,
},
{
text: "Email",
value: "email",
align: "center",
class: "white--text primary",
divider: false,
},
{
text: "Genero",
value: "gender",
align: "center",
class: "white--text primary",
divider: false,
},
{
text: "Edad",
value: "age",
align: "center",
class: "white--text primary",
divider: false,
},
{
text: "Actions",
value: "actions",
align: "center",
class: "white--text primary",
divider: false,
},
],
nameRules: [
value => !!value || 'Nombre del usuario es requerido', // Verifica si el campo está vacío
value => (value && value.length <= 50) || 'Máximo 50 caracteres' // Verifica si el campo tiene más de 50 caracteres
],
lastnameRules: [
value => !!value || 'Apellidos son requeridos',
value => (value && value.length <= 50) || 'Máximo 50 caracteres'
],
emailRules: [
value => !!value || 'Email es requerido',
value => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || 'Dirección de correo electrónico no válida'
],
ageRules: [
value => !!value || 'Edad es requerida',
value => !isNaN(parseFloat(value)) && isFinite(value) || 'Por favor, ingresa un número válido'
],
passwordRules: [
value => !!value || 'Contraseña es requerida',
value => (value && value.length >= 8) || 'La contraseña debe tener al menos 8 caracteres',
],
}),
methods:{
getUsers(){
this.$axios.get("Users").then((response) => {
this.users = response.data.users;
console.log("users: ",this.users);
})
.catch(() => {
})
.finally(() => {
});
},
editUser(item){
console.log("edit user",item);
this.user = Object.assign({}, item);
console.log("user: ",this.user);
this.editScreen = true;
},
edit(item){
console.log(item);
this.$axios.post("editUser", {
userModified: item
})
.then(() => {
})
.catch((error) => {
console.log("error",error);
this.errorSnackbar = true;
})
.finally(() => {
console.log("Exito");
this.editScreen = false;
this.getUsers();
this.successSnackbar = true;
});
},
deleteUser(item){
console.log("delete item",item);
this.userDelete = Object.assign({},item);
this.deleteScreen = true;
},
deleteBack(item){
this.$axios.post("deleteUser", {
userDelete: item
})
.then(() => {
})
.catch((error) => {
console.log("error",error);
this.errorSnackbar = true;
})
.finally(() => {
console.log("Exito");
this.deleteScreen = false;
this.successSnackbar = true;
this.getUsers();
});
}
},
mounted(){
this.getUsers();
}
}
</script>
|
import React, { useState, useEffect } from 'react'
// MUI
import Avatar from '@mui/material/Avatar'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Checkbox from '@mui/material/Checkbox'
import Container from '@mui/material/Container'
import FormControlLabel from '@mui/material/FormControlLabel'
import Grid from '@mui/material/Grid'
import IconButton from '@mui/material/IconButton'
import InputAdornment from '@mui/material/InputAdornment'
import LinkMUI from '@mui/material/Link'
import Paper from '@mui/material/Paper'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
// Icons
import VisibilityIcon from '@mui/icons-material/Visibility'
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff'
// Components
import BackgroundAnimation from '../components/BackgroundAnimation'
import Copyright from '../components/Copyright'
// Others
import axios from 'axios'
import { useNavigate, Link } from 'react-router-dom'
import { toast } from 'sonner'
export default function Register() {
useEffect(() => {
if (localStorage.getItem('Authenticated') === 'true') {
navigate('/user')
toast.message('You are already logged in')
}
}, [])
const navigate = useNavigate()
const [visible, setVisible] = useState(false)
const [allowExtraEmails, setAllowExtraEmails] = useState(false)
const [message, setMessage] = useState('')
const handleSubmit = async (event) => {
event.preventDefault()
const data = new FormData(event.currentTarget)
const body = {
firstName: data.get('firstName'),
lastName: data.get('lastName'),
email: data.get('email'),
password: data.get('password'),
}
console.log(body)
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const isEmailValid = emailRegex.test(body.email)
const isPasswordValid = body.password.length >= 6
if (!isEmailValid) {
return setMessage('Invalid Email')
}
if (!isPasswordValid) {
return setMessage('Your password is very weak')
}
if (!allowExtraEmails) {
return setMessage('Agree our terms and conditions')
}
const res = await axios.get(`/users?email=${body.email}`)
const userExists = res.data.length > 0
if (userExists) {
return setMessage('User already exists')
}
try {
const response = await axios.post('/users', body)
const res = response.data
console.log(res)
navigate('/login')
toast.success('User registered successfully')
} catch (error) {
setMessage(String(error))
console.error(error)
}
}
return (
<Box
sx={{
minHeight: '100vh',
display: 'grid',
placeItems: 'center',
}}
>
<BackgroundAnimation color={message && '#f00'} />
<Container
component="main"
sx={{
padding: '3rem 1.5rem',
}}
>
<Paper
style={{
maxWidth: '500px',
margin: 'auto',
padding: '1.5rem 2rem',
}}
elevation={0}
variant="outlined"
>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar
sx={{
m: 1,
p: 2,
bgcolor: 'secondary.main',
width: '100px',
height: '100px',
}}
>
<img
style={{ width: '100%', height: '100%' }}
src="https://cdn-icons-png.flaticon.com/128/9226/9226414.png"
/>
</Avatar>
<Box
component="form"
noValidate
onSubmit={handleSubmit}
sx={{ mt: 3 }}
>
<Typography variant="subtitle2" color={'red'} paddingY={3}>
{message}
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
autoComplete="given-name"
name="firstName"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
required
fullWidth
id="lastName"
label="Last Name"
name="lastName"
autoComplete="family-name"
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
name="password"
label="Password"
type={visible ? 'text' : 'password'}
id="password"
autoComplete="new-password"
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={() => setVisible((prev) => !prev)}
edge="end"
>
{visible ? (
<VisibilityIcon />
) : (
<VisibilityOffIcon />
)}
</IconButton>
</InputAdornment>
),
}}
/>
</Grid>
<Grid item xs={12}>
<FormControlLabel
control={
<Checkbox
value="allowExtraEmails"
color="primary"
// checked={remember}
onChange={() => setAllowExtraEmails((prev) => !prev)}
/>
}
label="Agree our terms and conditions"
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Register
</Button>
<Grid container justifyContent="flex-end">
<Grid item>
<LinkMUI component={Link} to="/login" variant="body2">
Already have an account?
</LinkMUI>
</Grid>
</Grid>
</Box>
</Box>
</Paper>
<Copyright sx={{ mt: 2 }} />
</Container>
</Box>
)
}
|
package it.unisa.tirocinio.gazzaladra.data;
import android.os.Parcel;
import android.os.Parcelable;
public class KeyPressData implements Parcelable {
public long timeEvent;
public long relativeToStartTimeEvent;
public String activityId;
public String fragmentId;
public String keyCode;
public String position;
public String orientation;
public KeyPressData(long timeEvent, long relativeToStartTimeEvent, String activityId, String fragmentId, String keyCode, String position, String orientation) {
this.timeEvent = timeEvent;
this.relativeToStartTimeEvent = relativeToStartTimeEvent;
this.activityId = activityId;
this.fragmentId = fragmentId;
this.keyCode = keyCode;
this.position = position;
this.orientation = orientation;
}
public String[] toStringArray() {
return new String[]{
"" + this.timeEvent,
"" + this.relativeToStartTimeEvent,
this.activityId,
this.fragmentId,
this.keyCode,
this.position,
this.orientation
};
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.timeEvent);
dest.writeLong(this.relativeToStartTimeEvent);
dest.writeString(this.activityId);
dest.writeString(this.fragmentId);
dest.writeString(this.keyCode);
dest.writeString(this.position);
dest.writeString(this.orientation);
}
protected KeyPressData(Parcel in) {
this.timeEvent = in.readLong();
this.relativeToStartTimeEvent = in.readLong();
this.activityId = in.readString();
this.fragmentId = in.readString();
this.keyCode = in.readString();
this.position = in.readString();
this.orientation = in.readString();
}
public static final Parcelable.Creator<KeyPressData> CREATOR = new Parcelable.Creator<KeyPressData>() {
@Override
public KeyPressData createFromParcel(Parcel source) {
return new KeyPressData(source);
}
@Override
public KeyPressData[] newArray(int size) {
return new KeyPressData[size];
}
};
}
|
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>User Page</title>
<link href="css/styles.css" rel="Stylesheet" type="text/css" />
</h:head>
<h:body>
<div id ="header">
<div id="logo">
<img src="img/logo.png" alt="Monash South Africa - A campus of Monash University Australia" />
</div>
<ul>
<li><a href="">Help</a></li>
<li><h:link value="Logout" outcome="#{sessionBean.invalidate()}" rendered="#{sessionBean.checkActive()}" /></li>
</ul>
</div>
<br />
<!-- <div>
<h:outputText value="As this is your first time, please fill in your " rendered="#{sessionBean.checkFirstTime()}" />
<h:link value="travel profile." outcome="#{userBean.goToProfile()}" rendered="#{sessionBean.checkFirstTime()}" />
</div>
<br />
--> <p:messages autoUpdate="true" id="appHomeTop" closable="true" showDetail="true" />
<div class="nav">
<p:menubar rendered="#{sessionBean.checkNotFirstTime()}">
<p:menuitem value="Home" icon="ui-icon-home" outcome="#{userBean.goHome()}"/>
<p:menuitem value="Profile" icon="ui-icon-person" outcome="#{userBean.viewProfile()}"/>
<p:menuitem value="Applications" icon="ui-icon-note" outcome="#{userBean.goAppHome()}" />
</p:menubar>
</div>
<div id="content">
<p:dataTable id="applications" var="app" value="#{appBean.allApps}">
<p:column headerText="Description" style="width:48%">
<h:outputText value="#{app.description}" />
</p:column>
<p:column headerText="Year" style="width:48%">
<h:outputText value="#{app.datemodified}" />
</p:column>
<p:column style="width:4%">
<p:commandButton id="selectButton" update="applications" icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{app}" target="#{appBean.selectedApp}" />
</p:commandButton>
</p:column>
</p:dataTable>
</div>
<div id= "footer">
<div class="row group">
<div class="col">
<h3>Quick links</h3>
<ul>
<li><a href="">Site Map</a></li>
<li><a href="">FAQ</a></li>
<li><a href="">Contact us</a></li>
</ul>
</div>
<h3>Legal</h3>
<p class="legal">Created by School of IT, Monash South Africa</p>
</div>
</div>
</h:body>
</html>
|
import {
Container,
ContextHeader,
ContextHeaderLabelSection,
ContextHeaderTopSection,
} from '@acpaas-ui/react-editorial-components';
import {
AlertContainer,
DataLoader,
LoadingState,
RenderChildRoutes,
useNavigate,
useWillUnmount,
} from '@redactie/utils';
import React, { FC, ReactElement, useEffect, useMemo, useState } from 'react';
import { Link, useHistory } from 'react-router-dom';
import { LockMessage } from '../../components';
import rolesRightsConnector from '../../connectors/rolesRights';
import translationsConnector, { CORE_TRANSLATIONS } from '../../connectors/translations';
import workflowsConnector from '../../connectors/workflows';
import { MODULE_PATHS, SITES_ROOT } from '../../content.const';
import { ALERT_CONTAINER_IDS, ContentRouteProps } from '../../content.types';
import { generateDetailBadges } from '../../helpers';
import {
useActiveTabs,
useContentItem,
useContentType,
useLock,
useMyContentTypeRights,
useRoutesBreadcrumbs,
} from '../../hooks';
import { useWorkflowState } from '../../hooks/useWorkflowState';
import { useExternalTabsFacade } from '../../store/api/externalTabs';
import { contentFacade } from '../../store/content';
import { contentTypesFacade } from '../../store/contentTypes';
import { CONTENT_UPDATE_TAB_MAP, CONTENT_UPDATE_TABS } from './ContentDetail.const';
import { ContentDetailMatchProps } from './ContentDetail.types';
import './ContentDetail.scss';
const ContentDetail: FC<ContentRouteProps<ContentDetailMatchProps>> = ({
match,
location,
route,
tenantId,
}) => {
const { siteId, contentId, contentTypeId } = match.params;
/**
* Hooks
*/
const { generatePath } = useNavigate(SITES_ROOT);
const [t] = translationsConnector.useCoreTranslation();
const { push } = useHistory();
const [contentItemLoading, contentItem, contentItemDraft, contentItemError] = useContentItem();
const [contentTypeLoading, contentType] = useContentType();
const [
mySecurityRightsLoading,
mySecurityrights,
] = rolesRightsConnector.api.hooks.useMySecurityRightsForSite({
siteUuid: siteId,
onlyKeys: false,
});
const contentTypeRights = useMyContentTypeRights(contentType?._id, mySecurityrights);
const breadcrumbs = useRoutesBreadcrumbs([
{
name: 'Content overzicht',
target: generatePath(`${MODULE_PATHS.overview}`, { siteId }),
},
]);
const [initialLoading, setInitialLoading] = useState(true);
const [, , externalLock] = useLock(contentId);
const [{ all: externalTabs }] = useExternalTabsFacade();
const activeTabs = useActiveTabs(CONTENT_UPDATE_TABS, externalTabs, location.pathname);
const workflowId = useMemo(() => {
if (!contentType || !siteId) {
return;
}
return contentType.modulesConfig?.find(
config => config.name === 'workflow' && config.site === siteId
)?.config.workflow;
}, [contentType, siteId]);
const [workflow] = workflowsConnector.hooks.useWorkflow(workflowId, siteId);
const currentWorkflowState = useWorkflowState(contentItem, workflow);
const guardsMeta = useMemo(
() => ({
tenantId,
}),
[tenantId]
);
const mySecurityrightKeys = useMemo(() => {
if (!Array.isArray(mySecurityrights)) {
return [];
}
return mySecurityrights.map(mySecurityRight => mySecurityRight.attributes.key);
}, [mySecurityrights]);
const [canUpdate, canDelete] = useMemo(() => {
return [
!!contentTypeRights?.update &&
rolesRightsConnector.api.helpers.checkSecurityRights(mySecurityrightKeys, [
rolesRightsConnector.securityRights.update,
]),
!!contentTypeRights?.delete &&
rolesRightsConnector.api.helpers.checkSecurityRights(mySecurityrightKeys, [
rolesRightsConnector.securityRights.remove,
]),
];
}, [mySecurityrightKeys, contentTypeRights]);
useWillUnmount(() => {
contentFacade.clearContentItemDraft();
contentFacade.clearContentItem();
});
useEffect(() => {
if (
initialLoading &&
contentTypeLoading !== LoadingState.Loading &&
contentItemLoading !== LoadingState.Loading &&
mySecurityRightsLoading !== LoadingState.Loading &&
contentType &&
contentItem &&
contentTypeRights
) {
setInitialLoading(false);
}
}, [
contentTypeLoading,
contentItemLoading,
contentType,
contentItem,
mySecurityRightsLoading,
initialLoading,
contentTypeRights,
]);
useEffect(() => {
if (contentItemLoading) {
setInitialLoading(true);
}
}, [contentItemLoading]);
const pageTabs = useMemo(() => {
// filter tabs based on user security rights
return activeTabs.filter(tab => {
if (tab.name === CONTENT_UPDATE_TAB_MAP.edit.name) {
return canUpdate;
}
return true;
});
}, [activeTabs, canUpdate]);
useEffect(() => {
// Redirect user to 403 page when we get a 403 error from
// the server when fetching the latest content item
if (
contentItemError?.actionType === 'fetchingOne' &&
contentItemError?.response?.status === 403
) {
contentFacade.clearError();
push(
`/${tenantId}${
rolesRightsConnector.api.consts.forbidden403Path
}?redirect=${generatePath(MODULE_PATHS.overview, {
siteId,
})}`
);
}
}, [contentItemError, generatePath, push, siteId, tenantId]);
useEffect(() => {
if (!siteId || !contentId || !contentTypeId) {
return;
}
contentFacade.getContentItem(siteId, contentId);
contentTypesFacade.getContentType(siteId, contentTypeId);
}, [siteId, contentId, contentTypeId]);
useEffect(() => {
if (contentItem && contentType) {
contentFacade.setContentItemDraft(contentItem, contentType);
}
}, [contentItem, contentType]);
/**
* Render
*/
const renderChildRoutes = (): ReactElement | null => {
const extraOptions = {
contentType,
contentItem,
contentItemDraft,
tenantId,
canUpdate,
canDelete,
workflow,
};
return (
<>
{externalLock && <LockMessage className="u-margin-bottom" lock={externalLock} />}
<RenderChildRoutes
routes={route.routes}
guardsMeta={guardsMeta}
extraOptions={extraOptions}
/>
</>
);
};
const contentItemLabel = contentItem?.meta.label;
const pageTitle = `${contentItemLabel ? `'${contentItemLabel}'` : 'Content'} ${t(
CORE_TRANSLATIONS.ROUTING_UPDATE
)}`;
const badges = generateDetailBadges(contentItem, contentType, currentWorkflowState?.data.name);
const render = (): ReactElement => {
return (
<>
<ContextHeader
className="v-content-detail__header"
title={pageTitle}
tabs={pageTabs}
linkProps={(props: any) => ({
...props,
to: generatePath(`${MODULE_PATHS.detail}/${props.href}`, {
siteId,
contentId,
contentTypeId,
}),
component: Link,
})}
badges={badges}
>
<ContextHeaderTopSection>{breadcrumbs}</ContextHeaderTopSection>
<ContextHeaderLabelSection>
<b>{contentItem?.meta.lang?.toUpperCase()}</b>
</ContextHeaderLabelSection>
</ContextHeader>
<Container>
<AlertContainer
toastClassName="u-margin-bottom"
containerId={ALERT_CONTAINER_IDS.contentDetail}
/>
{renderChildRoutes()}
</Container>
</>
);
};
return <DataLoader loadingState={initialLoading} render={render} />;
};
export default ContentDetail;
|
import React, { useState } from 'react';
type Props = {
className?: string;
onChange?: (value: boolean) => void;
defaultValue?: boolean;
on?: React.ReactNode;
off?: React.ReactNode;
};
const ToggleButton = ({ className, onChange, defaultValue, on, off }: Props) => {
const [value, setValue] = useState<boolean>(defaultValue === undefined ? false : defaultValue);
const onClick = () => setValue((v) => {
const val = !v;
onChange && onChange(val);
return val;
});
return (
<div className="toggle-button-container">
<button className={`${value ? 'toggle-overlay': 'd-none'}`} onClick={onClick}/>
<button className={`${className || 'toggle-button'} `} onClick={onClick}>
{value ? on : off}
</button>
</div>
);
};
export default ToggleButton;
|
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#toggle-sidenav').on('click', function(){
$('.sidenav-holder').toggle();
$('.content-holder').toggleClass('col-lg-10').toggleClass('col-lg-12');
});
});
</script>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<div id="app">
<div class="container-fluid" style="text-align: left; color: #000;">
<div class="row no-gutters">
<div class="sidenav-holder col-12 col-lg-2">
@include('inc.admin-sidenav')
</div>
<div class="content-holder col-12 col-lg-10">
@include('inc.admin-nav')
<div id="create-user">
@if($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@include('partials.alerts')
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<div class="card">
<div class="card-header">Create New User</div>
<div class="card-body">
<form action="/admin/users/createNew" method="POST">
@csrf
<div class="form-group row">
<label for="email" class="col-12 col-form-label">Email: <span class="asterisk">*</span></label>
<div class="col-12">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" required>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="roles" class="col-form-label">Roles <span class="asterisk">*</span> <br>(Please select at least one)</label>
<div class="col-12">
@foreach ($roles as $role)
<div class="form-check">
<input type="checkbox" name="roles[]" value="{{ $role->id }}" class="@error('roles') is-invalid @enderror">
@error('roles')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
@enderror
<label>{{ $role->name }}</label>
</div>
@endforeach
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">Create User</button>
</div>
</div>
</div>
</div>
</div>
</div>
|
import Loan from "./loan";
const INTEREST_FOR_CAR = 4;
const INTEREST_FOR_COMPUTER = 6;
const INTEREST_FOR_PHONE = 8;
export default class ConsumerLoan extends Loan {
itemType: string;
constructor (loanSize: number, period: number, itemType: string) {
super(loanSize, period);
this.itemType = itemType;
}
setInterest(): void {
switch(this.itemType){
case "automobilis":
this.interest = INTEREST_FOR_CAR;
break;
case "kompiuteris":
this.interest = INTEREST_FOR_COMPUTER;
break;
case "telefonas":
this.interest = INTEREST_FOR_PHONE;
break;
}
}
monthlyPayment(): number {
this.setInterest();
let monthlyInterestSum = this.loanSize * (this.interest / 100); // this.interest yra padalinamos iš 100, kad gautųsi procentali dalis
let monthlyPayment = (this.loanSize / this.period) + monthlyInterestSum;
return +Number(monthlyPayment).toFixed(2);
}
}
|
"""
https://catalog.data.gov/dataset/motor-vehicle-collisions-crashes
Name:John Valencia-Londono
Date:12/4/2023
Assignment:Module14: Dask Large Dataset
Due Date:12/3/2023
About this project:
Demonstrate knowledge of distributed computing by using the Dask library to compute
Data Sets and fetch Series to compute aggregates. Also visualize a DAG used by DASK
All work below was performed by John Valencia-Londono
"""
import time
from dask.diagnostics import ProgressBar
import dask.dataframe as ddf
CSV = "Motor_Vehicle_Collisions_-_Crashes.csv"
dtype={'CONTRIBUTING FACTOR VEHICLE 3': 'object',
'CONTRIBUTING FACTOR VEHICLE 4': 'object',
'CONTRIBUTING FACTOR VEHICLE 5': 'object',
'NUMBER OF PERSONS INJURED': 'float64',
'VEHICLE TYPE CODE 3': 'object',
'VEHICLE TYPE CODE 4': 'object',
'VEHICLE TYPE CODE 5': 'object',
'ZIP CODE': 'object'}
time_start = time.time()
df = ddf.read_csv(CSV, dtype=dtype,assume_missing=True)
time_elapsed = time.time()-time_start
print(f"Time elapsed: {time_elapsed}ms")
with ProgressBar():
print(df.dtypes)
print()
print("Aggregate for NUMBER OF PERSONS INJURED:")
series = df["NUMBER OF PERSONS INJURED"]
with ProgressBar():
print(series.describe().apply(lambda x: format(x,'f'), meta=('NUMBER OF PERSONS INJURED', 'float64')).compute())
print()
print("Aggregate for NUMBER OF PERSONS KILLED:")
series = df["NUMBER OF PERSONS KILLED"]
with ProgressBar():
print(series.describe().apply(lambda x: format(x,'f'), meta=('NUMBER OF PERSONS INJURED', 'float64')).compute())
print()
print("Aggregate for VEHICLE TYPE CODE 1:")
series = df["VEHICLE TYPE CODE 1"]
with ProgressBar():
print(series.describe().compute())
print()
print("Aggregate for VEHICLE TYPE CODE 3:")
series = df["VEHICLE TYPE CODE 3"]
with ProgressBar():
print(series.describe().compute())
print()
print("Aggregate for CONTRIBUTING FACTOR VEHICLE 3:")
series = df["CONTRIBUTING FACTOR VEHICLE 3"]
with ProgressBar():
print(series.describe().compute())
print()
print("Aggregate for ZIP CODE:")
series = df["ZIP CODE"]
with ProgressBar():
print(series.describe().compute())
|
//#region Imports
import { NotFoundException, Param, Put } from '@nestjs/common';
import { ApiNotFoundResponse, ApiOkResponse, ApiOperation } from '@nestjs/swagger';
import { CrudRequest, ParsedRequest } from '@nestjsx/crud';
import { ProtectTo } from '../decorators/protect/protect.decorator';
import { BaseEntity } from './base-entity';
import { BaseCrudController } from './base-crud.controller';
import { BaseCrudService } from './base-crud.service';
//#endregion
/**
* A classe que representa o controller base para o crud
*/
export class BaseEntityCrudController<TEntity extends BaseEntity, TService extends BaseCrudService<TEntity>> extends BaseCrudController<TEntity, TService> {
//#region Constructor
/**
* Construtor padrão
*/
constructor(
service: TService,
) {
super(service);
}
//#endregion
//#region Public Methods
/**
* Método que desativa uma entidade
*
* @param id A identificação da entidade
* @param crudRequest As informações da requisição do CRUD
*/
@ProtectTo('admin')
@Put('/:id/disable')
@ApiOperation({ title: 'Disable one Entity' })
@ApiOkResponse({ description: 'The entity was disabled with successful.' })
@ApiNotFoundResponse({ description: 'The entity was not found' })
public async disable(@Param('id') id: number, @ParsedRequest() crudRequest: CrudRequest): Promise<TEntity> {
const entity = await this.service.repository.findOne(id);
if (!entity)
throw new NotFoundException('A entidade procurada não existe.');
entity.isActive = false;
return await this.service.repository.save(entity as any);
}
/**
* Método que ativa uma nova entidade
*
* @param id A identificação da entidade
* @param crudRequest As informações da requisição do CRUD
*/
@ProtectTo('admin')
@Put('/:id/enable')
@ApiOperation({ title: 'Enable one Entity' })
@ApiOkResponse({ description: 'The entity was disabled with successfull.' })
@ApiNotFoundResponse({ description: 'The entity was not found' })
public async enable(@Param('id') id: number, @ParsedRequest() crudRequest: CrudRequest): Promise<TEntity> {
const entity = await this.service.repository.findOne(id);
if (!entity)
throw new NotFoundException('A entidade procurada não existe.');
entity.isActive = true;
return await this.service.repository.save(entity as any);
}
//#endregion
}
|
#ifndef OBJECTFACTORY_H
#define OBJECTFACTORY_H
#include <string>
#include <unordered_map>
#include <memory>
template<class MyClass, typename ...Argtype>
void* __createObjFunc(Argtype... arg)
{
return new MyClass(arg...);
}
#ifndef REFLECT_REGISTER
#define ReflectRegister(MyClass, ...)\
static int __type##MyClass = ObjectFactory::registerFunction(#MyClass, \
(void*)&__createObjFunc<MyClass, ##__VA_ARGS__>);
#endif
class ObjectFactory
{
public:
template<class _tp, typename ..._args>
static std::shared_ptr<_tp> CreateObject(const std::string &name, _args... args)
{
typedef _tp*(*funcPtr)(_args...);
auto &func_map = getClassFunctionMap();
auto find_func = func_map.find(name);
if(find_func == func_map.end()) return nullptr;
else
{
_tp *class_ptr = reinterpret_cast<funcPtr>(find_func->second)(args...);
return std::shared_ptr<_tp>(class_ptr);
}
}
static int registerFunction(const std::string &class_name, void *function_ptr)
{
getClassFunctionMap()[class_name] = function_ptr;
return 0;
}
private:
static std::unordered_map<std::string, void*> &getClassFunctionMap()
{
static std::unordered_map<std::string, void*> class_function_map;
return class_function_map;
}
};
#endif // OBJECTFACTORY_H
|
// Copyright 2004-2014, North State Software, LLC. All rights reserved.
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifndef NSF_SHALLOW_HISTORY_H
#define NSF_SHALLOW_HISTORY_H
#include "NSFState.h"
namespace NorthStateFramework
{
/// <summary>
/// Represents a shallow history pseudo-state.
/// </summary>
/// <remarks>
/// NSFShallowHistory is a transient state.
/// Once entered, it forces entry into the last active substate in the region.
/// </remarks>
class NSFShallowHistory : public NSFState
{
public:
/// <summary>
/// Creates a shallow history pseudo-state.
/// </summary>
/// <param name="name">The name of the shallow history pseudo-state.</param>
/// <param name="parentRegion">The parent region of the shallow history pseudo-state.</param>
NSFShallowHistory(const NSFString& name, NSFRegion* parentRegion);
/// <summary>
/// Creates a shallow history pseudo-state.
/// </summary>
/// <param name="name">The name of the shallow history pseudo-state.</param>
/// <param name="parentState">The parent state of the shallow history pseudo-state.</param>
NSFShallowHistory(const NSFString& name, NSFCompositeState* parentState);
protected:
virtual void enter(NSFStateMachineContext& context, bool useHistory);
};
}
#endif // NSF_SHALLOW_HISTORY_H
|
package com.day3.learning;
import java.util.Objects;
import java.util.TreeSet;
class Person implements Comparable<Person> {
private int id;
private String name;
private int age;
private double salary;
public Person(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}';
}
@Override
public int hashCode() {
return Objects.hash(age, id, name, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
return age == other.age && id == other.id && Objects.equals(name, other.name)
&& Double.doubleToLongBits(salary) == Double.doubleToLongBits(other.salary);
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.id, other.id);
}
}
public class D03P05 {
public static void main(String[] args) {
TreeSet<Person> personSet = new TreeSet<>();
// Predefined person information
Person person1 = new Person(1, "Jerry", 20, 999.0);
Person person2 = new Person(2, "Smith", 25, 2999.0);
Person person3 = new Person(3, "Popeye", 23, 5999.0);
Person person4 = new Person(4, "Jones", 18, 6999.0);
Person person5 = new Person(5, "John", 32, 1999.0);
Person person6 = new Person(6, "Tom", 42, 3999.0);
// Storing persons in TreeSet
personSet.add(person1);
personSet.add(person2);
personSet.add(person3);
personSet.add(person4);
personSet.add(person5);
personSet.add(person6);
// Print persons whose age is greater than 25
System.out.println("Persons whose age is greater than 25:");
for (Person person : personSet) {
if (person.getAge() > 25) {
System.out.println("Id=" + person.getId() + ",name=" + person.getName() + ",age=" + person.getAge()
+ ",salary=" + person.getSalary());
}
}
}
}
|
package com.austinv11.dartcraft2.api;
import net.minecraft.item.ItemStack;
import java.util.EnumSet;
import java.util.List;
/**
* This interface represents an armor piece which can be infused with upgrades
* <b>This MUST be implemented on the item class itself</b>
*/
public interface IForceArmor {
/**
* The tool types that this armor piece represents
* @return The set of tool types
*/
public EnumSet<ToolType> getToolTypes();
/**
* Called once an infusion has been performed on this item
* @param stack The stack infused
* @param upgrades The upgrades infused (may contain duplicates!)
* @return Whether to continue calculations - if you wish to handle how upgrades work on a tool yourself,
* return false
*/
public boolean onInfusion(ItemStack stack, List<IForceUpgrade> upgrades);
}
|
package com.tycoding.dictionary.feature_dictionary.data.remote.dto
import com.tycoding.dictionary.feature_dictionary.domain.model.Definition
data class DefinitionDto(
val antonyms: List<String>,
val definition: String,
val example: String?,
val synonyms: List<String>
) {
fun toDefinition(): Definition {
return Definition(
antonyms = antonyms,
definition = definition,
example = example,
synonyms = synonyms
)
}
}
|
export function getById<T extends HTMLElement>(id: string): T {
const el = document.getElementById(id);
if (!el) {
throw new ReferenceError(id + " is not defined");
}
return el as T;
}
export function strcmp(a: string, b: string): number {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
export function downloadURL(url: string, filename?: string, tab?: boolean): void {
const dl = document.createElement('a');
dl.href = url;
if (filename) { dl.download = filename; }
if (tab) { dl.target = '_blank'; }
document.body.appendChild(dl);
dl.click();
document.body.removeChild(dl);
}
export function copyClipboardPNG(url: string): void {
if (!navigator.clipboard?.write) {
console.warn("No clipboard API support!");
return;
}
fetch(url).then(res => res.blob()).then(blob => {
if (!blob)
return;
navigator.clipboard.write([new ClipboardItem(
Object.defineProperty({}, "image/png", {
value: blob,
enumerable: true
})
)]);
})
}
export function imageTempCanvas(image: HTMLImageElement, fn: (canvas: HTMLCanvasElement) => Promise<void>): void {
const canvas = document.createElement('canvas');
canvas.style.display = "none";
document.body.appendChild(canvas);
const rect = image.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
fn(canvas).finally(() => document.body.removeChild(canvas));
}
export function downloadImgSVG(image: HTMLImageElement, filename: string): void {
fetch(image.src).then((response) => {
return response.blob();
}).then(blob => {
downloadURL(URL.createObjectURL(blob), filename);
});
}
export function downloadImgPNG(image: HTMLImageElement, filename: string): void {
imageTempCanvas(image, async canvas => {
const imgURI = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
downloadURL(imgURI, filename);
});
}
export function copyImgSVGasPNG(image: HTMLImageElement): void {
if (!navigator.clipboard?.write) {
console.warn("No clipboard API support!");
return;
}
imageTempCanvas(image, async canvas => {
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve));
if (!blob)
return;
return await navigator.clipboard.write([new ClipboardItem(
Object.defineProperty({}, blob.type, {
value: blob,
enumerable: true
})
)]);
});
}
export function validNumberInput(input: HTMLInputElement, min: number, max: number): boolean {
const s = input.value;
if (!s.match(/^\d+$/)) return false;
const v = parseInt(s);
return (v >= min) && (v <= max);
}
export function setCssClass(element: HTMLElement, set: boolean, cssClass: string): boolean {
if (set) {
element.classList.add(cssClass);
} else {
element.classList.remove(cssClass);
}
return set;
}
const supportsNativeSmoothScroll = 'scrollBehavior' in document.documentElement.style;
export function safeScrollTo(elem: Element, options: ScrollToOptions): void {
if (supportsNativeSmoothScroll) {
elem.scrollTo(options);
} else {
elem.scrollTo(options.left ? options.left : 0, options.top ? options.top : 0);
}
}
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=invalid-name
"""Metrics for evaluating tuning process"""
import numpy as np
from ..utils import get_rank
def max_curve(trial_scores):
"""f(n) = max([s[i] fo i < n])
Parameters
----------
trial_scores: Array of float
the score of i th trial
Returns
-------
curve: Array of float
function values
"""
ret = np.empty(len(trial_scores))
keep = -1e9
for i, score in enumerate(trial_scores):
keep = max(keep, score)
ret[i] = keep
return ret
def mean_curve(trial_scores):
"""f(n) = mean([s[i] fo i < n])
Parameters
----------
trial_scores: Array of float
the score of i th trial
Returns
-------
curve: Array of float
function values
"""
ret = np.empty(len(trial_scores))
keep = 0
for i, score in enumerate(trial_scores):
keep += score
ret[i] = keep / (i + 1)
return ret
def recall_curve(trial_ranks, top=None):
"""
if top is None, f(n) = sum([I(rank[i] < n) for i < n]) / n
if top is K, f(n) = sum([I(rank[i] < K) for i < n]) / K
Parameters
----------
trial_ranks: Array of int
the rank of i th trial in labels
top: int or None
top-n recall
Returns
-------
curve: Array of float
function values
"""
if not isinstance(trial_ranks, np.ndarray):
trial_ranks = np.array(trial_ranks)
ret = np.zeros(len(trial_ranks))
if top is None:
for i in range(len(trial_ranks)):
ret[i] = np.sum(trial_ranks[:i] <= i) / (i + 1)
else:
for i in range(len(trial_ranks)):
ret[i] = 1.0 * np.sum(trial_ranks[:i] < top) / top
return ret
def cover_curve(trial_ranks):
"""
f(n) = max k s.t. {1,2,...,k} is a subset of {ranks[i] for i < n}
Parameters
----------
trial_ranks: Array of int
the rank of i th trial in labels
Returns
-------
curve: Array of float
function values
"""
ret = np.empty(len(trial_ranks))
keep = -1
cover = set()
for i, rank in enumerate(trial_ranks):
cover.add(rank)
while keep + 1 in cover:
keep += 1
ret[i] = keep + 1
return ret / len(trial_ranks)
def average_recall(preds, labels, N):
"""evaluate average recall-n for predictions and labels"""
trials = np.argsort(preds)[::-1]
ranks = get_rank(labels[trials])
curve = recall_curve(ranks)
return np.sum(curve[:N]) / N
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* universal selctor (it applies to all tag) */
*
{
letter-spacing: 1px;
word-spacing: 5px;
line-height: 150%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-align: justify;
/* border:1px solid red; */
margin:0px;
}
/* type selector */
body
{
background-color: #C49474;
}
h1
{
background-color: aliceblue;
margin:10px; /* same margin for all directions */
text-shadow: 2px 2px 4px gold;
}
table{
border:1px solid red;
width:80%;
margin: auto; /* will put table horizontally into center of the screen */
border-collapse:collapse;
/* display single border for each and every td tag (must be used inside table) */
}
td
{
border:1px dashed blue;
background-color: aliceblue;
padding: 10px; /* same padding for all directions */
}
div
{
border:1px solid black;
background-color: bisque;
padding: 5px 20px; /* first value is for top & bottom, second value left & right */
margin-left:50px;
margin-top:10px;
margin-bottom:20px;
margin-right:100px;
/* offset-x | offset-y | blur-radius | color */
box-shadow: 5px 5px 10px grey;
border-radius: 30px;
}
</style>
</head>
<body>
<h1>Sample Heading</h1>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Culpa, vel, eos ipsam nobis cupiditate labore reiciendis, harum nulla consectetur facilis repellendus impedit nemo repellat. Dicta, dignissimos. Id voluptatem aliquam sint beatae alias mollitia tempore veritatis soluta exercitationem velit ipsam minima dolore quidem illum, quos commodi tenetur aliquid sapiente natus quis consequatur blanditiis culpa. Consequatur rem minus nostrum! Quisquam asperiores nam, a quod quis consequuntur repudiandae culpa ab pariatur vel nihil possimus animi delectus vitae nulla, fuga enim modi illo explicabo, in corporis natus omnis saepe. Quos, quaerat praesentium rem voluptates animi possimus nisi ipsam unde nostrum voluptate error cumque doloremque?</p>
<div>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Provident consequatur velit nam quis incidunt ea, explicabo excepturi placeat itaque pariatur, iste harum saepe vel impedit? Amet, facilis iusto ipsa delectus sit est tempora expedita placeat, deleniti quia quidem vero, nisi incidunt. Autem asperiores doloribus maiores quae! At doloribus distinctio aliquid, autem eos quibusdam sequi totam enim nobis odit? Consectetur doloribus, eaque dolores quasi id aliquid exercitationem in eos voluptatibus, nulla magni recusandae asperiores minima. Laudantium vel maxime magni tenetur sunt nisi repellendus est repudiandae doloremque! Quos accusamus, adipisci, earum sapiente eius eaque nobis tempora voluptates recusandae magni quisquam temporibus expedita voluptatem eligendi, ad officiis! Vitae sequi ullam mollitia hic quam, harum maxime saepe, libero ratione impedit dolore earum natus doloribus atque maiores inventore voluptate debitis! Illo obcaecati beatae iste officia praesentium et veritatis itaque! Fugiat at sunt obcaecati illo eius, quia, accusantium modi sint suscipit tempora voluptas neque error facilis placeat nam deleniti officia minima. Tempora eius nostrum perspiciatis commodi alias, harum, minus quos eligendi molestias optio, ipsum ipsa? Eum commodi inventore necessitatibus aut in odio maiores deserunt ut doloribus non fugit fugiat ducimus aperiam officiis architecto excepturi ipsa, repudiandae, sed soluta modi facere voluptatum minima illum eius. Incidunt, autem.
</div>
<table>
<tr>
<td>detail</td>
<td>detail</td>
<td>detail</td>
</tr>
<tr>
<td>detail</td>
<td>detail</td>
<td>detail</td>
</tr>
<tr>
<td>detail</td>
<td>detail</td>
<td>detail</td>
</tr>
<tr>
<td>detail</td>
<td>detail</td>
<td>detail</td>
</tr>
<tr>
<td>detail</td>
<td>detail</td>
<td>detail</td>
</tr>
</table>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div id="app">
<h1>書架</h1>
<ul>
<li v-for="(item,index) in booklist" :key="item.id">
<span>{{item.name}}</span>
<span>{{item.author}}</span>
<!-- -->
<button @click="del(item.id)">delete</button>
</li>
</ul>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
booklist: [
{ id: 1, name: '<<紅樓夢>>', author: '曹雪芹' },
{ id: 2, name: '<<西遊記>>', author: '吳承恩' },
{ id: 3, name: '<<水滸傳>>', author: '施耐庵' },
{ id: 4, name: '<<三國演義>>', author: '羅貫中' }
]
},
methods: {
del(id) {
// console.log('delete');
// console.log(id);
this.booklist = this.booklist.filter(item => item.id !== id)
}
}
})
</script>
</body>
</html>
|
---
title: 다음에 올 숫자
date: 2022-10-21 18:24:00 +09:00
categories: ["프로그래머스", "입문"]
tags: ["programmers"]
---
[https://school.programmers.co.kr/learn/courses/30/lessons/120924](https://school.programmers.co.kr/learn/courses/30/lessons/120924)
## 📔 문제 설명
등차수열 혹은 등비수열 common이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return 하도록 solution 함수를 완성해보세요.
💡 입출력 예
| common | result |
| ------------ | ------ |
| [1, 2, 3, 4] | 5 |
| [2, 4, 8] | 16 |
## 💻내가 작성한 코드
- 등차수열인지 조건문 작성
- 2번째 인덱스 - 1번째 인덱스 === 1번째 인덱스 - 0번째 인덱스
- 조건이 true일 경우 마지막 숫자 + 공차 숫자
- 조건이 false 경우 마지막 숫자 + 공비 숫자(commin[1]을 commin[0]으로 나눈 몫)
```js
function solution(common) {
var answer = 0;
const isAdd = common[1] - common[0] === common[2] - common[1];
answer = isAdd
? common[common.length - 1] + common[1] - common[0]
: common[common.length - 1] * (common[1] / common[0]);
return answer;
}
```
|
#ifndef _IN_CSP_ADAPTERS_PARQUET_ArrowSingleColumnArrayBuilder_H
#define _IN_CSP_ADAPTERS_PARQUET_ArrowSingleColumnArrayBuilder_H
#include <csp/adapters/parquet/ParquetStatusUtils.h>
#include <csp/core/Exception.h>
#include <csp/core/Time.h>
#include <csp/engine/Struct.h>
#include <arrow/builder.h>
#include <string>
#include <csp/adapters/parquet/DialectGenericListWriterInterface.h>
namespace csp::adapters::parquet
{
class ArrowSingleColumnArrayBuilder
{
public:
ArrowSingleColumnArrayBuilder( std::string columnName, std::uint32_t chunkSize )
: m_columnName( columnName ), m_chunkSize( chunkSize )
{
}
ArrowSingleColumnArrayBuilder( const ArrowSingleColumnArrayBuilder &other ) = delete;
ArrowSingleColumnArrayBuilder &operator=( const ArrowSingleColumnArrayBuilder &other ) = delete;
virtual ~ArrowSingleColumnArrayBuilder() {}
virtual std::shared_ptr<arrow::DataType> getDataType() = 0;
virtual std::shared_ptr<arrow::ArrayBuilder> getBuilder() = 0;
virtual int64_t length() const = 0;
const std::string &getColumnName(){ return m_columnName; }
std::uint32_t getChunkSize() const{ return m_chunkSize; }
// Called for each row of the output parquet row, if no value was provided a null should be appended
virtual void handleRowFinished() = 0;
// Release the array from the currently built values
virtual std::shared_ptr<arrow::Array> buildArray() = 0;
private:
const std::string m_columnName;
const std::uint32_t m_chunkSize;
};
class StructColumnArrayBuilder : public ArrowSingleColumnArrayBuilder
{
public:
using ColumnBuilderPtr = std::shared_ptr<ArrowSingleColumnArrayBuilder>;
using FieldValueSetter = std::function<void( const Struct * )>;
StructColumnArrayBuilder( std::string columnName, std::uint32_t chunkSize,
const std::shared_ptr<::arrow::DataType> &type,
const std::vector<ColumnBuilderPtr> &childArrayBuilders,
FieldValueSetter fieldValueSetter )
: ArrowSingleColumnArrayBuilder( columnName, chunkSize ),
m_childArrayBuilders( childArrayBuilders ),
m_builderPtr( std::make_shared<::arrow::StructBuilder>( type, arrow::default_memory_pool(),
getArrowChildArrayBuilders( childArrayBuilders ) ) ),
m_fieldValueSetter( fieldValueSetter ),
m_hasValue( false )
{
}
virtual std::shared_ptr<arrow::DataType> getDataType() override
{
return m_builderPtr -> type();
}
virtual std::shared_ptr<arrow::ArrayBuilder> getBuilder() override
{
return m_builderPtr;
}
virtual int64_t length() const override
{
return m_builderPtr -> length();
}
// Called for each row of the output parquet row, if no value was provided a null should be appended
virtual void handleRowFinished() override
{
if( m_hasValue )
{
m_hasValue = false;
for( auto &childBuilder : m_childArrayBuilders )
{
childBuilder -> handleRowFinished();
}
CSP_TRUE_OR_THROW_RUNTIME( m_builderPtr -> Append().ok(), "Failed to append struct" );
}
else
{
STATUS_OK_OR_THROW_RUNTIME( m_builderPtr -> AppendNull(), "Failed to create arrow array" );
}
}
// Release the array from the currently built values
virtual std::shared_ptr<arrow::Array> buildArray() override
{
std::shared_ptr<arrow::Array> array;
STATUS_OK_OR_THROW_RUNTIME( m_builderPtr -> Finish( &array ), "Failed to create arrow array" );
return array;
}
void setValue( const Struct *value )
{
m_hasValue = true;
m_fieldValueSetter( value );
}
private:
static std::vector<std::shared_ptr<::arrow::ArrayBuilder>> getArrowChildArrayBuilders(
const std::vector<ColumnBuilderPtr> &childArrayBuilders )
{
std::vector<std::shared_ptr<::arrow::ArrayBuilder>> res;
for( auto &columnBuilder : childArrayBuilders )
{
res.push_back( columnBuilder -> getBuilder() );
}
return res;
}
private:
std::vector<ColumnBuilderPtr> m_childArrayBuilders;
std::shared_ptr<::arrow::StructBuilder> m_builderPtr;
FieldValueSetter m_fieldValueSetter;
bool m_hasValue;
};
class ListColumnArrayBuilder : public ArrowSingleColumnArrayBuilder
{
public:
using ColumnBuilderPtr = std::shared_ptr<ArrowSingleColumnArrayBuilder>;
ListColumnArrayBuilder( std::string columnName, std::uint32_t chunkSize,
const std::shared_ptr<arrow::ArrayBuilder>& valueBuilder,
const DialectGenericListWriterInterface::Ptr& listWriterInterface)
: ArrowSingleColumnArrayBuilder( columnName, chunkSize ),
m_valueBuilder( valueBuilder ),
m_builderPtr( std::make_shared<::arrow::ListBuilder>( arrow::default_memory_pool(), m_valueBuilder ) ),
m_listWriterInterface(listWriterInterface)
{
}
virtual std::shared_ptr<arrow::DataType> getDataType() override
{
return m_builderPtr -> type();
}
virtual std::shared_ptr<arrow::ArrayBuilder> getBuilder() override
{
return m_builderPtr;
}
virtual int64_t length() const override
{
return m_builderPtr -> length();
}
// Called for each row of the output parquet row, if no value was provided a null should be appended
virtual void handleRowFinished() override
{
if( m_value.has_value() )
{
CSP_TRUE_OR_THROW_RUNTIME( m_builderPtr -> Append().ok(), "Failed to append list" );
m_listWriterInterface->writeItems(m_value.value());
m_value.reset();
}
else
{
STATUS_OK_OR_THROW_RUNTIME( m_builderPtr -> AppendNull(), "Failed write null arrow list" );
}
}
// Release the array from the currently built values
virtual std::shared_ptr<arrow::Array> buildArray() override
{
std::shared_ptr<arrow::Array> array;
STATUS_OK_OR_THROW_RUNTIME( m_builderPtr -> Finish( &array ), "Failed to create arrow list array" );
return array;
}
void setValue( const DialectGenericType& value)
{
m_value = value;
}
private:
static std::shared_ptr<arrow::ArrayBuilder> createValueArrayBuilderForType( const std::shared_ptr<::arrow::DataType> &childType)
{
switch(childType->id())
{
case arrow::Type::INT64:
return std::make_shared<arrow::Int64Builder>();
case arrow::Type::DOUBLE:
return std::make_shared<arrow::DoubleBuilder>();
case arrow::Type::BOOL:
return std::make_shared<arrow::BooleanBuilder>();
default:
CSP_THROW(TypeError, "Trying to create arrow list array builder for unsupported element type " << childType->name());
}
}
static std::vector<std::shared_ptr<::arrow::ArrayBuilder>> getArrowChildArrayBuilders(
const std::vector<ColumnBuilderPtr> &childArrayBuilders )
{
std::vector<std::shared_ptr<::arrow::ArrayBuilder>> res;
for( auto &columnBuilder : childArrayBuilders )
{
res.push_back( columnBuilder -> getBuilder() );
}
return res;
}
private:
std::shared_ptr<arrow::ArrayBuilder> m_valueBuilder;
std::shared_ptr<::arrow::ListBuilder> m_builderPtr;
DialectGenericListWriterInterface::Ptr m_listWriterInterface;
std::optional<DialectGenericType> m_value;
};
template< typename ValueType, typename ArrowBuilderType >
class BaseTypedArrayBuilder : public ArrowSingleColumnArrayBuilder
{
public:
using ValueTypeT = ValueType;
using ArrowBuilderTypeT = ArrowBuilderType;
BaseTypedArrayBuilder( std::string columnName, std::uint32_t chunkSize )
: ArrowSingleColumnArrayBuilder( columnName, chunkSize ),
m_builderPtr( std::make_shared<ArrowBuilderType>() )
{
CSP_TRUE_OR_THROW_RUNTIME( m_builderPtr -> Reserve( getChunkSize() ).ok(), "Failed to reserve arrow array size" );
}
std::shared_ptr<arrow::ArrayBuilder> getBuilder() override
{
return m_builderPtr;
}
std::shared_ptr<arrow::DataType> getDataType() override
{
return m_builderPtr -> type();
}
virtual int64_t length() const override
{
return m_builderPtr -> length();
}
void handleRowFinished() override
{
if( m_value )
{
pushValueToArray();
}
else
{
STATUS_OK_OR_THROW_RUNTIME( m_builderPtr -> AppendNull(), "Failed to append null to arrow array" );
}
m_value = nullptr;
}
std::shared_ptr<arrow::Array> buildArray() override
{
std::shared_ptr<arrow::Array> array;
CSP_TRUE_OR_THROW_RUNTIME( m_builderPtr -> Finish( &array ).ok(), "Failed to create arrow array" );
return array;
}
void setValue( const ValueType &value )
{
m_value = &value;
}
protected:
template< typename ...BuilderArgs >
BaseTypedArrayBuilder( std::string columnName, std::uint32_t chunkSize, BuilderArgs ...args )
: ArrowSingleColumnArrayBuilder( columnName, chunkSize ),
m_builderPtr( std::make_shared<ArrowBuilderType>( args... ) )
{
}
virtual void pushValueToArray() = 0;
protected:
std::shared_ptr<ArrowBuilderType> m_builderPtr;
const ValueType *m_value = nullptr;
};
template< typename ValueType, typename ArrowBuilderType >
class PrimitiveTypedArrayBuilder : public BaseTypedArrayBuilder<ValueType, ArrowBuilderType>
{
public:
using BaseTypedArrayBuilder<ValueType, ArrowBuilderType>::BaseTypedArrayBuilder;
protected:
void pushValueToArray()
{
[[maybe_unused]] auto status = this -> m_builderPtr -> Append( *this -> m_value );
}
};
class StringArrayBuilder : public BaseTypedArrayBuilder<std::string, arrow::StringBuilder>
{
public:
using BaseTypedArrayBuilder<std::string, arrow::StringBuilder>::BaseTypedArrayBuilder;
protected:
void pushValueToArray()
{
const std::string &value = *m_value;
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( value.c_str(), value.length() ),
"Failed to append value to arrow array" );
}
};
class BytesArrayBuilder : public BaseTypedArrayBuilder<std::string, arrow::BinaryBuilder>
{
public:
using BaseTypedArrayBuilder<std::string, arrow::BinaryBuilder>::BaseTypedArrayBuilder;
protected:
void pushValueToArray()
{
const std::string &value = *m_value;
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( value.c_str(), value.length() ),
"Failed to append value to arrow array" );
}
};
class [[maybe_unused]] CStringArrayBuilder : public BaseTypedArrayBuilder<const char *, arrow::StringBuilder>
{
public:
using BaseTypedArrayBuilder<const char *, arrow::StringBuilder>::BaseTypedArrayBuilder;
[[maybe_unused]] void setValueCopyPtr( const char *value )
{
m_ptrCopy = value;
setValue( m_ptrCopy );
}
protected:
void pushValueToArray()
{
const char *value = *m_value;
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( value ), "Failed to append value to arrow array" );
}
private:
const char *m_ptrCopy;
};
class DatetimeArrayBuilder : public BaseTypedArrayBuilder<csp::DateTime, arrow::TimestampBuilder>
{
public:
DatetimeArrayBuilder( std::string columnName, std::uint32_t chunkSize )
: BaseTypedArrayBuilder<csp::DateTime, arrow::TimestampBuilder>( columnName,
chunkSize,
std::make_shared<arrow::TimestampType>( arrow::TimeUnit::NANO,
"UTC" ),
arrow::default_memory_pool() )
{
}
protected:
void pushValueToArray()
{
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( m_value -> asNanoseconds() ),
"Failed to append timestamp value to arrow array" );
}
};
class DateArrayBuilder : public BaseTypedArrayBuilder<csp::Date, arrow::Date32Builder>
{
public:
DateArrayBuilder( std::string columnName, std::uint32_t chunkSize )
: BaseTypedArrayBuilder<csp::Date, arrow::Date32Builder>( columnName,
chunkSize )
{
}
protected:
void pushValueToArray()
{
auto timedelta = *m_value - getOrigin();
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( timedelta.days() ), "Failed to append date value to arrow array" );
}
private:
static csp::Date &getOrigin()
{
static csp::Date origin{ 1970, 1, 1 };
return origin;
}
};
class TimeArrayBuilder : public BaseTypedArrayBuilder<csp::Time, arrow::Time64Builder>
{
public:
TimeArrayBuilder( std::string columnName, std::uint32_t chunkSize )
: BaseTypedArrayBuilder<csp::Time, arrow::Time64Builder>( columnName, chunkSize,
std::make_shared<arrow::Time64Type>( arrow::TimeUnit::NANO ), arrow::default_memory_pool() )
{
}
protected:
void pushValueToArray()
{
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( m_value -> asNanoseconds() ), "Failed to append time value to arrow array" );
}
};
class TimedeltaArrayBuilder : public BaseTypedArrayBuilder<csp::TimeDelta, arrow::DurationBuilder>
{
public:
TimedeltaArrayBuilder( std::string columnName, std::uint32_t chunkSize )
: BaseTypedArrayBuilder<csp::TimeDelta, arrow::DurationBuilder>(
columnName, chunkSize, std::make_shared<arrow::DurationType>( arrow::TimeUnit::NANO ),
arrow::default_memory_pool() )
{
}
protected:
void pushValueToArray()
{
STATUS_OK_OR_THROW_RUNTIME( this -> m_builderPtr -> Append( m_value -> asNanoseconds() ),
"Failed to append date value to arrow array" );
}
};
using BoolArrayBuilder = PrimitiveTypedArrayBuilder<bool, arrow::BooleanBuilder>;
using Int8ArrayBuilder = PrimitiveTypedArrayBuilder<std::int8_t, arrow::Int8Builder>;
using Int16ArrayBuilder = PrimitiveTypedArrayBuilder<std::int16_t, arrow::Int16Builder>;
using Int32ArrayBuilder = PrimitiveTypedArrayBuilder<std::int32_t, arrow::Int32Builder>;
using Int64ArrayBuilder = PrimitiveTypedArrayBuilder<std::int64_t, arrow::Int64Builder>;
using UInt8ArrayBuilder = PrimitiveTypedArrayBuilder<std::uint8_t, arrow::UInt8Builder>;
using UInt16ArrayBuilder = PrimitiveTypedArrayBuilder<std::uint16_t, arrow::UInt16Builder>;
using UInt32ArrayBuilder = PrimitiveTypedArrayBuilder<std::uint32_t, arrow::UInt32Builder>;
using UInt64ArrayBuilder = PrimitiveTypedArrayBuilder<std::uint64_t, arrow::UInt64Builder>;
using DoubleArrayBuilder = PrimitiveTypedArrayBuilder<double, arrow::DoubleBuilder>;
}
#endif
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:equatable/equatable.dart';
class Product extends Equatable {
final String name;
final String category;
final String imageUrl;
final double price;
final bool isRecommended;
final bool isPopular;
const Product({
required this.name,
required this.category,
required this.imageUrl,
required this.price,
required this.isPopular,
required this.isRecommended,
});
@override
List<Object?> get props => [
name,
category,
imageUrl,
price,
isPopular,
isRecommended,
];
static Product fromSnapshot(DocumentSnapshot snap) {
Product product = Product(
name: snap['name'],
category: snap['category'],
imageUrl: snap['imageUrl'],
price: snap['price'] is int
? (snap['price'] as int).toDouble()
: snap['price'],
isPopular: snap['isPopular'],
isRecommended: snap['isRecommended'],
);
return product;
}
static List<Product> products = [
Product(
name: 'Maxi Dress',
category: 'Women',
imageUrl:
'https://m.media-amazon.com/images/I/71F0A0G65xL._AC_SY500_.jpg',
price: 45.99,
isPopular: true,
isRecommended: true),
Product(
name: 'Mona pants',
category: 'Women',
imageUrl:
'https://m.media-amazon.com/images/I/31tBp3eCyAL._SR240,220_.jpg',
price: 50,
isPopular: false,
isRecommended: true),
Product(
name: 'Travel Backpack',
category: 'Luggage & Travel',
imageUrl:
'https://m.media-amazon.com/images/I/71twnynE71L._AC_UL320_.jpg',
price: 29.99,
isPopular: true,
isRecommended: false),
Product(
name: 'Lightweight ABS',
category: 'Luggage & Travel',
imageUrl:
'https://m.media-amazon.com/images/I/81IWqnzKiiL._AC_UL320_.jpg',
price: 44.99,
isPopular: true,
isRecommended: false),
Product(
name: 'Cotton hoodie',
category: 'Men',
imageUrl:
'https://m.media-amazon.com/images/I/71trlmd1g6L._AC_UL320_.jpg',
price: 86.99,
isPopular: true,
isRecommended: false),
Product(
name: 'cotton Shirts',
category: 'Men',
imageUrl:
'https://m.media-amazon.com/images/I/61NAbTElNEL._AC_UL320_.jpg',
price: 20.99,
isPopular: true,
isRecommended: true),
Product(
name: 'Boy jacket',
category: 'Kids & Baby',
imageUrl:
'https://m.media-amazon.com/images/I/71DIFMUCTAL._AC_UL320_.jpg',
price: 31.99,
isPopular: true,
isRecommended: true),
Product(
name: 'Girls Skirt',
category: 'Kids & Baby',
imageUrl:
'https://m.media-amazon.com/images/I/81WVBb1njTL._AC_UL320_.jpg',
price: 12.99,
isPopular: true,
isRecommended: true),
Product(
name: 'Printed Raincoat',
category: 'Kids & Baby',
imageUrl:
'https://m.media-amazon.com/images/I/81T5z9xdQaL._AC_UL320_.jpg',
price: 26.64,
isPopular: false,
isRecommended: true),
];
}
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
print('programa iniciado: SAM')
# In[12]:
print('1')
import numpy as np
print('2')
import sklearn
print('3')
import tensorflow
print('4')
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
from keras.layers import Dropout
from keras.layers import BatchNormalization
print('5')
from astropy.io import fits
print('5.6')
import pandas as pd
print('5.7')
import matplotlib.pyplot as plt
print('5.8')
import astropy
print('6')
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support
from sklearn.utils import class_weight
import seaborn as sns
from sklearn.model_selection import GridSearchCV
print('7')
from astropy.io import fits
#from astropy.table import Table
print('8')
# In[4]:
print('modulos cargados')
# In[5]:
### Leemos datos del archivo .fits pero unicamente de la clase de interes 'GALAXY', 'STAR', 'QSO'
# In[2]:
wave= fits.open('B_R_Z_wavelenght.fits')
Bwave = wave[1].data
Rwave = wave[2].data
Zwave = wave[3].data
wavelenght = np.hstack((Bwave, Rwave, Zwave)) #Contiene la cadena completa de longitudes de onda B+Z+R para cada espectro
# In[7]:
# Definir una máscara booleana para las longitudes de onda del flujo en U
#mascara = (wavelenght >= 3055.11) & (wavelenght <= 4030.64)
#wavelenght_filtrado= wavelenght[mascara]
# In[3]:
archivos= ['DataDESI_76.fits', 'DataDESI_152.fits', 'DataDESI_213.fits', 'DataDESI_284.fits', 'DataDESI_351.fits',
'DataDESI_438.fits' , 'DataDESI_530.fits', 'DataDESI_606.fits', 'DataDESI_690.fits', 'DataDESI_752.fits']
#archivos= ['DataDESI_752.fits']
#Generamos las listas con los datos:
Spectra_set = None #Este tensor contiene los elementos de flujo completo R+Z+B
spectype = np.array([]) # Esta lista contiene las etiquetas para el ejercicio de clasificación
z = np.array([]) #Esta matriz contiene los corrimientos z para el ejercicio de regresion
for h in range(len(archivos)):
espc = fits.open(archivos[h]) #open file
len_espc= len(espc[2].data)
#leemos la informacion
Bflux= espc[2].data
Rflux= espc[3].data
Zflux= espc[4].data
spectra=np.hstack((Bflux, Rflux, Zflux)) #Contiene la cadena completa de flujo B+Z+R para cada espectro
# Aplicar la máscara a la matriz spectra
# spectra = spectra[:, mascara]
spectra = spectra.reshape(spectra.shape[0], spectra.shape[1], 1)
if Spectra_set is None:
Spectra_set = spectra
else:
Spectra_set = np.concatenate((Spectra_set, spectra), axis=0)
# Obtener la clase espectral y corrimiento para cada espectro
# clases_espectrales = Table.read(espc, hdu=1)['SPECTYPE'].data
# corrimiento = Table.read(espc, hdu=1)['Z'].data
# Read the FITS file and access the SPECTYPE and Z extensions
clases_espectrales = espc[1].data['SPECTYPE'] # Get class data
corrimiento = espc[1].data['Z'] # Get redshift data
spectype = np.append(spectype,clases_espectrales)
z = np.append(z, corrimiento)
z=z.reshape(-1,1)
# Tenemos el tensor Spectra_set que contiene todos los flujos de los .fits seleccionados
# spectype es una lista con las etiquetas de dichos espectros
# z una matriz con los valores de corrimiento de cada espectro.
# In[9]:
print('archivos leidos y data creado')
# In[4]:
#Spectra_set= Spectra_set[:1000]
#spectype= spectype[:1000]
# In[11]:
### Ejercicio de clasifiación. Aqui predecimos la clase o tipo espectral de cada espectro de entrada
# In[12]:
num_classes = 3 # Número de clases
X=Spectra_set
#Aigna un numero entero a cada clase
y = spectype
label_encoder = LabelEncoder()
y = label_encoder.fit_transform(y)
# Divide los datos en conjuntos de entrenamiento y prueba de manera estratificada
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, stratify=y, random_state=42)
# Convierte las etiquetas a codificación one-hot
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes) #Galazxy=[0,0,1]
# Calcular los pesos de clase balanceados
class_weights = class_weight.compute_sample_weight(class_weight='balanced', y=y_train)
# Convertir los pesos a un diccionario
class_weights_dict = dict(enumerate(class_weights))
# Crea el modelo de CNN
model = Sequential()
#model.add(Conv1D(filters=64, kernel_size=20, activation='relu', strides=2!!, input_shape=(len(X[0]),1)))
model.add(Conv1D(filters=64, kernel_size=15, activation='relu', strides=2, input_shape=(len(X[0]),1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(filters=128, kernel_size=15, activation='relu', strides=2))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(filters=256, kernel_size=15, activation='relu', strides=2))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(filters=256, kernel_size=15, activation='relu', strides=2))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(16, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
# Compila el modelo
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Entrena el modelo
history = model.fit(X_train, y_train, epochs=75, batch_size=32, validation_split=0.4, sample_weight=class_weights)
# Guardar el modelo y sus pesos en un solo archivo HDF5
model.save("best_SAM_model.h5")
#Visualización del Rendimiento
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.legend()
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.savefig('Loss_curve_SAM')
plt.close()
plt.show()
# In[13]:
print('modelo entrenado')
# In[14]:
# Hacer predicciones en el conjunto de prueba
predictions = model.predict(X_test)
# Convierte las predicciones one-hot a etiquetas
predicted_labels = np.argmax(predictions, axis=1)
true_labels = np.argmax(y_test, axis=1)
# Crear la matriz de confusión
conf_matrix = confusion_matrix(true_labels, predicted_labels)
# Visualizar la matriz de confusión con seaborn
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=['GALAXY', 'QSO', 'STAR'], yticklabels=['GALAXY', 'QSO', 'STAR'])
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.savefig('conf_matrix_SAM')
plt.close()
plt.show()
# In[15]:
# Calcular precision, recall, y F1 Score
precision, recall, f1_score, _ = precision_recall_fscore_support(true_labels, predicted_labels, average='weighted')
print(f'Precision: {precision:.4f}')
print(f'Recall: {recall:.4f}')
print(f'F1 Score: {f1_score:.4f}')
# In[16]:
# Mapeo de índices de clase a nombres
class_names = {0: 'GALAXY', 1: 'QSO', 2: 'STAR'}
# Calcular precision, recall, y F1 Score por clase
precision_per_class, recall_per_class, f1_score_per_class, _ = precision_recall_fscore_support(true_labels, predicted_labels, average=None)
# Mostrar las métricas por clase
for i in range(num_classes):
class_name = class_names[i]
print(f'Class: {class_name}')
print(f'Precision: {precision_per_class[i]:.4f}')
print(f'Recall: {recall_per_class[i]:.4f}')
print(f'F1 Score: {f1_score_per_class[i]:.4f}')
print('---')
# In[17]:
# Contar las instancias correctamente clasificadas y las incorrectamente clasificadas
correctly_classified = np.where(predicted_labels == true_labels)[0]
incorrectly_classified = np.where(predicted_labels != true_labels)[0]
# Obtener las etiquetas verdaderas de las instancias mal clasificadas
true_labels_incorrect = true_labels[incorrectly_classified]
# Contar las clases correctamente clasificadas
correct_counts = np.bincount(true_labels[correctly_classified], minlength=num_classes)
# Contar las clases incorrectamente clasificadas
incorrect_counts = np.bincount(true_labels_incorrect, minlength=num_classes)
# Crear el histograma
plt.figure(figsize=(10, 6))
bar_width = 0.35
index = np.arange(num_classes)
plt.bar(index, correct_counts, bar_width, label='Correctly Classified', color='g')
plt.bar(index + bar_width, incorrect_counts, bar_width, label='Incorrectly Classified', color='r')
plt.xlabel('Class')
plt.ylabel('Count')
plt.title('Correct vs Incorrect Classification Count by Class')
plt.xticks(index + bar_width / 2, ['GALAXY', 'QSO', 'STAR'])
plt.legend()
plt.savefig('hist_accuracy_SAM')
plt.close()
plt.show()
# In[18]:
print('metricas calculadas, proceso finalizado')
|
import { pipe } from "fp-ts/function"
import * as A from "fp-ts/Array"
/* Imported inline from fp-ts-std */
/**
* Merge two records together. For merging many identical records, instead
* consider defining a semigroup.
*
* @example
* import { merge } from 'fp-ts-std/Struct'
*
* assert.deepStrictEqual(merge({ a: 1, b: 2 })({ b: 'two', c: true }), { a: 1, b: 'two', c: true })
*
* @since 0.14.0
*/
export const merge =
<A>(x: A) =>
<B>(y: B): A & B => ({ ...x, ...y })
/**
* Pick a set of keys from a `Record`. The value-level equivalent of the `Pick`
* type.
*
* @example
* import { pick } from 'fp-ts-std/Struct'
* import { pipe } from 'fp-ts/function'
*
* const picked = pipe(
* { a: 1, b: 'two', c: [true] },
* pick(['a', 'c'])
* )
*
* assert.deepStrictEqual(picked, { a: 1, c: [true] })
*
* @since 0.14.0
*/
export const pick =
<A, K extends keyof A>(ks: Array<K>) =>
(x: A): Pick<A, K> =>
// I don't believe there's any reasonable way to model this sort of
// transformation in the type system without an assertion - at least here
// it's in a single reused place.
pipe(
ks,
A.reduce({} as Pick<A, K>, (ys, k) => merge(ys)(k in x ? { [k]: x[k] } : {}))
)
|
# Dibujar primitivos
Existen varias formas de dibujar primitivos utilizando giftags y
primitive data
## Forma más fácil de dibujar.
No especificar campo REGS, dejarlo simplemente en GIF_REG_AD y
utilizar NLOOP para indicar la cantidad de data que se va a leer.
Luego cada qword tiene que indicar el tipo de data leída.
```c
// Indicar que se leera Address+Data 7 veces.
PACK_GIFTAG(q, GIF_SET_TAG(7, 1, 0, 0, 0, 1), GIF_REG_AD);
q++;
// Indicar primitivo
PACK_GIFTAG(q, GIF_SET_PRIM(GS_PRIM_TRIANGLE, 1, 0, 0, 0, 0, 0, 0, 0), GIF_REG_PRIM);
q++;
// Leer color y coordenada (repetir 3 veces para triangulo Gouraud)
PACK_GIFTAG(q, GIF_SET_RGBAQ(red, green, blue, 128, 128), GIF_REG_RGBAQ);
q++;
PACK_GIFTAG(q, GIF_SET_XYZ(ftoi4(-400 +OFFSET),ftoi4(-300+OFFSET),1), GIF_REG_XYZ2);
q++;
```
## Forma más complicada de dibujar.
Especificar los registros manualmente. Macros draw facilitan esto,
parecer el único caso de uso sería encontrar formas de estrujar
rendimiento.
```c
// Leer 6 registros, EOP(8), nloop una sola vez.
q->dw[0] = 0x6000000000008001;
// Especificar registros - col, pos, col, pos, col, pos
q->dw[1] = 0x0000000000515151;
q++;
```
# Requisitos para poder dibujar.
## FLG tiene que corresponder con el tipo de data de GS primitive.
En packed mode es un qword por registro.
## En primitive data se debe enviar qword que describa registro PRIM.
```c
q->dw[0] = GS_SET_PRIM(GS_PRIM_TRIANGLE, 0, 0, 0, 0, 0, 0, 0, 0);
q->dw[1] = GS_REG_PRIM;
```
## El numero de qwords que se leen tiene que ser el correcto.
Giftag debe ser seguido de data para 7 registros (7 qwords en packed mode).
```c
PACK_GIFTAG(q, GIF_SET_TAG(7, 1, 0, 0, 0, 1), GIF_REG_AD);
```
## El formato de color tiene que ser el correcto.
Al parecer el formato de color es diferente cuando se utiliza
GIF_REG_AD. En este caso el color se empaca en un solo dword, en el
otro se indica que se usara el registro de color GIF_REG_RGBAQ.
```c
PACK_GIFTAG(q, GIF_SET_RGBAQ(red, green, blue, 128, 128), GIF_REG_RGBAQ);
```
Cuando se especifica un registro de color en REGS (5) el formato es el siguiente.
Writes to RGBAQ register (Q is unchanged)
0-7 R
8-31 Unused
32-39 G
40-63 Unused
64-71 B
72-95 Unused
96-103 A
104-127 Unused
## El formato de las coordenadas tiene que ser el correcto.
Mitad de la pantalla es en (2048.0f 2048.0f), coordenadas en formato
fixed point 12.4. Esquina superior para 800x600 seria (ftoi4
(-(800/2) + 2048.0f).
# Conclusión
Cualquier error en alguno de estos puntos anteriores puede hacer que no se dibuje
nada en pantalla.
Los macros GIF_SET_RGBAQ, GIF_SET_XYZ y ftoi4 facilitan bastante el
proceso.
|
package com.example.slawcio.lab1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Just Apps");
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
changeFragment(new Shop());
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@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
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Intent intent = null;
if(id == R.id.nav_gallery){
// fragmentTransaction.remove().commit()
changeFragment(new Gallery());
} else if (id == R.id.nav_music) {
changeFragment(new Music());
} else if (id == R.id.nav_video) {
changeFragment(new Video());
} else if (id == R.id.nav_music_shop) {
changeFragment(new Shop());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
if(intent != null) {
startActivity(intent);
finish();
}
return true;
}
private void changeFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if(fragment!=null)
fragmentTransaction.add(R.id.frame_grid, fragment);
fragmentTransaction.commit();
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cloud Vision Demo</title>
<style type="text/css">
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<h1>Cloud Vision Demo</h1>
<form id="fileform" action="">
<select name="type" id="type">
<option value="LANDMARK_DETECTION">LANDMARK_DETECTION</option>
<option value="FACE_DETECTION">FACE_DETECTION</option>
</select>
<br /><br />
<input id="fileInput" type="file" name="fileField"><br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"></div>
</body>
<script type="text/javascript">
window.apiKey = 'AIzaSyA1HEkQ8nh8CoHIVbDdYFnwAa8VphhGphQ';
var CV_URL = 'https://vision.googleapis.com/v1/images:annotate?key=' + window.apiKey;
$(function () {
$('#fileform').on('submit', uploadFiles);
});
/**
* 'submit' event handler - reads the image bytes and sends it to the Cloud
* Vision API.
*/
function uploadFiles (event) {
event.preventDefault(); // Prevent the default form post
// Grab the file and asynchronously convert to base64.
var file = $('#fileform [name=fileField]')[0].files[0];
var reader = new FileReader();
reader.onloadend = processFile;
reader.readAsDataURL(file);
}
/**
* Event handler for a file's data url - extract the image data and pass it off.
*/
function processFile (event) {
var content = event.target.result;
sendFileToCloudVision(content.replace('data:image/jpeg;base64,', ''));
}
/**
* Sends the given file contents to the Cloud Vision API and outputs the
* results.
*/
function sendFileToCloudVision (content) {
var type = $('#fileform [name=type]').val();
// Strip out the file prefix when you convert to json.
var request = {
requests: [{
image: {
content: content
},
features: [{
type: type,
maxResults: 200
}]
}]
};
$('#results').text('Loading...');
$.post({
url: CV_URL,
data: JSON.stringify(request),
contentType: 'application/json'
}).fail(function (jqXHR, textStatus, errorThrown) {
$('#results').text('ERRORS: ' + textStatus + ' ' + errorThrown);
}).done(displayJSON);
}
/**
* Displays the results.
*/
function displayJSON (data) {
var contents = JSON.stringify(data, null, 4);
$('#results').text("Detection response");
output(syntaxHighlight(contents));
var evt = new Event('results-displayed');
evt.results = contents;
document.dispatchEvent(evt);
}
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
</script>
</html>
|
import '../styles/globals.css';
import '@rainbow-me/rainbowkit/styles.css';
import type { AppProps } from 'next/app';
import { ThemeProvider } from '../components/theme-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { WagmiProvider } from 'wagmi';
import {
arbitrum,
base,
mainnet,
optimism,
polygon,
sepolia,
zora,
} from 'wagmi/chains';
import { getDefaultConfig, RainbowKitProvider } from '@rainbow-me/rainbowkit';
const config = getDefaultConfig({
appName: 'NutriKnow',
projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID || "",
chains: [
mainnet,
sepolia,
polygon,
optimism,
arbitrum,
base,
zora,
...(process.env.NEXT_PUBLIC_ENABLE_TESTNETS === 'true' ? [sepolia] : []),
],
ssr: true,
});
const client = new QueryClient();
function MyApp({ Component, pageProps }: AppProps) {
return (
<WagmiProvider config={config}>
<QueryClientProvider client={client}>
<RainbowKitProvider>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<Component {...pageProps} />
</ThemeProvider>
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
);
}
export default MyApp;
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
import java.util.stream.IntStream;
public class DictionaryManagement {
private final Dictionary dictionary;
public DictionaryManagement() {
dictionary = new Dictionary();
}
// insert từ bằng dòng lệnh
public void insertFromCommandline() {
Scanner scanner = new Scanner(System.in);
System.out.print("Nhập vào số lượng từ: ");
int totalWords = scanner.nextInt();
IntStream.range(0, totalWords).forEach(e -> {
System.out.print("Nhập từ tiếng anh: ");
String wordTarget = scanner.next();
System.out.print("Nhập vào giải thích tiếng việt: ");
String wordExplain = scanner.next();
Word word = new Word(wordTarget, wordExplain);
dictionary.getWords().add(word);
});
}
// insert từ bởi file
public void insertFromFile() {
try {
URL resource = this.getClass().getClassLoader().getResource("dictionary.txt"); // Lấy đường dẫn file trong thư mục resources`
File file = new File(resource.toURI()); // Tạo đối tượng file dùng để đọc file
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) { // Duyệt từng hàng trong file
String data = myReader.nextLine();
String wordTarget = data.split("\t")[0]; // Tách chuỗi data bởi dấu tab thành mảng string gồm 2 phần tử, phân tử 1 là từ, phần tử 2 là nghĩa của từ đó
String wordExplain = data.split("\t")[1];
Word word = new Word(wordTarget, wordExplain);
dictionary.getWords().add(word); // Thêm từ đọc từ file vào từ điển
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("Đọc file không thành công, vui lòng kiểm tra lại!");
e.printStackTrace();
} catch (URISyntaxException e) {
System.out.println("Đường dẫn file bị lỗi vui lòng kiểm tra lại!");
throw new RuntimeException(e);
}
}
// Xóa từ bởi command
public void deleteFromCommandLine() {
Scanner scanner = new Scanner(System.in);
System.out.print("Nhập từ cần xóa: ");
String word = scanner.next();
for (Word element : this.dictionary.getWords()) {
if (element.getWordTarget().equals(word)) {
this.dictionary.getWords().remove(element);
return;
}
}
System.out.println("Từ nhập vào không tồn tại vui lòng kiểm tra lại!");
}
// edit từ bởi command
public void editFromCommandLine() {
Scanner scanner = new Scanner(System.in);
System.out.print("Nhập từ cần sửa: ");
String word = scanner.next();
for (Word element : this.dictionary.getWords()) {
if (element.getWordTarget().equals(word)) {
System.out.print("Nhập vào giải thích tiếng việt của từ: ");
String wordExplain = scanner.next();
element.setWordTarget(wordExplain);
return;
}
}
System.out.println("Từ nhập vào không tồn tại vui lòng kiểm tra lại!");
}
// Tìm kiếm từ chính xác
public void dictionaryLookup() {
Scanner scanner = new Scanner(System.in);
System.out.print("Nhập từ muốn tìm kiếm: ");
String word = scanner.next();
for (Word element : this.dictionary.getWords()) {
if (element.getWordTarget().equals(word)) {
System.out.format("Kết quả từ cần tìm là:\n%s: %s\n", element.getWordTarget(), element.getWordExplain());
return;
}
}
System.out.println("Không tìm thấy từ cần tìm!");
}
// Xuất file
public void dictionaryExportToFile() {
try {
FileWriter myWriter = new FileWriter("export_words.txt");
StringBuilder stringBuilder = new StringBuilder("");
for(Word word : dictionary.getWords()) {
stringBuilder.append(word.getWordTarget()).append(": ").append(word.getWordExplain()).append("\n");
}
myWriter.write(stringBuilder.toString());
System.out.println("Xuất file thành công!");
myWriter.close();
} catch (IOException e) {
System.out.println("Xuất file không thành công");
e.printStackTrace();
}
}
public Dictionary getDictionary() {
return this.dictionary;
}
}
|
package com.stan.demo;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.stan.demo.model.Product;
import com.stan.demo.repository.ProductRepository;
@Component
public class DataLoader implements CommandLineRunner {
@Autowired
private ProductRepository productRepository;
@Override
public void run(String... args) throws Exception {
// wait to allow the DDL to create the table before loading data to it.
Thread.sleep(5000);
List<Product> products = Arrays.asList(
new Product(null, "water", 1.00),
new Product(null, "bread", 2.00),
new Product(null, "chicken", 3.00));
productRepository.saveAll(products);
}
}
|
import { useEffect, useState } from "react";
import type { NextPage } from "next";
import styles from "@/styles/table.module.scss";
import { useRouter } from "next/router";
import { IUserBoxes } from "@/interfaces/box-items.interface";
import {
IPokemonData,
IPokemonDetail,
} from "@/interfaces/pokemon-detail.interface";
import { PokemonDetail } from "@/components/box/detail";
import { Header } from "@/components/layout/header";
import { TableBody } from "@/components/box/table-body";
import { TableHeader } from "@/components/box/table-header";
const Box: NextPage = (props: any) => {
useEffect(() => {
if (props.userData) {
setUserBoxes(props.userData);
let pokemonData: IPokemonData[] = props.userData.pokemonData;
var newMap = new Map(
pokemonData.map((p) => [p.pokemonGuid, p.pokemonDetail])
);
setDetailMap(newMap);
}
}, [props]);
const [userBoxes, setUserBoxes] = useState<IUserBoxes>();
const [pokemonGuid, setPokemonGuid] = useState<string>("");
const router = useRouter();
const [currentBox, setCurrentBox] = useState(0);
const [detailMap, setDetailMap] = useState<Map<string, IPokemonDetail>>(
new Map()
);
useEffect(() => {
if (!router.isReady) return;
setCurrentBox(parseInt(router.query["boxId"] as string));
}, [router.isReady, router.query]);
const onSave = () => {
let userId = userBoxes?.userId!;
let pokemonData: IPokemonData[] = [];
detailMap.forEach((val: any, key: string) => {
let data: IPokemonData = {
userId,
pokemonGuid: key,
pokemonDetail: val,
};
pokemonData.push(data);
});
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pokemonData }),
};
fetch(`${process.env.BACKEND_API}/boxes/update`, requestOptions)
.then((response) => response.json())
.then((data) => console.log(data));
};
return (
<>
<div style={{ position: "fixed", top: "0", left: "0" }}>
<button onClick={onSave}>SAVE</button>
</div>
<Header></Header>
<div className="container main center">
<div className={styles.table}>
<TableHeader currentBox={currentBox}></TableHeader>
<TableBody
boxItems={userBoxes?.boxData.boxes[currentBox - 1].boxItems!}
detailMap={detailMap}
setDetailMap={setDetailMap}
setPokemonGuid={setPokemonGuid}
></TableBody>
</div>
<div className="">
<PokemonDetail
detailMap={detailMap}
setDetailMap={setDetailMap}
pokemonGuid={pokemonGuid}
></PokemonDetail>
</div>
</div>
</>
);
};
export default Box;
|
class JSONNodeParsableSpecs: QuickSpec {
override func spec() {
describe("calls init(path)") {
context("with name only string") {
let jsonNode = JSONNode(path: "node")
it("returns JSONNode with name") {
expect(jsonNode?.name) == "node"
}
it("returs JSONNode with empty index") {
expect(jsonNode?.index).to(beNil())
}
}
context("with node string") {
let jsonNode = JSONNode(path: "node[2]")
it("returns JSONNode with name") {
expect(jsonNode?.name) == "node"
}
it("returs JSONNode with index") {
expect(jsonNode?.index) == 2
}
}
context("with left bracket only string") {
let jsonNode = JSONNode(path: "node[2")
it("returns nil") {
expect(jsonNode).to(beNil())
}
}
context("with right bracket only string") {
let jsonNode = JSONNode(path: "node2]")
it("returns nil") {
expect(jsonNode).to(beNil())
}
}
context("with disorder brackets string") {
let jsonNode = JSONNode(path: "node]2[")
it("returns nil") {
expect(jsonNode).to(beNil())
}
}
context("with other invalid string") {
let jsonNode = JSONNode(path: "node[[2]")
it("returns nil") {
expect(jsonNode).to(beNil())
}
}
}
}
}
import Quick
import Nimble
@testable import AdvancedFoundation
|
package com.subskill.service;
import com.subskill.dto.MicroSkillDto;
import com.subskill.enums.Level;
import com.subskill.enums.Tags;
import com.subskill.models.MicroSkill;
import com.subskill.models.Technology;
import com.subskill.repository.MicroSkillRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.springframework.test.util.AssertionErrors.assertEquals;
@Slf4j
@ExtendWith(MockitoExtension.class)
@ActiveProfiles("test")
@SpringBootTest
@Sql(scripts = {"classpath:data_for_the_database.sql"})
class SubSkillMicroSkillServiceTest {
@Autowired
private MicroSkillRepository microSkillRepository;
@Autowired
private MicroSkillService microSkillService;
@Test
public void testFindLevelFromMicroSkill() {
PageRequest pageable = PageRequest.of(0, 5);
Page<MicroSkillDto> result = microSkillService.findLevelFromMicroSkill(Level.INTERMEDIATE, pageable);
assertNotNull(result);
assertEquals("0", 0, result.getNumber());
assertEquals("5", 5, result.getSize());
assertEquals("2", 2, result.getTotalPages());
List<MicroSkillDto> microSkills = result.getContent();
assertNotNull(microSkills);
assertEquals("5", 5, microSkills.size());
MicroSkillDto microSkillDto = microSkills.get(0);
assertNotNull(microSkillDto);
assertEquals("Python Fundamentals", microSkillDto.name(), "Python Fundamentals");
assertEquals("INTERMEDIATE", microSkillDto.level(), Level.INTERMEDIATE);
}
@Test
public void testGetAllMicroSkills() {
String name = "Python Fundamentals";
List<MicroSkillDto> myTestMicroSkills = microSkillService.findAllMicroSkills();
List<String> myTestMicroSkillNames = myTestMicroSkills.stream().map(MicroSkillDto::name).toList();
assertEquals(name, myTestMicroSkillNames.get(0), "Python Fundamentals");
}
@Test
public void testFindMicroSkillById() {
long microSkillId = 10;
MicroSkillDto microskillFromService = microSkillService.findMicroSkillById(microSkillId);
Optional<MicroSkill> microSkill = microSkillRepository.findById(microSkillId);
assertNotNull(microskillFromService);
assertEquals("Same MicroSkill object",microSkill.get().getId() , microskillFromService.id());
}
@Test
void testFindTechnologyName() {
List<MicroSkill> microSkills = MyMicroSkill();
Pageable pageable = PageRequest.of(0, 5);
Page<MicroSkill> resultPage = new PageImpl<>(microSkills.stream()
.filter(microSkill -> microSkill.getTechnology().getName().equals("Java"))
.collect(Collectors.toList()), pageable, 5);
Page<MicroSkillDto> newResult = microSkillService.findTechnology("Java", pageable);
assertNotNull(newResult);
Assertions.assertEquals(resultPage.getTotalElements(), newResult.getTotalElements());
}
@Test
void testFindMicroSkillByTag() {
PageRequest pageable = PageRequest.of(0, 5);
Page<MicroSkillDto> result = microSkillService.findMicroSkillByTag(Tags.DEVELOPMENT, pageable);
assertNotNull(result);
assertEquals("0", 0, result.getNumber());
assertEquals("5", 5, result.getSize());
assertEquals("0", 0, result.getTotalPages());
List<MicroSkillDto> microSkills = result.getContent();
assertNotNull(microSkills);
assertEquals("0", 0, microSkills.size());
}
@Test
void testGetBestDealsByToday() {
List<MicroSkillDto> microSkillsList = new ArrayList<>();
microSkillsList.add(new MicroSkillDto(10L, "Python Fundamentals", "Fundamental concepts of Python programming"));
PageRequest pageable = PageRequest.of(0, 5);
Page<MicroSkillDto> actualMicroSkills = new PageImpl<>(microSkillsList, pageable, microSkillsList.size());
assertNotNull(actualMicroSkills, "Not null");
log.debug("Not Null in Best Deals by Today");
Assertions.assertEquals(5, actualMicroSkills.getSize(), "correct size");
List<MicroSkillDto> content = actualMicroSkills.getContent();
String description = "description1";
if (!content.isEmpty()) {
MicroSkillDto firstMicroSkill = content.get(0);
assertEquals(description, firstMicroSkill.name(), "Python Fundamentals");
} else {
fail("No MicroSkills in List");
}
}
public List<MicroSkill> MyMicroSkill() {
Technology javaTechnology = new Technology();
javaTechnology.setId(10L);
javaTechnology.setName("Java");
MicroSkill microSkill = new MicroSkill();
microSkill.setId(10L);
microSkill.setName("Python Fundamentals");
microSkill.setDescription("Fundamental concepts of Python programming");
microSkill.setLevel(Level.INTERMEDIATE);
microSkill.setViews(2000);
microSkill.setTechnology(javaTechnology);
Technology javaTechnology2 = new Technology();
javaTechnology2.setId(11L);
javaTechnology2.setName("Python");
MicroSkill microSkill2 = new MicroSkill();
microSkill2.setName("Web Development with React.js");
microSkill2.setDescription("Build modern web applications using React.js");
microSkill2.setLevel(Level.INTERMEDIATE);
microSkill2.setId(11L);
microSkill2.setViews(1800);
microSkill2.setTechnology(javaTechnology2);
Technology javaTechnology3 = new Technology();
javaTechnology3.setId(12L);
javaTechnology3.setName("React.js");
MicroSkill microSkill3 = new MicroSkill();
microSkill3.setName("Introduction to Data Science");
microSkill3.setDescription("Fundamental concepts of data science");
microSkill3.setLevel(Level.INTERMEDIATE);
microSkill3.setViews(1600);
microSkill3.setId(12L);
microSkill3.setTechnology(javaTechnology3);
return List.of(microSkill, microSkill2, microSkill3);
}
}
|
package com.adnanarch.securedoc.service.impl;
import com.adnanarch.securedoc.exception.ApiException;
import com.adnanarch.securedoc.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import static com.adnanarch.securedoc.utils.EmailUtils.getEmailMessage;
import static com.adnanarch.securedoc.utils.EmailUtils.getResetPasswordMessage;
/**
* Author: Adnan Rafique
* Date: 4/6/2024
* Time: 11:42 AM
* Version: 1.0
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class EmailServiceImpl implements EmailService {
private static final String NEW_USER_ACCOUNT_VERIFICATION = "NEW User Account Verification";
private static final String RESET_PASSWORD_REQUEST = "Reset Password Request";
private final JavaMailSender emailSender;
@Value("${spring.mail.verify.host}")
private String host;
@Value("${spring.mail.username}")
private String fromEmail;
@Async
@Override
public void sendNewAccountEmail(String name, String email, String token) {
try{
var message = new SimpleMailMessage();
message.setSubject(NEW_USER_ACCOUNT_VERIFICATION);
message.setFrom(fromEmail);
message.setTo(email);
message.setText(getEmailMessage(name, email, token));
emailSender.send(message);
}catch (Exception exception){
log.error(exception.getMessage());
throw new ApiException("Unable to send the email");
}
}
@Async
@Override
public void sendPasswordResetEmail(String name, String email, String token) {
try{
var message = new SimpleMailMessage();
message.setSubject(RESET_PASSWORD_REQUEST);
message.setFrom(fromEmail);
message.setTo(email);
message.setText(getResetPasswordMessage(name, email, token));
emailSender.send(message);
}catch (Exception exception){
log.error(exception.getMessage());
throw new ApiException("Unable to send the email");
}
}
}
|
"use client";
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { twMerge } from "tailwind-merge";
type Props = {};
export const Header = (props: Props) => {
const [scrollTop, setScrollTop] = useState(0);
const [openMenu, setOpenMenu] = useState(false);
const scrollOffset = 100;
useEffect(() => {
const handleScroll = (e: Event) => {
// @ts-expect-error
setScrollTop(e?.target?.scrollingElement?.scrollTop || 0);
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
const handleHamburgerOpen = () => setOpenMenu(!openMenu);
return (
<header
className={twMerge(
" fixed z-50 left-0 -translate-y-0 lg:inset-[unset] lg:translate-y-0 lg:top-0 max-w-7xl w-full px-4 lg:px-20 py-6 bg-white/50 backdrop-blur-md lg:bg-transparent lg:backdrop-blur-[unset]",
openMenu && "inset-0"
)}
>
<div
className={twMerge(
"z-[60] duration-300 bg-secondary-100 bg-opacity-0 border border-secondary-200 border-opacity-0 flex lg:items-center justify-between rounded-full transition-all",
scrollTop > scrollOffset &&
"lg:bg-opacity-60 lg:border-opacity-40 lg:p-4 lg:pl-8 lg:backdrop-blur"
)}
>
<h2
className={twMerge(
"text-4xl text-secondary-950 font-bold transition-all relative z-50"
)}
>
KM-IT<span className="text-orange-500">.</span>
</h2>
<div
className={twMerge(
"pointer-events-auto fixed lg:relative inset-0 translate-x-full lg:translate-x-0 transition-all bg-white lg:bg-transparent lg:flex items-center lg:gap-20 gap-8 flex-col lg:flex-row lg:pt-0 pt-20 mx-auto lg:mx-0",
openMenu && "flex translate-x-0"
)}
>
<ul className="flex items-center gap-5 flex-col lg:flex-row">
<li className="text-secondary-500 lg:text-sm text-lg hover:text-secondary-950">
<Link href="/">Home</Link>
</li>
<li className="text-secondary-500 lg:text-sm text-lg hover:text-secondary-950">
<Link href="/about-us">About Us</Link>
</li>
<li className="text-secondary-500 lg:text-sm text-lg hover:text-secondary-950">
<Link href="/courses">Courses</Link>
</li>
<li className="text-secondary-500 lg:text-sm text-lg hover:text-secondary-950">
<Link href="/">Testimonials</Link>
</li>
<li className="text-secondary-500 lg:text-sm text-lg hover:text-secondary-950">
<Link href="/management">Management</Link>
</li>
<li className="text-secondary-500 lg:text-sm text-lg hover:text-secondary-950">
<Link href="/">Contact Us</Link>
</li>
</ul>
<button className="px-5 py-2.5 hover:shadow-lg hover:shadow-orange-400/90 bg-gradient-to-b rounded-full from-orange-400 to-orange-500 text-secondary-50 transition-all">
Schoolity
</button>
</div>
</div>
<button
className="fixed top-6 lg:right-20 right-8 group lg:hidden flex"
onClick={handleHamburgerOpen}
>
<div
className={twMerge(
"relative flex overflow-hidden items-center justify-center rounded-full w-[50px] h-[50px] transform transition-all bg-slate-500 ring-0 ring-gray-300 hover:ring-8 ring-opacity-30 duration-200 shadow-md",
openMenu && "ring-4"
)}
>
<div className="flex flex-col justify-between w-[20px] h-[20px] transform transition-all duration-300 origin-center overflow-hidden">
<div
className={twMerge(
"bg-white h-[2px] w-7 transform transition-all duration-300 origin-left ",
openMenu && "translate-x-10"
)}
></div>
<div
className={twMerge(
"bg-white h-[2px] w-7 rounded transform transition-all duration-300 delay-75",
openMenu && "translate-x-10"
)}
></div>
<div
className={twMerge(
"bg-white h-[2px] w-7 transform transition-all duration-300 origin-left delay-150",
openMenu && "translate-x-10"
)}
></div>
<div
className={twMerge(
"absolute items-center justify-between transform transition-all duration-500 top-2.5 -translate-x-10 flex w-0 ",
openMenu && "translate-x-0 w-12"
)}
>
<div
className={twMerge(
"absolute bg-white h-[2px] w-5 transform transition-all duration-500 rotate-0 delay-300 ",
openMenu && "rotate-45"
)}
></div>
<div
className={twMerge(
"absolute bg-white h-[2px] w-5 transform transition-all duration-500 -rotate-0 delay-300 ",
openMenu && "-rotate-45"
)}
></div>
</div>
</div>
</div>
</button>
</header>
);
};
|
from discord.ext import commands
import mcstatus
import boto3
ERROR_MESSAGE = 'Usage: ,server [start|stop|status]'
INSTANCE_ID = 'i-0398a626488b90371'
APPROVED_USERS = ['shnooker94', '__jared__', 'hotwire12', 'pizzacat.rar']
class MinecraftServerCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(brief='Start, stop, or get server status')
async def server(self, ctx, *args):
if str(ctx.message.author) not in APPROVED_USERS:
await ctx.send(content='Eat my ass')
return
# Check the args
check = error_check(args)
# Initalize response variables
response = ERROR_MESSAGE
# Start command
if (check == 0):
response = start_server()
await ctx.send(content=response)
response = wait_for_server_start()
# Stop command
elif (check == 1):
response = stop_server()
# Status command
elif (check == 2):
response = get_server_status()
await ctx.send(content=response)
def error_check(args):
if args[0] == 'start':
return 0
elif args[0] == 'stop':
return 1
elif args[0] == 'status':
return 2
return -1
def start_server():
ec2 = boto3.client('ec2', 'us-east-1')
try:
# Get instance from boto3
response = ec2.describe_instances(
InstanceIds=[
INSTANCE_ID
]
)
# Get instance info
instance = response['Reservations'][0]['Instances'][0]
instance_state = instance['State']['Name']
# Check server status
if instance_state == 'running':
instance_ip = instance['PublicIpAddress']
return 'Server is running with ip: ' + instance_ip
if instance_state != 'stopped':
return 'Server is unavailable. Try again later'
# Start instance
start_response = ec2.start_instances(
InstanceIds=[
INSTANCE_ID,
]
)
except Exception as e:
return e
return 'Starting server...'
def wait_for_server_start():
ec2 = boto3.client('ec2', 'us-east-1')
try:
# Wait for instance to start
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=[INSTANCE_ID])
# Get instance info again
response = ec2.describe_instances(
InstanceIds=[
INSTANCE_ID
]
)
# Get instance ip
instance = response['Reservations'][0]['Instances'][0]
instance_ip = instance['PublicIpAddress']
except Exception as e:
return e
return 'Successfully started server with ip: ' + instance_ip
def stop_server():
ec2 = boto3.client('ec2', 'us-east-1')
try:
instance_state = get_instance_status()
if instance_state != 'running':
return 'Server is not currently running'
stop_response = ec2.stop_instances(
InstanceIds=[
INSTANCE_ID
]
)
return "Stopping server"
except Exception as e:
return e
def get_server_status():
ec2 = boto3.client('ec2', 'us-east-1')
try:
response = ec2.describe_instances(
InstanceIds=[
INSTANCE_ID
]
)
# Get instance info
instance = response['Reservations'][0]['Instances'][0]
instance_state = instance['State']['Name']
if instance_state != 'running':
return 'Server is not currently running'
instance_ip = instance['PublicIpAddress']
server = mcstatus.JavaServer.lookup(instance_ip + ':25565')
status = server.status()
return 'Server with ip ' + instance_ip + ' has ' + str(status.players.online) + ' player(s) online and replied in ' + "{:.2f}".format(status.latency) + 'ms'
except Exception as e:
return e
def get_instance_status():
ec2 = boto3.client('ec2', 'us-east-1')
try:
response = ec2.describe_instances(
InstanceIds=[
INSTANCE_ID
]
)
# Get instance info
instance = response['Reservations'][0]['Instances'][0]
instance_state = instance['State']['Name']
return instance_state
except Exception as e:
return e
async def setup(bot):
await bot.add_cog(MinecraftServerCog(bot))
|
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
height: 100%;
width: 100%;
background-color: gainsboro;
}
.wrapper {
text-align: center;
position: absolute;
/* margin: 0 auto; */
height: 100%;
width: 100%;
background: gainsboro;
overflow-y: hidden;
}
.svg-container {
display: inline-block;
position: relative;
width: 100%;
height:100%;
vertical-align: top;
overflow: hidden;
overflow-y: hidden;
}
.svg-content {
display: inline-block;
position: relative;
background: none;
top: 0;
left: 0;
padding: 0;
overflow-y: hidden;
}
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
}
text {
font-family: minion-pro;
font-size: 10px;
}
h1 {
position: absolute;
overflow-y: hidden;
}
#toolbar {
margin-top: 10px;
margin-left: 25px;
background:#fff;
background-color:rgba(255,255,255,0.8);
border:1px solid #ccc;
z-index:20;
position:fixed;
top:0;
}
#mainpanel .col {
width: 240px;
padding: 18px 18px 18px 18px;
margin: 0;
}
#toolbar a,
#toolbar h3 {
font-size: 0.9em;
margin: 0 0.5em;
color: white;
}
</style>
<body style="overflow-y:hidden">
<title>Lexical Field Generator</title>
<div class="wrapper">
<nav class="toolbar">
<h3>Semantic.map</h3>
<form><input type="text" id="searchBar" autofocus /></form>
</nav>
<div id="container" class="svg-container">
</div>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var w = 1000;
var h = 1000
var svg = d3.select("div#container")
.append("svg")
.attr(
"style",
"padding-bottom: " + Math.ceil(h * 100 / w) + "%"
)
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 " + w + " " + h)
.attr("id", "svg-id")
.classed("svg-content", true)
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform)
})).append("g");
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) { return d.id; }))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(w / 2, h / 4));
d3.json("data.json", function (error, graph) {
if (error) throw error;
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", function (d) { return Math.sqrt(d.value); });
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("g")
.data(graph.nodes)
.enter().append("g")
var circles = node.append("circle")
.attr("r", 5)
.attr("fill", function (d) { return d.color; })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
var lables = node.append("text")
.text(function (d) {
return d.label;
})
.attr('x', 6)
.attr('y', 3);
node.append("title")
.text(function (d) { return d.label; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
link
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
node
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
})
}
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</script>
</body>
|
#include <SFML/Graphics.hpp>
#include <math.h>
#define PI 3.14159
class Player
{
public:
float x, y, angle; // angle is a radian
float sinx, cosx;
int boxX, boxY, m_speed, r_speed;
sf::CircleShape circle;
sf::RectangleShape direction;
void init()
{
cosx = cos(angle);
sinx = sin(angle);
}
void update()
{
cosx = cos(angle);
sinx = sin(angle);
move();
draw();
drawLine();
}
void move()
{
// forward / backward
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
x += cosx * m_speed;
y += sinx * m_speed;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
x -= cosx * m_speed;
y -= sinx * m_speed;
}
// rotate
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
if (abs(angle) >= PI * 2)
{
angle = 0;
}
angle -= 0.01 * r_speed ;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
if (abs(angle) >= PI * 2)
{
angle = 0;
}
angle += 0.01 * r_speed;
}
}
void draw()
{
int radius = 10;
circle.setPosition(x - radius, y - radius);
circle.setRadius(radius);
window.draw(circle);
}
void drawLine()
{
direction.setSize(sf::Vector2f(50, 2)); // length, width
direction.setPosition(x, y - 1);
direction.setRotation((angle * 180) / PI);
window.draw(direction);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.