text
stringlengths 184
4.48M
|
|---|
import React, { useContext, useState } from "react";
import ReactDOM from "react-dom";
import styles from "./Cart.module.css";
import CartItem from "./CartItem";
import CartContext from "../../Store/cart-context";
import { ToastContainer, toast } from "react-toastify";
import AuthContext from "../../Store/auth-context";
import { Link, useNavigate } from "react-router-dom";
const Cart = (props) => {
const portalElement = document.getElementById("cart");
const cartCtx = useContext(CartContext);
const authCtx = useContext(AuthContext);
const navigate = useNavigate();
const onOrderHandler = () => {
cartCtx.removeAllItems();
toast.success("Ordered Successfully", {
position: "top-center",
theme: "colored",
});
};
const redirectToLoginHandler = () => {
props.onCartClose();
navigate("/login");
};
const onAddButton = (item) => {
cartCtx.addItem({
id: item.id,
title: item.title,
amount: 1,
price: item.price,
image: item.image,
});
};
const onRemoveButton = (id) => {
cartCtx.removeItem(id);
};
return (
<>
{ReactDOM.createPortal(
<div className={styles["cart-container-blur"]}>
<div className={styles["cart-container"]}>
<div className={styles["first-div"]}>
<h2>Shopping Cart</h2>
<button onClick={props.onCartClose}>Close</button>
</div>
<ul className={styles["second-div"]}>
{cartCtx.items?.map((item) => (
<CartItem
key={item.id}
item={item}
onAdd={() => onAddButton(item)}
onRemove={() => onRemoveButton(item.id)}
onCartClose={props.onCartClose}
/>
))}
</ul>
{cartCtx.items?.length !== 0 && (
<div className={styles["third-div"]}>
<h2>SubTotal: ₹{cartCtx.totalAmount}</h2>
<button onClick={onOrderHandler}>Place Order</button>
</div>
)}
{!authCtx.isLoggedIn && (
<button onClick={redirectToLoginHandler} className={styles.login}>
Login
</button>
)}
{cartCtx.items?.length === 0 && authCtx.isLoggedIn && (
<h2 className={styles.empty}>Empty</h2>
)}
</div>
<ToastContainer />
</div>,
portalElement
)}
</>
);
};
export default Cart;
|
/*****************************************************************************************************************/
// @author Michael Roberts <michael@observerly.com>
// @package @observerly/nitro-helmet
// @license Copyright © 2021-2023 observerly
/*****************************************************************************************************************/
import { beforeEach, describe, expect, it } from 'vitest'
import supertest, { type SuperTest, type Test } from 'supertest'
import { toNodeListener } from 'h3'
import { server } from './utilities/server'
import {
defaultContentSecurityPolicy,
useContentSecurityPolicy
} from '../src/internals/useContentSecurityPolicy'
/*****************************************************************************************************************/
describe('useContentSecurityPolicy', () => {
let request: SuperTest<Test>
beforeEach(() => {
request = supertest(toNodeListener(server))
})
it('should be defined', () => {
expect(useContentSecurityPolicy).toBeDefined()
})
it('should set Content-Security-Policy headers correctly on the request', async () => {
const res = await request.get('/helmet/content-security-policy', {
method: 'GET'
})
expect(res.header['content-security-policy']).toEqual("default-src 'self';")
})
it('should set Content-Security-Policy headers correctly on the request', async () => {
const res = await request.get('/helmet/default-content-security-policy', {
method: 'GET'
})
expect(res.header['content-security-policy']).toEqual(defaultContentSecurityPolicy)
})
it('should not set Content-Security-Policy headers correctly on the request', async () => {
const res = await request.get('/helmet/no-content-security-policy', {
method: 'GET'
})
expect(res.header['content-security-policy']).toEqual(undefined)
})
})
|
use std::ops::{Add, AddAssign, Sub, SubAssign};
use curve25519_dalek::{traits::Identity, RistrettoPoint, Scalar};
use serde::{Deserialize, Deserializer, Serialize};
use super::{pedersen::{DecryptHandle, PedersenCommitment}, CompressedCiphertext, CompressedCommitment, CompressedHandle};
// Represents a twisted ElGamal Ciphertext
// One part is a Pedersen commitment to be bulletproofs compatible
// The other part is a handle to be used for decryption
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ciphertext {
commitment: PedersenCommitment,
handle: DecryptHandle,
}
impl Ciphertext {
// Create a new Ciphertext
pub fn new(commitment: PedersenCommitment, handle: DecryptHandle) -> Self {
Self { commitment, handle }
}
// Create a ciphertext with a zero value
pub fn zero() -> Self {
Self {
commitment: PedersenCommitment::from_point(RistrettoPoint::identity()),
handle: DecryptHandle::from_point(RistrettoPoint::identity()),
}
}
// Get the commitment
pub fn commitment(&self) -> &PedersenCommitment {
&self.commitment
}
// Get the handle
pub fn handle(&self) -> &DecryptHandle {
&self.handle
}
// Compress the Ciphertext
pub fn compress(&self) -> CompressedCiphertext {
CompressedCiphertext::new(
CompressedCommitment::new(self.commitment.as_point().compress()),
CompressedHandle::new(self.handle.as_point().compress())
)
}
}
// ADD TRAITS
impl Add<u64> for Ciphertext {
type Output = Self;
fn add(self, rhs: u64) -> Self {
Self {
commitment: self.commitment + Scalar::from(rhs),
handle: self.handle,
}
}
}
impl Add for Ciphertext {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self {
commitment: self.commitment + rhs.commitment,
handle: self.handle + rhs.handle,
}
}
}
impl Add<&Ciphertext> for Ciphertext {
type Output = Self;
fn add(self, rhs: &Self) -> Self {
Self {
commitment: self.commitment + &rhs.commitment,
handle: self.handle + &rhs.handle,
}
}
}
impl Add<Scalar> for Ciphertext {
type Output = Self;
fn add(self, rhs: Scalar) -> Self {
Self {
commitment: self.commitment + rhs,
handle: self.handle,
}
}
}
impl Add<&Scalar> for Ciphertext {
type Output = Self;
fn add(self, rhs: &Scalar) -> Self {
Self {
commitment: self.commitment + rhs,
handle: self.handle,
}
}
}
// ADD ASSIGN TRAITS
impl AddAssign<u64> for Ciphertext {
fn add_assign(&mut self, rhs: u64) {
self.commitment += Scalar::from(rhs);
}
}
impl AddAssign for Ciphertext {
fn add_assign(&mut self, rhs: Self) {
self.commitment += rhs.commitment;
self.handle += rhs.handle;
}
}
impl AddAssign<&Ciphertext> for Ciphertext {
fn add_assign(&mut self, rhs: &Self) {
self.commitment += &rhs.commitment;
self.handle += &rhs.handle;
}
}
impl AddAssign<Scalar> for Ciphertext {
fn add_assign(&mut self, rhs: Scalar) {
self.commitment += rhs;
}
}
impl AddAssign<&Scalar> for Ciphertext {
fn add_assign(&mut self, rhs: &Scalar) {
self.commitment += rhs;
}
}
// SUB TRAITS
impl Sub<u64> for Ciphertext {
type Output = Self;
fn sub(self, rhs: u64) -> Self {
Self {
commitment: self.commitment - Scalar::from(rhs),
handle: self.handle,
}
}
}
impl Sub for Ciphertext {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self {
commitment: self.commitment - rhs.commitment,
handle: self.handle - rhs.handle,
}
}
}
impl Sub<&Ciphertext> for Ciphertext {
type Output = Self;
fn sub(self, rhs: &Self) -> Self {
Self {
commitment: self.commitment - &rhs.commitment,
handle: self.handle - &rhs.handle,
}
}
}
impl Sub<Scalar> for Ciphertext {
type Output = Self;
fn sub(self, rhs: Scalar) -> Self {
Self {
commitment: self.commitment - rhs,
handle: self.handle,
}
}
}
impl Sub<&Scalar> for Ciphertext {
type Output = Self;
fn sub(self, rhs: &Scalar) -> Self {
Self {
commitment: self.commitment - rhs,
handle: self.handle,
}
}
}
// SUB ASSIGN TRAITS
impl SubAssign<u64> for Ciphertext {
fn sub_assign(&mut self, rhs: u64) {
self.commitment -= Scalar::from(rhs);
}
}
impl SubAssign for Ciphertext {
fn sub_assign(&mut self, rhs: Self) {
self.commitment -= rhs.commitment;
self.handle -= rhs.handle;
}
}
impl SubAssign<&Ciphertext> for Ciphertext {
fn sub_assign(&mut self, rhs: &Self) {
self.commitment -= &rhs.commitment;
self.handle -= &rhs.handle;
}
}
impl SubAssign<Scalar> for Ciphertext {
fn sub_assign(&mut self, rhs: Scalar) {
self.commitment -= rhs;
}
}
impl SubAssign<&Scalar> for Ciphertext {
fn sub_assign(&mut self, rhs: &Scalar) {
self.commitment -= rhs;
}
}
impl Serialize for Ciphertext {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
self.compress().serialize(serializer)
}
}
impl<'a> Deserialize<'a> for Ciphertext {
fn deserialize<D>(deserializer: D) -> Result<Ciphertext, D::Error>
where
D: Deserializer<'a>,
{
let compressed = CompressedCiphertext::deserialize(deserializer)?;
compressed.decompress().map_err(serde::de::Error::custom)
}
}
|
//
// ACDSegmentedControl.swift
// ACDUIKit
//
// Created by jaeyoung on 2020/05/02.
// Copyright © 2020 Appcid. All rights reserved.
//
import UIKit
public protocol HasTitleAndImage {
var title: String? { get }
var image: UIImage? { get }
}
struct TitleAndImage: HasTitleAndImage {
var title: String?
var image: UIImage?
}
public protocol ACDSegmentedControlProtocol_ {
var isMomentary: Bool { get set }
var numberOfSegments: Int { get }
var selectedSegmentIndex: Int { get set }
func insertSegment(withTitle title: String?, at segment: Int, animated: Bool)
func insertSegment(with image: UIImage?, at segment: Int, animated: Bool)
func removeSegment(at segment: Int, animated: Bool)
func removeAllSegments()
}
public typealias ACDSegmentedControlProtocol = ACDSegmentedControlProtocol_ & UIControl
open class ACDSegmentedControl: UIControl {
var _stackView: ACDStackView!
open var isMomentary: Bool = false
public var numberOfSegments: Int {
_stackView.numberOfItems
}
open var selectedSegmentIndex: Int = -1 {
didSet {
invalidateButtonsSelected()
if oldValue != selectedSegmentIndex {
sendActions(for: .valueChanged)
}
}
}
open func insertSegment(withTitle title: String?, at segment: Int, animated: Bool) {
insertSegment(withTitleAndImage: TitleAndImage(title: title), at: segment, animated: animated)
}
open func insertSegment(with image: UIImage?, at segment: Int, animated: Bool) {
insertSegment(withTitleAndImage: TitleAndImage(image: image), at: segment, animated: animated)
}
open func removeSegment(at segment: Int, animated: Bool) {
_stackView.removeArrangedSubview(at: segment, animated: animated)
}
open func removeAllSegments() {
_stackView.cleanup()
}
open func insertSegment(withTitleAndImage titleAndImage: HasTitleAndImage?, at segment: Int, animated: Bool) {
let button = makeButton(titleAndImage: titleAndImage)
_stackView.insertArrangedSubview(button, at: segment)
if segment <= selectedSegmentIndex {
selectedSegmentIndex += 1
}
}
open func setSegment(withTitleAndImages titleAndImages: [HasTitleAndImage], animated: Bool) {
removeAllSegments()
for (i, titleAndImage) in titleAndImages.enumerated() {
insertSegment(withTitleAndImage: titleAndImage, at: i, animated: animated)
}
}
// MARK: - Stack View Properties
public var alignment: UIStackView.Alignment {
get {
_stackView.alignment
}
set {
_stackView.alignment = newValue
}
}
public var axis: NSLayoutConstraint.Axis {
get {
_stackView.axis
}
set {
_stackView.axis = newValue
}
}
public var distribution: UIStackView.Distribution {
get {
_stackView.distribution
}
set {
_stackView.distribution = newValue
}
}
public var spacing: CGFloat {
get {
_stackView.spacing
}
set {
_stackView.spacing = newValue
}
}
// MARK: - init
private let makeButtonClosure: () -> ACDButton
convenience public init(items: [Any]?, buttonBuilder: @escaping () -> ACDButton) {
if let strings = items as? [String] {
self.init(strings: strings, buttonBuilder: buttonBuilder)
} else if let images = items as? [UIImage] {
self.init(images: images, buttonBuilder: buttonBuilder)
} else if let titleAndImage = items as? [HasTitleAndImage] {
self.init(titleAndImages: titleAndImage, buttonBuilder: buttonBuilder)
} else {
self.init(buttonBuilder: buttonBuilder)
}
}
convenience public init(buttonBuilder: @escaping () -> ACDButton) {
self.init(titleAndImages: [], buttonBuilder: buttonBuilder)
}
convenience public init(strings: [String], buttonBuilder: @escaping () -> ACDButton) {
self.init(titleAndImages: strings.map ({ TitleAndImage(title: $0, image: nil)}), buttonBuilder: buttonBuilder)
}
convenience public init(images: [UIImage], buttonBuilder: @escaping () -> ACDButton) {
self.init(titleAndImages: images.map ({ TitleAndImage(title: nil, image: $0)}), buttonBuilder: buttonBuilder)
}
public init(titleAndImages: [HasTitleAndImage], buttonBuilder: @escaping () -> ACDButton) {
makeButtonClosure = buttonBuilder
super.init(frame: .zero)
let buttons: [UIButton] = titleAndImages.map { makeButton(titleAndImage: $0) }
_stackView = ACDStackView(arrangedSubviews: buttons)
if !titleAndImages.isEmpty {
selectedSegmentIndex = 0
}
addSubview(_stackView)
_stackView.fillToSuperview()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
invalidateButtonsSelected()
}
private func makeButton(titleAndImage: HasTitleAndImage?) -> ACDButton {
let button = makeButtonClosure()
button.setTitle(titleAndImage?.title, for: .normal)
button.setImage(titleAndImage?.image, for: .normal)
if let tabBarItem = titleAndImage as? UITabBarItem {
button.setImage(tabBarItem.selectedImage, for: .selected)
}
button.addAction(for: .touchUpInside) {
self.buttonTouched(button: button)
}
return button
}
private func invalidateButtonsSelected() {
guard !isMomentary else {
return
}
for (i, view) in _stackView.arrangedSubviews.enumerated() {
let button = view as! UIButton
button.isSelected = i == selectedSegmentIndex
}
}
private func buttonTouched(button: UIButton) {
if let index = _stackView.arrangedSubviews.firstIndex(of: button) {
selectedSegmentIndex = index
}
}
}
extension UITabBarItem: HasTitleAndImage {}
extension ACDSegmentedControl: ACDSegmentedControlProtocol_ {}
extension UISegmentedControl: ACDSegmentedControlProtocol_ {}
|
import { ReactElement } from 'react'
import Script from 'next/script'
import Image from 'next/image'
import Head from 'next/head'
import { GetStaticProps } from 'next'
import rehypePrism from 'rehype-prism-plus'
import rehypeCodeTitles from 'rehype-code-titles'
import { FiExternalLink } from 'react-icons/fi'
import { serialize } from 'next-mdx-remote/serialize'
import { MDXRemote } from 'next-mdx-remote'
import { GET_PROJECT, GET_PROJECTS_SLUGS } from 'graphql/projects'
import { AppLayout } from 'layouts/AppLayout'
import { WriterPostTitle } from 'components/WriterPostTitle'
import { Footer } from 'components/Footer'
import { ButtonSizesEnum } from 'components/Button/types'
import { Button } from 'components/Button'
import { apolloClient } from 'services/apolloClient'
import { ProjectPageProps } from 'interfaces/pages/project'
import { PostApiResponseProps } from 'interfaces/pages/posts'
import * as Styles from 'styles/pages/project'
import { secondary } from 'styles/fonts'
function Project({ project }: ProjectPageProps): ReactElement {
function handleOpenProject() {
window.open(project.name, '_blank')
}
return (
<AppLayout>
<Styles.ProjectContainer>
<Head>
<link href="themes/prism-vsc-dark-plus.css" rel="stylesheet" />
</Head>
<section>
<WriterPostTitle
author="Guilherme Illescas"
imageSrc="/assets/me.jpeg"
publishedAt={new Date(project.createdAt)}
/>
<div className="cover">
<Image
src={`http://localhost:1337${project.cover}`}
alt={`Imagem do projeto ${project.name}`}
fill
/>
</div>
<div className="post-header">
<h1 className={`${secondary.className} project-title`}>
{project.name}
</h1>
<Button
size={ButtonSizesEnum.Small}
rightIcon={<FiExternalLink fontWeight={500} />}
onClick={handleOpenProject}
>
Open project
</Button>
</div>
<MDXRemote {...project.content} />
</section>
<Footer />
<Script src="prism.js" />
</Styles.ProjectContainer>
</AppLayout>
)
}
export default Project
export const getStaticPaths = async () => {
const { data } = await apolloClient.query({ query: GET_PROJECTS_SLUGS })
const paths = data.projects.data.map((post: PostApiResponseProps) => {
return { params: { slug: post.attributes.urlSlug } }
})
return {
paths,
fallback: false
}
}
export const getStaticProps: GetStaticProps = async ({ params }) => {
const { data } = await apolloClient.query({
query: GET_PROJECT,
variables: {
slugUrl: params ? params.slug : ''
}
})
const attrs = data.projects.data[0].attributes
const html = await serialize(attrs.content, {
mdxOptions: {
rehypePlugins: [rehypeCodeTitles, rehypePrism]
}
})
return {
props: {
project: {
name: attrs.name,
createdAt: attrs.createdAt,
content: html,
cover: attrs.cover.data.attributes.url
}
}
}
}
|
package com.zebra.assignment.service;
import com.zebra.assignment.dto.request.BookSaveRequestDto;
import com.zebra.assignment.dto.request.BookUpdateRequestDto;
import com.zebra.assignment.dto.response.BaseResponseDto;
import com.zebra.assignment.dto.response.BookResponseDto;
import com.zebra.assignment.dto.response.GetAllBookResponseDto;
import com.zebra.assignment.repository.entity.Book;
import com.zebra.assignment.exception.ErrorType;
import com.zebra.assignment.exception.ZebraException;
import com.zebra.assignment.mapper.IBookMapper;
import com.zebra.assignment.repository.BookRepository;
import com.zebra.assignment.utility.ServiceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class BookService extends ServiceManager<Book, Long> {
private final BookRepository repository;
private final IBookMapper bookMapper;
private final BookMemberService bookMemberService;
Logger logger = LoggerFactory.getLogger(BookService.class);
public BookService(BookRepository repository, IBookMapper bookMapper, BookMemberService bookMemberService) {
super(repository);
this.repository = repository;
this.bookMapper = bookMapper;
this.bookMemberService = bookMemberService;
}
public BookResponseDto saveBook(BookSaveRequestDto dto) {
if (repository.existsByIsbn(dto.getIsbn())) throw new ZebraException(ErrorType.BOOK_ALREADY_EXISTS);
Book book = save(bookMapper.toBook(dto));
BookResponseDto responseDto = bookMapper.toDto(book);
responseDto.setMessage("ok");
responseDto.setStatusCode(200);
logger.info("create a new book: {}.", book);
return responseDto;
}
public GetAllBookResponseDto getAllBook() {
List<BookResponseDto> dtos = findAll().stream().map(book -> {
BookResponseDto dto = bookMapper.toDto(book);
dto.setStatusCode(200);
dto.setMessage("ok");
return dto;
}).toList();
logger.info("get all book: {}.", dtos);
return GetAllBookResponseDto.builder().books(dtos).message("ok").statusCode(200).build();
}
public BookResponseDto updateBook(BookUpdateRequestDto dto) {
Book book = null;
if ((dto.getId() != null)) {
book = findById(dto.getId()).orElseThrow(() -> {
throw new ZebraException(ErrorType.BOOK_NOT_FOUND_ID);
});
} else if ((dto.getIsbn() != null)) {
book = repository.findOptionalByIsbn(dto.getIsbn()).orElseThrow(() -> {
throw new ZebraException(ErrorType.BOOK_NOT_FOUND_ISBN);
});
}
if (book == null) throw new ZebraException(ErrorType.BOOK_NOT_FOUND_ID_ISBN);
Book updateBook = bookMapper.toBook(dto);
updateBook.setIsbn(book.getIsbn());
updateBook.setId(book.getId());
update(updateBook);
logger.info("update book: {}.", updateBook);
BookResponseDto responseDto = bookMapper.toDto(updateBook);
responseDto.setMessage("ok");
responseDto.setStatusCode(200);
return responseDto;
}
public BaseResponseDto deleteBookByid(Long id) {
if (findById(id).isEmpty()) throw new ZebraException(ErrorType.BOOK_NOT_FOUND_ID);
boolean isBorrowed = bookMemberService.existsByBookId(id);
if (isBorrowed) throw new ZebraException(ErrorType.BOOK_CANNOT_BE_DELETED);
deleteById(id);
logger.info("deleted book with id {}", id);
return BaseResponseDto.builder().statusCode(200).message("ok").build();
}
public BaseResponseDto deleteBookByIsbn(String isbn) {
System.out.println("controller1");
Book book = findByIsbn(isbn);
System.out.println("controlle2");
boolean isBorrowed = bookMemberService.existsByBookId(book.getId());
System.out.println("controller3");
if (isBorrowed) throw new ZebraException(ErrorType.BOOK_CANNOT_BE_DELETED);
System.out.println("controlle4");
delete(book);
System.out.println("controller5");
logger.info("delete book: {}.", book);
return BaseResponseDto.builder().statusCode(200).message("ok").build();
}
public BaseResponseDto getBookByIsbn(String isbn) {
Book book = repository.findOptionalByIsbn(isbn).orElseThrow(() -> {
throw new ZebraException(ErrorType.BOOK_NOT_FOUND_ISBN);
});
BaseResponseDto dto = bookMapper.toDto(book);
dto.setStatusCode(200);
dto.setMessage("ok");
logger.info("get book by ISBN: {}. ", dto);
return dto;
}
public Book findByIsbn(String isbn) {
Optional<Book> book = repository.findOptionalByIsbn(isbn);
if (book.isEmpty()) throw new ZebraException(ErrorType.BOOK_NOT_FOUND_ISBN);
return book.get();
}
}
|
/*
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is LunAS Library.
The Initial Developer of the Original Code is
ALCARAZ Marc (aka eKameleon) <vegas@ekameleon.net>.
Portions created by the Initial Developer are Copyright (C) 2004-2008
the Initial Developer. All Rights Reserved.
Contributor(s) :
*/
import vegas.core.CoreObject;
import vegas.core.ICloneable;
import vegas.core.ICopyable;
import vegas.core.IEquality;
/**
* The EdgeMetrics class specifies the thickness, in pixels, of the four edge regions around a visual component.
* @author eKameleon
*/
class lunas.core.EdgeMetrics extends CoreObject implements ICloneable, ICopyable, IEquality
{
/**
* Creates a new EdgeMetrics instance.
* @param left The width, in pixels, of the left edge region.
* @param top The height, in pixels, of the top edge region.
* @param right The width, in pixels, of the right edge region.
* @param bottom The height, in pixels, of the bottom edge region.
*/
public function EdgeMetrics( left:Number , top:Number , right:Number , bottom:Number )
{
super();
if ( !isNaN( bottom ) )
{
this.bottom = bottom ;
}
if ( !isNaN( left ) )
{
this.left = left ;
}
if ( !isNaN( right ) )
{
this.right = right ;
}
if ( !isNaN(top) )
{
this.top = top ;
}
}
/**
* An EdgeMetrics object with a value of zero for its
* <code>left</code>, <code>top</code>, <code>right</code>,
* and <code>bottom</code> properties.
*/
public static var EMPTY:EdgeMetrics = new EdgeMetrics(0, 0, 0, 0) ;
/**
* The height, in pixels, of the bottom edge region.
*/
public var bottom:Number ;
/**
* The width, in pixels, of the left edge region.
*/
public var left:Number ;
/**
* The width, in pixels, of the right edge region.
*/
public var right:Number ;
/**
* The height, in pixels, of the top edge region.
*/
public var top:Number ;
/**
* Returns a shallow copy of this instance.
* @return a shallow copy of this instance.
*/
public function clone()
{
return new EdgeMetrics(left, top, right, bottom);
}
/**
* Returns a deep copy of this instance.
* @return a deep copy of this instance.
*/
public function copy()
{
return new EdgeMetrics(left, top, right, bottom);
}
/**
* Compares the specified object with this object for equality.
* @return {@code true} if the the specified object is equal with this object.
*/
public function equals( o ):Boolean
{
if ( o instanceof EdgeMetrics )
{
return o.top == top && o.left == left && o.right == right && o.bottom == bottom ;
}
else
{
return false ;
}
}
/**
* Filters the passed-in Number value, if the value is NaN the return value is the default value in second argument.
* @param value The Number value to filter, if this value is NaN the value is changed.
* @param defaultValue The default value to apply over the specified value if this value is NaN (default 0).
* @return The filter Number value.
*/
public static function filterNaNValue( value:Number, defaultValue:Number ):Number
{
return isNaN( value ) ? (isNaN(defaultValue) ? 0 : defaultValue) : value ;
}
/**
* Returns the Object representation of this object.
* @return the Object representation of this object.
*/
public function toObject():Object
{
return { bottom:bottom , left:left , right:right , top:top } ;
}
}
|
/* normalize-scss | MIT/GPLv2 License | bit.ly/normalize-scss */
@import 'variables';
@import 'vertical-rhythm';
// If we've customized any font variables, we'll need extra properties.
@if $base-line-height != 24px
or $base-unit != 'em'
or $h2-font-size != 1.5 * $base-font-size
or $h3-font-size != 1.17 * $base-font-size
or $h4-font-size != 1 * $base-font-size
or $h5-font-size != 0.83 * $base-font-size
or $h6-font-size != 0.67 * $base-font-size
or $indent-amount != 40px {
$normalize-vertical-rhythm: true !global;
}
/* Document
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in
* IE on Windows Phone and in iOS.
*/
html {
@if $base-font-family {
/* Change the default font family in all browsers (opinionated). */
font-family: $base-font-family;
}
@if $base-font-size != 16px or $normalize-vertical-rhythm {
// Correct old browser bug that prevented accessible resizing of text
// when root font-size is set with px or em.
font-size: ($base-font-size / 16px) * 100%;
}
@if $normalize-vertical-rhythm {
// Establish a vertical rhythm unit using $base-font-size and
// $base-line-height variables.
line-height: ($base-line-height / $base-font-size) * 1em; /* 1 */
}
@else {
line-height: 1.15; /* 1 */
}
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
/**
* Remove the margin in all browsers (opinionated).
*/
body {
margin: 0;
}
/**
* Add the correct display in IE 9-.
*/
article,
aside,
footer,
header,
nav,
section {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
@include normalize-font-size($h1-font-size);
@if $normalize-vertical-rhythm {
@include normalize-line-height($h1-font-size);
}
@if $normalize-vertical-rhythm {
/* Set 1 unit of vertical rhythm on the top and bottom margins. */
@include normalize-margin(1 0, $h1-font-size);
}
@else {
margin: 0.67em 0;
}
}
@if $normalize-vertical-rhythm {
h2 {
@include normalize-font-size($h2-font-size);
@include normalize-line-height($h2-font-size);
@include normalize-margin(1 0, $h2-font-size);
}
h3 {
@include normalize-font-size($h3-font-size);
@include normalize-line-height($h3-font-size);
@include normalize-margin(1 0, $h3-font-size);
}
h4 {
@include normalize-font-size($h4-font-size);
@include normalize-line-height($h4-font-size);
@include normalize-margin(1 0, $h4-font-size);
}
h5 {
@include normalize-font-size($h5-font-size);
@include normalize-line-height($h5-font-size);
@include normalize-margin(1 0, $h5-font-size);
}
h6 {
@include normalize-font-size($h6-font-size);
@include normalize-line-height($h6-font-size);
@include normalize-margin(1 0, $h6-font-size);
}
}
/* Grouping content
// @if $normalize-vertical-rhythm {
// /**
// * Set 1 unit of vertical rhythm on the top and bottom margin.
// */
// blockquote {
// @include normalize-margin(1 $indent-amount);
// }
// dl,
// ol,
// ul {
// @include normalize-margin(1 0);
// }
/**
* Turn off margins on nested lists.
*/
// ol,
// ul {
// ol,
// ul {
// margin: 0;
// }
// }
// dd {
// margin: 0 0 0 $indent-amount;
// }
// ol,
// ul {
// padding: 0 0 0 $indent-amount;
// }
// }
/**
* Add the correct display in IE 9-.
*/
// figcaption,
// figure {
// display: block;
// }
/**
* Add the correct margin in IE 8.
*/
// figure {
// @if $normalize-vertical-rhythm {
// @include normalize-margin(1 $indent-amount);
// }
// @else {
// margin: 1em $indent-amount;
// }
// }
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
// hr {
// box-sizing: content-box; /* 1 */
// height: 0; /* 1 */
// overflow: visible; /* 2 */
// }
/**
* Add the correct display in IE.
*/
main {
display: block;
}
@if $normalize-vertical-rhythm {
/**
* Set 1 unit of vertical rhythm on the top and bottom margin.
*/
p,
pre {
@include normalize-margin(1 0);
}
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
// %monospace {
// font-family: monospace, monospace; /* 1 */
// font-size: 1em; /* 2 */
// }
// pre {
// @extend %monospace;
// }
/* Links
/**
* 1. Remove the gray background on active links in IE 10.
* 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
*/
a {
background-color: transparent; /* 1 */
-webkit-text-decoration-skip: objects; /* 2 */
}
/* Text-level semantics
/**
* 1. Remove the bottom border in Chrome 57- and Firefox 39-.
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
// abbr[title] {
// border-bottom: none; /* 1 */
// text-decoration: underline; /* 2 */
// text-decoration: underline dotted; /* 2 */
// }
/**
* Prevent the duplicate application of `bolder` by the next rule in Safari 6.
*/
// b,
// strong {
// font-weight: inherit;
// }
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
// b,
// strong {
// font-weight: bolder;
// }
// code,
// kbd,
// samp {
// @extend %monospace;
// }
/**
* Add the correct font style in Android 4.3-.
*/
// dfn {
// font-style: italic;
// }
/**
* Add the correct background and color in IE 9-.
*/
// mark {
// background-color: #ff0;
// color: #000;
// }
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
// sub,
// sup {
// font-size: 75%;
// line-height: 0;
// position: relative;
// vertical-align: baseline;
// }
// sub {
// bottom: -0.25em;
// }
// sup {
// top: -0.5em;
// }
/* Embedded content
/**
* Add the correct display in IE 9-.
*/
// audio,
// video {
// display: inline-block;
// }
/**
* Add the correct display in iOS 4-7.
*/
// audio:not([controls]) {
// display: none;
// height: 0;
// }
/**
* Remove the border on images inside links in IE 10-.
*/
// img {
// border-style: none;
// }
/**
* Hide the overflow in IE.
*/
// svg:not(:root) {
// overflow: hidden;
// }
/* Forms
/**
* Known issues:
* - `select`:
* By default, Chrome on OS X and Safari on OS X allow very limited styling of
* select, unless a border property is set. The default font weight on
* optgroup elements cannot safely be changed in Chrome on OSX and Safari on
* OS X.
* - `[type="checkbox"]`:
* It is recommended that you do not style checkbox and radio inputs as
* Firefox's implementation does not respect box-sizing, padding, or width.
* - `[type="number"]`:
* Certain font size values applied to number inputs cause the cursor style of
* the decrement button to change from `default` to `text`.
* - `[type="search"]`:
* The search input is not fully stylable by default. In Chrome and Safari on
* OSX/iOS you can't control `font`, `padding`, `border`, or `background`. In
* Chrome and Safari on Windows you can't control `border` properly. It will
* apply `border-width` but will only show a border color (which cannot be
* controlled) for the outer 1px of that border. Applying
* `-webkit-appearance: textfield` addresses these issues without removing the
* benefits of search inputs (e.g. showing past searches). Safari (but not
* Chrome) will clip the cancel button on when it has padding (and `textfield`
* appearance).
* - `::placeholder`:
* In Edge, placeholders will disappear on `relative` or `absolute` positioned
* `<input>` elements if you use `opacity` less than `1` due to a
* [bug](https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/3901363/).
*/
/**
* 1. Change the font styles in all browsers (opinionated).
* 2. Remove the margin in Firefox and Safari.
*/
// button,
// input,
// optgroup,
// select,
// textarea {
// @if $normalize-vertical-rhythm {
// @include normalize-line-height($base-font-size); /* 1 */
// }
// @else {
// line-height: 1.15; /* 1 */
// }
// font-family: if($base-font-family, $base-font-family, sans-serif); /* 1 */
// font-size: 100%; /* 1 */
// margin: 0; /* 2 */
// }
/**
* Show the overflow in IE.
*/
// button {
// overflow: visible;
// }
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
// button,
// select { /* 1 */
// text-transform: none;
// }
/**
* 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
* controls in Android 4.
* 2. Correct the inability to style clickable types in iOS and Safari.
*/
// button,
// html [type="button"], /* 1 */
// [type="reset"],
// [type="submit"] {
// -webkit-appearance: button; /* 2 */
// }
// button,
// [type="button"],
// [type="reset"],
// [type="submit"] {
// /**
// * Remove the inner border and padding in Firefox.
// */
// &::-moz-focus-inner {
// border-style: none;
// padding: 0;
// }
// /**
// * Restore the focus styles unset by the previous rule.
// */
// &:-moz-focusring {
// outline: 1px dotted ButtonText;
// }
// }
/**
* Show the overflow in Edge.
*/
// input {
// overflow: visible;
// }
/**
* 1. Add the correct box sizing in IE 10-.
* 2. Remove the padding in IE 10-.
*/
// [type="checkbox"],
// [type="radio"] {
// box-sizing: border-box; /* 1 */
// padding: 0; /* 2 */
// }
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
// [type="number"]::-webkit-inner-spin-button,
// [type="number"]::-webkit-outer-spin-button {
// height: auto;
// }
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
// [type="search"] {
// -webkit-appearance: textfield; /* 1 */
// outline-offset: -2px; /* 2 */
// /**
// * Remove the inner padding and cancel buttons in Chrome and Safari on macOS.
// */
// &::-webkit-search-cancel-button,
// &::-webkit-search-decoration {
// -webkit-appearance: none;
// }
// }
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
// ::-webkit-file-upload-button {
// -webkit-appearance: button; /* 1 */
// font: inherit; /* 2 */
// }
// /**
// * Correct the padding in Firefox.
// */
// fieldset {
// padding: 0.35em 0.75em 0.625em;
// }
// /**
// * 1. Correct the text wrapping in Edge and IE.
// * 2. Correct the color inheritance from `fieldset` elements in IE.
// * 3. Remove the padding so developers are not caught out when they zero out
// * `fieldset` elements in all browsers.
// */
// legend {
// box-sizing: border-box; /* 1 */
// display: table; /* 1 */
// max-width: 100%; /* 1 */
// padding: 0; /* 3 */
// color: inherit; /* 2 */
// white-space: normal; /* 1 */
// }
// /**
// * 1. Add the correct display in IE 9-.
// * 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.
// */
// progress {
// display: inline-block; /* 1 */
// vertical-align: baseline; /* 2 */
// }
// /**
// * Remove the default vertical scrollbar in IE.
// */
// textarea {
// overflow: auto;
// }
// /* Interactive
// /*
// * Add the correct display in Edge, IE, and Firefox.
// */
// details {
// display: block;
// }
// /*
// * Add the correct display in all browsers.
// */
// summary {
// display: list-item;
// }
// /*
// * Add the correct display in IE 9-.
// */
// menu {
// display: block;
// @if $normalize-vertical-rhythm {
// /*
// * 1. Set 1 unit of vertical rhythm on the top and bottom margin.
// * 2. Set consistent space for the list style image.
// */
// @include normalize-margin(1 0); /* 1 */
// padding: 0 0 0 $indent-amount; /* 2 */
// /**
// * Turn off margins on nested lists.
// */
// menu &,
// ol &,
// ul & {
// margin: 0;
// }
// }
// }
// /* Scripting
// /**
// * Add the correct display in IE 9-.
// */
canvas {
display: inline-block;
}
/**
* Add the correct display in IE.
*/
// template {
// display: none;
// }
// /* Hidden
/**
* Add the correct display in IE 10-.
*/
// [hidden] {
// display: none;
// }
|
import { expect, vitest } from "vitest";
import { json, jsonLanguage } from "@codemirror/lang-json";
import { json5, json5Language } from "codemirror-json5";
import { EditorState } from "@codemirror/state";
import {
Completion,
CompletionContext,
CompletionResult,
CompletionSource,
} from "@codemirror/autocomplete";
import { jsonCompletion } from "../../json-completion.js";
import { JSONSchema7 } from "json-schema";
import { testSchema2 } from "../__fixtures__/schemas.js";
import { EditorView } from "@codemirror/view";
import { stateExtensions } from "../../state.js";
vitest.mock("@codemirror/autocomplete", async () => {
const mod = await vitest.importActual<
typeof import("@codemirror/autocomplete")
>("@codemirror/autocomplete");
return {
...mod,
snippetCompletion(template: string, completion: Completion) {
const c = {
...completion,
// pass the snippet template to the completion result
// to make it easier to test
TESTONLY_template: template,
};
return mod.snippetCompletion(template, c);
},
};
});
type MockedCompletionResult = CompletionResult["options"][0] & {
template?: string;
};
export async function expectCompletion(
doc: string,
results: MockedCompletionResult[],
conf: {
explicit?: boolean;
schema?: JSONSchema7;
mode?: "json" | "json5";
} = {}
) {
let cur = doc.indexOf("|"),
currentSchema = conf?.schema || testSchema2;
doc = doc.slice(0, cur) + doc.slice(cur + 1);
const jsonMode = conf?.mode === "json5" ? json5 : json;
const jsonLang = conf?.mode === "json5" ? json5Language : jsonLanguage;
let state = EditorState.create({
doc,
selection: { anchor: cur },
extensions: [
jsonMode(),
stateExtensions(currentSchema),
jsonLang.data.of({
autocomplete: jsonCompletion({ mode: conf.mode }),
}),
],
});
const view = new EditorView({ state });
let result = await state.languageDataAt<CompletionSource>(
"autocomplete",
cur
)[0](new CompletionContext(state, cur, !!conf.explicit));
if (!result) {
return expect(result).toEqual(results);
}
const filteredResults = result.options.map((item) => ({
detail: item.detail,
info: item.info,
label: item.label,
type: item.type,
// @ts-expect-error
template: item?.TESTONLY_template as string | undefined,
}));
expect(filteredResults).toEqual(results);
}
|
import static utils.Utilities.writeFile;
import org.objectweb.asm.*;
import org.objectweb.asm.Opcodes;
public class gen9{
// Get input (I or D), from the user, run a loop that adds that number to an accumulator, and then print the result. (gen9.java,program9.class)
public static void main(String[] args){
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC,"program9", null, "java/lang/Object",null);
{
MethodVisitor mv=cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0); //load the first local variable: this
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V",false);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1,1);
mv.visitEnd();
}
{
MethodVisitor mv=cw.visitMethod(Opcodes.ACC_PUBLIC+Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
mv.visitCode();
// Labels for jumping too
Label jump13 = new Label();
// Get Scanner and store it
/*
* 0: new
* 3: dup
* 4: getstatic
* 7: invokespecial
* 10: astore 1
*/
mv.visitTypeInsn(Opcodes.NEW, "java/util/Scanner");
mv.visitInsn(Opcodes.DUP);
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "in", "Ljava/io/InputStream;");
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/Scanner", "<init>", "(Ljava/io/InputStream;)V", false);
mv.visitVarInsn(Opcodes.ASTORE, 1);
// Declare accumulator
/*
* 11: dconst 0
* 12: dstore 2
*/
mv.visitInsn(Opcodes.DCONST_0);
mv.visitVarInsn(Opcodes.DSTORE, 2);
// 44 jump to 13
mv.visitLabel(jump13);
// Get user input for double using Scanner
/*
* 13: getstatic
* 16: ldc
* 18: invokevirtual
* 21: aload 1
* 22: invokevirtual
* 25: dstore 4
*/
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mv.visitLdcInsn((String)"Enter double");
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
mv.visitVarInsn(Opcodes.ALOAD, 1);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/Scanner", "nextDouble", "()D", false);
mv.visitVarInsn(Opcodes.DSTORE, 4);
// Add and store the value to the accumulator
/*
* 27: dload 2
* 28: dload 4
* 30: dadd
* 31: dstore 2
*/
mv.visitVarInsn(Opcodes.DLOAD, 2);
mv.visitVarInsn(Opcodes.DLOAD, 4);
mv.visitInsn(Opcodes.DADD);
mv.visitVarInsn(Opcodes.DSTORE, 2);
// Print the accumulator value
/*
* 32: getstatic
* 35: ldc
* 37: invokevirtual
* 40: getstatic
* 43: dload 2
* 44: invokevirtual
*/
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mv.visitLdcInsn((String)"Accumulator: ");
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "print", "(Ljava/lang/String;)V", false);
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
mv.visitVarInsn(Opcodes.DLOAD, 2);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(D)V", false);
// Loop back up
/*
* 47: goto 13
*/
mv.visitJumpInsn(Opcodes.GOTO, jump13);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0,0);
mv.visitEnd();
}
cw.visitEnd();
byte[] b = cw.toByteArray();
writeFile(b,"program9.class");
System.out.println("Done!");
}//end main
}//end class
|
History of Containerization
A quick review
12 Apr 2018
Tags: Docker, Linux Containers
Jay Taylor
Senior Engineering Manager, Intelligent Chat Bots Service, Oracle
jay.taylor@oracle.com
* How did we get here?
** Quick history review
* 1979: Unix V7
The `chroot()` system call was first introduced during the development of Unix V7.
In 1982 it was also added to BSD.
Invoking `chroot()` changes the apparent root directory for the current running process and its children, effectively providing a layer of isolation from the rest of the system.
* 2000: FreeBSD Jails
Nearly 20 years later, a small shared-environment hosting provider came up with FreeBSD jails to keep its services and customers separate.
`chroot` `jails` were a pretty slick way to securely share computing resources.
.link http://phk.freebsd.dk/pubs/sane2000-jail.pdf Y2K Jails
* 2001: Linux VServer
Implemented as a Linux Kernel Patch, Linux VServer is a jail mechanism which can partition:
- File Systems
- Network Addresses
- System Memory
* 2004: Oracle Solaris Zones
In 2004 Oracle released container functionality in Solaris that combined system resource controls and boundary separation.
.image img/solaris-containers.jpg
#* 2005: Open VZ (Open Virtuzzo)
#
#A Linux Kernel Patch for OS-level virtualization.
#Never merged into Linux Kernel.
* 2006: Process Containers, AKA Linux CGroups
Google launched `Process` `Containers` in 2006, and later renamed the project to `CGROUPS` (Control Groups).
`CGROUPS` are designed to limit, isolate, and account for usage of system resources.
- CPU
- Memory
- Disk I/O
- Network
Merged into the Linux Kernel a year later.
* 2008: LXC
LXC (LinuX Containers) was the first (mostly) complete implementation of Linux Container Manager.
Implemented using cgroups and Linux namespaces, and it works on a single Linux kernel without requiring any patches.
* 2009: Heroku
_Containers_meet_SaaS_
In 2009 the Heroku PaaS launched, and over subsequent years became a huge success with developers all over the world.
Deploying became as simple as `git` `push` `heroku`.
Acquired by Salesforce in 2010.
Heroku was what first got me really curious and ultimately excited about Platform-as-a-Service. "How do they make this work?", I couldn't help but wonder.
* 2013: LMCTFY
`LMCTFY` stands for "Let Me Control That For You", and was released in 2013 as an open-source version of the Google Container Stack. Written in C++
Development ceased in 2015 when Google altered course and began contributing to `libcontainer`, which has now become part of the Open Container Foundation.
.link https://github.com/google/lmctfy LMCTFY source code (primarily C++)
* 2013: Enter Docker
.image img/shykes.jpg
* 2013: Enter Docker, cont'd..
Docker was created and first released by Solomon Hykes in 2013.
After starting out years earlier as a way to have git-like version control for an entire operating system, by 2013 Docker had evolved into a serious contender in the container space.
Initially Docker used LXC under the covers, and later transitioned to Docker's own in-house container manager, `libcontainer`.
* 2015: A Container E X P L O S I O N
*
*Container* *Wars.*
*Docker* *vs.* *CoreOS* */* *Rkt*
*Docker* *vs.* *LXC* *v2*
*Apache* *Mesos* *vs.* *Kubernetes*
* References
.link https://blog.aquasec.com/a-brief-history-of-containers-from-1970s-chroot-to-docker-2016 A Brief History of Containers from 1970s Chroot to Docker 2016
|
<script>
export default {
props: {
msg: {
type: String,
default: 'hi ~'
},
str: {
type: String,
default: 'hi ~'
},
bool: {
type: Boolean,
default: true
},
num: {
type: Number,
default: 100
},
arr: {
type: Array,
default: () => []
},
obj: {
type: Object,
default: () => ({})
},
foo: {
type: Function,
default: () => {}
},
},
setup(props) {
return {
props
}
}
}
</script>
<template>
<!-- <h1>{{ props.msg }}</h1> -->
<p>{{ props.str }}</p>
<p>{{ props.bool }}</p>
<p>{{ props.num }}</p>
<p>{{ props.arr }}</p>
<p>{{ props.obj }}</p>
<p>{{ props.foo }}</p>
</template>
<style>
h1 {
color: blue;
}
</style>
|
import React from "react";
import "./Createblogs.css";
import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useContext } from "react";
import { Context } from "../../Context/Context";
export default function Createblogs() {
let Navigate = useNavigate();
const { isFetching, error, token, dispatch } = useContext(Context);
const [title, settitle] = useState("");
const [descrip, setdescrip] = useState("");
const [previewSource, setPreviewSource] = useState("");
const changetitle = (e) => {
settitle(e.target.value);
};
const changedescrip = (e) => {
setdescrip(e.target.value);
};
const changeimglink = (e) => {
const file=e.target.files[0];
previewFile(file);
};
const previewFile =(file)=>{
const reader=new FileReader();
reader.readAsDataURL(file);
reader.onloadend=()=>{
setPreviewSource(reader.result);
}
}
const submitHandler = async (e) => {
e.preventDefault();
var data = token;
dispatch({ type: "NEW_BLOG_START" });
try {
await axios.post("https://blogmernapp.onrender.com/newBlogs",{title,descrip,previewSource}, {
headers: { data },
});
dispatch({ type: "NEW_BLOG_SUCCESS" });
Navigate("/");
} catch (err) {
dispatch({ type: "NEW_BLOG_FAIL" });
}
};
if (isFetching) {
return <div className="loading"></div>;
}
if (error) {
return <div>error</div>;
}
if (token === null) {
return (
<div>
please <a href="/login">login</a>
</div>
);
}
return (
<>
<div className="createblogs_navigate ">
<a href="/">Home</a>
</div>
<form
className="createblogs_div container"
encType="multipart/form-data"
onSubmit={submitHandler}
>
<textarea
type="text"
placeholder="Title"
value={title}
name="title"
onChange={changetitle}
required
/>
<textarea
type="text"
placeholder="Description"
name="description"
value={descrip}
onChange={changedescrip}
required
/>
{previewSource && (<img src={previewSource} />)}
<input required type="file" filename="image" onChange={changeimglink} />
<button type="submit">Publish</button>
</form>
</>
);
}
|
#include <iostream>
#include <vector>
using namespace std;
//BRUTE FORCE APPROACH
//T.C = O(N^2)
//We will run a loop that will select the elements of the array one by one.
//Now, for each element, we will run another loop and count its occurrence in the given array.
//If any element occurs more than the floor of (N/2), we will simply return it.
int majorityElementBrute(vector<int> arr){
int ans = -1;
int n = arr.size() - 1;
for(int i = 0; i < n; i++){
int count = 0;
for(int j = 0; j < n; j++){
if(arr[i] == arr[j])
count++;
}
if(count > n/2)
ans = arr[i];
}
return ans;
}
//OPTIMAL APPROACH - MOORES VOTING ALGORITHM
//T.C = O(N) + O(N)
//The element with the most occurrence will remain and the rest will cancel themselves.
int majorityElementOptimal(vector<int>arr){
int n = arr.size();
int count = 0;
int ele = -1; //-1 if no majority element
for(int i = 0; i < n; i++){
if(count == 0){
count = 1;
ele = arr[i];
}
else if(arr[i] == ele){
count++;
}
else if(arr[i] != ele){
count--;
}
}
int count1 = 0;
for(int i = 0; i < n; i++){
if(arr[i] == ele) count1++;
}
if(count1 > n/2) return ele;
return -1;
}
|
class DynamicSerializerMixin:
"""
A mixin that allows you to use different serializers for different actions.
"""
serializer_classes = {}
def get_serializer_class(self):
"""
Return the serializer class based on the action being performed.
"""
if self.action in self.serializer_classes:
return self.serializer_classes[self.action]
return super().get_serializer_class()
|
import usePagination from './usePagination';
jest.mock('react', () => ({
useMemo: jest.fn().mockImplementation((fn: () => void) => fn()),
}));
describe('usePagination', () => {
it('should return correct data based on props', () => {
const mockedArray = Array.from(Array(10)).map((_, index) => index);
const firstPage = usePagination(mockedArray, 0, 10);
expect(firstPage).toEqual(mockedArray.slice(0, 10));
const per15Rows = usePagination(mockedArray, 0, 15);
expect(per15Rows).toEqual(mockedArray);
const nonExistingPage = usePagination(mockedArray, 1, 15);
expect(nonExistingPage).toEqual([]);
});
it('should return an empty array if page or elementsToShow are invalid', () => {
const mockedArray = Array.from(Array(10)).map((_, index) => index);
const resultInvalidPage = usePagination(mockedArray, -1, 10);
expect(resultInvalidPage).toEqual([]);
const resultInvalidElementsPerPage = usePagination(mockedArray, -1, 10);
expect(resultInvalidElementsPerPage).toEqual([]);
});
});
|
<p-dialog #dialog [header]="modelEdit.id > 0 ? 'Đơn hàng #' + modelEdit.id + ' - ' + modelEdit.code + (modelEdit.idParent > 0 ? ' - Đơn cha: #' + modelEdit.idParent : '') : 'Tạo đơn mới'" styleClass="vs-modal force-full-width" positionTop="50" [(visible)]="isShow"
[style]="{'max-width': '1100px'}" [contentStyle]="{'max-height': getMaxDialogHeight()}" [modal]="true" appendTo="body">
<div class="vs-form-container default-control-label-width vs-modal-content-panel">
<div class="vs-form-container default-control-label-width">
<div class="ui-g row">
<form action="" [formGroup]="formGroup">
<!-- <div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Chọn khách hàng</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper required">
<p-autoComplete [readonly]="isView" [(ngModel)]="khachCu" formControlName="khachCu" [suggestions]="listKhachCu"
(completeMethod)="autoCompleteKhachCu($event)" field="fullInfo" [size]="30" placeholder="Nhập họ tên hoặc số điện thoại khách hàng cũ"
[minLength]="1" (onSelect)="onSelectKhachCu($event)">
</p-autoComplete>
</div>
</div>
</div>
</div> -->
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Họ và tên</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper required" style="position: relative;">
<input type="text" [readonly]="isView" [(ngModel)]="modelEdit.name" formControlName="name" placeholder="Họ và tên" />
<div class="form-control-feedback" *ngIf="formGroup.controls['name'].hasError('required') && formGroup.controls['name'].touched">
Trường thông tin này là bắt buộc!</div>
</div>
</div>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">SĐT</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper required" style="position: relative;">
<input type="text" [readonly]="isView" [(ngModel)]="modelEdit.phone" formControlName="phone" placeholder="Số điện thoại" />
<div class="form-control-feedback" *ngIf="formGroup.controls['phone'].hasError('required') && formGroup.controls['phone'].touched">
Trường thông tin này là bắt buộc!</div>
<div class="form-control-feedback" *ngIf="formGroup.controls['phone'].hasError('pattern') && formGroup.controls['phone'].touched">
Số điện thoại không hợp lệ!</div>
</div>
</div>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-3">
Địa chỉ</div>
<div class="__form-control-inputs ui-g-12 ui-md-3">
<div class="__input-wrapper required" style="position: relative;">
<p-dropdown [disabled]="isView" [baseZIndex]="15000" formControlName="idProvince" [(ngModel)]="modelEdit.idProvince" [showClear]="true" filter="true" placeholder="-- Tỉnh/TP --" [emptyFilterMessage]="'Không tìm thấy kết quả'" [options]="province_options"
[style]="{'width':'100%', 'min-width':'0'}" appendTo="body" (onChange)="onLoadDistricts()"></p-dropdown>
<div class="form-control-feedback" *ngIf="formGroup.controls['idProvince'].hasError('required') && formGroup.controls['idProvince'].touched">
Trường thông tin này là bắt buộc!</div>
</div>
</div>
<div class="__form-control-inputs ui-g-12 ui-md-3">
<div class="__input-wrapper required" style="position: relative;">
<p-dropdown [disabled]="isView" [baseZIndex]="15000" formControlName="idDistrict" [(ngModel)]="modelEdit.idDistrict" [showClear]="true" filter="true" placeholder="-- Quận/Huyện --" [emptyFilterMessage]="'Không tìm thấy kết quả'" [options]="distric_options"
[style]="{'width':'100%', 'min-width':'0'}" appendTo="body" (onChange)="onLoadWards()"></p-dropdown>
<div class="form-control-feedback" *ngIf="formGroup.controls['idDistrict'].hasError('required') && formGroup.controls['idDistrict'].touched">
Trường thông tin này là bắt buộc!</div>
</div>
</div>
<div class="__form-control-inputs ui-g-12 ui-md-3">
<div class="__input-wrapper required" style="position: relative;">
<p-dropdown [disabled]="isView" [baseZIndex]="15000" [(ngModel)]="modelEdit.idWard" formControlName="idWard" [showClear]="true" filter="true" placeholder="-- Xã/Phường --" [emptyFilterMessage]="'Không tìm thấy kết quả'" [options]="ward_options" [style]="{'width':'100%', 'min-width':'0'}"
appendTo="body" (onChange)="GetShipFee()"></p-dropdown>
<div class="form-control-feedback" *ngIf="formGroup.controls['idWard'].hasError('required') && formGroup.controls['idWard'].touched">
Trường thông tin này là bắt buộc!</div>
</div>
</div>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Số nhà</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper required" style="position: relative;">
<input type="text" [readonly]="isView" [(ngModel)]="modelEdit.address" formControlName="address" placeholder="Số nhà/đường/ngõ/nghách" />
<div class="form-control-feedback" *ngIf="formGroup.controls['address'].hasError('required') && formGroup.controls['address'].touched">
Trường thông tin này là bắt buộc!</div>
</div>
</div>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Ghi chú giao hàng</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper">
<textarea type="text" [readonly]="isView" [(ngModel)]="modelEdit.note" rows="2" formControlName="note" placeholder="Ghi chú"></textarea>
</div>
</div>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Thanh toán</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper">
<p-radioButton name="isVerified" value="1" [(ngModel)]="isVerified" formControlName="isVerified" [disabled]="isView" (onClick)="changeOder()" label="Qua ví DapFood"></p-radioButton>
<p-radioButton name="isVerified" value="0" [(ngModel)]="isVerified" formControlName="isVerified" [disabled]="isView" (onClick)="changeOder()" label="Thanh toán khi nhận hàng" [style]="{'margin-left':'50px'}">
</p-radioButton>
<!-- <p-inputSwitch [(ngModel)]="modelEdit.isVerified" formControlName="isVerified" pTooltip="Thanh toán luôn" [style]="{'float':'left'}">
</p-inputSwitch>
<div style="line-height: 25px;float: left; margin-left: 10px;">(Thanh toán trên số dư tài khoản và nhận thêm 5% hoa hồng)</div> -->
</div>
</div>
</div>
</div>
</form>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Thêm sản phẩm</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper required">
<!-- (onFocus)="!autocomplete.value && autocomplete.handleDropdownClick()" (onClear)="clearItem(autocomplete)" #autocomplete -->
<p-autoComplete [readonly]="isView" [(ngModel)]="key" [suggestions]="results" (completeMethod)="autoComplete($event)" field="name" [size]="30" placeholder="Nhập tên hoặc mã sản phẩm" [minLength]="1" (onSelect)="onSelect($event)">
</p-autoComplete>
</div>
</div>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="ui-g" id="table">
<p-table #mainTable [columns]="cols" selectionMode="multiple" [rows]="limit" [scrollable]="false" scrollHeight="auto" [value]="dataSource" [(selection)]="selectedItems" [totalRecords]="total" class="vs-table responsive-table" [customSort]="false" [loading]="isLoading"
[lazy]="false" [resizableColumns]="true" dataKey="id" [style]="{'min-height': '200px'}">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<ng-container *ngFor="let col of columns" [ngSwitch]="col.field">
<ng-container *ngSwitchDefault>
<col [hidden]="!col.visible" [style.width]="col.width">
</ng-container>
</ng-container>
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns>
<tr>
<ng-container *ngFor="let col of columns;">
<th class="ui-resizable-column" [hidden]="!col.visible"> {{col.header}}</th>
</ng-container>
<th *ngIf="!isView" class="align-center" style="width: 10%;"></th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-item let-columns="columns" let-rowIndex="rowIndex">
<tr align="center">
<ng-container *ngFor="let col of columns;let i = index;" [ngSwitch]="col.field">
<td class="ui-resizable-column" [hidden]="!col.visible" [class.align-left]="!col.align || col.align === 'left'" [class.align-center]="col.align === 'center'" [class.align-right]="col.align === 'right'">
<ng-container *ngSwitchCase="'image'">
<vs-view-image [(file)]="item.image" [height]="'80'">
</vs-view-image>
</ng-container>
<ng-container *ngSwitchCase="'price'">
{{item.price | mask :'separator':'.'}}
</ng-container>
<ng-container *ngSwitchCase="'quantity'">
<input [readonly]="isView" type="number" min="1" step="1" (change)="changeOder()" [(ngModel)]="item.quantity" style="width: 100%" />
</ng-container>
<ng-container *ngSwitchCase="'totalBill'">
{{item.price * item.quantity | mask :'separator':'.'}}
</ng-container>
<ng-container *ngSwitchCase="'reward'">
<!-- {{item.reward * item.quantity | mask :'separator':'.'}} -->
<div *ngIf="!isView">
{{item.reward * item.quantity | mask :'separator':'.'}}
</div>
<div *ngIf="isView">
{{item.reward| mask :'separator':'.'}}
</div>
</ng-container>
<span *ngSwitchDefault class="break-word">{{item[col.field]}}</span>
</td>
</ng-container>
<td *ngIf="!isView" style="width: 10%;">
<button type="button" class="vs-btn icon-only vs-btn-red" (click)="onRemove(rowIndex)" pTooltip="Xoá">
<span class="__icon fa fa-trash"></span>
</button>
</td>
</tr>
</ng-template>
<ng-template pTemplate="footer">
<tr align="right" style="line-height: 30px">
<th class="ui-resizable-column align-right" colspan="5">Tổng tiền hàng</th>
<th class="ui-resizable-column align-right" style="width: 10%;">
{{modelEdit.total | mask :'separator':'.'}}</th>
<th *ngIf="isVerified == 1" class="ui-resizable-column align-right" style="width: 10%;font-weight: normal;">
{{modelEdit.productReward + modelEdit.prepayReward | mask :'separator':'.'}}</th>
<th *ngIf="isVerified == 0" class="ui-resizable-column align-right" style="width: 10%;font-weight: normal;">
{{modelEdit.productReward | mask :'separator':'.'}}</th>
<th class="ui-resizable-column align-right" style="width: 10%;" *ngIf="!isView">
</th>
</tr>
<tr align="right" style="line-height: 30px">
<th class="ui-resizable-column align-right" colspan="5" style="font-weight: normal;">Phí vận chuyển</th>
<th class="ui-resizable-column align-right" style="width: 10%;font-weight: normal;">
{{modelEdit.ship | mask :'separator':'.'}}</th>
<th class="ui-resizable-column align-right" style="width: 10%;"></th>
<th class="ui-resizable-column align-right" style="width: 10%;" *ngIf="!isView">
</th>
</tr>
<tr align="right" style="line-height: 30px">
<th class="ui-resizable-column align-right" colspan="5" style="font-weight: normal;">
Tổng hoa hồng
</th>
<th class="ui-resizable-column align-right" style="width: 10%;font-weight: normal;">
{{modelEdit.totalReward | mask :'separator':'.'}}</th>
<th class="ui-resizable-column align-right" style="width: 10%;"></th>
<th class="ui-resizable-column align-right" style="width: 10%;" *ngIf="!isView">
</th>
</tr>
<!-- <tr align="right" style="line-height: 30px">
<th class="ui-resizable-column align-right" colspan="5" style="font-weight: normal;">
Tổng quà tặng
</th>
<th class="ui-resizable-column align-right" style="width: 10%;font-weight: normal;">
{{modelEdit.totalGift | mask :'separator':'.'}}</th>
<th class="ui-resizable-column align-right" style="width: 10%;"></th>
<th class="ui-resizable-column align-right" style="width: 10%;" *ngIf="!isView">
</th>
</tr> -->
<tr align="right" style="line-height: 30px">
<th class="ui-resizable-column align-right" colspan="5" style="font-weight: normal;">
Giảm giá
</th>
<th class="ui-resizable-column align-right" style="width: 10%;font-weight: normal;">
{{modelEdit.discount | mask :'separator':'.'}}</th>
<th class="ui-resizable-column align-right" style="width: 10%;"></th>
<th class="ui-resizable-column align-right" style="width: 10%;" *ngIf="!isView">
</th>
</tr>
<tr align="right" style="line-height: 30px">
<th class="ui-resizable-column align-right" colspan="5">Tổng tiền thanh toán</th>
<th class="ui-resizable-column align-right" style="width: 10%;">
{{modelEdit.total + modelEdit.ship - modelEdit.totalGift - modelEdit.discount | mask :'separator':'.'}}</th>
<th class="ui-resizable-column align-right" style="width: 10%;"></th>
<th class="ui-resizable-column align-right" style="width: 10%;" *ngIf="!isView">
</th>
</tr>
</ng-template>
</p-table>
</div>
</div>
<div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Chương trình thưởng</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper">
<button *ngIf="!isView" type="button" (click)="showPromotions()" pButton icon="pi pi-info-circle" label="Chọn chương trình thưởng"></button> {{modelEdit.promotion?.name}}
<button *ngIf="modelEdit.promotion != null && modelEdit.promotion.length > 0" type="button" class="vs-btn icon-only vs-btn-red" (click)="changeOder()" pTooltip="Xoá">
<span class="__icon fa fa-trash"></span>
</button>
</div>
</div>
</div>
</div>
<!-- <div class="ui-g-12 ui-lg-12">
<div class="vs-form-control ui-g">
<div class="__form-control-label ui-g-12 ui-md-4">Quà tặng cho khách</div>
<div class="__form-control-inputs ui-g-12 ui-md-8">
<div class="__input-wrapper">
<button *ngIf="!isView" type="button" (click)="showGifts()" pButton icon="pi pi-info-circle" label="Chọn quà tặng"
style="margin-right: 15px ;"></button>
<ng-container *ngFor="let item of modelEdit.orderGifts;let i = index;" [ngSwitch]="item.type">
<span *ngSwitchDefault class="break-word">{{item.name + ', '}}</span>
</ng-container>
<button *ngIf="modelEdit.orderGifts != null && modelEdit.orderGifts.length > 0" type="button" class="vs-btn icon-only vs-btn-red"
(click)="changeOder()" pTooltip="Xoá">
<span class="__icon fa fa-trash"></span>
</button>
</div>
</div>
</div>
</div> -->
</div>
</div>
</div>
<p-footer>
<div class="ui-g row">
<div class="ui-g-12">
<p-progressSpinner *ngIf="isLoading" [style]="{width: '30px', height: '30px', margin:'-11px 8px'}" strokeWidth="8" fill="#EEEEEE" animationDuration=".5s">
</p-progressSpinner>
<button class="vs-btn vs-modal-btn vs-btn-red" *ngIf="(modelEdit.idStatus == enumOrderStatus.HuyDon || modelEdit.idStatus == enumOrderStatus.DaXacNhan) && crrUser?.idClient == null" (click)="CancelContact()" type="button">
<span class="__icon fa fa-floppy-o"></span>
<span class="__label">Hủy đơn</span>
</button>
<button type="button" (click)="closePopupMethod(null)" class="vs-btn vs-modal-btn vs-btn-action-back">
<span class="__icon fa fa-times"></span>
<span class="__label">Đóng</span>
</button>
</div>
</div>
</p-footer>
</p-dialog>
|
<template>
<el-dialog :title="dialogTitle" :visible.sync="showDialog" width="60%" top="5vh">
<div class="dialog-body">
<div class="table-wrapper">
<el-table :data="leave">
<el-table-column label="请假时间" show-overflow-tooltip width="300">
<template slot-scope="{row}">{{ row.leaveStartTime }} - {{ row.leaveEndTime }}</template>
</el-table-column>
<el-table-column label="请假类型" show-overflow-tooltip>
<template slot-scope="{row}">{{ setOTType(row.leaveType) }}</template>
</el-table-column>
<el-table-column label="请假时长(小时)" prop="totalHour" width="120" show-overflow-tooltip />
<el-table-column label="审核状态" show-overflow-tooltip>
<template slot-scope="{row}">
<div :class="setAuditStatusColorClass(row.statue)">{{ setAuditStatus(row.statue) }}</div>
</template>
</el-table-column>
<el-table-column label="状态" show-overflow-tooltip>
<template slot-scope="{row}">
<div :class="setStatusColorClass(row.log.approveStatue)">{{ setStatus(row.log.approveStatue) }}</div>
</template>
</el-table-column>
</el-table>
</div>
</div>
</el-dialog>
</template>
<script>
export default {
name: 'UserDialog',
data() {
return {
dialogTitle: '',
showDialog: false,
leave: [],
leaveTypes: this.$paramsModel.opm.get('leaveType'),
audioStatus: this.$paramsModel.common.get('audioStatus')
}
},
computed: {
setOTType() {
return function (value) {
const getItem = this.leaveTypes.filter(ele => +ele.value === +value)
return getItem.length > 0 ? getItem[0].label : ''
}
},
setStatus() {
return function(approveStatue) {
if (!approveStatue) return ''
return this.$defineData.processStatus(approveStatue)
}
},
setStatusColorClass() {
return function(approveStatue) {
if (!approveStatue) return ''
return this.$defineData.processStatus(approveStatue, 'color')
}
},
setAuditStatus() {
return function(statue) {
const getItem = this.audioStatus.findIndex((item) => Number(item.statue) === Number(statue))
return getItem !== -1 ? this.audioStatus[getItem].value : ''
}
},
setAuditStatusColorClass() {
return function(statue) {
const getItem = this.audioStatus.findIndex((item) => Number(item.statue) === Number(statue))
return getItem !== -1 ? this.audioStatus[getItem].color : ''
}
}
},
methods: {
// 打开
open(options) {
if (options) {
this.dialogTitle = `查看${options.realName}${options.tel}请假记录`
this.showDialog = true
this.leave = options.leave
}
}
}
}
</script>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="styleForm.css">
<link rel="stylesheet" href="styleFooter.css">
<title>Actividad 12</title>
</head>
<body>
<header>
<nav class="d-flex justify-content-around align-items-center">
<div class="logo">
<img src="./logo-color.jpg" class="logo" alt="logo">
</div>
<div>
<a href="#formulario">Cotizacion</a>
<a href="#contacto">Nosotros</a>
<a href="#contacto">Contacto</a>
</div>
</nav>
<img src="./imagen.png" class="banner" alt="imagen">
</header>
<main id="formulario" class="main container mx-auto">
<form action="#" class="grid gap-3">
<div class="primer-div-form">
<h4 class="m-0">Formulario de contacto</h4>
<button class="btn-reset" type="reset"> Borrar info </button>
</div>
<div class="segundo-div-form">
<div class="datosDueño">
<h6 class="my-4">Dato del datos del dueño:</h6>
<div id="name">
<label for="name"> Nombre del responsable:</label>
<input type="text" id="name" placeholder="Nombre">
</div>
<div id="lastname">
<label for="lastname"> Apellido: </label>
<input type="text" id="name" placeholder="Apellido">
</div>
<div id="email">
<label for="email"> Email: </label>
<input type="email" id="email" placeholder="Email">
</div>
<div id="telefono">
<label for="telefono"> Telefono de contacto: </label>
<input type="tel" id="telefono" placeholder="Telefono de contacto">
</div>
</div>
<div class="datosMascota">
<h6 class="my-4">Datos de la mascota:</h6>
<div id="nameanimal">
<label for="nameanimal"> Nombre del animal: </label>
<input type="text" id="nameanimal" placeholder="Nombre del animal">
</div>
<div class="envoltorio-inputs-radio">
<div id="tipodeanimal">
<p>
Tipo de animal:<br>
<label>
<input type="radio" name="tipodeanimal" value="gato"> Gato<br>
</label><br>
<label>
<input type="radio" name="tipodeanimal" value="perro"> Perro<br>
</label><br>
<label>
<input type="radio" name="tipodeanimal" value="tortuga"> Tortuga<br>
</label><br>
<label>
<input type="radio" name="tipodeanimal" value="coballo"> Coballo<br>
</label><br>
<label>
<input type="radio" name="tipodeanimal" value="conejo"> Conejo<br>
</label><br>
</p>
</div>
<div id="edadanimal">
<p>
Edad del animal:<br>
<label>
<input type="radio" name="edadanimal" value="bebe"> 0-3 meses
</label><br>
<label>
<input type="radio" name="edadanimal" value="chico"> 3-6 meses
</label><br>
<label>
<input type="radio" name="edadanimal" value="joven"> 6-12 meses
</label><br>
<label>
<input type="radio" name="edadanimal" value="adulto"> +1 año
</label><br>
<label>
<input type="radio" name="edadanimal" value="adulto+"> +5 años
</label><br>
</p>
</div>
<div id="sexo">
<p>
Sexo:<br>
<label>
<input type="radio" name="sexo" value="hembra"> Hembra
</label><br>
<label>
<input type="radio" name="sexo" value="macho"> Macho
</label><br>
</p>
</div>
</div>
<div id="raza">
<label for="raza"> Raza: </label>
<input type="text" id="raza" placeholder="Raza">
</div>
<div id="color">
<label for="color"> Color: </label>
<input type="text" id="color" placeholder="Color">
</div>
</div>
<div class="envoltorio-btn-enviar">
<button class="btn-enviar" type="submit">Enviar</button>
</div>
</div>
</form>
</main>
<footer class="d-flex align-items-center justify-content-center flex-column">
<section id="contacto">
<h1 class="my-4">Veterinaria online</h1>
<p class="my-4 p-footer">Somos Veterinaria Online, con más de 20 años de trayectoria en el rubro. Contamos con un gran equipo ; disponibles para asesorarte cuando lo necesites. Trabajamos para hacer más sencilla y placentera tu experiencia de compra, simplificando la transacción con simple pasos.</p>
</section>
<div class="ultimo-footer">
<div class="envoltorio-iconos mb-4">
<div>
<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" fill="currentColor" class="bi bi-phone"
viewBox="0 0 16 16">
<path
d="M11 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h6zM5 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H5z" />
<path d="M8 14a1 1 0 1 0 0-2 1 1 0 0 0 0 2z" />
</svg>
<div >
<span>Celular</span>
<span>3517804796</span>
</div>
</div>
<div>
<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" fill="currentColor" class="bi bi-calendar-plus"
viewBox="0 0 16 16">
<path
d="M8 7a.5.5 0 0 1 .5.5V9H10a.5.5 0 0 1 0 1H8.5v1.5a.5.5 0 0 1-1 0V10H6a.5.5 0 0 1 0-1h1.5V7.5A.5.5 0 0 1 8 7z" />
<path
d="M3.5 0a.5.5 0 0 1 .5.5V1h8V.5a.5.5 0 0 1 1 0V1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h1V.5a.5.5 0 0 1 .5-.5zM1 4v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V4H1z" />
</svg>
<div>
<span>Turnero</span>
<span>Solicite turno online</span>
</div>
</div>
</div>
</div>
</footer>
</body>
</html>
|
/**
* Take an array of data and turn it into an encoded audio data.
*
* Designed for the Audioino boot loader.
* See: http://www.hobby-roboter.de/forum/viewtopic.php?f=4&t=128&p=531
*
*
* Copyright (c) 2012 Michael Conrad Tadpol Tilstra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function(tadAvrAsm, undefined ) {
/**
* Converts an array of program data into a manchester encoded signal array.
*/
function numsToSignal(hexes) {
/* The format that the Audioino boot loader expects seems to be as follows:
* The wave data is broken into frames.
* Each Frame is Frame header, followed by data, followed by silence.
* There are two kinds of Frames: A Page Frame, and a Run Frame.
* - The Run Frame leaves the boot loader and runs the application.
* - A Page Frame loads a page of data to be burned to flash.
*
* A Frame header is 5 bytes: Command, Page Index (2bytes), CRC (2bytes)
*
* Then the whole frame is Manchester Encoded with a sync sequence and a start bit.
*/
/* Some private functions for this */
/**
* Append a block of silence
* At 44100, this is about 1/100th of a second.
*/
function appendSilence(signal) {
for(var i=0; i < 441; i++) {
signal.push(0);
}
}
/**
* Appends a single Manchester encoded bit onto signal.
*/
function encodeEdge(edge, signal) {
var val = edge?-1:1;
signal.push( -val );
signal.push( -val );
signal.push( val );
signal.push( val );
}
/**
* Encodes by Manchester and appends a frame to signal.
* Also adds a Start Sequence an Start bit for synchronising.
*/
function encodeFrame(frame, signal) {
var i;
/* Generate Start sequence */
for(i=0; i < 40; i++) {
encodeEdge(false, signal);
}
/* Generate start pulse */
encodeEdge(true, signal);
var d;
for(i=0; i < frame.length; i++) {
if( !(i in frame) || typeof frame[i] == 'undefined') {
d = 0;
} else {
d = frame[i];
}
for(var j=0; j < 8; j++) {
encodeEdge( ((d&0x80)!=0), signal);
d = d << 1;
}
}
}
var signal = new Array();
/* Convert data into Page Frames */
for(var i=0; i < hexes.length;) {
/* Skip over gaps. ?better way to do this? */
if( !(i in hexes) ) {
continue;
}
var pageIdx = i >> 7; /* Convert byte location to page index. */
var frame = new Array();
frame.push(2); // Program Page Command
frame.push(pageIdx&0xff); // Page Index Lo.
frame.push((pageIdx>>8)&0xff); // Page Index Hi.
/* Not a true CRC. Is actually a Magic Number. Always 0x55AA */
frame.push(0xaa); // CRC Lo.
frame.push(0x55); // CRC Hi.
for(var j=0; j < 128 ; j++, i++ ) {
if( i in hexes ) {
frame.push( hexes[i] );
} else {
frame.push( 0xff );
}
}
encodeFrame(frame, signal);
appendSilence(signal);
}
/* Append a Run Frame */
var frame = new Array();
frame.push(3); // Run Command
frame.push(0); // Page Index Lo.
frame.push(0); // Page Index Hi.
/* Not a true CRC. Is actually a Magic Number. Always is 0x55AA */
frame.push(0xaa); // CRC Lo.
frame.push(0x55); // CRC Hi.
for(var j=0; j < 128; j++) {
frame.push(0);
}
encodeFrame(frame, signal);
return signal;
}
/**
* Convert array into WAV data
*
* Assumes array is of values: -1,0,1
*
* Based on code from sk89q
* See: http://www.sk89q.com/2008/11/dynamically-generating-a-wav-in-javascript/
*/
function signalToWave(signal) {
var channels = 2;
var sampleRate = 44100;
var bitsPerSample = 16;
function packLE16(arg) {return String.fromCharCode(arg & 255, (arg >> 8) & 255);}
function packLE32(arg) {
return String.fromCharCode(arg & 255, (arg >> 8) & 255, (arg >> 16) & 255, (arg >> 24) & 255);
}
var data = new Array();
for(var i=0; i < signal.length; i++) {
var v = signal[i] * 32767;
/* push twice, once for each channel */
data.push( packLE16(v) );
data.push( packLE16(v) );
}
// Format sub-chunk
var chunk1 = [
"fmt ", // Sub-chunk identifier
packLE32(16), // Chunk length
packLE16(1), // Audio format (1 is linear quantization)
packLE16(channels),
packLE32(sampleRate),
packLE32(sampleRate * channels * bitsPerSample / 8), // Byte rate
packLE16(channels * bitsPerSample / 8),
packLE16(bitsPerSample)
].join('');
// Data sub-chunk (contains the sound)
var chunk2 = [
"data", // Sub-chunk identifier
packLE32(signal.length * channels * bitsPerSample / 8), // Chunk length
data.join('')
].join('');
// Header
var header = [
"RIFF",
packLE32(4 + (8 + chunk1.length) + (8 + chunk2.length)), // Length
"WAVE"
].join('');
var wave = [header, chunk1, chunk2].join('');
return wave;
}
/**
* Convert the hexes array into one of numbers.
*/
function hexesToNums(hexes) {
var da = [];
var spl = /(..)(..)/;
var md;
for(var i=0; i < hexes.length; i+=2) {
/* skip over gaps */
if( !(i in hexes) ) {
continue;
}
md = hexes[i].match(spl);
if(md == null) throw ("Not a string in hexes! at " + i);
/* push right side first for little Endian */
da[i] = parseInt(md[2], 16);
da[i+1] = parseInt(md[1], 16);
}
return da;
}
/**
* Add a new output mode.
*/
tadAvrAsm.outModes.audioino = function(state) {
var da = hexesToNums(state.bytes);
var sig = numsToSignal(da);
var wav = signalToWave(sig);
return wav;
}
/**
* Convert wave to base64 and twist into an URI, then play.
*/
tadAvrAsm.playWaveData = function(wave) {
var dataURI = "data:audio/wav;base64," + escape(btoa(wave));
var audio = new Audio(dataURI);
audio.play();
}
/**
* Convert wave to base64 and twist into an URI, then open.
*/
tadAvrAsm.openWaveData = function(wave) {
var dataURI = "data:audio/wav;base64," + escape(btoa(wave));
open(dataURI);
}
}( window.tadAvrAsm = window.tadAvrAsm || {} ));
/* vim: set cin sw=4 ts=4 noet : */
|
<script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>
<script>
$(() => {
$('li').map((i, e) => console.log(i, e)) // map - each와 사용법은 동일하다.
let collection = $('li').map((i, e) => e.id) // 변수로 받을때는, 받을 값을 지정해줘야한다.
console.log(collection)
console.log(collection.get()) // get() - collection을 toArray가 아닌 array로 변환시키는 2번째 방법
// 과제: 위 get() return array 를 'abc'로 serializing 하라.
console.log(collection.get().join(''))
//map utility
// 주의) each utility와는 다르게 순서가 element, index 순이다.
$.map(collection.get(), (e, i) => console.log(i, e))
// 여기서도 마찬가지로 순서가 value, key순이다.
let array = $.map({name: 'adelia', age: 20}, (v, k) => v)
console.log(array)
})
</script>
<ul>
<li id='a'>A</li>
<li id='b'>B</li>
<li id='c'>C</li>
</ul>
|
// class Animal{
// constructor (name) {
// this.name = name;
// }
// speaks() {
// console.log(`${this.name} makes a noise`);
// }
// }
// class Dog extends Animal {
// constructor (name) {
// super(name); // call the superclass and pass in the name parameter
// }
// speak() {
// console.log(`${this.name} barks`);
// }
// }
// const d = new Dog('Mitzie');
// d.speak();
// d.speaks();
/* NOTE IF THERE IS A CONSTRUCTOR PRESENT IN THE SUBCLASS , IT NEEDS TO FIRST CALL SUPER() BEFORE USING this. THE SUPER() KEYWORD CAN ALSO BE USED TO CALL CORRESPONDING METHODS OF SUPER CLASS */
// class Cat {
// constructor(name) {
// this.name = name;
// }
// speak() {
// console.log(`${this.name} makes a noise`)
// }
// }
// // f there is a constructor present in the subclass, it needs to first call super() before using this. The super keyword can also be used to call corresponding methods of super class.
// class Lion extends Cat {
// speak() {
// super.speak();
// console.log(`${this.name} roars`);
// }
// }
// const l = new Lion("fuzzy")
// l.speak();
// class Animal {
// speak() {
// return this;
// }
// static eat() {
// return this;
// }
// }
// const obj = new Animal();
// obj.speak();
// const speak = obj.speak;
// speak();
// Animal.eat();
// const eat = Animal.eat;
// eat();
class C {
#x;
constructor(x) {
this.#x = x;
}
static getX(obj) {
if(#x in obj) return obj.#x;
return "obj must be an instnce of C"
}
}
console.log(C.getX(new C('foo')));
console.log(C.getX(new C(0.196)));
console.log(C.getX(new C(new Date())));
console.log(C.getX({}));
|
from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape("turtle")
self.color("white")
self.penup()
self.go_to_start()
self.left(90)
def go_up(self):
new_y = self.ycor() + MOVE_DISTANCE
self.goto(self.xcor(), new_y)
def go_to_start(self):
self.goto(STARTING_POSITION)
# 4. Detect when turtle reaches other side
def is_at_finish_line(self):
if self.ycor() > FINISH_LINE_Y:
return True
else:
return False
|
import { FC } from 'react';
export interface SkeletonProps {
className?: string;
rounded?: 'full' | '2xl' | 'xl' | 'lg' | 'md' | 'sm';
backgroundColor?: string;
}
export const Skeleton: FC<SkeletonProps> = ({
className,
rounded = 'lg',
backgroundColor = 'bg-light-active',
}) => {
return (
<div
className={`animate-pulse ${
rounded ? 'rounded-' + rounded : ''
} ${className} ${backgroundColor}`}
/>
);
};
|
import { useCallback, useState } from "react";
import { Button } from "@chakra-ui/react";
import { CopyToClipboard } from "react-copy-to-clipboard";
import {
Clipboard as ClipboardIcon,
ClipboardCheckFill as ClipboardCheckFillIcon,
ClipboardXFill as ClipboardXFillIcon,
} from "@chakra-icons/bootstrap";
export default function CopyButton({ valueToCopy }: { valueToCopy: string }) {
const [buttonText, setButtonText] = useState("Copy");
const [buttonIcon, setButtonIcon] = useState(<ClipboardIcon />);
const onCopy = useCallback(() => {
if (valueToCopy) {
console.log(valueToCopy);
setButtonText("Copied!");
setButtonIcon(<ClipboardCheckFillIcon />);
} else {
setButtonText("No value");
setButtonIcon(<ClipboardXFillIcon />);
}
setTimeout(() => {
setButtonText("Copy");
setButtonIcon(<ClipboardIcon />);
}, 3000);
}, [valueToCopy]);
return (
<CopyToClipboard onCopy={onCopy} text={valueToCopy}>
<Button leftIcon={buttonIcon}>{buttonText}</Button>
</CopyToClipboard>
);
}
|
package com.doctopdf
import android.app.Activity
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.doctopdf.helpers.CustomArrayAdapter
import com.doctopdf.services.FileService
import com.example.doctopdf.R
import com.example.doctopdf.databinding.ActivityMainBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import java.io.File
class FileManager : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nearbyShare, R.id.createdDocumentsFragment, R.id.savedDocumentsFragment
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
val searchDir = arrayListOf<File>(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS))
val files = FileService.getPDFFiles(searchDir)
val listView = findViewById<ListView>(R.id.pdf_documents_list)
val adapter = CustomArrayAdapter(this, R.layout.list_item_file, files)
listView.adapter = adapter
}
}
|
import React, { useState, useEffect, useCallback } from "react";
import { useFocusEffect, useIsFocused } from '@react-navigation/native';
import { View, Text, TouchableOpacity, Image } from "react-native";
import Slider from "@react-native-community/slider";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import {
faPlay,
faPause,
faBackward,
faForward,
faRepeat,
} from "@fortawesome/free-solid-svg-icons";
import colours from "../config/colours.js";
import { styles } from "../styles/playerStyles.js";
function AudioPlayerComponent(props) {
const {
audio,
songInfo,
duration,
isPlaying,
setIsPlaying,
elapsedTime,
setElapsedTime,
onTrackFinish,
onTrackPrev
} = props;
const [position, setPosition] = useState(0);
const [isLooping, setIsLooping] = useState(false);
const [trackFinished, setTrackFinished] = useState(false);
const isFocused = useIsFocused();
useFocusEffect(
useCallback(() => {
return () => {
const stopAudio = async () => {
if(audio && isPlaying) {
await audio.pauseAsync();
setIsPlaying(false);
}
}
stopAudio();
};
}, [audio, isPlaying, isFocused])
);
useEffect(() => {
if (audio) {
audio.setOnPlaybackStatusUpdate((status) => {
setPosition(status.positionMillis);
const totalSeconds = Math.floor(status.positionMillis / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
setElapsedTime(
`${minutes}:${seconds < 10 ? "0" : ""}${seconds}`
);
if (status.didJustFinish) {
if (isLooping) {
// TODO: increase rating for this track by 1
audio.replayAsync(); // Replay track if isLooping is true
} else {
setTrackFinished(true); // Set trackFinished to true if the track has finished
}
}
});
}
}, [audio, isLooping]); // add audio and isLooping as dependency
useEffect(() => {
if (trackFinished) {
onTrackFinish(); // Call onTrackFinish when trackFinished is true
setTrackFinished(false); // Reset trackFinished to false
}
}, [trackFinished, onTrackFinish]);
const togglePlayPause = async () => {
if (!audio) return;
if (isPlaying) {
await audio.pauseAsync();
} else {
const playbackStatus = await audio.playAsync();
setPosition(playbackStatus.positionMillis);
}
setIsPlaying(!isPlaying);
};
const handleSliderValueChange = async (value) =>
{
if (audio)
await audio.setPositionAsync(value);
};
return (
<View style={styles.topContainer}>
<Text style={styles.title}>Project FUXI</Text>
<View style={styles.musicInfoContainer}>
<Image
style={styles.coverImage}
source={{ uri: songInfo.imgUri }}
/>
<Text style={styles.songName} numberOfLines={1}>
{songInfo.title}
</Text>
<View style={styles.progressBarContainer}>
<Slider
style={styles.slider}
minimumValue={0}
maximumValue={duration}
value={position}
onSlidingComplete={handleSliderValueChange}
minimumTrackTintColor="#3d5875"
maximumTrackTintColor="#d3d3d3"
thumbTintColor="#3d5875"
/>
<Text style={styles.elapsedTime}>{elapsedTime}</Text>
</View>
<View style={styles.controlsContainer}>
<TouchableOpacity
style={styles.button}
onPress={() => onTrackPrev()}
>
<FontAwesomeIcon icon={faBackward} size={20} />
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => {
setIsLooping(!isLooping);
}}
>
<FontAwesomeIcon icon={faRepeat} size={20} />
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={togglePlayPause}
>
<FontAwesomeIcon
icon={isPlaying ? faPause : faPlay}
size={20}
/>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => {
if (isLooping) audio.replayAsync();
else onTrackFinish();
}} // Call onTrackFinish directly instead of using a flag
>
<FontAwesomeIcon icon={faForward} size={20} />
</TouchableOpacity>
</View>
<Text
style={[
{
color: isLooping
? colours.primary
: colours.secondary,
},
styles.loopText,
]}
>
Loop: {isLooping ? "On" : "Off"}
</Text>
</View>
</View>
);
}
export default AudioPlayerComponent;
|
# Frontend Mentor - Sunnyside agency landing page solution
This is a solution to the [Sunnyside agency landing page challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/sunnyside-agency-landing-page-7yVs3B6ef). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [Built with](#built-with)
- [What I learned](#what-i-learned)
- [Useful resources](#useful-resources)
- [Author](#author)
## Overview
A landing page built with HTML, CSS and basic Javascript.
### The challenge
Users should be able to:
- View the optimal layout for the site depending on their device's screen size
- See hover states for all interactive elements on the page
### Screenshot

### Links
- Solution URL: (https://https://www.frontendmentor.io/solutions/responsive-landing-page-using-plain-css-AdGki6xFjQ)
- Live Site URL: (https://susu-spec.github.io/sunny-side-landing-page/)
### Built with
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- CSS Grid
- Mobile-first workflow
### What I learned
```html
<div class="bottles">
<img src="images/mobile/image-gallery-milkbottles.jpg" alt="Picture of bottles of milk">
</div>
<div class="desktop__bottles">
<img src="images/desktop/image-gallery-milkbottles.jpg" alt="Picture of bottles of milk">
</div>
```
```css
a {
cursor: pointer;
display: inline-block;
}
path:hover,
path:active {
fill: white;
}
```
### Useful resources
- [Resource 1](https://css-tricks.com/change-color-of-svg-on-hover/) - Changing the svg color in its hover state.
- [Resource 2](https://stackoverflow.com/questions/4476526/do-i-use-img-object-or-embed-for-svg-files) - I ended up sticking to the classic svg tag but this was helpful to learn anyway.
## Author
- Frontend Mentor - [@Susu-spec](https://www.frontendmentor.io/profile/Susu-spec)
- Twitter - [@actual_susu](https://www.twitter.com/actual_susu)
|
import {Service} from '@prisma/client'
import Link from 'next/link';
import PriceTag from './PriceTag';
import Image from "next/image";
interface ServiceCardProps {
service: Service;
}
export default function ServiceCard({service}: ServiceCardProps) {
const isNew = Date.now() - new Date(service.createdAt).getTime() <
1000 * 60 * 60 * 24 * 7;
return(
<Link
href={'/services/' + service.id}
className='card w-full bg-base-100 hover: shadow-xl transition-shadow'
>
<figure>
<Image
src={service.imageURL}
alt={service.name}
width={800}
height={400}
className='h-48 object-cover'
/>
</figure>
<div className='card-body'>
<h2 className='card-title'>
{service.name}
{isNew && <div className='badge badge-secondary'>NUEVO</div>}
</h2>
<p>{service.description}</p>
<PriceTag price={service.price} />
</div>
</Link>
)
}
|
.equ EDGE_TRIGGERED, 0x1
.equ LEVEL_SENSITIVE, 0x0
.equ CPU0, 0x01 // bit-mask; bit 0 represents cpu0
.equ ENABLE, 0x1
.equ KEY0, 0b0001
.equ KEY1, 0b0010
.equ KEY2, 0b0100
.equ KEY3, 0b1000
.equ IRQ_MODE, 0b10010
.equ SVC_MODE, 0b10011
.equ INT_ENABLE, 0b01000000
.equ INT_DISABLE, 0b11000000
/*********************************************************************************
* Initialize the exception vector table
********************************************************************************/
.section .vectors, "ax"
B _start // reset vector
.word 0 // undefined instruction vector
.word 0 // software interrrupt vector
.word 0 // aborted prefetch vector
.word 0 // aborted data vector
.word 0 // unused vector
B IRQ_HANDLER // IRQ interrupt vector
.word 0 // FIQ interrupt vector
/* ********************************************************************************
* This program demonstrates use of interrupts with assembly code. The program
* responds to interrupts from a timer and the pushbutton KEYs in the FPGA.
*
* The interrupt service routine for the timer increments a counter that is shown
* on the red lights LEDR by the main program. The counter can be stopped/run by
* pressing any of the KEYs.
********************************************************************************/
.text
.global _start
_start:
/* Set up stack pointers for IRQ and SVC processor modes */
MOV R1, #0b11010010 // interrupts masked, MODE = IRQ
MSR CPSR_c, R1 // change to IRQ mode
LDR SP, =0x40000 // set IRQ stack pointer
/* Change to SVC (supervisor) mode with interrupts disabled */
MOV R1, #0b11010011 // interrupts masked, MODE = SVC
MSR CPSR, R1 // change to supervisor mode
LDR SP, =0x20000 // set SVC stack
BL CONFIG_GIC // configure the ARM generic
// interrupt controller
BL CONFIG_PRIV_TIMER // configure A9 Private Timer
BL CONFIG_KEYS // configure the pushbutton
// KEYs port
/* Enable IRQ interrupts in the ARM processor */
MOV R0, #0b01010011 // IRQ unmasked, MODE = SVC
MSR CPSR, R0
LDR R5, =0xFF200000 // LEDR base address
LOOP:
LDR R3, COUNT // global variable
STR R3, [R5] // write to the LEDR lights
B LOOP
/* Global variables */
.global COUNT
COUNT: .word 0x0 // used by timer
.global RUN
RUN: .word 0x1 // initial value to increment COUNT
/* Configure the A9 Private Timer to create interrupts at 0.25 second intervals */
CONFIG_PRIV_TIMER:
LDR R1, =0xFFFEC600 // load address of A9 timer
LDR R0, =50000000 // load value to count down from
STR R0, [R1] // load the load value in the timer
MOV R0, #0b111
STR R0, [R1, #0x8] // auto reload timer, enable interrupt, and enable timer.
MOV PC, LR
/* Configure the pushbutton KEYS to generate interrupts */
CONFIG_KEYS:
// write to the pushbutton KEY interrupt mask register
LDR R0, =0xFF200050 // pushbutton KEY base address
MOV R1, #0xF // set interrupt mask bits
STR R1, [R0, #0x8] // interrupt mask register is (base + 8)
MOV PC, LR
/*--- IRQ ---------------------------------------------------------------------*/
IRQ_HANDLER:
PUSH {R0-R7, LR}
/* Read the ICCIAR in the CPU interface */
LDR R4, =0xFFFEC100
LDR R5, [R4, #0x0C] // read the interrupt ID
CMP R5, #73 // check if interrupt is from pushbuttons
BLEQ KEY_ISR
CMP R5, #29 // check if interrupt is from timer
BLEQ PRIV_TIMER_ISR
/* Write to the End of Interrupt Register (ICCEOIR) */
STR R5, [R4, #0x10]
POP {R0-R7, LR}
SUBS PC, LR, #4
/****************************************************************************************
* Pushbutton - Interrupt Service Routine
*
* This routine toggles the RUN global variable.
***************************************************************************************/
.global KEY_ISR
KEY_ISR: LDR R3, =0xFF200050
LDR R2, [R3, #0xC] // get value of edgecapture register
CMP R2, #1 // check for key 0
BEQ KEY_0
CMP R2, #2 // check for key 1
BEQ KEY_1
CMP R2, #4 // check for key 2
BEQ KEY_2
KEY_0: LDR R1, =RUN // get address of the run memory location
LDR R0, [R1] // load value of run increment value
CMP R0, #1 // check if run is 1
MOVEQ R0, #0 // set it to 0 if it is 1
MOVNE R0, #1 // else set it to 1
STR R0, [R1] // update the run value
B CONTINUE
KEY_1: LDR R1, =0xFFFEC600 // store the address of the timer
MOV R0, #0b110
STR R0, [R1, #0x8] // disable the timer
LDR R0, [R1] // get the load value
LSL R0, #1 // shift by 1 to the left to double the value
STR R0, [R1] // update the load value
MOV R0, #0b111
STR R0, [R1, #0x8] // enable the timer
B CONTINUE
KEY_2: LDR R1, =0xFFFEC600 // store the address of the timer
MOV R0, #0b110
STR R0, [R1, #0x8] // disable the timer
LDR R0, [R1] // get the load value
LSR R0, #1 // shift by 1 to the right to halve the value
STR R0, [R1] // update the load value
MOV R0, #0b111
STR R0, [R1, #0x8] // enable the timer
B CONTINUE
CONTINUE: LDR R2, [R3, #0xC]
STR R2, [R3, #0xC]
MOV PC, LR
/******************************************************************************
* A9 Private Timer interrupt service routine
*
* This code toggles performs the operation COUNT = COUNT + RUN
*****************************************************************************/
.global TIMER_ISR
PRIV_TIMER_ISR:
LDR R1, =COUNT // get the address of the count memory location
LDR R0, [R1] // load value at count memory location
LDR R3, =0x3FF
CMP R0, R3 // check if all leds are on
MOVEQ R0, #0 // reset the count to 0 if all leds are on
BEQ UPDATE_COUNT
LDR R2, RUN // load value of run increment
ADD R0, R2 // add count with run increment
UPDATE_COUNT: STR R0, [R1] // store the new count into the count memory location
// reset the status on the timer
LDR R0, =0xFFFEC600
MOV R3, #1
STR R3, [R0, #0xC]
MOV PC, LR
/*
* Configure the Generic Interrupt Controller (GIC)
*/
.global CONFIG_GIC
CONFIG_GIC:
PUSH {LR}
MOV R0, #29
MOV R1, #CPU0
BL CONFIG_INTERRUPT
/* Enable the KEYs interrupts */
MOV R0, #73
MOV R1, #CPU0
/* CONFIG_INTERRUPT (int_ID (R0), CPU_target (R1)); */
BL CONFIG_INTERRUPT
/* configure the GIC CPU interface */
LDR R0, =0xFFFEC100 // base address of CPU interface
/* Set Interrupt Priority Mask Register (ICCPMR) */
LDR R1, =0xFFFF // enable interrupts of all priorities levels
STR R1, [R0, #0x04]
/* Set the enable bit in the CPU Interface Control Register (ICCICR). This bit
* allows interrupts to be forwarded to the CPU(s) */
MOV R1, #1
STR R1, [R0]
/* Set the enable bit in the Distributor Control Register (ICDDCR). This bit
* allows the distributor to forward interrupts to the CPU interface(s) */
LDR R0, =0xFFFED000
STR R1, [R0]
POP {PC}
/*
* Configure registers in the GIC for an individual interrupt ID
* We configure only the Interrupt Set Enable Registers (ICDISERn) and Interrupt
* Processor Target Registers (ICDIPTRn). The default (reset) values are used for
* other registers in the GIC
* Arguments: R0 = interrupt ID, N
* R1 = CPU target
*/
CONFIG_INTERRUPT:
PUSH {R4-R5, LR}
/* Configure Interrupt Set-Enable Registers (ICDISERn).
* reg_offset = (integer_div(N / 32) * 4
* value = 1 << (N mod 32) */
LSR R4, R0, #3 // calculate reg_offset
BIC R4, R4, #3 // R4 = reg_offset
LDR R2, =0xFFFED100
ADD R4, R2, R4 // R4 = address of ICDISER
AND R2, R0, #0x1F // N mod 32
MOV R5, #1 // enable
LSL R2, R5, R2 // R2 = value
/* now that we have the register address (R4) and value (R2), we need to set the
* correct bit in the GIC register */
LDR R3, [R4] // read current register value
ORR R3, R3, R2 // set the enable bit
STR R3, [R4] // store the new register value
/* Configure Interrupt Processor Targets Register (ICDIPTRn)
* reg_offset = integer_div(N / 4) * 4
* index = N mod 4 */
BIC R4, R0, #3 // R4 = reg_offset
LDR R2, =0xFFFED800
ADD R4, R2, R4 // R4 = word address of ICDIPTR
AND R2, R0, #0x3 // N mod 4
ADD R4, R2, R4 // R4 = byte address in ICDIPTR
/* now that we have the register address (R4) and value (R2), write to (only)
* the appropriate byte */
STRB R1, [R4]
POP {R4-R5, PC}
.end
|
import os
import numpy as np
import time
import warnings
import xarray as xa
import argparse
from pathlib import Path
import re
from cdo import Cdo
from cmipper import config, utils, downloading, file_ops
"""
Script to download monthly-averaged CMIP6 climate simulation runs from the Earth
System Grid Federation (ESFG):
https://esgf-node.llnl.gov/search/cmip6/.
The simulations are regridded from latitude/longitude...
The --source_id and --member_id command line inputs control which climate model
and model run to download.
The `model_dict` dictates which variables to download from each climate
model. Entries within the variable dictionaries of `variable_dict` provide
further specification for the variable to download - e.g. whether it is on an
ocean grid and whether to download data at a specified pressure level. All this
information is used to create the `query` dictionary that is passed to
downloading.esgf_search to find download links for the variable. The script loops
through and downloads each variable specified in the variable dictionary.
Variable files are saved to relevant folders beneath cmip6/<source_id>/<member_id>/
directory.
See download_cmip6_data_in_parallel.sh to download and regrid multiple climate
simulations in parallel using this script.
# TODO: add notebook option
"""
# Ignore "Missing CF-netCDF variable" warnings from download
warnings.simplefilter("ignore", UserWarning)
# Download function
################################################################################
def download_cmip_variable_data(
source_id: str,
member_id: str,
variable_id: str,
):
"""
This downloads a single variable, for however many experiments are specified in the source_id_dict.
"""
# read download values
source_id_dict = utils.read_yaml(config.model_info)[source_id]
download_config_dict = utils.read_yaml(config.download_config)
# TODO: parallelise by source_id and member_id
variable_id_dict = source_id_dict["variable_dict"][variable_id]
# spatial values
LATS = sorted(download_config_dict["lats"])
LONS = sorted(download_config_dict["lons"])
INT_LATS = [int(lat) for lat in LATS]
INT_LONS = [int(lon) for lon in LONS]
LEVS = sorted([abs(val) for val in download_config_dict["levs"]])
RESOLUTION = source_id_dict["resolution"]
# processing values
do_regrid = download_config_dict["processing"]["do_regrid"]
do_delete_og = download_config_dict["processing"]["do_delete_og"]
do_crop = download_config_dict["processing"]["do_crop"]
if do_crop and not do_regrid:
print("WARNING: cropping without regridding may lead to unexpected results")
# file setting
download_dir = (
config.cmip6_data_dir / source_id / member_id / "newtest"
) # TODO: remove testing folder
if not download_dir.exists():
download_dir.mkdir(parents=True, exist_ok=True)
tic = time.time()
print(f"TIME CREATED: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tic))}")
print(f"\nProcessing data for {source_id}, {member_id}, {variable_id}\n")
# BUILD QUERY
query = {
"source_id": source_id,
"member_id": member_id,
"frequency": source_id_dict["frequency"],
"variable_id": variable_id,
"table_id": variable_id_dict["table_id"],
}
if (
"ocean_variable" in variable_id_dict.keys()
): # this originally included "or EC-Earth3" (lower-res version)
# TODO: figure out what this is doing. May be redundant
query["grid_label"] = "gr"
else:
query["grid_label"] = "gn"
print("\n\n{}: ".format(variable_id), end="", flush=True)
print("searching ESGF servers... \n", end="", flush=True)
results = []
for experiment_id in source_id_dict["experiment_ids"]:
query["experiment_id"] = experiment_id
experiment_id_results = []
for data_node in source_id_dict["data_nodes"]:
query["data_node"] = data_node
# EXECUTE QUERY
experiment_id_results.extend(downloading.esgf_search(**query))
# Keep looping over possible data nodes until the experiment data is found
if len(experiment_id_results) > 0:
print("\nfound {}, ".format(experiment_id), end="", flush=True)
results.extend(experiment_id_results)
break # Break out of the loop over data nodes when data found
results = list(set(results)) # remove any duplicate values
YEAR_RANGE = sorted(download_config_dict["experiment_ids"][experiment_id])
# skip any unrequired dates
relevant_results = file_ops.find_files_for_time(results, year_range=YEAR_RANGE)
print(
f"""found {len(results)} files on {data_node} node of which {len(relevant_results)}
fall(s) within required date range.""".format(
end="", flush=True
)
)
# SET UP FILE PATHS REFERENCING
fpaths_og = {}
fpaths_regridded = {}
plevels = (
list(variable_id_dict["plevels"])
if not isinstance(variable_id_dict["plevels"], list)
else variable_id_dict["plevels"]
)
for plevel in plevels:
# reset indices for each level
seafloor_indices = None
failed_regrids = []
print("downloading individual files... ", flush=True)
ind_download_dir = download_dir / "og_grid" / variable_id
if not ind_download_dir.exists():
ind_download_dir.mkdir(parents=True, exist_ok=True)
for i, result in enumerate(relevant_results):
date_range = result.split("_")[-1].split(".")[0]
fname_og = utils.FileName(
variable_id=variable_id,
grid_type="tripolar", # TODO: get this info from the associated dataset
fname_type="individual",
levs=LEVS,
date_range=date_range,
plevels=plevel,
).construct_fname()
print(
f"\n{i}: handling {fname_og}",
flush=True,
)
save_fp = ind_download_dir / fname_og
if save_fp.exists():
print(
f"\t{i}: skipping download due to existing file: {save_fp}",
flush=True,
)
fpaths_og[i] = save_fp
else:
# OPEN AND SELECT CORRECT PRESSURE LEVELS
if not plevel: # if surface variable: chunk by time
ds = xa.open_dataset(
result, decode_times=True, chunks={"time": "499MB"}
)[variable_id]
else: # if seafloor or specified pressure, open with limited levels, chunked spatially
ds = xa.open_dataset(
result,
decode_times=True, # not all times easily decoded
chunks={"i": "499MB"},
).isel(lev=slice(min(LEVS), max(LEVS)))
if plevel == -1: # if seafloor
if (
seafloor_indices is None
): # if seafloor indices not yet calculated, calculate
print("\tdetermining seafloor indices... ", flush=True)
seafloor_indices = utils.gen_seafloor_indices(
ds.isel(time=0),
var=variable_id,
)
seafloor_indices = np.broadcast_to(
seafloor_indices,
(
len(ds.time),
len(ds.j),
len(ds.i),
), # these variable names may differ by model
)
print("\textracting seafloor values...\n", flush=True)
cmip6_array = utils.extract_seafloor_vals(
ds[variable_id], seafloor_indices
)
ds[variable_id] = (["time", "j", "i"], cmip6_array)
else: # if surface
print(
f"extracting {plevel / 100:.03f} hPa",
flush=True,
)
ds = ds.sel(lev=plevel)[variable_id]
print(
f"\t{i}: saving {fname_og} file: {save_fp}",
flush=True,
)
fpaths_og[i] = save_fp
# TODO: change dtype?
ds.to_netcdf(save_fp)
if do_regrid:
regrid_dir_fp = download_dir / "regridded" / variable_id
if not regrid_dir_fp.exists():
regrid_dir_fp.mkdir(parents=True, exist_ok=True)
remap_template_fp = (
config.cmip6_data_dir
/ source_id
/ f"{source_id}_remap_template.txt"
)
if not remap_template_fp.exists():
utils.generate_remapping_file(
ds,
remap_template_fp=remap_template_fp,
resolution=RESOLUTION,
out_grid="latlon",
)
# initialise instance of Cdo for regridding
cdo = Cdo()
fname_regrid = utils.FileName(
variable_id=variable_id,
grid_type="latlon",
fname_type="individual",
plevels=plevel,
levs=LEVS,
date_range=date_range,
).construct_fname()
# add to list of regridded files
fpaths_regridded[i] = regrid_dir_fp / fname_regrid
if not fpaths_regridded[i].exists():
print(f"\t{i}: regridding to {fpaths_regridded[i]}...")
try:
cdo.remapbil( # TODO: different types of regridding. Will have to update filenames
str(remap_template_fp),
input=str(fpaths_og[i]),
output=str(fpaths_regridded[i]),
)
except: # noqa # TODO: find proper exception
print(
f"regridding failed for {fpaths_og[i]}, skipping...",
flush=True,
)
failed_regrids.append(fpaths_og[i])
continue
else:
print(
f"\t{i}: skipping regrid due to existing file: {fpaths_regridded[i]}",
flush=True,
)
# TODO: process_xa_d on these files then re-waving
if do_delete_og:
print(fpaths_og[i])
os.remove(fpaths_og[i])
ds = xa.open_dataset(fpaths_regridded[i])
if do_crop:
cropped_dir_name = f"cropped_{utils.lat_lon_string_from_tuples(INT_LATS, INT_LONS).upper()}"
cropped_dir_fp = (
download_dir / "regridded" / cropped_dir_name / variable_id
)
if not cropped_dir_fp.exists():
cropped_dir_fp.mkdir(parents=True, exist_ok=True)
fname_cropped = utils.FileName(
variable_id=variable_id,
grid_type="latlon",
fname_type="individual",
lats=INT_LATS,
lons=INT_LONS,
levs=LEVS,
plevels=plevel,
date_range=date_range,
).construct_fname()
cropped_save_fp = cropped_dir_fp / fname_cropped
if not cropped_save_fp.exists():
# N.B. may be different between models, and may need to include levs
ds = utils.process_xa_d(ds).sel(
latitude=slice(min(LATS), max(LATS)),
longitude=slice(min(LONS), max(LONS)),
)
print(
f"\t{i}: saving {fname_cropped} file: {cropped_save_fp}",
flush=True,
)
# TODO: change dtype?
ds.to_netcdf(cropped_save_fp)
else:
print(
f"\t{i}: skipping cropping due to existing file: {cropped_save_fp}",
flush=True,
)
download_tic = time.time() - tic
actions_undertaken = [
action
for action, flag in [("regridding", do_regrid), ("cropping", do_crop)]
if flag
]
message = (
f"Downloading/{'/'.join(actions_undertaken)}"
if actions_undertaken
else "Downloading"
)
print(
f"\n{message} took {np.floor(download_tic / 60):.0f}m:{download_tic % 60:.0f}s."
)
print(
f"\n{len(failed_regrids)} regrids failed.\n"
if len(failed_regrids) == 0
else f"\n{len(failed_regrids)} regrids failed. The following are likely corrupted: \n{failed_regrids}\n"
)
# Processing (concatenation by time, merging by variables) functions
################################################################################
def concat_cmip_files_by_time(source_id, experiment_id, member_id, variable_id):
download_dir = (
config.cmip6_data_dir / source_id / member_id / "newtest"
) # TODO: remove testing folder
source_id_dict = utils.read_yaml(config.model_info)[source_id]
download_config_dict = utils.read_yaml(config.download_config)
DO_CROP = download_config_dict["processing"]["do_crop"]
LATS = sorted(download_config_dict["lats"])
LONS = sorted(download_config_dict["lons"])
INT_LATS = [int(lat) for lat in LATS]
INT_LONS = [int(lon) for lon in LONS]
LEVS = sorted([abs(val) for val in download_config_dict["levs"]])
YEAR_RANGE = download_config_dict["experiment_ids"][experiment_id]
# CONCATENATE BY TIME
tic = time.time()
conc_var_dir = download_dir / "concatted_vars"
if DO_CROP:
conc_var_dir = Path(
str(conc_var_dir)
+ f"_{utils.lat_lon_string_from_tuples(INT_LATS, INT_LONS).upper()}"
)
if not conc_var_dir.exists():
conc_var_dir.mkdir(parents=True, exist_ok=True)
# fetch variable_id to fetch all files to be concatted
# for variable_id in list(source_id_dict["variable_dict"].keys()):
if DO_CROP:
variable_dir = (
download_dir
/ "regridded"
/ f"cropped_{utils.lat_lon_string_from_tuples(INT_LATS, INT_LONS).upper()}"
/ variable_id
)
else:
# directory with individual files for single variable
variable_dir = download_dir / "regridded" / variable_id
# if not variable_dir.exists():
# print(f"{variable_dir} does not exist, skipping", flush=True)
# continue
fps = list(variable_dir.glob("*.nc"))
if YEAR_RANGE:
oldest_date = str(min(YEAR_RANGE)) + "00"
newest_date = str(max(YEAR_RANGE) - 1) + "12"
else:
oldest_file = min(
fps, key=lambda filename: int(re.findall(r"\d{4}", str(filename))[0])
)
newest_file = max(
fps, key=lambda filename: int(re.findall(r"\d{4}", str(filename))[0])
)
oldest_date = str(oldest_file.name).split("_")[-1].split("-")[0]
newest_date = str(newest_file.name).split("_")[-1].split("-")[1].split(".")[0]
fname = utils.FileName(
variable_id=variable_id,
grid_type="latlon",
fname_type="time_concatted",
lats=LATS,
lons=LONS,
levs=LEVS,
plevels=source_id_dict["variable_dict"][variable_id]["plevels"],
date_range=[oldest_date, newest_date],
).construct_fname()
concatted_fp = conc_var_dir / fname
if concatted_fp.exists():
print(f"\nconcatenated file already exists at {str(concatted_fp)}", flush=True)
else:
# fetch all the filepaths of the files containing dates between oldest_date and newest_date
nc_fps = [
fp
for fp in fps
if oldest_date <= str(fp.name).split("_")[-1].split("-")[0]
and newest_date >= str(fp.name).split("_")[-1].split("-")[1].split(".")[0]
]
if len(nc_fps) == 0:
print(
f"skipping {variable_id} since no files found between {oldest_date} and {newest_date}..."
)
# continue
else:
print(f"concatenating {variable_id} files by time... ", flush=True)
concatted = xa.open_mfdataset(nc_fps)
# decode time
concatted = concatted.convert_calendar(
"gregorian", dim="time"
) # may not be universal for all models
print(
f"saving concatenated file to {concatted_fp}... ",
flush=True,
)
concatted.to_netcdf(concatted_fp)
time_concat_tic = time.time() - tic
print(
f"\nConcatenating files by time took {np.floor(time_concat_tic / 60):.0f}m:{time_concat_tic % 60:.0f}s.\n"
)
def merge_cmip_data_by_variables(source_id, experiment_id, member_id):
download_dir = (
config.cmip6_data_dir / source_id / member_id / "newtest"
) # TODO: remove testing folder
# source_id_dict = utils.read_yaml(config.model_info)[source_id]
download_config_dict = utils.read_yaml(config.download_config)
DO_CROP = download_config_dict["processing"]["do_crop"]
LATS = sorted(download_config_dict["lats"])
LONS = sorted(download_config_dict["lons"])
INT_LATS = [int(lat) for lat in LATS]
INT_LONS = [int(lon) for lon in LONS]
LEVS = sorted([abs(val) for val in download_config_dict["levs"]])
YEAR_RANGE = download_config_dict["experiment_ids"][experiment_id]
tic = time.time()
# MERGE VARIABLES
conc_var_dir = download_dir / "concatted_vars"
if DO_CROP:
conc_var_dir = str(conc_var_dir) + (
f"_{utils.lat_lon_string_from_tuples(INT_LATS, INT_LONS).upper()}"
)
if not Path(conc_var_dir).exists():
conc_var_dir.mkdir(parents=True, exist_ok=True)
# select all files in conc_var_dir which have correct YEAR_RANGE
oldest_date = str(min(YEAR_RANGE)) + "00"
newest_date = str(max(YEAR_RANGE) - 1) + "12"
YEAR_RANGE_str = f"{oldest_date}-{newest_date}"
var_nc_fps = list(Path(conc_var_dir).glob(f"*{YEAR_RANGE_str}.nc"))
vars = [str(fname.name).split("_")[0] for fname in var_nc_fps]
# sort vars in alphabetical for consistency between files
vars.sort()
merged_fname = utils.FileName(
variable_id=vars,
grid_type="latlon",
fname_type="var_concatted",
lats=LATS,
lons=LONS,
levs=LEVS,
plevels=LEVS, # TODO: Hmm? What's going on here?
date_range=[oldest_date, newest_date],
).construct_fname()
merged_fp = download_dir / merged_fname
if not merged_fp.exists():
print(
f"\nmerging variable files and saving to {merged_fp}... ",
flush=True,
)
dss = [xa.open_dataset(fp) for fp in var_nc_fps]
merged = xa.merge(dss)
merged.to_netcdf(merged_fp)
var_concat_tic = time.time() - tic
print(
f"\nMerging files by variable took {np.floor(var_concat_tic / 60):.0f}m:{var_concat_tic % 60:.0f}s."
)
else:
print(
f"\nmerged file already exists at {merged_fp}",
flush=True,
)
def process_cmip6_data(source_id, experiment_id, member_id, variable_id):
tic = time.time()
print(f"TIME CREATED: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(tic))}")
concat_cmip_files_by_time(source_id, experiment_id, member_id, variable_id)
merge_cmip_data_by_variables(source_id, experiment_id, member_id)
dur = time.time() - tic
print(f"\n\nTOTAL DURATION: {np.floor(dur / 60):.0f}m:{dur % 60:.0f}s\n")
def main():
# COMMAND LINE INPUT FROM BASH SCRIPT
################################################################################
parser = argparse.ArgumentParser()
# model info
source_id = parser.add_argument("--source_id", default="EC-Earth3P-HR", type=str)
member_id = parser.add_argument("--member_id", default="r1i1p2f1", type=str)
variable_id = parser.add_argument("--variable_id", default="tos", type=str)
commandline_args = parser.parse_args()
source_id = commandline_args.source_id
member_id = commandline_args.member_id
variable_id = commandline_args.variable_id
# source_id = "EC-Earth3P-HR"
# member_id = "r1i1p2f1"
# variable_id = "tos"
# DOWNLOAD DATA
################################################################################
download_cmip_variable_data(source_id, member_id, variable_id)
if __name__ == "__main__":
main()
|
@extends('layouts.master')
@section('title')
@endsection
@section('content')
<div id="app">
<!-- Breadcrumb -->
<d-header :title="`{{__('setting.external_department_list')}}`" :show-icon="false"></d-header>
<div class="w-full bg-white rounded-lg shadow mt-1 dark:bg-gray-800">
<!--- Top Title and add button --->
<div class="w-full mx-auto max-w-screen-xl p-4 md:flex md:items-center md:justify-between">
<h3 class="text-3xl font-bold dark:text-white"></h3>
@if(hasPermission(['external_directorate_create']))
<div
class="flex flex-wrap items-center mt-3 text-sm font-medium text-gray-500 dark:text-gray-400 sm:mt-0">
<add-new @click="openModal" :btn_name="`{{__('setting.add_external_department')}}`"/>
</div>
@endif
</div>
<!--- dataTable -->
<div class="mt-2">
<datatable ref="child" :per-page="{{perPage()}}"
:no-record-found-text="'@lang('general_words.no_record_found')'"
:search="'@lang('general_words.search')'"
:current="'@lang('general_words.current')'"
:next="'@lang('general_words.next')'"
:previous="'@lang('general_words.previous')'"
:per-page-text="'@lang('general_words.per_page_record')'"
:app-per-page="{!! perPage(1) !!}"
:columns="columns" :data="apiData" @pagination-change-page="getRecord"
:limit="1" :filterRecord="getRecord"
@delete-method-action="deleteRecord">
<template slot="tbody">
<tbody v-show="!apiData.data || showLoading">
<tr v-for="skeleton in 3">
<td v-for="skeleton in 4">
<skeleton-loader-vue
type="rect"
:height="34"
:width="150"
:radius="8"
class="m-2"
animation="fade"
/>
</td>
</tr>
</tbody>
<tbody v-show="apiData.data && !showLoading">
<tr v-for="(record,index) in apiData.data" :key="record.id"
class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white"> @{{index
+ 1}}
</td>
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
@{{record.name}}
</td>
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
@{{record.price}}
</td>
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
@{{record.stock_quantity}}
</td>
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
@{{record.category}}
</td>
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
@{{record.created_at}}
</td>
<td scope="row"
class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
<action-btn @edit="editRecord(record.id)" :showInfo="false"
@delete="deleteRecord(record.id)" :permissions="permissions"/>
</td>
</tr>
</tbody>
</template>
</datatable>
</div>
</div>
</div>
@endsection
@section('scripts')
<script>
let vm = new Vue({
el: '#app',
components: {
'skeleton-loader-vue': window.VueSkeletonLoader,
},
data() {
return {
loading: false,
showLoading: false,
url: '{{route("product.index")}}?',
columns: [
{
label: "@lang('lang.index')",
name: 'id',
sort: false,
},
{
label: "@lang('lang.name')",
name: 'products.name',
sort: false,
activeSort: true,
order_direction: 'desc',
},
{
label: "@lang('lang.price')",
name: 'products.price',
sort: true,
activeSort: true,
order_direction: 'desc',
},
{
label: "stock_quantity",
name: 'products.stock_quantity',
sort: true,
activeSort: true,
order_direction: 'desc',
},
{
label: "@lang('lang.category')",
name: 'products.category',
sort: true,
activeSort: true,
order_direction: 'desc',
},
{
label: "@lang('lang.actions')",
name: 'action',
sort: false
}
],
apiData: {},
appPerPage: '{!! perPage(1) !!}',
perPage: "{{ perPage() }}",
page: 1,
show_search: null,
save_directorate_loader: false,
selectedRows: [],
isModalOpen: false,
form: {
name: '',
},
permissions: {
delete: "{!! hasPermission(['external_directorate_delete']) !!}",
edit: "{!! hasPermission(['external_directorate_edit']) !!}",
view: "{!! hasPermission(['external_directorate_view']) !!}",
},
}
},
mounted() {
this.getRecord();
},
methods: {
/**
* get record from api
*/
getRecord: _.debounce((page = vm.page) => {
vm.showLoading = true;
axios.get(vm.url
+ '¤t_page=' + page
+ '&per_page=' + vm.perPage
)
.then((response) => {
vm.showLoading = false;
if (response.data) {
vm.page = response.data.current_page;
}
vm.apiData = response.data;
})
.catch((error) => {
console.log(error);
});
}, 200),
openModal() {
this.isModalOpen = true;
},
handleSubmit() {
if (this.isEdit) {
this.updateRecord();
} else {
this.saveRecord();
}
},
closeModal() {
this.isModalOpen = false;
},
editRecord(id = null, index) {
this.rowIndex = index;
this.isEdit = true;
this.id = id;
this.isModalOpen = true;
axios.get(`{!!url('external-directorates/edit')!!}/${id}`).then((res) => {
this.form.name = res.data.name;
});
},
updateRecord() {
if (this.form.name && this.form.name !== ' ') {
this.save_directorate_loader = true;
axios.patch(`{!!url('external-directorates/update')!!}/${this.id}`, this.form).then((res) => {
let response = res.data;
if (response.status == 200) {
this.isModalOpen = false;
showMessage(response.message, 'success');
this.resetForm();
this.getRecord();
this.save_directorate_loader = false;
this.isEdit = false;
} else {
this.save_directorate_loader = false;
showMessage(response.message, 'warning');
}
});
}
},
// delete record
deleteRecord(id = null) {
deleteItem(`external-directorates/${id}`);
},
resetForm() {
this.name = '';
},
}
});
</script>
@endsection
|
<form nz-form [formGroup]="form" (ngSubmit)="submit()" [nzLayout]="'vertical'" >
<div class="row">
<div class="col-lg-6 col-sm-6 col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.name' | translate }}</nz-form-label>
<nz-form-control>
<input nz-input placeholder="{{ 'customers.name' | translate }}" formControlName="full_name" maxlength="255" minlength="5">
</nz-form-control>
</nz-form-item>
</div>
<div class="col-lg-6 col-sm-6 col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.email' | translate }}</nz-form-label>
<nz-form-control>
<input nz-input placeholder="{{ 'customers.email' | translate }}" formControlName="email" type="email" maxlength="255">
</nz-form-control>
</nz-form-item>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6 col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.typeDocument' | translate }}</nz-form-label>
<nz-form-control>
<nz-select class="w-100" nzPlaceHolder="{{ 'customers.typeDocument' | translate }}" nzAllowClear formControlName="id_type_document">
<nz-option *ngFor="let option of typeDocumentsList" [nzValue]="option.id" [nzLabel]="option.name" ></nz-option>
</nz-select>
</nz-form-control>
</nz-form-item>
</div>
<div class="col-lg-6 col-sm-6 col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.document' | translate }}</nz-form-label>
<nz-form-control>
<input nz-input placeholder="{{ 'customers.document' | translate }}" formControlName="document" maxlength="20">
</nz-form-control>
</nz-form-item>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6 col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.typePerson' | translate }}</nz-form-label>
<nz-form-control>
<nz-select class="w-100" nzPlaceHolder="{{ 'customers.typePerson' | translate }}" nzAllowClear formControlName="id_type_person">
<nz-option *ngFor="let option of typePersonsList" [nzValue]="option.id" [nzLabel]="option.name" ></nz-option>
</nz-select>
</nz-form-control>
</nz-form-item>
</div>
<div class="col-lg-6 col-sm-6 col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.cellphone' | translate }}</nz-form-label>
<nz-form-control>
<input nz-input placeholder="{{ 'customers.cellphone' | translate }}" formControlName="cellphone" type="number" maxlength="10" >
</nz-form-control>
</nz-form-item>
</div>
</div>
<div class="row">
<div class="col-12">
<nz-form-item>
<nz-form-label>{{ 'customers.address' | translate }}</nz-form-label>
<nz-form-control>
<textarea nz-input placeholder="{{ 'customers.address' | translate }}" [nzAutosize]="{ minRows: 2 }" formControlName="address"></textarea>
</nz-form-control>
</nz-form-item>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<nz-form-item>
<nz-form-control>
<button nz-button nzType="primary" [disabled]="!form.valid" nz-button nzType="primary" [nzLoading]="loading">{{ 'global.save' | translate }}</button>
</nz-form-control>
</nz-form-item>
</div>
</div>
</form>
|
package com.money.project.system.domain;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.money.framework.aspectj.lang.annotation.Excel;
import com.money.framework.aspectj.lang.annotation.Excel.ColumnType;
import com.money.framework.web.domain.BaseEntity;
public class SysPost extends BaseEntity
{
private static final long serialVersionUID = 1L;
@Excel(name = "postId", cellType = ColumnType.NUMERIC)
private Long postId;
@Excel(name = "postCode")
private String postCode;
@Excel(name = "postName")
private String postName;
@Excel(name = "postSort")
private Integer postSort;
@Excel(name = "status", readConverterExp = "0=YES,1=NO")
private String status;
private boolean flag = false;
public Long getPostId()
{
return postId;
}
public void setPostId(Long postId)
{
this.postId = postId;
}
@NotBlank(message = "Job code cannot be empty")
@Size(min = 0, max = 64, message = "Job code length cannot exceed 64 characters")
public String getPostCode()
{
return postCode;
}
public void setPostCode(String postCode)
{
this.postCode = postCode;
}
@NotBlank(message = "Job code length cannot exceed 64 characters")
@Size(min = 0, max = 50, message = "Job title length cannot exceed 50 characters")
public String getPostName()
{
return postName;
}
public void setPostName(String postName)
{
this.postName = postName;
}
@NotNull(message = "Display order cannot be empty")
public Integer getPostSort()
{
return postSort;
}
public void setPostSort(Integer postSort)
{
this.postSort = postSort;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public boolean isFlag()
{
return flag;
}
public void setFlag(boolean flag)
{
this.flag = flag;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("postId", getPostId())
.append("postCode", getPostCode())
.append("postName", getPostName())
.append("postSort", getPostSort())
.append("status", getStatus())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}
|
//
// Copyright 2024 Huawei Cloud Computing Technologies Co., Ltd.
//
// 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.
//
#ifndef OPENGEMINI_EXCEPTION_HPP
#define OPENGEMINI_EXCEPTION_HPP
#include <exception>
#include "opengemini/Error.hpp"
namespace opengemini {
///
/// \~English
/// @brief General exception of the library.
///
/// \~Chinese
/// @brief 库通用异常类。
///
class Exception : public std::exception {
public:
explicit Exception(Error error) :
error_(std::move(error)),
what_(error_.What())
{ }
explicit Exception(std::error_code code, std::string info = {}) :
error_(code, info),
what_(error_.What())
{ }
Exception(const Exception& ex) : error_(ex.error_) { }
Exception(Exception&& ex) noexcept : error_(std::move(ex.error_)) { }
~Exception() = default;
///
/// \~English
/// @brief Returns a string object describing the exception.
///
/// \~Chinese
/// @brief 返回描述异常信息的字符串。
///
const std::string& What() const noexcept { return what_; }
///
/// \~English
/// @brief Returns the stored error object.
///
/// \~Chinese
/// @brief 返回承载的错误对象。
///
const Error& UnderlyingError() const noexcept { return error_; }
///
/// \~English
/// @brief Returns a static string describing the exception。Same as @ref
/// What(), just for compatibility with std::exception.
///
/// \~Chinese
/// @brief 返回描述异常信息的字符串。与 @ref What() 相同,仅为满足
/// std::exception 约束而实现。
///
const char* what() const noexcept override { return what_.c_str(); }
Exception& operator=(Exception ex) noexcept
{
swap(*this, ex);
return *this;
}
friend void swap(Exception& lhs, Exception& rhs) noexcept
{
using std::swap;
swap(lhs.error_, rhs.error_);
swap(lhs.what_, rhs.what_);
}
friend std::ostream& operator<<(std::ostream& os, const Exception& ex)
{
os << ex.What();
return os;
}
private:
Error error_;
std::string what_;
};
} // namespace opengemini
#endif // !OPENGEMINI_EXCEPTION_HPP
|
import { Link } from 'react-router-dom';
import { AiFillHeart, AiOutlineHeart } from 'react-icons/ai';
import { API_URL } from '../utils/helper';
import { useAddToCart } from '../features/cart/useAddToCart';
import { useUser } from '../features/authentication/useUser';
import { useRemoveFromCart } from '../features/cart/useRemoveFromCart';
import Star from './Star';
import Spinner from './Spinner';
import { useAddToWishlist } from '../features/wishlist/useAddToWishlist';
import { useRemoveFromWishlist } from '../features/wishlist/useRemoveFromWishlist';
import { toast } from 'react-hot-toast';
const Product = ({ w, product }) => {
const { status: addStatus, addToCart } = useAddToCart();
const { status: removeStatus, removeFromCart } = useRemoveFromCart();
const { addToWishlist } = useAddToWishlist();
const { removeFromWishlist } = useRemoveFromWishlist();
const { status, user } = useUser();
const title = `${product?.title.slice(0, 19)}...`;
const carts = user?.carts?.find((cart) => cart.id === product._id);
const wishlists = user?.wishlists?.find(
(wishlist) => wishlist === product._id
);
// EVENTS
const handleAddToCart = () => {
if (status === 'success') {
return addToCart({
id: product._id,
quantity: 1,
});
}
toast.error('please login before attemping any action');
};
const handleRemoveCart = () => {
if (status === 'success') {
return removeFromCart(product._id);
}
toast.error('please login before attemping any action');
};
const handleAddeAndRemoveFromWishlists = () => {
if (status !== 'success') {
return toast.error('please login before attemping any action');
}
if (status === 'success') {
if (!wishlists) {
addToWishlist(product._id);
} else {
removeFromWishlist(product._id);
}
}
};
return (
<div className={`${w ? 'w-[250px]' : ''} flex flex-col space-y-3`}>
<div className='relative'>
<img
src={`${API_URL}/products/${product?.imageUrl}`}
alt={product?.title}
className='object-cover w-full h-36 rounded-md hover:scale-110 transition-all duration-300 border border-gray-200 hover:shadow-lg hover:shadow-gray-400/50'
/>
<span
className='absolute top-2 right-3 text-gray-500 text-[18px] bg-orange-50 cursor-pointer rounded-full w-7 h-7 flex justify-center items-center'
onClick={handleAddeAndRemoveFromWishlists}
>
{!wishlists ? (
<AiOutlineHeart className='text-orange-400' />
) : (
<AiFillHeart
className={`${
wishlists ? 'text-orange-500' : ''
}`}
/>
)}
</span>
</div>
<div className='flex justify-between'>
<div className='flex flex-col space-y-1'>
<Link
to={`/products/${product?.slug}`}
className='font-light text-[12px] underline'
>
{title}
</Link>
<span className='text-xs text-gray-500'>
{product?.category}
</span>
<div className='text-orange-300 flex gap-[1px] items-center'>
<Star />
<span className='text-xs font-medium text-gray-900'>
{product?.avgRatings || 0}
</span>
</div>
{/* ADD AND REMOVE CART BUTTONS */}
{carts ? (
<button
onClick={handleRemoveCart}
className='flex justify-center items-center px-2 py-1 border-[1px] border-orange-600 text-orange-800 text-xs rounded-full hover:bg-orange-700 transition-all duration-300 hover:text-orange-100'
>
{removeStatus === 'pending' ? (
<Spinner h='16' w='40' />
) : (
'unselect'
)}
</button>
) : (
<button
onClick={handleAddToCart}
className='flex justify-center items-center px-2 py-1 border-[1px] border-orange-600 text-orange-800 text-xs rounded-full hover:bg-orange-700 transition-all duration-300 hover:text-orange-100'
>
{addStatus === 'pending' ? (
<Spinner h='16' w='40' />
) : (
'select'
)}
</button>
)}
</div>
<div className='font-medium text-[14px]'>
${product?.price.toLocaleString()}
</div>
</div>
</div>
);
};
export default Product;
|
import React, { useState, useEffect } from 'react'
import './Formulaire.css'
const Formulaire = ({ isCheck, selectGroupe }) => {
const [noCreteria, setNoCreteria] = useState(true)
const [creteria, setCreteria] = useState({
instrument: '',
experience: '',
style: '',
location: '',
objectif: '',
gs: `${selectGroupe}`
})
const [locFilter, setLocFilter] = useState([])
const [instFilter, setInstFilter] = useState([])
const [nivFilter, setNivFilter] = useState([])
const [styleFilter, setStyleFilter] = useState([])
const [objFilter, setObjFilter] = useState([])
const handleChange = target => {
setNoCreteria(false)
if (target.id === 'selectInst') {
setCreteria({ ...creteria, instrument: target.value })
}
if (target.id === 'selectNiv') {
setCreteria({ ...creteria, experience: target.value })
}
if (target.id === 'selectObj') {
setCreteria({ ...creteria, objectif: target.value })
}
if (target.id === 'selectLoc') {
setCreteria({ ...creteria, location: target.value })
}
if (target.id === 'selectStyle') {
setCreteria({ ...creteria, style: target.value })
}
if (target.id === 'selectGs') {
setCreteria({ ...creteria, gs: target.value })
}
}
useEffect(() => {
document.getElementById('selectGs').value = selectGroupe
}, [])
useEffect(() => {
fetch('https://yv3o2geh.directus.app/items/locations')
.then(res => res.json())
.then(res => setLocFilter(res.data))
}, [])
useEffect(() => {
fetch('https://yv3o2geh.directus.app/items/objectif')
.then(res => res.json())
.then(res => setObjFilter(res.data))
}, [])
useEffect(() => {
console.log(creteria)
}, [creteria])
useEffect(() => {
fetch('https://yv3o2geh.directus.app/items/instruments')
.then(res => res.json())
.then(res => setInstFilter(res.data))
}, [])
useEffect(() => {
fetch('https://yv3o2geh.directus.app/items/level')
.then(res => res.json())
.then(res => setNivFilter(res.data))
}, [])
useEffect(() => {
fetch('https://yv3o2geh.directus.app/items/style')
.then(res => res.json())
.then(res => setStyleFilter(res.data))
}, [])
return (
<div className='contenerForm'>
<form className='form'>
<div className='contener-1'>
<label htmlFor='select' className='labelFrom'>
Recherche Groupe / <br />
Personne solos :
<select
id='selectGs'
className='selectForm'
onChange={e => handleChange(e.target)}
>
<option value={true}>Groupe</option>
<option value={false}>Solo</option>
</select>
</label>
<label htmlFor='select' className='labelFrom'>
Instruments :
<select
id='selectInst'
className='selectForm'
onChange={e => handleChange(e.target)}
>
<option value=''>---Type---</option>
{instFilter.length &&
instFilter.map((inst, i) => (
<option key={i} value={inst.name}>
{inst.name}
</option>
))}
</select>
</label>
</div>
<div className='contener-1'>
<label htmlFor='select' className='labelFrom'>
Niveau :
<select
id='selectNiv'
className='selectForm'
placeholder='Choisir niveau'
onChange={e => handleChange(e.target)}
>
<option value=''>---Type---</option>
{nivFilter.length &&
nivFilter.map((niv, i) => (
<option key={i} value={niv.niveau}>
{niv.niveau}
</option>
))}
</select>
</label>
<label htmlFor='select' className='labelFrom'>
Objectif recherché :
<select
id='selectObj'
className='selectForm'
onChange={e => handleChange(e.target)}
>
<option value=''>---Type---</option>
{objFilter.length &&
objFilter.map((obj, i) => (
<option key={i} value={obj.objectif}>
{obj.objectif}
</option>
))}
</select>
</label>
</div>
<div className='contener-1'>
<label className='labelFrom'>
Localisation :
<select
id='selectLoc'
className='selectForm'
onChange={e => handleChange(e.target)}
>
<option value=''>---Type---</option>
{locFilter.length &&
locFilter.map((loc, i) => (
<option key={i} value={loc.name}>
{loc.name}
</option>
))}
</select>
</label>
<label className='labelFrom'>
Genre musical :
<select
id='selectStyle'
className='selectForm'
onChange={e => handleChange(e.target)}
>
<option value=''>---Type---</option>
{styleFilter.length &&
styleFilter.map((sty, i) => (
<option key={i} value={sty.name}>
{sty.name}
</option>
))}
</select>
</label>
</div>
<div className='contButton'>
<button className='buttonForm' onClick={e => isCheck(e, creteria)}>
RECHERCHE
</button>
</div>
</form>
</div>
)
}
export default Formulaire
|
import { Carousel } from "@material-tailwind/react";
import { useEffect, useState } from "react";
import axios from 'axios';
const Home = ({ searchValue }) => {
//Bütün veriler için state
const [allNews, setAllNews] = useState([]);
//Slider verileri için state(ilk üç haber)
const [slider, setSlider] = useState([]);
//İlk üç haberden sonraki haberler
const [otherNews, setOtherNews] = useState([]);
//Çektiğimiz apilerin sayfa açıldığında görülenmesi için useEffect
useEffect(() => {
const getResponse = async () => {
const response = await axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=a696c20c66a14d83b49a0e92733c1675');
const data = response.data;
console.log(data);
const allNews = data.articles;
const slider = allNews.slice(0, 3);
const otherNews = allNews.slice(3);
setAllNews(allNews);
setSlider(slider);
setOtherNews(otherNews);
}
getResponse();
}, [])
//otherNews array’indeki apiler, searchValue değerine göre filtrelendi.
const filteredOtherNews = otherNews.filter((news) =>
news.title.toLowerCase().includes(searchValue.toLowerCase())
);
return (
<div className="mx-auto max-w-6xl">
<div className="px-14">
{/* Slider için hazır bir component kullanıdı */}
<Carousel className="rounded-xl">
{
slider.map((item, i) => (
<a href={item.url} target="blank" key={i} className="h-full w-full">
<img src={item.urlToImage} className="h-[500px] w-full object-cover rounded-xl" />
<h1 className="font-bold pt-2 text-xl">{item.title}</h1>
<p className="text-lg">{item.description}</p>
</a>
))
}
</Carousel>
</div>
<div className="pt-20">
{
filteredOtherNews.map((item, i) => (
<a href={item.url} target="blank" key={i} className="mx-14 md-mx-0 pt-4 pb-20 items-center md:items-start flex flex-col md:flex-row md:gap-x-6">
<img src={item.urlToImage} className="md:w-1/2 object-cover" />
<div className="md:border-t md:border-black md:w-1/2">
<h1 className="font-bold text-xl md:py-4 py-2">{item.title}</h1>
<p className="text-lg">{item.description}</p>
</div>
</a>
))
}
</div>
</div>
)
}
export default Home
|
// Copyright (C) 2012 von Karman Institute for Fluid Dynamics, Belgium
//
// This software is distributed under the terms of the
// GNU Lesser General Public License version 3 (LGPLv3).
// See doc/lgpl.txt and doc/gpl.txt for the license text.
#ifndef COOLFluiD_Framework_BaseMethodCommandProvider_hh
#define COOLFluiD_Framework_BaseMethodCommandProvider_hh
#include "Common/StringOps.hh"
#include "Common/SharedPtr.hh"
#include "Common/SelfRegistPtr.hh"
#include "Environment/Provider.hh"
namespace COOLFluiD {
namespace Framework {
/// This class is used as the base class for Providers who create a Commands
/// belonging to a Method.
/// It is an factory method pattern implementation.
/// This class in an abstract class.
/// @see Provider
/// @see CommandProvider
/// @author Tiago Quintino
/// @author Andrea Lani
template <class DATA, class BASECOMMAND>
class BaseMethodCommandProvider : public Environment::Provider<BASECOMMAND> {
public:
/// Constructor
/// @param name String defining the element type to be created
explicit BaseMethodCommandProvider(const std::string& name)
: Environment::Provider<BASECOMMAND>(name)
{
}
/// Default destructor
virtual ~BaseMethodCommandProvider()
{
}
/// Creates a new MethodCommand with the supplied Data object.
/// @param data the Data object.
/// @return Pointer to the new MethodCommand
Common::SelfRegistPtr<BASECOMMAND> create(const Common::SharedPtr<DATA>& data)
{
return create(BaseMethodCommandProvider
<DATA, BASECOMMAND>::getName(), data);
}
/// Creates a new MethodCommand with the supplied Data object.
/// @param name the name of the object to be used in configuration.
/// @param data the Data object.
/// @return Pointer to the new MethdCommand
virtual Common::SelfRegistPtr<BASECOMMAND> create(const std::string& name,
const Common::SharedPtr<DATA>& data) = 0;
/// Free an instance created by this factory.
/// (warning: If a provider is capable of instantiating multiple kinds of
/// objects, the freeInstance method should make sure to call the right
/// delete operator!)
virtual void freeInstance (void* ptr) = 0;
}; // class BaseMethodCommandProvider
} // namespace Framework
} // namespace COOLFluiD
#endif // COOLFluiD_Framework_BaseMethodCommandProvider_hh
|
import { JSX, mergeProps, splitProps } from 'solid-js';
import clsx from 'clsx';
import './Button.scss';
export type ButtonVariant = 'default' | 'raised' | 'outlined';
export type ButtonProps = JSX.ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: ButtonVariant;
fluid?: boolean;
rounded?: boolean;
emphasized?: boolean;
static?: boolean;
};
export function Button(props: ButtonProps) {
props = mergeProps({ type: 'button', variant: 'default' } as ButtonProps, props);
const [local, rest] = splitProps(props, [
'class',
'children',
'fluid',
'rounded',
'emphasized',
'static',
'type',
'variant',
]);
return (
<button
class={clsx(
{
'Button--fluid': local.fluid,
'Button--emphasized': local.emphasized,
'Button--rounded': local.rounded,
'Button--static': local.static,
[`Button--variant--${local.variant}`]: local.variant,
},
local.class,
)}
type={local.type}
{...rest}
>
{local.children}
</button>
);
}
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProductModel = void 0;
const Database_1 = require("../Database");
class ProductModel {
constructor() {
this.collectionName = 'products';
this.connect = new Database_1.MongoDB();
}
createProduct(Product) {
return __awaiter(this, void 0, void 0, function* () {
const collection = yield this.connect.client(this.collectionName);
const newProduct = yield collection.insertOne(Product).finally(this.connect.closeConnection());
return newProduct.insertedId;
});
}
getAllProduct() {
return __awaiter(this, void 0, void 0, function* () {
const collection = yield this.connect.client(this.collectionName);
return yield collection.find().toArray().finally(this.connect.closeConnection());
});
}
getProductById(ProductId) {
return __awaiter(this, void 0, void 0, function* () {
const collection = yield this.connect.client(this.collectionName);
const Product = yield collection.find({ _id: ProductId }).toArray().finally(this.connect.closeConnection());
console.log(Product);
return Product;
});
}
getProductBySearch(key) {
return __awaiter(this, void 0, void 0, function* () {
const collection = yield this.connect.client(this.collectionName);
return yield collection.find({ name: { $regex: key, $options: 'i' } }).toArray().finally(this.connect.closeConnection());
});
}
editProduct(id, Product) {
return __awaiter(this, void 0, void 0, function* () {
const collection = yield this.connect.client(this.collectionName);
const newProduct = yield collection.updateMany({ _id: id }, { $set: Product }).finally(this.connect.closeConnection());
return newProduct.upsertedId;
});
}
deleteProduct(ProductId) {
return __awaiter(this, void 0, void 0, function* () {
const collection = yield this.connect.client(this.collectionName);
return yield collection.deleteOne({ _id: ProductId }).finally(this.connect.closeConnection());
});
}
}
exports.ProductModel = ProductModel;
|
"use client";
import Image from "next/image";
import iconX from "../../../public/icons/iconcancel.svg";
import InputField from "@/components/InputField";
const RegisterModal = ({
title,
setShowModal1,
register,
errors,
loading,
handleSubmit,
submitForm,
}) => {
return (
<div className=" w-full flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<div className="inline-block align-bottom p-8 bg-white rounded-[50px] text-left overflow-hidden shadow-xl transform transition-all sm:mt-0 sm:mb-8 md:mt-0 sm:align-middle sm:max-w-lg sm:w-full w-full">
<div className="flex justify-between items-center">
<div>
<p className="font-cabinet font-bold text-3xl">
{title?.city}
</p>
<p className="text-sm">{title?.date}</p>
</div>
<button
onClick={() => setShowModal1(false)}
className="font-semibold"
>
<Image
src={iconX}
alt="cancel"
/>
</button>
</div>
<hr className=" border-t-[0.1px] my-1 mt-4 border-black" />
<div className="my-[1rem]">
<InputField
label="Name"
id="name"
name="name"
type="text"
required={true}
register={register}
/>
<p className=" mt-[1rem] mb-[0.2rem] text-[12px] text-red-500 ">
{errors.name?.message}
</p>
</div>
<div className="my-[1rem]">
<InputField
label="Startup Name"
id="startupName"
name="startupName"
type="text"
required={true}
register={register}
/>
<p className=" mt-[1rem] mb-[0.2rem] text-[12px] text-red-500 ">
{errors.startupName?.message}
</p>
</div>
<div className="my-[1rem]">
<InputField
label="Email Address"
id="email"
name="email"
type="email"
required={true}
register={register}
/>
<p className=" mt-[1rem] mb-[0.2rem] text-[12px] text-red-500 ">
{errors.email?.message}
</p>
</div>
<div className="my-[1rem]">
<InputField
label="Phone Number"
id="phoneNumber"
name="phoneNumber"
type="text"
required={true}
register={register}
/>
<p className=" mt-[1rem] mb-[0.2rem] text-[12px] text-red-500 ">
{errors.phoneNumber?.message}
</p>
</div>
<div className="flex justify-center mt-6 -mb-4">
<button
onClick={handleSubmit(submitForm)}
className="bg-btnBg py-4 px-16 rounded-[22px] text-white"
>
{loading ? "Submitting..." : "Submit"}
</button>
</div>
</div>
</div>
);
};
export default RegisterModal;
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './home/dashboard/dashboard.component';
import { ClientsComponent } from './home/clients/clients.component';
import { AppointmentsComponent } from './home/appointments/appointments.component';
import { RequestsComponent } from './home/requests/requests.component';
import { PendingComponent } from './home/pending/pending.component';
const routes: Routes = [
{ path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{ path: 'login',
component: LoginComponent
},
{ path: 'home',
component: HomeComponent,
children: [
{
path: 'dashboard',
component: DashboardComponent,
},
{ path: 'clients',
component: ClientsComponent,
},
{ path: 'appointments',
component: AppointmentsComponent,
},
{ path: 'requests',
component: RequestsComponent,
},
{ path: 'pending',
component: PendingComponent,
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
__author__= "Campbell Barton", "Jiri Hnidek", "Paolo Ciccone"
__url__= ['http://wiki.blender.org/index.php/Scripts/Manual/Import/wavefront_obj', 'blender.org', 'blenderartists.org']
__version__= "2.11"
__bpydoc__= """\
This script imports a Wavefront OBJ files to Blender.
Usage:
Run this script from "File->Import" menu and then load the desired OBJ file.
Note, This loads mesh objects and materials only, nurbs and curves are not supported.
"""
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Script copyright (C) Campbell J Barton 2007
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
import os
import time
import bpy
import Mathutils
import Geometry
# from Blender import Mesh, Draw, Window, Texture, Material, sys
# # import BPyMesh
# import BPyImage
# import BPyMessages
# try: import os
# except: os= False
# Generic path functions
def stripFile(path):
'''Return directory, where the file is'''
lastSlash= max(path.rfind('\\'), path.rfind('/'))
if lastSlash != -1:
path= path[:lastSlash]
return '%s%s' % (path, os.sep)
# return '%s%s' % (path, sys.sep)
def stripPath(path):
'''Strips the slashes from the back of a string'''
return path.split('/')[-1].split('\\')[-1]
def stripExt(name): # name is a string
'''Strips the prefix off the name before writing'''
index= name.rfind('.')
if index != -1:
return name[ : index ]
else:
return name
# end path funcs
def unpack_list(list_of_tuples):
l = []
for t in list_of_tuples:
l.extend(t)
return l
# same as above except that it adds 0 for triangle faces
def unpack_face_list(list_of_tuples):
l = []
for t in list_of_tuples:
face = [i for i in t]
if len(face) != 3 and len(face) != 4:
raise RuntimeError("{0} vertices in face.".format(len(face)))
# rotate indices if the 4th is 0
if len(face) == 4 and face[3] == 0:
face = [face[3], face[0], face[1], face[2]]
if len(face) == 3:
face.append(0)
l.extend(face)
return l
def BPyMesh_ngon(from_data, indices, PREF_FIX_LOOPS= True):
'''
Takes a polyline of indices (fgon)
and returns a list of face indicie lists.
Designed to be used for importers that need indices for an fgon to create from existing verts.
from_data: either a mesh, or a list/tuple of vectors.
indices: a list of indicies to use this list is the ordered closed polyline to fill, and can be a subset of the data given.
PREF_FIX_LOOPS: If this is enabled polylines that use loops to make multiple polylines are delt with correctly.
'''
if not set: # Need sets for this, otherwise do a normal fill.
PREF_FIX_LOOPS= False
Vector= Mathutils.Vector
if not indices:
return []
# return []
def rvec(co): return round(co.x, 6), round(co.y, 6), round(co.z, 6)
def mlen(co): return abs(co[0])+abs(co[1])+abs(co[2]) # manhatten length of a vector, faster then length
def vert_treplet(v, i):
return v, rvec(v), i, mlen(v)
def ed_key_mlen(v1, v2):
if v1[3] > v2[3]:
return v2[1], v1[1]
else:
return v1[1], v2[1]
if not PREF_FIX_LOOPS:
'''
Normal single concave loop filling
'''
if type(from_data) in (tuple, list):
verts= [Vector(from_data[i]) for ii, i in enumerate(indices)]
else:
verts= [from_data.verts[i].co for ii, i in enumerate(indices)]
for i in range(len(verts)-1, 0, -1): # same as reversed(xrange(1, len(verts))):
if verts[i][1]==verts[i-1][0]:
verts.pop(i-1)
fill= Geometry.PolyFill([verts])
else:
'''
Seperate this loop into multiple loops be finding edges that are used twice
This is used by lightwave LWO files a lot
'''
if type(from_data) in (tuple, list):
verts= [vert_treplet(Vector(from_data[i]), ii) for ii, i in enumerate(indices)]
else:
verts= [vert_treplet(from_data.verts[i].co, ii) for ii, i in enumerate(indices)]
edges= [(i, i-1) for i in range(len(verts))]
if edges:
edges[0]= (0,len(verts)-1)
if not verts:
return []
edges_used= set()
edges_doubles= set()
# We need to check if any edges are used twice location based.
for ed in edges:
edkey= ed_key_mlen(verts[ed[0]], verts[ed[1]])
if edkey in edges_used:
edges_doubles.add(edkey)
else:
edges_used.add(edkey)
# Store a list of unconnected loop segments split by double edges.
# will join later
loop_segments= []
v_prev= verts[0]
context_loop= [v_prev]
loop_segments= [context_loop]
for v in verts:
if v!=v_prev:
# Are we crossing an edge we removed?
if ed_key_mlen(v, v_prev) in edges_doubles:
context_loop= [v]
loop_segments.append(context_loop)
else:
if context_loop and context_loop[-1][1]==v[1]:
#raise "as"
pass
else:
context_loop.append(v)
v_prev= v
# Now join loop segments
def join_seg(s1,s2):
if s2[-1][1]==s1[0][1]: #
s1,s2= s2,s1
elif s1[-1][1]==s2[0][1]:
pass
else:
return False
# If were stuill here s1 and s2 are 2 segments in the same polyline
s1.pop() # remove the last vert from s1
s1.extend(s2) # add segment 2 to segment 1
if s1[0][1]==s1[-1][1]: # remove endpoints double
s1.pop()
s2[:]= [] # Empty this segment s2 so we dont use it again.
return True
joining_segments= True
while joining_segments:
joining_segments= False
segcount= len(loop_segments)
for j in range(segcount-1, -1, -1): #reversed(range(segcount)):
seg_j= loop_segments[j]
if seg_j:
for k in range(j-1, -1, -1): # reversed(range(j)):
if not seg_j:
break
seg_k= loop_segments[k]
if seg_k and join_seg(seg_j, seg_k):
joining_segments= True
loop_list= loop_segments
for verts in loop_list:
while verts and verts[0][1]==verts[-1][1]:
verts.pop()
loop_list= [verts for verts in loop_list if len(verts)>2]
# DONE DEALING WITH LOOP FIXING
# vert mapping
vert_map= [None]*len(indices)
ii=0
for verts in loop_list:
if len(verts)>2:
for i, vert in enumerate(verts):
vert_map[i+ii]= vert[2]
ii+=len(verts)
fill= Geometry.PolyFill([ [v[0] for v in loop] for loop in loop_list ])
#draw_loops(loop_list)
#raise 'done loop'
# map to original indicies
fill= [[vert_map[i] for i in reversed(f)] for f in fill]
if not fill:
print('Warning Cannot scanfill, fallback on a triangle fan.')
fill= [ [0, i-1, i] for i in range(2, len(indices)) ]
else:
# Use real scanfill.
# See if its flipped the wrong way.
flip= None
for fi in fill:
if flip != None:
break
for i, vi in enumerate(fi):
if vi==0 and fi[i-1]==1:
flip= False
break
elif vi==1 and fi[i-1]==0:
flip= True
break
if not flip:
for i, fi in enumerate(fill):
fill[i]= tuple([ii for ii in reversed(fi)])
return fill
def line_value(line_split):
'''
Returns 1 string represneting the value for this line
None will be returned if theres only 1 word
'''
length= len(line_split)
if length == 1:
return None
elif length == 2:
return line_split[1]
elif length > 2:
return ' '.join( line_split[1:] )
# limited replacement for BPyImage.comprehensiveImageLoad
def load_image(imagepath, dirname):
if os.path.exists(imagepath):
return bpy.data.add_image(imagepath)
variants = [os.path.join(dirname, imagepath), os.path.join(dirname, os.path.basename(imagepath))]
for path in variants:
if os.path.exists(path):
return bpy.data.add_image(path)
else:
print(path, "doesn't exist")
# TODO comprehensiveImageLoad also searched in bpy.config.textureDir
return None
def obj_image_load(imagepath, DIR, IMAGE_SEARCH):
if '_' in imagepath:
image= load_image(imagepath.replace('_', ' '), DIR)
if image: return image
return load_image(imagepath, DIR)
# def obj_image_load(imagepath, DIR, IMAGE_SEARCH):
# '''
# Mainly uses comprehensiveImageLoad
# but tries to replace '_' with ' ' for Max's exporter replaces spaces with underscores.
# '''
# if '_' in imagepath:
# image= BPyImage.comprehensiveImageLoad(imagepath, DIR, PLACE_HOLDER= False, RECURSIVE= IMAGE_SEARCH)
# if image: return image
# # Did the exporter rename the image?
# image= BPyImage.comprehensiveImageLoad(imagepath.replace('_', ' '), DIR, PLACE_HOLDER= False, RECURSIVE= IMAGE_SEARCH)
# if image: return image
# # Return an image, placeholder if it dosnt exist
# image= BPyImage.comprehensiveImageLoad(imagepath, DIR, PLACE_HOLDER= True, RECURSIVE= IMAGE_SEARCH)
# return image
def create_materials(filepath, material_libs, unique_materials, unique_material_images, IMAGE_SEARCH):
'''
Create all the used materials in this obj,
assign colors and images to the materials from all referenced material libs
'''
DIR= stripFile(filepath)
# This function sets textures defined in .mtl file #
def load_material_image(blender_material, context_material_name, imagepath, type):
texture= bpy.data.add_texture(type)
texture.type= 'IMAGE'
# texture= bpy.data.textures.new(type)
# texture.setType('Image')
# Absolute path - c:\.. etc would work here
image= obj_image_load(imagepath, DIR, IMAGE_SEARCH)
has_data = image.has_data if image else False
if image:
texture.image = image
# Adds textures for materials (rendering)
if type == 'Kd':
if has_data and image.depth == 32:
# Image has alpha
# XXX bitmask won't work?
blender_material.add_texture(texture, "UV", ("COLOR", "ALPHA"))
texture.mipmap = True
texture.interpolation = True
texture.use_alpha = True
blender_material.z_transparency = True
blender_material.alpha = 0.0
# blender_material.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL | Texture.MapTo.ALPHA)
# texture.setImageFlags('MipMap', 'InterPol', 'UseAlpha')
# blender_material.mode |= Material.Modes.ZTRANSP
# blender_material.alpha = 0.0
else:
blender_material.add_texture(texture, "UV", "COLOR")
# blender_material.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL)
# adds textures to faces (Textured/Alt-Z mode)
# Only apply the diffuse texture to the face if the image has not been set with the inline usemat func.
unique_material_images[context_material_name]= image, has_data # set the texface image
elif type == 'Ka':
blender_material.add_texture(texture, "UV", "AMBIENT")
# blender_material.setTexture(1, texture, Texture.TexCo.UV, Texture.MapTo.CMIR) # TODO- Add AMB to BPY API
elif type == 'Ks':
blender_material.add_texture(texture, "UV", "SPECULARITY")
# blender_material.setTexture(2, texture, Texture.TexCo.UV, Texture.MapTo.SPEC)
elif type == 'Bump':
blender_material.add_texture(texture, "UV", "NORMAL")
# blender_material.setTexture(3, texture, Texture.TexCo.UV, Texture.MapTo.NOR)
elif type == 'D':
blender_material.add_texture(texture, "UV", "ALPHA")
blender_material.z_transparency = True
blender_material.alpha = 0.0
# blender_material.setTexture(4, texture, Texture.TexCo.UV, Texture.MapTo.ALPHA)
# blender_material.mode |= Material.Modes.ZTRANSP
# blender_material.alpha = 0.0
# Todo, unset deffuse material alpha if it has an alpha channel
elif type == 'refl':
blender_material.add_texture(texture, "UV", "REFLECTION")
# blender_material.setTexture(5, texture, Texture.TexCo.UV, Texture.MapTo.REF)
# Add an MTL with the same name as the obj if no MTLs are spesified.
temp_mtl= stripExt(stripPath(filepath))+ '.mtl'
if os.path.exists(DIR + temp_mtl) and temp_mtl not in material_libs:
# if sys.exists(DIR + temp_mtl) and temp_mtl not in material_libs:
material_libs.append( temp_mtl )
del temp_mtl
#Create new materials
for name in unique_materials: # .keys()
if name != None:
unique_materials[name]= bpy.data.add_material(name)
# unique_materials[name]= bpy.data.materials.new(name)
unique_material_images[name]= None, False # assign None to all material images to start with, add to later.
unique_materials[None]= None
unique_material_images[None]= None, False
for libname in material_libs:
mtlpath= DIR + libname
if not os.path.exists(mtlpath):
# if not sys.exists(mtlpath):
#print '\tError Missing MTL: "%s"' % mtlpath
pass
else:
#print '\t\tloading mtl: "%s"' % mtlpath
context_material= None
mtl= open(mtlpath, 'rU')
for line in mtl: #.xreadlines():
if line.startswith('newmtl'):
context_material_name= line_value(line.split())
if context_material_name in unique_materials:
context_material = unique_materials[ context_material_name ]
else:
context_material = None
elif context_material:
# we need to make a material to assign properties to it.
line_split= line.split()
line_lower= line.lower().lstrip()
if line_lower.startswith('ka'):
context_material.mirror_color = (float(line_split[1]), float(line_split[2]), float(line_split[3]))
# context_material.setMirCol((float(line_split[1]), float(line_split[2]), float(line_split[3])))
elif line_lower.startswith('kd'):
context_material.diffuse_color = (float(line_split[1]), float(line_split[2]), float(line_split[3]))
# context_material.setRGBCol((float(line_split[1]), float(line_split[2]), float(line_split[3])))
elif line_lower.startswith('ks'):
context_material.specular_color = (float(line_split[1]), float(line_split[2]), float(line_split[3]))
# context_material.setSpecCol((float(line_split[1]), float(line_split[2]), float(line_split[3])))
elif line_lower.startswith('ns'):
context_material.specular_hardness = int((float(line_split[1])*0.51))
# context_material.setHardness( int((float(line_split[1])*0.51)) )
elif line_lower.startswith('ni'): # Refraction index
context_material.ior = max(1, min(float(line_split[1]), 3))
# context_material.setIOR( max(1, min(float(line_split[1]), 3))) # Between 1 and 3
elif line_lower.startswith('d') or line_lower.startswith('tr'):
context_material.alpha = float(line_split[1])
# context_material.setAlpha(float(line_split[1]))
elif line_lower.startswith('map_ka'):
img_filepath= line_value(line.split())
if img_filepath:
load_material_image(context_material, context_material_name, img_filepath, 'Ka')
elif line_lower.startswith('map_ks'):
img_filepath= line_value(line.split())
if img_filepath:
load_material_image(context_material, context_material_name, img_filepath, 'Ks')
elif line_lower.startswith('map_kd'):
img_filepath= line_value(line.split())
if img_filepath:
load_material_image(context_material, context_material_name, img_filepath, 'Kd')
elif line_lower.startswith('map_bump'):
img_filepath= line_value(line.split())
if img_filepath:
load_material_image(context_material, context_material_name, img_filepath, 'Bump')
elif line_lower.startswith('map_d') or line_lower.startswith('map_tr'): # Alpha map - Dissolve
img_filepath= line_value(line.split())
if img_filepath:
load_material_image(context_material, context_material_name, img_filepath, 'D')
elif line_lower.startswith('refl'): # Reflectionmap
img_filepath= line_value(line.split())
if img_filepath:
load_material_image(context_material, context_material_name, img_filepath, 'refl')
mtl.close()
def split_mesh(verts_loc, faces, unique_materials, filepath, SPLIT_OB_OR_GROUP, SPLIT_MATERIALS):
'''
Takes vert_loc and faces, and seperates into multiple sets of
(verts_loc, faces, unique_materials, dataname)
This is done so objects do not overload the 16 material limit.
'''
filename = stripExt(stripPath(filepath))
if not SPLIT_OB_OR_GROUP and not SPLIT_MATERIALS:
# use the filename for the object name since we arnt chopping up the mesh.
return [(verts_loc, faces, unique_materials, filename)]
def key_to_name(key):
# if the key is a tuple, join it to make a string
if type(key) == tuple:
return '%s_%s' % key
elif not key:
return filename # assume its a string. make sure this is true if the splitting code is changed
else:
return key
# Return a key that makes the faces unique.
if SPLIT_OB_OR_GROUP and not SPLIT_MATERIALS:
def face_key(face):
return face[4] # object
elif not SPLIT_OB_OR_GROUP and SPLIT_MATERIALS:
def face_key(face):
return face[2] # material
else: # Both
def face_key(face):
return face[4], face[2] # object,material
face_split_dict= {}
oldkey= -1 # initialize to a value that will never match the key
for face in faces:
key= face_key(face)
if oldkey != key:
# Check the key has changed.
try:
verts_split, faces_split, unique_materials_split, vert_remap= face_split_dict[key]
except KeyError:
faces_split= []
verts_split= []
unique_materials_split= {}
vert_remap= [-1]*len(verts_loc)
face_split_dict[key]= (verts_split, faces_split, unique_materials_split, vert_remap)
oldkey= key
face_vert_loc_indicies= face[0]
# Remap verts to new vert list and add where needed
for enum, i in enumerate(face_vert_loc_indicies):
if vert_remap[i] == -1:
new_index= len(verts_split)
vert_remap[i]= new_index # set the new remapped index so we only add once and can reference next time.
face_vert_loc_indicies[enum] = new_index # remap to the local index
verts_split.append( verts_loc[i] ) # add the vert to the local verts
else:
face_vert_loc_indicies[enum] = vert_remap[i] # remap to the local index
matname= face[2]
if matname and matname not in unique_materials_split:
unique_materials_split[matname] = unique_materials[matname]
faces_split.append(face)
# remove one of the itemas and reorder
return [(value[0], value[1], value[2], key_to_name(key)) for key, value in list(face_split_dict.items())]
def create_mesh(scn, new_objects, has_ngons, CREATE_FGONS, CREATE_EDGES, verts_loc, verts_tex, faces, unique_materials, unique_material_images, unique_smooth_groups, vertex_groups, dataname):
'''
Takes all the data gathered and generates a mesh, adding the new object to new_objects
deals with fgons, sharp edges and assigning materials
'''
if not has_ngons:
CREATE_FGONS= False
if unique_smooth_groups:
sharp_edges= {}
smooth_group_users= dict([ (context_smooth_group, {}) for context_smooth_group in list(unique_smooth_groups.keys()) ])
context_smooth_group_old= -1
# Split fgons into tri's
fgon_edges= {} # Used for storing fgon keys
if CREATE_EDGES:
edges= []
context_object= None
# reverse loop through face indicies
for f_idx in range(len(faces)-1, -1, -1):
face_vert_loc_indicies,\
face_vert_tex_indicies,\
context_material,\
context_smooth_group,\
context_object= faces[f_idx]
len_face_vert_loc_indicies = len(face_vert_loc_indicies)
if len_face_vert_loc_indicies==1:
faces.pop(f_idx)# cant add single vert faces
elif not face_vert_tex_indicies or len_face_vert_loc_indicies == 2: # faces that have no texture coords are lines
if CREATE_EDGES:
# generators are better in python 2.4+ but can't be used in 2.3
# edges.extend( (face_vert_loc_indicies[i], face_vert_loc_indicies[i+1]) for i in xrange(len_face_vert_loc_indicies-1) )
edges.extend( [(face_vert_loc_indicies[i], face_vert_loc_indicies[i+1]) for i in range(len_face_vert_loc_indicies-1)] )
faces.pop(f_idx)
else:
# Smooth Group
if unique_smooth_groups and context_smooth_group:
# Is a part of of a smooth group and is a face
if context_smooth_group_old is not context_smooth_group:
edge_dict= smooth_group_users[context_smooth_group]
context_smooth_group_old= context_smooth_group
for i in range(len_face_vert_loc_indicies):
i1= face_vert_loc_indicies[i]
i2= face_vert_loc_indicies[i-1]
if i1>i2: i1,i2= i2,i1
try:
edge_dict[i1,i2]+= 1
except KeyError:
edge_dict[i1,i2]= 1
# FGons into triangles
if has_ngons and len_face_vert_loc_indicies > 4:
ngon_face_indices= BPyMesh_ngon(verts_loc, face_vert_loc_indicies)
faces.extend(\
[(\
[face_vert_loc_indicies[ngon[0]], face_vert_loc_indicies[ngon[1]], face_vert_loc_indicies[ngon[2]] ],\
[face_vert_tex_indicies[ngon[0]], face_vert_tex_indicies[ngon[1]], face_vert_tex_indicies[ngon[2]] ],\
context_material,\
context_smooth_group,\
context_object)\
for ngon in ngon_face_indices]\
)
# edges to make fgons
if CREATE_FGONS:
edge_users= {}
for ngon in ngon_face_indices:
for i in (0,1,2):
i1= face_vert_loc_indicies[ngon[i ]]
i2= face_vert_loc_indicies[ngon[i-1]]
if i1>i2: i1,i2= i2,i1
try:
edge_users[i1,i2]+=1
except KeyError:
edge_users[i1,i2]= 1
for key, users in edge_users.items():
if users>1:
fgon_edges[key]= None
# remove all after 3, means we dont have to pop this one.
faces.pop(f_idx)
# Build sharp edges
if unique_smooth_groups:
for edge_dict in list(smooth_group_users.values()):
for key, users in list(edge_dict.items()):
if users==1: # This edge is on the boundry of a group
sharp_edges[key]= None
# map the material names to an index
material_mapping= dict([(name, i) for i, name in enumerate(unique_materials)]) # enumerate over unique_materials keys()
materials= [None] * len(unique_materials)
for name, index in list(material_mapping.items()):
materials[index]= unique_materials[name]
me= bpy.data.add_mesh(dataname)
# me= bpy.data.meshes.new(dataname)
# make sure the list isnt too big
for material in materials[0:16]:
me.add_material(material)
# me.materials= materials[0:16] # make sure the list isnt too big.
#me.verts.extend([(0,0,0)]) # dummy vert
me.add_geometry(len(verts_loc), 0, len(faces))
# verts_loc is a list of (x, y, z) tuples
me.verts.foreach_set("co", unpack_list(verts_loc))
# me.verts.extend(verts_loc)
# faces is a list of (vert_indices, texco_indices, ...) tuples
# XXX faces should contain either 3 or 4 verts
# XXX no check for valid face indices
me.faces.foreach_set("verts_raw", unpack_face_list([f[0] for f in faces]))
# face_mapping= me.faces.extend([f[0] for f in faces], indexList=True)
if verts_tex and me.faces:
me.add_uv_texture()
# me.faceUV= 1
# TEXMODE= Mesh.FaceModes['TEX']
context_material_old= -1 # avoid a dict lookup
mat= 0 # rare case it may be un-initialized.
me_faces= me.faces
# ALPHA= Mesh.FaceTranspModes.ALPHA
for i, face in enumerate(faces):
if len(face[0]) < 2:
pass #raise "bad face"
elif len(face[0])==2:
if CREATE_EDGES:
edges.append(face[0])
else:
# face_index_map= face_mapping[i]
# since we use foreach_set to add faces, all of them are added
if 1:
# if face_index_map!=None: # None means the face wasnt added
blender_face = me.faces[i]
# blender_face= me_faces[face_index_map]
face_vert_loc_indicies,\
face_vert_tex_indicies,\
context_material,\
context_smooth_group,\
context_object= face
if context_smooth_group:
blender_face.smooth= True
if context_material:
if context_material_old is not context_material:
mat= material_mapping[context_material]
if mat>15:
mat= 15
context_material_old= context_material
blender_face.material_index= mat
# blender_face.mat= mat
if verts_tex:
blender_tface= me.uv_textures[0].data[i]
if context_material:
image, has_data= unique_material_images[context_material]
if image: # Can be none if the material dosnt have an image.
blender_tface.image= image
# blender_face.image= image
if has_data:
# if has_data and image.depth == 32:
blender_tface.transp = 'ALPHA'
# blender_face.transp |= ALPHA
# BUG - Evil eekadoodle problem where faces that have vert index 0 location at 3 or 4 are shuffled.
if len(face_vert_loc_indicies)==4:
if face_vert_loc_indicies[2]==0 or face_vert_loc_indicies[3]==0:
face_vert_tex_indicies= face_vert_tex_indicies[2], face_vert_tex_indicies[3], face_vert_tex_indicies[0], face_vert_tex_indicies[1]
else: # length of 3
if face_vert_loc_indicies[2]==0:
face_vert_tex_indicies= face_vert_tex_indicies[1], face_vert_tex_indicies[2], face_vert_tex_indicies[0]
# END EEEKADOODLE FIX
# assign material, uv's and image
blender_tface.uv1= verts_tex[face_vert_tex_indicies[0]]
blender_tface.uv2= verts_tex[face_vert_tex_indicies[1]]
blender_tface.uv3= verts_tex[face_vert_tex_indicies[2]]
if blender_face.verts[3] != 0:
blender_tface.uv4= verts_tex[face_vert_tex_indicies[3]]
# for ii, uv in enumerate(blender_face.uv):
# uv.x, uv.y= verts_tex[face_vert_tex_indicies[ii]]
del me_faces
# del ALPHA
if CREATE_EDGES:
me.add_geometry(0, len(edges), 0)
# edges should be a list of (a, b) tuples
me.edges.foreach_set("verts", unpack_list(edges))
# me_edges.extend( edges )
# del me_edges
# Add edge faces.
# me_edges= me.edges
def edges_match(e1, e2):
return (e1[0] == e2[0] and e1[1] == e2[1]) or (e1[0] == e2[1] and e1[1] == e2[0])
# XXX slow
# if CREATE_FGONS and fgon_edges:
# for fgon_edge in fgon_edges.keys():
# for ed in me.edges:
# if edges_match(fgon_edge, ed.verts):
# ed.fgon = True
# if CREATE_FGONS and fgon_edges:
# FGON= Mesh.EdgeFlags.FGON
# for ed in me.findEdges( fgon_edges.keys() ):
# if ed!=None:
# me_edges[ed].flag |= FGON
# del FGON
# XXX slow
# if unique_smooth_groups and sharp_edges:
# for sharp_edge in sharp_edges.keys():
# for ed in me.edges:
# if edges_match(sharp_edge, ed.verts):
# ed.sharp = True
# if unique_smooth_groups and sharp_edges:
# SHARP= Mesh.EdgeFlags.SHARP
# for ed in me.findEdges( sharp_edges.keys() ):
# if ed!=None:
# me_edges[ed].flag |= SHARP
# del SHARP
me.update()
# me.calcNormals()
ob= bpy.data.add_object("MESH", "Mesh")
ob.data= me
scn.add_object(ob)
# ob= scn.objects.new(me)
new_objects.append(ob)
# Create the vertex groups. No need to have the flag passed here since we test for the
# content of the vertex_groups. If the user selects to NOT have vertex groups saved then
# the following test will never run
for group_name, group_indicies in vertex_groups.items():
group= ob.add_vertex_group(group_name)
# me.addVertGroup(group_name)
for vertex_index in group_indicies:
ob.add_vertex_to_group(vertex_index, group, 1.0, 'REPLACE')
# me.assignVertsToGroup(group_name, group_indicies, 1.00, Mesh.AssignModes.REPLACE)
def create_nurbs(scn, context_nurbs, vert_loc, new_objects):
'''
Add nurbs object to blender, only support one type at the moment
'''
deg = context_nurbs.get('deg', (3,))
curv_range = context_nurbs.get('curv_range', None)
curv_idx = context_nurbs.get('curv_idx', [])
parm_u = context_nurbs.get('parm_u', [])
parm_v = context_nurbs.get('parm_v', [])
name = context_nurbs.get('name', 'ObjNurb')
cstype = context_nurbs.get('cstype', None)
if cstype == None:
print('\tWarning, cstype not found')
return
if cstype != 'bspline':
print('\tWarning, cstype is not supported (only bspline)')
return
if not curv_idx:
print('\tWarning, curv argument empty or not set')
return
if len(deg) > 1 or parm_v:
print('\tWarning, surfaces not supported')
return
cu = bpy.data.curves.new(name, 'Curve')
cu.flag |= 1 # 3D curve
nu = None
for pt in curv_idx:
pt = vert_loc[pt]
pt = (pt[0], pt[1], pt[2], 1.0)
if nu == None:
nu = cu.appendNurb(pt)
else:
nu.append(pt)
nu.orderU = deg[0]+1
# get for endpoint flag from the weighting
if curv_range and len(parm_u) > deg[0]+1:
do_endpoints = True
for i in range(deg[0]+1):
if abs(parm_u[i]-curv_range[0]) > 0.0001:
do_endpoints = False
break
if abs(parm_u[-(i+1)]-curv_range[1]) > 0.0001:
do_endpoints = False
break
else:
do_endpoints = False
if do_endpoints:
nu.flagU |= 2
# close
'''
do_closed = False
if len(parm_u) > deg[0]+1:
for i in xrange(deg[0]+1):
#print curv_idx[i], curv_idx[-(i+1)]
if curv_idx[i]==curv_idx[-(i+1)]:
do_closed = True
break
if do_closed:
nu.flagU |= 1
'''
ob = scn.objects.new(cu)
new_objects.append(ob)
def strip_slash(line_split):
if line_split[-1][-1]== '\\':
if len(line_split[-1])==1:
line_split.pop() # remove the \ item
else:
line_split[-1]= line_split[-1][:-1] # remove the \ from the end last number
return True
return False
def get_float_func(filepath):
'''
find the float function for this obj file
- weather to replace commas or not
'''
file= open(filepath, 'rU')
for line in file: #.xreadlines():
line = line.lstrip()
if line.startswith('v'): # vn vt v
if ',' in line:
return lambda f: float(f.replace(',', '.'))
elif '.' in line:
return float
# incase all vert values were ints
return float
def load_obj(filepath,
context,
CLAMP_SIZE= 0.0,
CREATE_FGONS= True,
CREATE_SMOOTH_GROUPS= True,
CREATE_EDGES= True,
SPLIT_OBJECTS= True,
SPLIT_GROUPS= True,
SPLIT_MATERIALS= True,
ROTATE_X90= True,
IMAGE_SEARCH=True,
POLYGROUPS=False):
'''
Called by the user interface or another script.
load_obj(path) - should give acceptable results.
This function passes the file and sends the data off
to be split into objects and then converted into mesh objects
'''
print('\nimporting obj "%s"' % filepath)
if SPLIT_OBJECTS or SPLIT_GROUPS or SPLIT_MATERIALS:
POLYGROUPS = False
time_main= time.time()
# time_main= sys.time()
verts_loc= []
verts_tex= []
faces= [] # tuples of the faces
material_libs= [] # filanems to material libs this uses
vertex_groups = {} # when POLYGROUPS is true
# Get the string to float conversion func for this file- is 'float' for almost all files.
float_func= get_float_func(filepath)
# Context variables
context_material= None
context_smooth_group= None
context_object= None
context_vgroup = None
# Nurbs
context_nurbs = {}
nurbs = []
context_parm = '' # used by nurbs too but could be used elsewhere
has_ngons= False
# has_smoothgroups= False - is explicit with len(unique_smooth_groups) being > 0
# Until we can use sets
unique_materials= {}
unique_material_images= {}
unique_smooth_groups= {}
# unique_obects= {} - no use for this variable since the objects are stored in the face.
# when there are faces that end with \
# it means they are multiline-
# since we use xreadline we cant skip to the next line
# so we need to know weather
context_multi_line= ''
print('\tparsing obj file "%s"...' % filepath)
time_sub= time.time()
# time_sub= sys.time()
file= open(filepath, 'rU')
for line in file: #.xreadlines():
line = line.lstrip() # rare cases there is white space at the start of the line
if line.startswith('v '):
line_split= line.split()
# rotate X90: (x,-z,y)
verts_loc.append( (float_func(line_split[1]), -float_func(line_split[3]), float_func(line_split[2])) )
elif line.startswith('vn '):
pass
elif line.startswith('vt '):
line_split= line.split()
verts_tex.append( (float_func(line_split[1]), float_func(line_split[2])) )
# Handel faces lines (as faces) and the second+ lines of fa multiline face here
# use 'f' not 'f ' because some objs (very rare have 'fo ' for faces)
elif line.startswith('f') or context_multi_line == 'f':
if context_multi_line:
# use face_vert_loc_indicies and face_vert_tex_indicies previously defined and used the obj_face
line_split= line.split()
else:
line_split= line[2:].split()
face_vert_loc_indicies= []
face_vert_tex_indicies= []
# Instance a face
faces.append((\
face_vert_loc_indicies,\
face_vert_tex_indicies,\
context_material,\
context_smooth_group,\
context_object\
))
if strip_slash(line_split):
context_multi_line = 'f'
else:
context_multi_line = ''
for v in line_split:
obj_vert= v.split('/')
vert_loc_index= int(obj_vert[0])-1
# Add the vertex to the current group
# *warning*, this wont work for files that have groups defined around verts
if POLYGROUPS and context_vgroup:
vertex_groups[context_vgroup].append(vert_loc_index)
# Make relative negative vert indicies absolute
if vert_loc_index < 0:
vert_loc_index= len(verts_loc) + vert_loc_index + 1
face_vert_loc_indicies.append(vert_loc_index)
if len(obj_vert)>1 and obj_vert[1]:
# formatting for faces with normals and textures us
# loc_index/tex_index/nor_index
vert_tex_index= int(obj_vert[1])-1
# Make relative negative vert indicies absolute
if vert_tex_index < 0:
vert_tex_index= len(verts_tex) + vert_tex_index + 1
face_vert_tex_indicies.append(vert_tex_index)
else:
# dummy
face_vert_tex_indicies.append(0)
if len(face_vert_loc_indicies) > 4:
has_ngons= True
elif CREATE_EDGES and (line.startswith('l ') or context_multi_line == 'l'):
# very similar to the face load function above with some parts removed
if context_multi_line:
# use face_vert_loc_indicies and face_vert_tex_indicies previously defined and used the obj_face
line_split= line.split()
else:
line_split= line[2:].split()
face_vert_loc_indicies= []
face_vert_tex_indicies= []
# Instance a face
faces.append((\
face_vert_loc_indicies,\
face_vert_tex_indicies,\
context_material,\
context_smooth_group,\
context_object\
))
if strip_slash(line_split):
context_multi_line = 'l'
else:
context_multi_line = ''
isline= line.startswith('l')
for v in line_split:
vert_loc_index= int(v)-1
# Make relative negative vert indicies absolute
if vert_loc_index < 0:
vert_loc_index= len(verts_loc) + vert_loc_index + 1
face_vert_loc_indicies.append(vert_loc_index)
elif line.startswith('s'):
if CREATE_SMOOTH_GROUPS:
context_smooth_group= line_value(line.split())
if context_smooth_group=='off':
context_smooth_group= None
elif context_smooth_group: # is not None
unique_smooth_groups[context_smooth_group]= None
elif line.startswith('o'):
if SPLIT_OBJECTS:
context_object= line_value(line.split())
# unique_obects[context_object]= None
elif line.startswith('g'):
if SPLIT_GROUPS:
context_object= line_value(line.split())
# print 'context_object', context_object
# unique_obects[context_object]= None
elif POLYGROUPS:
context_vgroup = line_value(line.split())
if context_vgroup and context_vgroup != '(null)':
vertex_groups.setdefault(context_vgroup, [])
else:
context_vgroup = None # dont assign a vgroup
elif line.startswith('usemtl'):
context_material= line_value(line.split())
unique_materials[context_material]= None
elif line.startswith('mtllib'): # usemap or usemat
material_libs.extend( line.split()[1:] ) # can have multiple mtllib filenames per line
# Nurbs support
elif line.startswith('cstype '):
context_nurbs['cstype']= line_value(line.split()) # 'rat bspline' / 'bspline'
elif line.startswith('curv ') or context_multi_line == 'curv':
line_split= line.split()
curv_idx = context_nurbs['curv_idx'] = context_nurbs.get('curv_idx', []) # incase were multiline
if not context_multi_line:
context_nurbs['curv_range'] = float_func(line_split[1]), float_func(line_split[2])
line_split[0:3] = [] # remove first 3 items
if strip_slash(line_split):
context_multi_line = 'curv'
else:
context_multi_line = ''
for i in line_split:
vert_loc_index = int(i)-1
if vert_loc_index < 0:
vert_loc_index= len(verts_loc) + vert_loc_index + 1
curv_idx.append(vert_loc_index)
elif line.startswith('parm') or context_multi_line == 'parm':
line_split= line.split()
if context_multi_line:
context_multi_line = ''
else:
context_parm = line_split[1]
line_split[0:2] = [] # remove first 2
if strip_slash(line_split):
context_multi_line = 'parm'
else:
context_multi_line = ''
if context_parm.lower() == 'u':
context_nurbs.setdefault('parm_u', []).extend( [float_func(f) for f in line_split] )
elif context_parm.lower() == 'v': # surfaces not suported yet
context_nurbs.setdefault('parm_v', []).extend( [float_func(f) for f in line_split] )
# else: # may want to support other parm's ?
elif line.startswith('deg '):
context_nurbs['deg']= [int(i) for i in line.split()[1:]]
elif line.startswith('end'):
# Add the nurbs curve
if context_object:
context_nurbs['name'] = context_object
nurbs.append(context_nurbs)
context_nurbs = {}
context_parm = ''
''' # How to use usemap? depricated?
elif line.startswith('usema'): # usemap or usemat
context_image= line_value(line.split())
'''
file.close()
time_new= time.time()
# time_new= sys.time()
print('%.4f sec' % (time_new-time_sub))
time_sub= time_new
print('\tloading materials and images...')
create_materials(filepath, material_libs, unique_materials, unique_material_images, IMAGE_SEARCH)
time_new= time.time()
# time_new= sys.time()
print('%.4f sec' % (time_new-time_sub))
time_sub= time_new
if not ROTATE_X90:
verts_loc[:] = [(v[0], v[2], -v[1]) for v in verts_loc]
# deselect all
# if context.selected_objects:
# bpy.ops.OBJECT_OT_select_all_toggle()
scene = context.scene
# scn = bpy.data.scenes.active
# scn.objects.selected = []
new_objects= [] # put new objects here
print('\tbuilding geometry...\n\tverts:%i faces:%i materials: %i smoothgroups:%i ...' % ( len(verts_loc), len(faces), len(unique_materials), len(unique_smooth_groups) ))
# Split the mesh by objects/materials, may
if SPLIT_OBJECTS or SPLIT_GROUPS: SPLIT_OB_OR_GROUP = True
else: SPLIT_OB_OR_GROUP = False
for verts_loc_split, faces_split, unique_materials_split, dataname in split_mesh(verts_loc, faces, unique_materials, filepath, SPLIT_OB_OR_GROUP, SPLIT_MATERIALS):
# Create meshes from the data, warning 'vertex_groups' wont support splitting
create_mesh(scene, new_objects, has_ngons, CREATE_FGONS, CREATE_EDGES, verts_loc_split, verts_tex, faces_split, unique_materials_split, unique_material_images, unique_smooth_groups, vertex_groups, dataname)
# nurbs support
# for context_nurbs in nurbs:
# create_nurbs(scn, context_nurbs, verts_loc, new_objects)
axis_min= [ 1000000000]*3
axis_max= [-1000000000]*3
# if CLAMP_SIZE:
# # Get all object bounds
# for ob in new_objects:
# for v in ob.getBoundBox():
# for axis, value in enumerate(v):
# if axis_min[axis] > value: axis_min[axis]= value
# if axis_max[axis] < value: axis_max[axis]= value
# # Scale objects
# max_axis= max(axis_max[0]-axis_min[0], axis_max[1]-axis_min[1], axis_max[2]-axis_min[2])
# scale= 1.0
# while CLAMP_SIZE < max_axis * scale:
# scale= scale/10.0
# for ob in new_objects:
# ob.setSize(scale, scale, scale)
# Better rotate the vert locations
#if not ROTATE_X90:
# for ob in new_objects:
# ob.RotX = -1.570796326794896558
time_new= time.time()
# time_new= sys.time()
print('%.4f sec' % (time_new-time_sub))
print('finished importing: "%s" in %.4f sec.' % (filepath, (time_new-time_main)))
DEBUG= True
def load_obj_ui(filepath, BATCH_LOAD= False):
if BPyMessages.Error_NoFile(filepath):
return
global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, POLYGROUPS, KEEP_VERT_ORDER, ROTATE_X90
CREATE_SMOOTH_GROUPS= Draw.Create(0)
CREATE_FGONS= Draw.Create(1)
CREATE_EDGES= Draw.Create(1)
SPLIT_OBJECTS= Draw.Create(0)
SPLIT_GROUPS= Draw.Create(0)
SPLIT_MATERIALS= Draw.Create(0)
CLAMP_SIZE= Draw.Create(10.0)
IMAGE_SEARCH= Draw.Create(1)
POLYGROUPS= Draw.Create(0)
KEEP_VERT_ORDER= Draw.Create(1)
ROTATE_X90= Draw.Create(1)
# Get USER Options
# Note, Works but not pretty, instead use a more complicated GUI
'''
pup_block= [\
'Import...',\
('Smooth Groups', CREATE_SMOOTH_GROUPS, 'Surround smooth groups by sharp edges'),\
('Create FGons', CREATE_FGONS, 'Import faces with more then 4 verts as fgons.'),\
('Lines', CREATE_EDGES, 'Import lines and faces with 2 verts as edges'),\
'Separate objects from obj...',\
('Object', SPLIT_OBJECTS, 'Import OBJ Objects into Blender Objects'),\
('Group', SPLIT_GROUPS, 'Import OBJ Groups into Blender Objects'),\
('Material', SPLIT_MATERIALS, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)'),\
'Options...',\
('Keep Vert Order', KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
('Clamp Scale:', CLAMP_SIZE, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)'),\
('Image Search', IMAGE_SEARCH, 'Search subdirs for any assosiated images (Warning, may be slow)'),\
]
if not Draw.PupBlock('Import OBJ...', pup_block):
return
if KEEP_VERT_ORDER.val:
SPLIT_OBJECTS.val = False
SPLIT_GROUPS.val = False
SPLIT_MATERIALS.val = False
'''
# BEGIN ALTERNATIVE UI *******************
if True:
EVENT_NONE = 0
EVENT_EXIT = 1
EVENT_REDRAW = 2
EVENT_IMPORT = 3
GLOBALS = {}
GLOBALS['EVENT'] = EVENT_REDRAW
#GLOBALS['MOUSE'] = Window.GetMouseCoords()
GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
def obj_ui_set_event(e,v):
GLOBALS['EVENT'] = e
def do_split(e,v):
global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER, POLYGROUPS
if SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val:
KEEP_VERT_ORDER.val = 0
POLYGROUPS.val = 0
else:
KEEP_VERT_ORDER.val = 1
def do_vertorder(e,v):
global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER
if KEEP_VERT_ORDER.val:
SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0
else:
if not (SPLIT_OBJECTS.val or SPLIT_GROUPS.val or SPLIT_MATERIALS.val):
KEEP_VERT_ORDER.val = 1
def do_polygroups(e,v):
global SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, KEEP_VERT_ORDER, POLYGROUPS
if POLYGROUPS.val:
SPLIT_OBJECTS.val = SPLIT_GROUPS.val = SPLIT_MATERIALS.val = 0
def do_help(e,v):
url = __url__[0]
print('Trying to open web browser with documentation at this address...')
print('\t' + url)
try:
import webbrowser
webbrowser.open(url)
except:
print('...could not open a browser window.')
def obj_ui():
ui_x, ui_y = GLOBALS['MOUSE']
# Center based on overall pup size
ui_x -= 165
ui_y -= 90
global CREATE_SMOOTH_GROUPS, CREATE_FGONS, CREATE_EDGES, SPLIT_OBJECTS, SPLIT_GROUPS, SPLIT_MATERIALS, CLAMP_SIZE, IMAGE_SEARCH, POLYGROUPS, KEEP_VERT_ORDER, ROTATE_X90
Draw.Label('Import...', ui_x+9, ui_y+159, 220, 21)
Draw.BeginAlign()
CREATE_SMOOTH_GROUPS = Draw.Toggle('Smooth Groups', EVENT_NONE, ui_x+9, ui_y+139, 110, 20, CREATE_SMOOTH_GROUPS.val, 'Surround smooth groups by sharp edges')
CREATE_FGONS = Draw.Toggle('NGons as FGons', EVENT_NONE, ui_x+119, ui_y+139, 110, 20, CREATE_FGONS.val, 'Import faces with more then 4 verts as fgons')
CREATE_EDGES = Draw.Toggle('Lines as Edges', EVENT_NONE, ui_x+229, ui_y+139, 110, 20, CREATE_EDGES.val, 'Import lines and faces with 2 verts as edges')
Draw.EndAlign()
Draw.Label('Separate objects by OBJ...', ui_x+9, ui_y+110, 220, 20)
Draw.BeginAlign()
SPLIT_OBJECTS = Draw.Toggle('Object', EVENT_REDRAW, ui_x+9, ui_y+89, 55, 21, SPLIT_OBJECTS.val, 'Import OBJ Objects into Blender Objects', do_split)
SPLIT_GROUPS = Draw.Toggle('Group', EVENT_REDRAW, ui_x+64, ui_y+89, 55, 21, SPLIT_GROUPS.val, 'Import OBJ Groups into Blender Objects', do_split)
SPLIT_MATERIALS = Draw.Toggle('Material', EVENT_REDRAW, ui_x+119, ui_y+89, 60, 21, SPLIT_MATERIALS.val, 'Import each material into a seperate mesh (Avoids > 16 per mesh error)', do_split)
Draw.EndAlign()
# Only used for user feedback
KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+184, ui_y+89, 113, 21, KEEP_VERT_ORDER.val, 'Keep vert and face order, disables split options, enable for morph targets', do_vertorder)
ROTATE_X90 = Draw.Toggle('-X90', EVENT_REDRAW, ui_x+302, ui_y+89, 38, 21, ROTATE_X90.val, 'Rotate X 90.')
Draw.Label('Options...', ui_x+9, ui_y+60, 211, 20)
CLAMP_SIZE = Draw.Number('Clamp Scale: ', EVENT_NONE, ui_x+9, ui_y+39, 130, 21, CLAMP_SIZE.val, 0.0, 1000.0, 'Clamp the size to this maximum (Zero to Disable)')
POLYGROUPS = Draw.Toggle('Poly Groups', EVENT_REDRAW, ui_x+144, ui_y+39, 90, 21, POLYGROUPS.val, 'Import OBJ groups as vertex groups.', do_polygroups)
IMAGE_SEARCH = Draw.Toggle('Image Search', EVENT_NONE, ui_x+239, ui_y+39, 100, 21, IMAGE_SEARCH.val, 'Search subdirs for any assosiated images (Warning, may be slow)')
Draw.BeginAlign()
Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 21, 'Load the wiki page for this script', do_help)
Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 21, '', obj_ui_set_event)
Draw.PushButton('Import', EVENT_IMPORT, ui_x+229, ui_y+9, 110, 21, 'Import with these settings', obj_ui_set_event)
Draw.EndAlign()
# hack so the toggle buttons redraw. this is not nice at all
while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_IMPORT):
Draw.UIBlock(obj_ui, 0)
if GLOBALS['EVENT'] != EVENT_IMPORT:
return
# END ALTERNATIVE UI *********************
Window.WaitCursor(1)
if BATCH_LOAD: # load the dir
try:
files= [ f for f in os.listdir(filepath) if f.lower().endswith('.obj') ]
except:
Window.WaitCursor(0)
Draw.PupMenu('Error%t|Could not open path ' + filepath)
return
if not files:
Window.WaitCursor(0)
Draw.PupMenu('Error%t|No files at path ' + filepath)
return
for f in files:
scn= bpy.data.scenes.new( stripExt(f) )
scn.makeCurrent()
load_obj(sys.join(filepath, f),\
CLAMP_SIZE.val,\
CREATE_FGONS.val,\
CREATE_SMOOTH_GROUPS.val,\
CREATE_EDGES.val,\
SPLIT_OBJECTS.val,\
SPLIT_GROUPS.val,\
SPLIT_MATERIALS.val,\
ROTATE_X90.val,\
IMAGE_SEARCH.val,\
POLYGROUPS.val
)
else: # Normal load
load_obj(filepath,\
CLAMP_SIZE.val,\
CREATE_FGONS.val,\
CREATE_SMOOTH_GROUPS.val,\
CREATE_EDGES.val,\
SPLIT_OBJECTS.val,\
SPLIT_GROUPS.val,\
SPLIT_MATERIALS.val,\
ROTATE_X90.val,\
IMAGE_SEARCH.val,\
POLYGROUPS.val
)
Window.WaitCursor(0)
def load_obj_ui_batch(file):
load_obj_ui(file, True)
DEBUG= False
# if __name__=='__main__' and not DEBUG:
# if os and Window.GetKeyQualifiers() & Window.Qual.SHIFT:
# Window.FileSelector(load_obj_ui_batch, 'Import OBJ Dir', '')
# else:
# Window.FileSelector(load_obj_ui, 'Import a Wavefront OBJ', '*.obj')
# For testing compatibility
'''
else:
# DEBUG ONLY
TIME= sys.time()
DIR = '/fe/obj'
import os
print 'Searching for files'
def fileList(path):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
yield os.path.join(dirpath, filename)
files = [f for f in fileList(DIR) if f.lower().endswith('.obj')]
files.sort()
for i, obj_file in enumerate(files):
if 0 < i < 20:
print 'Importing', obj_file, '\nNUMBER', i, 'of', len(files)
newScn= bpy.data.scenes.new(os.path.basename(obj_file))
newScn.makeCurrent()
load_obj(obj_file, False, IMAGE_SEARCH=0)
print 'TOTAL TIME: %.6f' % (sys.time() - TIME)
'''
class IMPORT_OT_obj(bpy.types.Operator):
'''Load a Wavefront OBJ File.'''
__idname__ = "import.obj"
__label__ = "Import OBJ"
# List of operator properties, the attributes will be assigned
# to the class instance from the operator settings before calling.
__props__ = [
bpy.props.StringProperty(attr="path", name="File Path", description="File path used for importing the OBJ file", maxlen= 1024, default= ""),
bpy.props.BoolProperty(attr="CREATE_SMOOTH_GROUPS", name="Smooth Groups", description="Surround smooth groups by sharp edges", default= True),
bpy.props.BoolProperty(attr="CREATE_FGONS", name="NGons as FGons", description="Import faces with more then 4 verts as fgons", default= True),
bpy.props.BoolProperty(attr="CREATE_EDGES", name="Lines as Edges", description="Import lines and faces with 2 verts as edge", default= True),
bpy.props.BoolProperty(attr="SPLIT_OBJECTS", name="Object", description="Import OBJ Objects into Blender Objects", default= True),
bpy.props.BoolProperty(attr="SPLIT_GROUPS", name="Group", description="Import OBJ Groups into Blender Objects", default= True),
bpy.props.BoolProperty(attr="SPLIT_MATERIALS", name="Material", description="Import each material into a seperate mesh (Avoids > 16 per mesh error)", default= True),
# old comment: only used for user feedback
# disabled this option because in old code a handler for it disabled SPLIT* params, it's not passed to load_obj
# bpy.props.BoolProperty(attr="KEEP_VERT_ORDER", name="Keep Vert Order", description="Keep vert and face order, disables split options, enable for morph targets", default= True),
bpy.props.BoolProperty(attr="ROTATE_X90", name="-X90", description="Rotate X 90.", default= True),
bpy.props.FloatProperty(attr="CLAMP_SIZE", name="Clamp Scale", description="Clamp the size to this maximum (Zero to Disable)", min=0.01, max=1000.0, soft_min=0.0, soft_max=1000.0, default=0.0),
bpy.props.BoolProperty(attr="POLYGROUPS", name="Poly Groups", description="Import OBJ groups as vertex groups.", default= True),
bpy.props.BoolProperty(attr="IMAGE_SEARCH", name="Image Search", description="Search subdirs for any assosiated images (Warning, may be slow)", default= True),
]
def execute(self, context):
# print("Selected: " + context.active_object.name)
load_obj(self.path,
context,
self.CLAMP_SIZE,
self.CREATE_FGONS,
self.CREATE_SMOOTH_GROUPS,
self.CREATE_EDGES,
self.SPLIT_OBJECTS,
self.SPLIT_GROUPS,
self.SPLIT_MATERIALS,
self.ROTATE_X90,
self.IMAGE_SEARCH,
self.POLYGROUPS)
return ('FINISHED',)
def invoke(self, context, event):
wm = context.manager
wm.add_fileselect(self.__operator__)
return ('RUNNING_MODAL',)
bpy.ops.add(IMPORT_OT_obj)
import dynamic_menu
menu_func = lambda self, context: self.layout.itemO("import.obj", text="Wavefront (.obj)...")
menu_item = dynamic_menu.add(bpy.types.INFO_MT_file_import, menu_func)
# NOTES (all line numbers refer to 2.4x import_obj.py, not this file)
# check later: line 489
# can convert now: edge flags, edges: lines 508-528
# ngon (uses python module BPyMesh): 384-414
# nurbs: 947-
# NEXT clamp size: get bound box with RNA
# get back to l 140 (here)
# search image in bpy.config.textureDir - load_image
# replaced BPyImage.comprehensiveImageLoad with a simplified version that only checks additional directory specified, but doesn't search dirs recursively (obj_image_load)
# bitmask won't work? - 132
# uses operator bpy.ops.OBJECT_OT_select_all_toggle() to deselect all (not necessary?)
# uses bpy.sys.time()
|
import { compose, applyMiddleware } from "@reduxjs/toolkit";
import { createStore } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // defaults to localStorage for web
import thunkMiddleware from "redux-thunk-recursion-detect";
import { encryptTransform } from "redux-persist-transform-encrypt";
import currentReducer from "./Redux.reducer";
const encryptConfig = {
transforms: [
encryptTransform({
secretKey: "my-super-secret-key",
onError: function (error) {
console.log(error);
},
}),
],
};
const persistConfig = {
key: "root",
storage,
...encryptConfig,
};
const persistedReducer = persistReducer(persistConfig, currentReducer);
export const store = createStore(
persistedReducer,
compose(applyMiddleware(thunkMiddleware))
);
export const persistor = persistStore(store);
|
package koreait.day11.test;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class DateTimeTest {
public static void main(String[] args) {
//현재시간 :ms, ns (1970년 1웡1일 자정을 기준으로 단위마다 카운트한 값입니다.)
//1일 , 1년은 각가 몇 ms 일까요? 1초=1000ms(1ms=0.001초)
int result = 24*60*60*1000;
System.out.println("1일은 "+ result + "ms 입니다.");
//int 범위벗어나면 overflow 입니다. long변환 필요
System.out.println("1년은 "+ result*365L + "ms 입니다 " );
DecimalFormat df =new DecimalFormat("###,###,###,###");
System.out.println("1년은 "+ df.format(result*365L)+"ms 입니다");
System.out.println("1일은 "+ df.format(result)+"ms 입니다");
//String.format("%15s", ~)으로 하면 자리 정렬 위치를 맞출수 있습니다
/*
* 날짜와 시간형식을 다루는 자바클래스를 연습합니다.
1)java.util.Date 클래스
2)java.util.Calendar 클래스
3) java 8 버전 java.time.LocalDate(날짜) , LocalTime(시간) , LocalDateTime(날짜와 시간) 클래스
4) java.sql
*
*/
LocalDate currentDate = LocalDate.now(); //static 매소드로 객체를 생성
System.out.println("날짜 확인 : " + currentDate);
LocalTime currentTime =LocalTime.now();
System.out.println("시간확인 : "+currentTime);
LocalDateTime current =LocalDateTime.now();
System.out.println(" 날자와 시간확인"+current);
LocalDate mybirth =LocalDate.of(1929, 11,29 );
System.out.println("내생일 :"+mybirth);
LocalTime mybirth_time =LocalTime.of(18, 10);
System.out.println("내 탄생시간"+mybirth_time);
//날자 사이에 간격계산 클래스가 있습니다
Period between = Period.between(mybirth, currentDate);
System.out.println("내가 태어난지"+between.getYears()+"년(years)");
System.out.println("내가 태어난지"+between.getMonths() +"개월(months)");
System.out.println("내가 태어난지"+between.getDays() +"일(days)");
System.out.println("테스트 : "+ChronoUnit.DAYS.between(mybirth, currentDate)+"일 지났습니다");
//Duration 클레스
}
}
|
import * as S from "./index.styled";
import logoImg from "../../../asset/img/logo/2.png";
import Datepicker from "components/datepicker";
import SelectBox from "components/selectbox";
import { ProfileInfo, TokenValue, UserInfo } from "atoms/atoms";
import { useRecoilState, useRecoilValue } from "recoil";
type inputModalProps = {
setShowModal: (value: boolean) => void;
};
const InputModal = ({ setShowModal }: inputModalProps) => {
const [userInfo, setUserInfo] = useRecoilState(UserInfo);
const [profileInfo, setProfileInfo] = useRecoilState(ProfileInfo);
const token = useRecoilValue(TokenValue);
const handleCloseModal = () => {
setShowModal(false); //부모가 보내준 함수를 사용, 즉 부모에서 이 모달을 여닫을 변수를 관리하는 것
};
const handleInputChange = (
source: "phoneNumber" | "content" | "userHobby" | "userJob",
e: React.ChangeEvent<HTMLInputElement>
) => {
// console.log("source", source, "value", e.target.value);
if (source === "content") {
let tmp = e.target.value;
let replaced_str = tmp.replace(/_/g, " ");
setProfileInfo({ ...profileInfo, [source]: replaced_str });
} else {
source === "phoneNumber" &&
setUserInfo({ ...userInfo, [source]: e.target.value });
source !== "phoneNumber" &&
setProfileInfo({ ...profileInfo, [source]: e.target.value });
}
};
const putProfile = async () => {
console.log("POSTProfile", token, profileInfo);
fetch(`${process.env.REACT_APP_BASE_URL}/profile`, {
method: "POST",
headers: {
Auth: token,
"Content-Type": "application/json",
},
body: JSON.stringify({
userSido: profileInfo.userSido,
userGugun: profileInfo.userGugun,
userJob: profileInfo.userJob,
userHobby: profileInfo.userHobby,
userMbti: profileInfo.userMbti,
content: profileInfo.content,
}),
});
};
const putUsers = async () => {
console.log("putUsers", token, userInfo);
fetch(`${process.env.REACT_APP_BASE_URL}/users/mypage`, {
method: "PUT",
headers: {
Auth: token,
"Content-Type": "application/json",
},
body: JSON.stringify({
phoneNumber: userInfo.phoneNumber,
userAge: userInfo.userAge,
userGender: userInfo.userGender,
}),
});
};
const handleOnClick = async () => {
await putProfile();
await putUsers();
window.location.href = "/home";
};
return (
<S.ModalWrapper onClick={handleCloseModal}>
<S.ModalContent onClick={(e) => e.stopPropagation()}>
<S.LogoImg src={logoImg} alt="logo" />
<S.Title>기본정보</S.Title>
<S.UserBox>
<S.Section>
<S.SubTitle> 성별 </S.SubTitle>
<SelectBox name="userGender" />
</S.Section>
<S.Section>
<S.SubTitle> 생일 </S.SubTitle>
<Datepicker name="userAge" />
</S.Section>
<S.Section>
<S.SubTitle> 번호 </S.SubTitle>
<S.StyledInput
onChange={(e) => handleInputChange("phoneNumber", e)}
placeholder="휴대폰 번호 ( - 없이 입력)"
/>
</S.Section>
</S.UserBox>
<S.Title source="profile">선택정보</S.Title>
<S.ProfileBox>
<S.Section>
<S.SubTitle> 주소 </S.SubTitle>
<SelectBox name="userSido" />
<SelectBox name="userGugun" />
</S.Section>
<S.Section>
<S.SubTitle> 소개 </S.SubTitle>
<S.StyledInput
onChange={(e) => handleInputChange("content", e)}
placeholder="한줄 소개"
/>
</S.Section>
<S.Section>
<S.SubTitle> 취미 </S.SubTitle>
<S.StyledInput
onChange={(e) => handleInputChange("userHobby", e)}
placeholder="취미"
/>
</S.Section>
<S.Section>
<S.SubTitle> 직업 </S.SubTitle>
<S.StyledInput
onChange={(e) => handleInputChange("userJob", e)}
placeholder="직업"
/>
</S.Section>
<S.Section>
<S.SubTitle> MBTI </S.SubTitle>
<SelectBox name="userMbti" />
</S.Section>
</S.ProfileBox>
<S.Button onClick={handleOnClick}>입력완료</S.Button>
</S.ModalContent>
</S.ModalWrapper>
);
};
export default InputModal;
|
package com.travel.api.faq.domain.repository;
import com.travel.api.common.domain.CommonDto;
import com.travel.api.common.domain.CommonEntity;
import com.travel.api.faq.domain.FaqDto;
import com.travel.api.faq.domain.FaqEntity;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.TestConstructor;
import org.springframework.test.context.TestPropertySource;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace.NONE;
import static org.springframework.test.context.TestConstructor.AutowireMode.ALL;
@DataJpaTest
@Transactional
@TestPropertySource(locations = "classpath:application.properties")
@TestConstructor(autowireMode = ALL)
@RequiredArgsConstructor
@AutoConfigureTestDatabase(replace = NONE)
@ExtendWith(MockitoExtension.class)
@DisplayName("FAQ Repository Test")
class FaqQueryRepositoryTest {
@Mock private FaqQueryRepository mockFaqQueryRepository;
private final FaqQueryRepository faqQueryRepository;
private final EntityManager em;
private FaqEntity faqEntity;
private FaqDto faqDTO;
private CommonEntity commonEntity;
private CommonDto commonDto;
void createFaq() {
commonEntity = CommonEntity.builder()
.commonCode(999)
.commonName("서울")
.visible("Y")
.build();
em.persist(commonEntity);
faqEntity = FaqEntity.builder()
.title("FAQ 등록 테스트")
.description("FAQ 등록 테스트")
.viewCount(1)
.visible("Y")
.newFaqCode(commonEntity)
.build();
em.persist(faqEntity);
faqDTO = FaqEntity.toDto(faqEntity);
}
@BeforeEach
@EventListener(ApplicationReadyEvent.class)
public void init() { createFaq(); }
@Test
@DisplayName("FAQ 리스트 조회 테스트")
void FAQ리스트조회테스트() {
Map<String, Object> faqMap = new HashMap<>();
PageRequest pageRequest = PageRequest.of(0, 3);
Page<FaqDto> faqList = faqQueryRepository.findFaqList(faqMap, pageRequest);
assertThat(faqList.getTotalElements()).isGreaterThan(0);
}
@Test
@DisplayName("FAQ 리스트 조회 Mockito 테스트")
void FAQ리스트조회Mockito테스트() {
Map<String, Object> faqMap = new HashMap<>();
PageRequest pageRequest = PageRequest.of(0, 3);
List<FaqDto> faqList = new ArrayList<>();
faqList.add(faqDTO);
Page<FaqDto> resultPage = new PageImpl<>(faqList, pageRequest, faqList.size());
// when
when(mockFaqQueryRepository.findFaqList(faqMap, pageRequest)).thenReturn(resultPage);
Page<FaqDto> newFaqList = mockFaqQueryRepository.findFaqList(faqMap, pageRequest);
List<FaqDto> findFaqList = newFaqList.stream().collect(Collectors.toList());
// then
assertThat(findFaqList.get(0).getFaqCode()).isEqualTo(faqList.get(0).getFaqCode());
assertThat(findFaqList.get(0).getTitle()).isEqualTo(faqList.get(0).getTitle());
assertThat(findFaqList.get(0).getDescription()).isEqualTo(faqList.get(0).getDescription());
// verify
verify(mockFaqQueryRepository, times(1)).findFaqList(faqMap, pageRequest);
verify(mockFaqQueryRepository, atLeastOnce()).findFaqList(faqMap, pageRequest);
verifyNoMoreInteractions(mockFaqQueryRepository);
InOrder inOrder = inOrder(mockFaqQueryRepository);
inOrder.verify(mockFaqQueryRepository).findFaqList(faqMap, pageRequest);
}
@Test
@DisplayName("FAQ 상세 조회 Mockito 테스트")
void FAQ상세조회Mockito테스트() {
// when
when(mockFaqQueryRepository.findOneFaq(faqEntity.getIdx())).thenReturn(faqDTO);
FaqDto faqInfo = mockFaqQueryRepository.findOneFaq(faqEntity.getIdx());
// then
assertThat(faqInfo.getTitle()).isEqualTo(faqEntity.getTitle());
assertThat(faqInfo.getDescription()).isEqualTo(faqEntity.getDescription());
// verify
verify(mockFaqQueryRepository, times(1)).findOneFaq(faqEntity.getIdx());
verify(mockFaqQueryRepository, atLeastOnce()).findOneFaq(faqEntity.getIdx());
verifyNoMoreInteractions(mockFaqQueryRepository);
InOrder inOrder = inOrder(mockFaqQueryRepository);
inOrder.verify(mockFaqQueryRepository).findOneFaq(faqEntity.getIdx());
}
}
|
import UIKit
import Combine
class EditScreenViewController: BaseViewController {
private let editView = EditUserInfoView(frame: .zero)
private var viewModel: EditScreenViewModel
private var currentUser: User?
private var cancellable: Set<AnyCancellable> = []
let imagePicker = ImagePicker()
init(viewModel: EditScreenViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = editView
editView.didTapEditAvatarImage = { [weak self] in
self?.imagePicker.showImagePicker(in: self ?? UIViewController())
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Обо мне"
createTextFieldUserDataCards()
setupBindings()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.setCurrentUser()
editView.configure(user: currentUser ?? User(id: nil, email: "", userName: "", avatarImageUrl: nil, password: ""))
}
private func createTextFieldUserDataCards() {
let dataManager = SystemUICardsManager()
for card in dataManager.changeDataUsersCards {
card.dataTextField.delegate = self
editView.dataCardsSV.addArrangedSubview(card)
}
}
private func setupBindings() {
viewModel.$currentUser.sink { [weak self] user in
self?.currentUser = user
self?.editView.configure(user: self?.currentUser ?? User(id: nil, email: "", userName: "", avatarImageUrl: nil, password: ""))
}.store(in: &cancellable)
}
}
extension EditScreenViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
for card in editView.dataCardsSV.arrangedSubviews {
(card as? ChangeDataUserCardView)?.dataTextField.resignFirstResponder()
}
return true
}
}
|
import {
deductBalance,
saveForwardTraffic,
tempWaitDeductBalance,
} from "./forward";
import { dbMock, redisMock } from "../../../test/jest.setup";
import { forwardStub } from "../../../test/fixtures/forward.stub";
import { configStub } from "../../../test/fixtures/config.stub";
import { walletStub } from "../../../test/fixtures/wallet.stub";
import { updateUserWallet } from "./user";
import { agentStub } from "../../../test/fixtures/agent.stub";
import { BalanceLogType, BalanceType } from "@prisma/client";
import { forwardTrafficStub } from "../../../test/fixtures/forward-traffic.stub";
import { agentTaskStub } from "../../../test/fixtures/agent-task.stub";
import { distributeTask } from "./agent-task";
import { deleteNetwork } from "./network";
jest.mock("~/server/core/user", () => ({
updateUserWallet: jest.fn().mockImplementation(async () => walletStub.wallet),
}));
jest.mock("~/server/core/agent-task", () => ({
distributeTask: jest
.fn()
.mockImplementation(async () => agentTaskStub.helloTask.id),
getTaskResult: jest
.fn()
.mockImplementation(async () => agentTaskStub.helloTask.result),
}));
jest.mock("~/server/core/network", () => ({
deleteNetwork: jest.fn().mockImplementation(async () => ({
id: "networkId",
})),
}));
describe("forward", () => {
describe("saveForwardTraffic", () => {
it("should update last traffic if time is less than 2 minutes", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.forwardTraffic.findFirst.mockResolvedValue({
...forwardTrafficStub.kb,
});
await saveForwardTraffic({
forwardId: forwardStub.forward.id,
traffics: [forwardTrafficStub.kb],
});
expect(dbMock.forwardTraffic.createMany).toHaveBeenCalledTimes(0);
expect(dbMock.forwardTraffic.update).toHaveBeenCalledTimes(1);
expect(dbMock.forwardTraffic.update).toHaveBeenCalledWith({
where: {
id: forwardTrafficStub.kb.id,
},
data: {
upload: 2048,
download: 2048,
},
});
});
it("should create new traffic if time is more than 2 minutes", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.forwardTraffic.findFirst.mockResolvedValue(null);
await saveForwardTraffic({
forwardId: forwardStub.forward.id,
traffics: [forwardTrafficStub.kb],
});
expect(dbMock.forwardTraffic.createMany).toHaveBeenCalledTimes(1);
expect(dbMock.forwardTraffic.update).toHaveBeenCalledTimes(0);
expect(dbMock.forwardTraffic.createMany).toHaveBeenCalledWith({
data: [forwardTrafficStub.kb],
});
});
it("should update last traffic and create new traffic for multiple traffics", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.forwardTraffic.findFirst.mockResolvedValue({
...forwardTrafficStub.kb,
});
const secondTraffic = {
...forwardTrafficStub.kb,
time: new Date("2024-01-01T00:02:30Z"),
};
await saveForwardTraffic({
forwardId: forwardStub.forward.id,
traffics: [forwardTrafficStub.kb, secondTraffic],
});
expect(dbMock.forwardTraffic.createMany).toHaveBeenCalledTimes(1);
expect(dbMock.forwardTraffic.update).toHaveBeenCalledTimes(1);
expect(dbMock.forwardTraffic.update).toHaveBeenCalledWith({
where: {
id: forwardTrafficStub.kb.id,
},
data: {
upload: 2048,
download: 2048,
},
});
expect(dbMock.forwardTraffic.createMany).toHaveBeenCalledWith({
data: [secondTraffic],
});
});
});
describe("deductBalance", () => {
it("should deduct balance correctly", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.config.findUnique.mockResolvedValue(configStub.trafficPrice);
dbMock.agent.findUnique.mockResolvedValue(agentStub.agent);
await deductBalance({
forwardId: forwardStub.forward.id,
startTime: new Date("2024-01-01T00:01:00Z"),
endTime: new Date("2024-01-01T00:02:00Z"),
traffic: 1024,
});
const relatedInfo = {
forwardId: forwardStub.forward.id,
startTime: new Date("2024-01-01T00:01:00Z"),
endTime: new Date("2024-01-01T00:02:00Z"),
traffic: 1024,
convertedTraffic: 1,
trafficPrice: {
price: 0.01,
unit: "Kilobytes",
},
};
expect(updateUserWallet).toHaveBeenCalledTimes(2);
expect(updateUserWallet).toHaveBeenNthCalledWith(1, {
id: forwardStub.forward.createdById,
amount: -0.01,
balanceType: BalanceType.CONSUMPTION,
type: BalanceLogType.TRAFFIC_CONSUMPTION,
extra: `使用流量 1 KB 扣除`,
relatedInfo: relatedInfo,
});
expect(updateUserWallet).toHaveBeenNthCalledWith(2, {
id: agentStub.agent.createdById,
amount: 0.01,
balanceType: BalanceType.INCOME,
type: BalanceLogType.TRAFFIC_INCOME,
extra: `流量[ 1 KB ]收入`,
relatedInfo: relatedInfo,
});
});
it("should not deduct balance if traffic is less than 1 KB and time is less than 2 minutes", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.config.findUnique.mockResolvedValue(configStub.trafficPrice);
await deductBalance({
forwardId: forwardStub.forward.id,
startTime: new Date("2024-01-01T00:01:00Z"),
endTime: new Date("2024-01-01T00:02:00Z"),
traffic: 100,
});
expect(updateUserWallet).toHaveBeenCalledTimes(0);
});
it("should delete forward if balance is not enough", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.config.findUnique.mockResolvedValue(configStub.trafficPrice);
jest.mock("~/server/core/user", () => ({
updateUserWallet: jest.fn().mockImplementation(async () => {
throw new Error("Insufficient balance");
}),
}));
await deductBalance({
forwardId: forwardStub.forward.id,
startTime: new Date("2024-01-01T00:01:00Z"),
endTime: new Date("2024-01-01T00:01:30Z"),
traffic: 1024,
});
expect(updateUserWallet).toHaveBeenCalledTimes(1);
expect(distributeTask).toHaveBeenCalledTimes(1);
});
it("should delete network if balance is not enough", async () => {
dbMock.forward.findUnique.mockResolvedValue(forwardStub.forward);
dbMock.config.findUnique.mockResolvedValue(configStub.trafficPrice);
dbMock.networkEdge.findFirst.mockResolvedValue({
id: "edgeId",
networkId: "networkId",
sourceAgentId: "sourceAgentId",
deleted: false,
sourceForwardId: null,
targetAgentId: null,
nextEdgeId: null,
});
jest.mock("~/server/core/user", () => ({
updateUserWallet: jest.fn().mockImplementation(async () => {
throw new Error("Insufficient balance");
}),
}));
await deductBalance({
forwardId: forwardStub.forward.id,
startTime: new Date("2024-01-01T00:01:00Z"),
endTime: new Date("2024-01-01T00:02:00Z"),
traffic: 1024,
});
expect(updateUserWallet).toHaveBeenCalledTimes(1);
expect(deleteNetwork).toHaveBeenCalledTimes(1);
});
});
describe("tempWaitDeductBalance", () => {
it("should save wait deduct balance correctly", async () => {
const history = {
forwardId: "forwardId",
startTime: "2024-01-01T00:01:00Z",
endTime: "2024-01-01T00:02:00Z",
traffic: 10,
};
redisMock.hget.mockResolvedValueOnce(JSON.stringify(history));
const balanceParams = await tempWaitDeductBalance({
forwardId: "forwardId",
startTime: new Date("2024-01-01T00:03:00Z"),
endTime: new Date("2024-01-01T00:04:00Z"),
traffic: 10,
});
expect(balanceParams).toStrictEqual({
forwardId: "forwardId",
startTime: new Date("2024-01-01T00:01:00Z"),
endTime: new Date("2024-01-01T00:04:00Z"),
traffic: 20,
});
expect(redisMock.hset).toHaveBeenCalledTimes(1);
});
});
});
|
<!DOCTYPE html>
<html>
<head>
<title>Prof. Assistente - planejamento</title>
<style>
body {
background-image: url('plandeaula.png');
background-size: cover; /* Define a imagem para cobrir toda a tela sem distorção */
text-align: center;
color: white;
}
.stylearquivos {
text-align: center;
color: black;
}
.calendar {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 10px;
width: 70%;
margin: 0 auto;
}
.day {
border: 1px solid #ccc;
padding: 10px;
text-align: center;
background-color: #2A1E50; /* Cor de fundo roxa */
border-radius: 10px;
}
.day-header {
color: #fff; /* Cor do texto branco */
font-weight: bold;
font-family: 'Poppins-1.zip', sans-serif; /* Defina o nome da fonte personalizada ou uma fonte instalada no seu computador */
cursor: pointer; /* Adicionado para indicar que o cabeçalho é clicável */
}
.task-input {
position: relative;
}
.add-button {
background-color: white;
color: #2A1E50; /* Cor do texto */
border: 2px solid white; /* Adiciona uma borda branca */
border-radius: 50%; /* Deixa o botão em forma de círculo */
width: 30px; /* Largura do círculo */
height: 30px; /* Altura do círculo */
cursor: pointer;
font-size: 20px; /* Tamanho do texto dentro do círculo */
position: absolute;
right: 5px; /* Distância da borda direita */
bottom: 5px; /* Distância da borda inferior */
}
.day-details.active {
display: block; /* Exibe quando ativada */
}
</style>
</head>
<body>
<div class="stylearquivos">
<h1>Planejamento de Aula</h1>
<label for="instrução">Clique para adicionar tarefa</label>
</div>
<div class="calendar">
<div class="day">
<div class="day-header">Segunda-feira</div>
<div class="task-input">
<input type="text" id="segunda" placeholder="Adicionar tarefa">
<button class="add-button" onclick="adicionarTarefa('segunda')">+</button>
</div>
<ul id="tarefas-segunda"></ul>
</div>
<div class="day">
<div class="day-header">Terca-feira</div>
<div class="task-input">
<input type="text" id="terca" placeholder="Adicionar tarefa">
<button class="add-button" onclick="adicionarTarefa('terca')">+</button>
</div>
<ul id="tarefas-terca"></ul>
</div>
<div class = "day">
<div class="day-header">Quarta-feira</div>
<div class="task-input">
<input type="text" id="quarta" placeholder="Adicionar tarefa">
<button class="add-button" onclick="adicionarTarefa('quarta')">+</button>
</div>
<ul id="tarefas-quarta"></ul>
</div>
<div class="day">
<div class="day-header">Quinta-feira</div>
<div class = "task-input">
<input type="text" id="quinta" placeholder="Adicionar tarefa">
<button class="add-button" onclick="adicionarTarefa('quinta')">+</button>
</div>
<ul id="tarefas-quinta"></ul>
</div>
<div class="day">
<div class="day-header">Sexta-feira</div>
<div class="task-input">
<input type="text" id="sexta" placeholder="Adicionar tarefa">
<button class="add-button" onclick="adicionarTarefa('sexta')">+</button>
</div>
<ul id="tarefas-sexta"></ul>
</div>
</div>
<script>
function adicionarTarefa(dia) {
const input = document.getElementById(dia);
const ul = document.getElementById("tarefas-" + dia);
const tarefa = input.value;
if (tarefa) {
const li = document.createElement("li");
li.textContent = tarefa;
ul.appendChild(li);
input.value = "";
}
}
</script>
</body>
</html>
|
'use client'
import Image from "next/image";
import React, {useState} from "react";
import Toggle from "@/app/profile/Toggle";
import {useMutation, useQueryClient} from "@tanstack/react-query";
import axios from "axios";
import toast from "react-hot-toast";
type EditPostProps = {
id: string;
avatar: string;
name: string;
title: string;
comments?: {
id: string;
postId: string;
userId: string;
}[]
};
const EditPost = ({avatar, name, title, comments, id}: EditPostProps) => {
const [toggle, setToggle] = useState(false);
let deleteToastId: string;
const queryClient = useQueryClient();
const { mutate } = useMutation(
async (id: string) => await axios.delete('/api/posts/deletePost/', {data: id}),
{
onError: (error) => {
toast.error('Error deleting post!', { id: deleteToastId });
},
onSuccess: (data) => {
toast.success('Post has been deleted!', { id: deleteToastId });
queryClient.invalidateQueries(['auth-posts']);
}
}
)
const deletePostHandler = async () => {
deleteToastId = toast.loading('Deleting post...', { id: deleteToastId });
await mutate(id);
};
const deleteButtonHandler = () => {
setToggle(true);
};
return (
<React.Fragment>
<div className="bg-white my-8 p-8 rounded-lg">
<div className="flex gap-2 items-center">
<Image width={32} height={32} src={avatar} alt={'avatar'} className="rounded-full"/>
<h3 className="font-bold text-gray-700">{name}</h3>
</div>
<div className="my-8">
<p className="break-all">{title}</p>
</div>
<div className="flex items-center gap-4">
<p className="text-sm font-bold text-gray-700">{comments?.length} Comments</p>
<button onClick={deleteButtonHandler} className="text-sm font-bold text-red-500">Delete</button>
</div>
</div>
{toggle && <Toggle onDeletePost={deletePostHandler} onToggle={setToggle}/>}
</React.Fragment>
)
};
export default EditPost;
|
import { Injectable } from '@angular/core';
import { OysaaGenericServiceService } from './oysaa-generic-service.service';
import { HttpClient } from '@angular/common/http';
import { AppconfigService } from '../Shared/appconfig.service';
import { Observable } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { RoleManager } from '../Models/role';
@Injectable({
providedIn: 'root'
})
export class RoleManagementService{
endpoint: string = this.appConfig.AccountApi;
roleManagementEndpoint = this.appConfig.RoleManagementApi;
constructor(public http: HttpClient, public appConfig: AppconfigService) {
}
public getAllRoles()
{
return this.http.get<RoleManager[]>(this.roleManagementEndpoint)
.pipe(catchError(error=>this.appConfig.handleError(error)));
}
public getRoleById(id: string): Observable<RoleManager>
{
const Id = `${this.roleManagementEndpoint}/${id}`;
return this.http.get<RoleManager>(Id)
.pipe(catchError(error=>this.appConfig.handleError(error)));
}
public addRole(role: RoleManager): Observable<RoleManager>
{
const url = `${this.roleManagementEndpoint}`;
return this.http.post<RoleManager>(url,role)
.pipe(catchError(error=>this.appConfig.handleError(error)));
}
public updateRole(id: string,role: RoleManager): Observable<RoleManager>
{
const url = `${this.roleManagementEndpoint}/${id}`;
return this.http.put<RoleManager>(url,role)
.pipe(catchError(error=>this.appConfig.handleError(error)));
}
public removeRole(id: string): Observable<RoleManager>
{
const Id = `${this.roleManagementEndpoint}/${id}`;
return this.http.delete<RoleManager>(Id)
.pipe(catchError(error=>this.appConfig.handleError(error)));
}
}
|
import React, {useLayoutEffect, useState} from 'react';
import {Text} from 'react-native';
import {useTailwind} from 'tailwind-rn/dist';
import {
CreateEditHabitProps,
EditHabitScreenNavigationProp,
TimePeriod,
} from '../utils/types';
import firestore from '@react-native-firebase/firestore';
import {StackActions} from '@react-navigation/native';
import CreateEditHabit from '../components/CreateEditHabit';
import {calcGoalPerTP, useUserContext} from '../utils/fn';
const EditHabitScreen = ({
navigation,
route,
}: EditHabitScreenNavigationProp) => {
const tailwind = useTailwind();
const {setSnackE} = useUserContext();
const {
uid,
name,
description,
goalPerTP,
timePeriod,
friends,
user,
inCompetition,
} = route.params;
const [TPRadioBtn, setTPRadioBtn] = useState(timePeriod);
const [newName, setNewName] = useState(name);
const [newDescription, setNewDescription] = useState(description);
const [newWeeklyGoal, setNewWeeklyGoal] = useState<string>(
timePeriod === TimePeriod.Week ? goalPerTP.toString() : '3',
);
const [newMonthlyGoal, setNewMonthlyGoal] = useState<string>(
timePeriod === TimePeriod.Month ? goalPerTP.toString() : '10',
);
const [newSharedWith, setNewSharedWith] = useState(friends);
const props: CreateEditHabitProps = {
newName,
newDescription,
newSharedWith,
newWeeklyGoal,
newMonthlyGoal,
TPRadioBtn,
goalPerTP,
timePeriod,
user,
setNewWeeklyGoal,
setNewMonthlyGoal,
setNewName,
setNewDescription,
setNewSharedWith,
setTPRadioBtn,
uid,
type: 'Edit',
navigation,
inCompetition,
};
useLayoutEffect(() => {
const handleSave = () => {
if (newName.trim() === '') {
setSnackE('Habit name cannot be blank');
return;
}
if (newName.trim().length > 12) {
setSnackE('Habit name cannot be longer than 12 characters.');
return;
}
if (newDescription.length > 200) {
setSnackE('Description cannot be longer than 200 characters.');
return;
}
const habitRef = firestore().collection('habits').doc(uid);
habitRef.update({
name: newName.trim(),
description: newDescription,
timePeriod: TPRadioBtn,
goalPerTP: calcGoalPerTP(TPRadioBtn, newWeeklyGoal, newMonthlyGoal),
friends: newSharedWith,
});
const popAction = StackActions.pop(1);
navigation.dispatch(popAction);
};
navigation.setOptions({
headerRight: () => (
<Text
style={tailwind('text-xl font-YC_SemiBold right-9')}
onPress={handleSave}
>
Save
</Text>
),
});
}, [
TPRadioBtn,
navigation,
newDescription,
newMonthlyGoal,
newName,
newWeeklyGoal,
uid,
newSharedWith,
tailwind,
setSnackE,
]);
return <CreateEditHabit {...props} />;
};
export default EditHabitScreen;
|
import * as S from "./style";
import Header from "../../componets/header";
import Button from "../../componets/button";
import Input from "../../componets/input";
import { useNavigation } from "@react-navigation/native";
import ModalOp from "../../componets/modal";
import { Platform } from "react-native";
import DateTimePickerModal from "react-native-modal-datetime-picker";
import { useState } from "react";
import DatePiker from "../../componets/date/date";
import api from "../../service/api";
const Register = () => {
const nav = useNavigation();
const [modalDeleteVisible, setModalDeleteVisible] = useState(false);
const [modalDeleteVisible1, setModalDeleteVisible1] = useState(false);
const [data, setDate] = useState()
const [NewData, setDataNew] = useState()
const [Responsta, setResponsta] = useState()
const [loading, setLoading] = useState(false); // Estado de carregamento
const [values, setValues] = useState({
name: '',
email: '',
date_birth: '',
professional_goal: '',
neighborhood: ''
})
const fecharModalDelete = () => {
setModalDeleteVisible(false);
};
const fecharModalDelete1 = () => {
setModalDeleteVisible1(false);
nav.navigate("Home");
};
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
setDate(formattedDate);
setValues({ ...values, date_birth: formattedDate });
hideDatePicker();
DataView(formattedDate);
};
const DataView = (formattedDate) => {
const dateView = formattedDate.split('-').reverse().join('/');
setDataNew(dateView);
}
const handleSubmit = () => {
// Verificação se os campos de email e senha estão em branco
if (!values.name || !values.email || !NewData || !values.professional_goal || !values.neighborhood) {
setModalDeleteVisible(true)
return;
}
setLoading(true); // Iniciar o estado de carregamento
setModalDeleteVisible1(true)
api.post('/presence/add', values)
.then(res => {
setResponsta(res);
})
.catch(error => {
console.warn(error)
});
}
return (
<S.Body
behavior={Platform.OS == "ios" ? "padding" : "height"}
keyboardVerticalOffset={10}
>
<S.Scroll>
<S.Main>
<S.HeaderConatiner>
<Header
SubTitle="Cadastro de Perfil"
onPress={() => {
nav.navigate("Home");
}}
/>
</S.HeaderConatiner>
<Input placeholder="Digite seu nome" onChangeText={text => setValues({ ...values, name: text })} Title="Nome:" />
<Input placeholder="Digite seu email" onChangeText={text => setValues({ ...values, email: text })} Title="Email:" />
<S.ButtonContainer>
<DatePiker Title="Data de Nascimento:" onPress={showDatePicker} Data={NewData} />
</S.ButtonContainer>
<Input placeholder="Digite seu profissão dos sonhos" onChangeText={text => setValues({ ...values, professional_goal: text })} Title="Profissão dos Sonhos:" />
<Input placeholder="Digite o bairro onde mora" onChangeText={text => setValues({ ...values, neighborhood: text })} Title="Seu Bairro:" />
<S.ButtonContainer>
<Button
onPress={() => { handleSubmit() }}
Title="Cadastrar"
disabled={loading}
/>
</S.ButtonContainer>
</S.Main>
</S.Scroll>
<ModalOp isVisible={modalDeleteVisible} onClose={fecharModalDelete} />
<ModalOp isVisible={modalDeleteVisible1} onClose={fecharModalDelete1} op={true} />
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
</S.Body>
);
};
export default Register;
|
import styled from '@emotion/styled';
import { useEffect } from 'react';
import { Container, Row } from 'react-bootstrap';
import PokedexHeader from './components/PokedexHeader';
import SelectedPokemon from './components/SelectedPokemon';
import { useAppDispatch } from './hooks/store.hooks';
import { loadAllPokemon } from './store/allPokemon.slice';
export function App() {
const dispatch = useAppDispatch();
useEffect(() => {
// load the inital list of Pokemon to search
dispatch(loadAllPokemon());
}, [dispatch]);
const StyledApp = styled.div`
background-image: url('assets/container_bg.png');
`;
return (
<StyledApp className="d-flex justify-content-center">
<Container fluid>
<Row>
<PokedexHeader></PokedexHeader>
</Row>
<Row>
<SelectedPokemon></SelectedPokemon>
</Row>
</Container>
</StyledApp>
);
}
export default App;
|
"""My FastAPI app."""
import sys
from pathlib import Path
import time
from enum import Enum
from fastapi import FastAPI, Request
from pydantic import BaseModel, Field
path = Path(sys.path[0])
sys.path.append(str(path.parent))
# pylint: disable=wrong-import-position
from my_fastapi_app.routers import items, users # noqa: E402
class ModelName(str, Enum):
"""Machine learning models.
Args:
str (str): The string datatype.
Enum (Enum): The Enum datatype.
"""
# pylint: disable=invalid-name
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
class Item(BaseModel):
"""This is the dataclass for items.
Args:
BaseModel (BaseModel): A base class for creating Pydantic models.
"""
name: str
description: str | None = Field(
default=None,
title="The description of the item",
max_length=300,
)
price: float = Field(
gt=0,
description="The price must be greater than zero"
)
tax: float | None = None
app: FastAPI = FastAPI()
app.include_router(router=users.router)
app.include_router(router=items.router)
@app.get("/")
async def root():
"""Return Hello Bigger Applications.
Returns:
dict: The message.
"""
return {"message": "Hello Bigger Applications!"}
@app.get("/dua_lipa")
def running_away_with_dua_lipa():
"""Love Dua Lipa.
Returns:
dict: Dua Lipa's social media.
"""
return {
"her wiki": "https://en.wikipedia.org/wiki/Dua_Lipa",
"her insta": "https://www.instagram.com/dualipa/",
"her store": "https://store.dualipa.com/",
}
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
"""Get model info by model name.
Args:
model_name (ModelName): Name of the machine learning model.
Returns:
dict: Information on the machine learning model.
"""
if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""Modify the request (and the response).
Args:
request (Request): The request.
call_next (_type_): A function that passes the request
to the path operation.
Returns:
_type_: The response.
"""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
|
import React, { useState } from 'react'
import * as XLSX from 'xlsx'
import { productFileToModel } from '../../mappers/product.mapper'
import ButtonUploadDb from '../buttonsUpload/ButtonUploadDb'
const InputProduct = ({ label, postProductToApi, removeExtraSpaces }) => {
const [inventory, setInventory] = useState([])
const handleReadProducts = (event) => {
const file = event.target.files[0]
// eslint-disable-next-line no-undef
const reader = new FileReader()
reader.onload = (e) => {
const fileContent = e.target.result
const workbook = XLSX.read(new Uint8Array(fileContent), { type: 'array' })
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
setInventory(jsonData)
}
reader.readAsArrayBuffer(file)
}
const formatInventory = (headers = [], rows = []) => {
const inventoryFile = rows.map(row => {
const rowData = {}
headers.forEach((header, index) => {
rowData[header] = row[index]
})
return rowData
})
return productFileToModel(inventoryFile)
}
const headersInventoryFile = inventory[3]
const rowsInventoryFile = inventory.slice(6)
const formattedInventory = formatInventory(headersInventoryFile, rowsInventoryFile)
const productCategory = (product) => {
if (product.includes('Alarma')) return 'Alarmas'
if (product.includes('Bombillo Farola')) return 'Bombillos de Faro'
if (product.includes('Bombillo Stop') || product.includes('Bombilllo Stop')) return 'Bombillos de Stop'
if (product.includes('Bombillo Direccional') || product.includes('Direccionales') || product.includes('Bombillo Piloto') || product.includes('Direccional')) return 'Bombillos de Direccional'
if (product.includes('Bombillo Techo')) return 'Bombillos de Techo'
if (product.includes('Lagrima')) return 'Lagrimas'
if (product.includes('Exploradora') || product.includes('Explorador')) return 'Exploradoras'
if (product.includes('Switche') || product.includes('Terminal') || product.includes('Socket') || product.includes('Fusible') || product.includes('Flasher')) { return 'Electricos' }
if (product.includes('Protector') || product.includes('Maniguetas')) return 'Protectores'
if (product.includes('Tornillo')) return 'Tornillos'
if (product.includes('Modulo Led') || product.includes('Modulo')) return 'Modulos LED'
if (product.includes('Cinta Led') || product.includes('Modulo') || product.includes('Amarra') || product.includes('Luz Maletero') || product.includes('Ojo')) return 'Otros'
if (product.includes('Guardabarros')) return 'Guardabarros'
if (product.includes('Lubricante')) return 'Linea de Mtto'
if (product.includes('Guardapolvo')) return 'Guardapolvos'
return 'Sin Categoria'
}
const categorizedInventory = formattedInventory
.filter(el => el.codigoInventario !== undefined && el.descripcion !== undefined)
.map(el => {
const category = productCategory(el.descripcion)
return {
...el,
categoria: category
}
})
const leakedData = []
categorizedInventory.forEach(el => {
const { categoria, codigoInventario, descripcion } = el
leakedData.push({
categoria,
codigo: codigoInventario,
nombre: removeExtraSpaces(descripcion)
})
})
return (
<>
<label className='form-label'>{label}</label>
<input className='form-control' type='file' accept='.xls , .xlsx' onChange={handleReadProducts} />
<section className='mt-3 d-grid gap-2 justify-content-md-end'>
<ButtonUploadDb title='Subir Productos' products={leakedData} postFunction={postProductToApi} />
</section>
</>
)
}
export default InputProduct
|
/*
* DatastoreModule.h
*
* Created on: Nov 21, 2022
* Author: Jeremy Cote
*/
#ifndef MODULES_DATAAGGREGATIONMODULE_H_
#define MODULES_DATAAGGREGATIONMODULE_H_
#include "ApplicationTypes.h"
typedef struct
{
percentage_t throttle; // Percentage value. Ranges from 0 to 1000. 1 = 0.1%. Thus 0% to 100%.
MotorMode mode;
flag_status_t ignoreThrottle;
uint16_t maxVelocity;
flag_status_t reverseVelocity;
uint8_t motionMode;
} motor_config_t;
typedef union {
uint32_t all;
struct {
uint32_t iCommsError:1;
uint32_t spiError:1;
uint32_t safetyError:1;
uint32_t throttleError:1; // High if throttle was set too high (See SafetyModule)
uint32_t motorInitializing:1;
uint32_t driverEnabled:1;
uint32_t reserved;
};
} motor_status_t;
void InitDataAggregator();
// ===== Motor Config Getters and Setters =====
PUBLIC percentage_t SystemGetThrottlePercentage();
PUBLIC void SystemSetThrottlePercentage(percentage_t throttle);
PUBLIC MotorMode SystemGetMotorMode();
PUBLIC void SystemSetMotorMode(MotorMode mode);
PUBLIC flag_status_t SystemGetIgnoreThrottle();
PUBLIC void SystemSetIgnoreThrottle(flag_status_t ignore);
PUBLIC uint16_t SystemGetMaxVelocity();
PUBLIC void SystemSetMaxVelocity(uint16_t velocity);
PUBLIC flag_status_t SystemGetReverseVelocity();
PUBLIC void SystemSetReverseVelocity(flag_status_t reverse);
PUBLIC uint8_t SystemGetMotionMode();
PUBLIC void SystemSetMotionMode(uint8_t mode);
PUBLIC flag_status_t SystemGetDriverEnabled();
PUBLIC void SystemSetDriverEnabled(flag_status_t enabled);
// ===== Motor Status Getters and Setters =====
PUBLIC const uint32_t SystemGetStatusCode();
PUBLIC flag_status_t SystemGetiCommsError();
PUBLIC void SystemSetiCommsError(flag_status_t status);
PUBLIC flag_status_t SystemGetSPIError();
PUBLIC void SystemSetSPIError(flag_status_t status);
PUBLIC flag_status_t SystemGetSafetyError();
PUBLIC void SystemSetSafetyError(flag_status_t status);
PUBLIC flag_status_t SystemGetThrottleError();
PUBLIC void SystemSetThrottleError(flag_status_t status);
PUBLIC flag_status_t SystemGetMotorInitializing();
PUBLIC void SystemSetMotorInitializing(flag_status_t status);
PUBLIC velocity_t SystemGetMotorVelocity();
PUBLIC void SystemSetMotorVelocity(velocity_t velocity);
#endif /* MODULES_DATAAGGREGATIONMODULE_H_ */
|
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
const Result = () => {
const [quizResult, setQuizResult] = useState(null);
const navigate = useNavigate();
useEffect(() => {
const resultData = JSON.parse(localStorage.getItem('quizResult'));
setQuizResult(resultData);
}, []);
const handleLogout = () => {
// Navigate kembali ke halaman utama
navigate('/signin');
};
if (!quizResult) {
return <p className="text-center">Loading result...</p>;
}
const { correctAnswers, totalQuestions } = quizResult;
return (
<div className="flex flex-col items-center justify-center h-screen">
<h1 className="text-3xl font-bold mb-4">Quiz Finished!</h1>
<div className="border border-gray-300 rounded-md p-4">
<p>Correct Answers: {correctAnswers}</p>
<p>Incorrect Answers: {totalQuestions - correctAnswers}</p>
<p>Total Answered Questions: {totalQuestions}</p>
</div>
<button className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600" onClick={handleLogout}>Logout</button>
</div>
);
};
export default Result;
|
import Link from "next/link";
import CONFIG from "morethan-log.config";
import { formatDate } from "@/src/libs/utils";
import Tag from "./Tag";
import { TPost } from "../types";
import imageLoader from "@/src/libs/next/imageLoader";
import Image from "next/image";
import { getTheme } from "@hooks/useThemeEffect";
type Props = {
post: TPost;
};
const PostCard: React.FC<Props> = ({ post }) => {
const theme = getTheme();
if (post.thumbnail) {
}
return (
<Link href={`/${post.slug}`}>
<a>
<article
key={post.id}
className="overflow-hidden mb-6 md:mb-8 rounded-2xl bg-white dark:bg-zinc-700 transition-shadow hover:shadow-lg"
>
<div className="relative w-full pb-[66%] lg:pb-[50%] bg-gray-200 dark:bg-zinc-700 ">
<Image
src={`https://thumbnail.hyeok.dev/${post.title}.png?subTitle=&theme=${theme}&md=1&fontSize=100px&images=https%3A%2F%2Fthumbnail.hyeok.dev%2Fassets%2FblogIcon.svg`}
className="object-cover"
width={990}
height={654}
loader={imageLoader}
layout="fill"
placeholder="blur"
blurDataURL="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFklEQVR42mN8//HLfwYiAOOoQvoqBABbWyZJf74GZgAAAABJRU5ErkJggg=="
alt={post.title}
/>
</div>
<div className="p-4">
<header className="flex flex-col justify-between md:flex-row md:items-baseline">
<h2 className="text-lg md:text-xl font-medium mb-2 cursor-pointer text-black dark:text-gray-100">
{post.title}
</h2>
</header>
<div className="mb-4">
<time className="flex-shrink-0 text-sm text-gray-600 dark:text-gray-400 ">
{formatDate(
post?.date?.start_date || post.createdTime,
CONFIG.lang
)}
</time>
</div>
<main className="mb-4">
<p className="hidden leading-8 text-gray-700 dark:text-gray-300 line-clamp-2">
{post.summary}
</p>
</main>
<div className="flex gap-2">
{post.tags &&
post.tags.map((tag: string, idx: number) => (
<Tag key={idx}>{tag}</Tag>
))}
</div>
</div>
</article>
</a>
</Link>
);
};
export default PostCard;
|
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import { contactReducer } from "./Services/Reducers/contactReducer";
import { composeWithDevTools } from "redux-devtools-extension";
const store = createStore(contactReducer, composeWithDevTools());
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
/*
* 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.
*/
package org.dromara.dynamictp.common.timer;
/**
* A handle associated with a {@link TimerTask} that is returned by a{@link Timer}.
* <p>
* Copy from dubbo, see <a href="https://github.com/apache/dubbo/blob/3.2/dubbo-common/src/main/java/org/apache/dubbo/common/timer/Timeout.java">here</a> for more details.
* </p>
*/
public interface Timeout {
/**
* Returns the {@link Timer} that created this handle.
*
* @return the {@link Timer} that created this handle
*/
Timer timer();
/**
* Returns the {@link TimerTask} which is associated with this handle.
*
* @return the {@link TimerTask} which is associated with this handle
*/
TimerTask task();
/**
* Returns {@code true} if and only if the {@link TimerTask} associated
* with this handle has been expired.
*
* @return {@code true} if and only if the {@link TimerTask} associated
*/
boolean isExpired();
/**
* Returns {@code true} if and only if the {@link TimerTask} associated
* with this handle has been cancelled.
*
* @return {@code true} if and only if the {@link TimerTask} associated
*/
boolean isCancelled();
/**
* Attempts to cancel the {@link TimerTask} associated with this handle.
* If the task has been executed or cancelled already, it will return with
* no side effect.
*
* @return True if the cancellation completed successfully, otherwise false
*/
boolean cancel();
}
|
import styles from "./StepThree.module.css";
import { useContext } from "react";
import { FormContext } from "../../../../context/FormContext.js";
function StepThree() {
const {handleInputChange} = useContext(FormContext)
return (
<form data-phase="credit-card">
<h3 className={styles.formTitle}>付款資訊</h3>
<section className={styles.formBody}>
<div className={styles.inputLine1}>
<div className={styles.inputGroup}>
<div className={styles.inputLabel}>持卡人姓名</div>
<input
className={styles.inputStyle}
name="cardName"
type="text"
placeholder="John Doe"
onChange={e => {
handleInputChange(e);
}}
/>
</div>
</div>
<div className={styles.inputLine2}>
<div className={styles.inputGroup}>
<div className={styles.inputLabel}>卡號</div>
<input
className={styles.inputStyle}
name="cardNumber"
type="text"
placeholder="1111 2222 3333 4444"
onChange={e => {
handleInputChange(e);
}}
/>
</div>
</div>
<div className={styles.inputLine3}>
<div className={styles.inputGroup}>
<div className={styles.inputLabel}>有效期限</div>
<input
className={styles.inputStyle}
name="cardValid"
type="text"
placeholder="MM/YY"
onChange={e => {
handleInputChange(e);
}}
/>
</div>
<div className={styles.inputGroup}>
<div className={styles.inputLabel}>CVC / CCV</div>
<input
className={styles.inputStyle}
name="cardCvc"
type="text"
placeholder="123"
onChange={e => {
handleInputChange(e);
}}
/>
</div>
</div>
</section>
</form>
);
}
export default StepThree;
|
/**
* Copyright 2021 Comcast Cable Communications Management, LLC
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.automatics.snmp;
/**
* Enumeration for Snmp Data type.
*
* @author selvarajm
*/
public enum SnmpDataType {
/** Data type - string. */
STRING("s"),
/** Data type - integer. */
INTEGER("i"),
/** Data type - unsigned integer. */
UNSIGNED_INTEGER("u"),
/** Date Type - string a */
STRING_A("a"),
/** Date Type - Hexadecimal x */
HEXADECIMAL("x");
/** Data type. */
private String type;
/**
* Constructor.
*
* @param type
* The data type.
*/
private SnmpDataType(String type) {
this.type = type;
}
/**
* Get the data type.
*
* @return
*/
public String getType() {
return this.type;
}
@Override
public String toString() {
return this.type;
}
}
|
#include "sort.h"
void switch_ints(int *a, int *b);
int hoare_parts(int *array, size_t size, int left, int right);
void hoare_sort(int *array, size_t size, int left, int right);
void quick_sort_hoare(int *array, size_t size);
/**
* switch_ints - switch two integers in an array.
* @a: The first integer to switch.
* @b: The second integer to switch.
*/
void switch_ints(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/**
* hoare_parts - Order a subset of an array of integers
* according to the hoare partition scheme.
* @array: The array of integers.
* @size: The size of the array.
* @left: The starting index of the subset to order.
* @right: The ending index of the subset to order.
*
* Return: The final partition index.
*
* Description: Uses the last element of the partition as the pivot.
* Prints the array after each switch of two elements.
*/
int hoare_parts(int *array, size_t size, int left, int right)
{
int pivot, above, below;
pivot = array[right];
for (above = left - 1, below = right + 1; above < below;)
{
do {
above++;
} while (array[above] < pivot);
do {
below--;
} while (array[below] > pivot);
if (above < below)
{
switch_ints(array + above, array + below);
print_array(array, size);
}
}
return (above);
}
/**
* hoare_sort - Implement the quicksort algorithm through recursion.
* @array: An array of integers to sort.
* @size: The size of the array.
* @left: The starting index of the array parts to order.
* @right: The ending index of the array parts to order.
*
* Description: Uses the Hoare partition scheme.
*/
void hoare_sort(int *array, size_t size, int left, int right)
{
int parts;
if (right - left > 0)
{
parts = hoare_parts(array, size, left, right);
hoare_sort(array, size, left, parts - 1);
hoare_sort(array, size, parts, right);
}
}
/**
* quick_sort_hoare - Sort an array of integers in ascending
* order using the quicksort algorithm.
* Description: Uses the Hoare parts scheme. Prints
* the array after each switch of two elements.
*/
void quick_sort_hoare(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
hoare_sort(array, size, 0, size - 1);
}
|
from datetime import datetime
from fastapi import FastAPI, HTTPException
import databases
import sqlalchemy
from pydantic import BaseModel, Field, EmailStr
from enum import Enum
from passlib.context import CryptContext
from typing import List
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
DATABASE_URL = "sqlite:///mydatabase.db"
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
app = FastAPI()
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
class OrderStatus(str, Enum):
processing = "processing"
completed = "completed"
cancelled = "cancelled"
users = sqlalchemy.Table(
"users",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("first_name", sqlalchemy.String(50)),
sqlalchemy.Column("last_name", sqlalchemy.String(50)),
sqlalchemy.Column("email", sqlalchemy.String(128), unique=True),
sqlalchemy.Column("password", sqlalchemy.String(128))
)
class UserIn(BaseModel):
first_name: str = Field(..., title="First Name", min_length=3, max_length=50)
last_name: str = Field(..., title="Last Name", min_length=3, max_length=50)
email: EmailStr = Field(..., title="Email", max_length=128)
password: str = Field(..., title="Password", min_length=8)
class User(UserIn):
id: int
class UserCreate(UserIn):
@classmethod
def hash_password(cls, password):
return pwd_context.hash(password)
async def validate_email_uniqueness(email):
query = users.select().where(users.c.email == email)
existing_user = await database.fetch_one(query)
if existing_user:
raise ValueError("Email address already exists")
return email
@app.post("/users/", response_model=User)
async def create_user(user: UserCreate):
hashed_password = UserCreate.hash_password(user.password)
query = users.insert().values(
first_name=user.first_name,
last_name=user.last_name,
email=user.email,
password=hashed_password
)
last_record_id = await database.execute(query)
return {**user.dict(), "id": last_record_id}
@app.get("/users/{user_id}", response_model=User)
async def read_user(user_id: int):
query = users.select().where(users.c.id == user_id)
user = await database.fetch_one(query)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.get("/users/", response_model=List[User])
async def read_users(skip: int = 0, limit: int = 10):
query = users.select().offset(skip).limit(limit)
return await database.fetch_all(query)
@app.put("/users/{user_id}", response_model=User)
async def update_user(user_id: int, user: UserCreate):
hashed_password = UserCreate.hash_password(user.password)
query = users.update().where(users.c.id == user_id).values(
first_name=user.first_name,
last_name=user.last_name,
email=user.email,
password=hashed_password
)
await database.execute(query)
return {**user.dict(), "id": user_id}
@app.delete("/users/{user_id}")
async def delete_user(user_id: int):
query = users.delete().where(users.c.id == user_id)
await database.execute(query)
return {"message": "User deleted successfully"}
items = sqlalchemy.Table(
"items",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("title", sqlalchemy.String(50)),
sqlalchemy.Column("description", sqlalchemy.String(800)),
sqlalchemy.Column("price", sqlalchemy.Float(1000000)),
)
class ItemIn(BaseModel):
title: str = Field(..., title="Item Name", min_length=3, max_length=50)
description: str = Field(default=None, title="Description", max_length=800)
price: float = Field(..., title="Price", ge=10, le=1000000)
class ItemCreate(ItemIn):
pass
class Item(ItemIn):
id: int
@app.post("/items/", response_model=Item)
async def create_item(item: ItemCreate):
query = items.insert().values(**item.dict())
last_record_item_id = await database.execute(query)
return {**item.dict(), "id": last_record_item_id}
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
query = items.select().where(items.c.id == item_id)
item = await database.fetch_one(query)
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.get("/items/", response_model=List[Item])
async def read_items(skip: int = 0, limit: int = 10):
query = items.select().offset(skip).limit(limit)
return await database.fetch_all(query)
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: ItemCreate):
query = items.update().where(items.c.id == item_id).values(**item.dict())
await database.execute(query)
return {**item.dict(), "id": item_id}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
query = items.delete().where(items.c.id == item_id)
await database.execute(query)
return {"message": "Item deleted successfully"}
orders = sqlalchemy.Table(
"orders",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("user_id", sqlalchemy.Integer, sqlalchemy.ForeignKey("users.id")),
sqlalchemy.Column("item_id", sqlalchemy.Integer, sqlalchemy.ForeignKey("items.id")),
sqlalchemy.Column("order_date", sqlalchemy.DateTime),
sqlalchemy.Column("status", sqlalchemy.String(50)),
)
class OrderIn(BaseModel):
user_id: int
item_id: int
order_date: datetime = Field(..., title="Order Date")
status: str
class OrderCreate(OrderIn):
pass
class Order(OrderIn):
id: int
@app.post("/orders/", response_model=Order)
async def create_order(order: OrderCreate):
query = orders.insert().values(**order.dict())
last_record_order_id = await database.execute(query)
return {**order.dict(), "id": last_record_order_id}
@app.get("/orders/{order_id}", response_model=Order)
async def read_order(order_id: int, order=None):
query = orders.select().where(orders.c.id == order_id)
order = await database.fetch_one(query)
if order is None:
raise HTTPException(status_code=404, detail="Order not found")
return order
@app.get("/orders/", response_model=List[Order])
async def read_orders(skip: int = 0, limit: int = 10):
query = orders.select().offset(skip).limit(limit)
return await database.fetch_all(query)
@app.delete("/orders/{order_id}")
async def delete_order(order_id: int):
query = orders.delete().where(orders.c.id == order_id)
await database.execute(query)
return {"message": "Order deleted successfully"}
engine = sqlalchemy.create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
metadata.create_all(engine)
|
/* eslint-disable consistent-return */
import { HttpStatus, Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { handleServiceCustomErrorPrisma } from 'src/core/utils/api-client.prisma.error';
@Injectable()
export class PostgresDbClient {
constructor(private prismaClient: PrismaClient) {}
async create(payload: any, module: string): Promise<any> {
try {
const response = await this.prismaClient[module].create({ data: payload });
return response;
} catch (error) {
handleServiceCustomErrorPrisma(error, HttpStatus.BAD_REQUEST);
}
}
async find<T>(payloadLocalize: T, module: string): Promise<any> {
try {
const response = await this.prismaClient[module].findUnique({ where: payloadLocalize });
if (response && response !== null) {
return response;
}
handleServiceCustomErrorPrisma('Not Found.', HttpStatus.NOT_FOUND);
} catch (error) {
handleServiceCustomErrorPrisma(error, error.status);
}
}
async list<T>(payloadLocalize: T, module: string): Promise<any> {
try {
const response = await this.prismaClient.transaction.findMany({ where: payloadLocalize, orderBy: { createAt: 'desc'} });
if (response && response !== null) {
return response;
}
handleServiceCustomErrorPrisma('Not Found.', HttpStatus.NOT_FOUND);
} catch (error) {
handleServiceCustomErrorPrisma(error, error.status);
}
}
async update<T, Y>(payload: T, localize: Y, module: string): Promise<any> {
try {
const response = await this.prismaClient[module].update({ where: localize, data: payload });
return response;
} catch (error) {
handleServiceCustomErrorPrisma(error, HttpStatus.BAD_REQUEST);
}
}
async delete<T>(localize: T, module: string): Promise<any> {
try {
const response = await this.prismaClient[module].delete({ where: localize });
return response;
} catch (error) {
return 'delete - delete';
}
}
}
|
### Conceptual Exercise
Answer the following questions below:
- What are important differences between Python and JavaScript?
While many of the same things can be accomplished in Python and Javascript, there are many differences especially in the syntax of how each language is written. Python more closely resembles English with keywords like "is" and "not" compared to JS's "!=" and "=". Additionally JS is camel cased while Python is snakecased. Overall, Python is primarily back-end and JS is both back and front end.
- Given a dictionary like ``{"a": 1, "b": 2}``: , list two ways you
can try to get a missing key (like "c") *without* your programming
crashing.
Using setdefault() or get('key', 'val')
- What is a unit test?
A testing program for part of an app.
- What is an integration test?
A test to see how pieces of an app work together.
- What is the role of web application framework, like Flask?
Flask is used to run th server and can also be used to debug.
- You can pass information to Flask either as a parameter in a route URL
(like '/foods/pretzel') or using a URL query param (like
'foods?type=pretzel'). How might you choose which one is a better fit
for an application?
You can choose which option to use based on whether or not these routes are unchanging. Query params are better for search engines, but hard coding routes is better for directories.
- How do you collect data from a URL placeholder parameter using Flask?
Using <name> placeholders in the URL and accepting the corresponding <name> arguments in the view function.
- How do you collect data from the query string using Flask?
Accessing the query_string property of the request.
- How do you collect data from the body of the request using Flask?
Using the request method, i.e. request.form, request.data, etc.
- What is a cookie and what kinds of things are they commonly used for?
Cookies are used to store information in a browser for a specific user. Often used for things like browsing preferences or user information.
- What is the session object in Flask?
The session object is similar to cookies and dictionaries, but is used with a secret key to store values.
- What does Flask's `jsonify()` do?
Converts JSON (Javascript Object Notation) into a response object.
|
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
final class ProductState extends Equatable {
const ProductState({
this.themeMode = ThemeMode.light,
});
final ThemeMode themeMode;
@override
List<Object> get props => [themeMode];
ProductState copyWith({
ThemeMode? themeMode,
}) {
return ProductState(
themeMode: themeMode ?? this.themeMode,
);
}
}
|
import map from 'lodash/map'
import React, { Component } from 'react'
import { NavLink } from'react-router-dom'
import { connect } from'react-redux'
import { default as PropTypes} from 'prop-types'
import { DEFAULT_MENU } from '../../reducers/app-routes'
const keys = {
init: 'MENU_INIT'
}
const actions = {
/**
* {menuItems: flat array}
*/
init: (initState) => ({
type: keys.init,
initState
})
}
const reducer = (state = {}, action) => {
switch (action.type) {
case keys.init:
return action.initState;
default:
return state;
}
}
const stateToProps = (state) => {
return ({
menuItems: state.appRouter.menus[ DEFAULT_MENU ]
})
}
class Menu extends Component {
static propTypes = {
menuItems: PropTypes.array.isRequired
}
static defaultProps = {
menuItems: []
}
render() {
const { menuItems } = this.props;
return (
<ul className="menu text-uppercase pl-0 mb-0">
{
map(menuItems, ({ exact, baseUrl, url, label }, index) => {
return (
<li key={ index } className="menu-item d-inline-block">
<NavLink exact={ exact } to={ baseUrl || url } activeClassName="current">
<span>{ label }</span>
</NavLink>
</li>
)
})
}
</ul>
);
}
}
export {
actions,
reducer
}
export default connect(stateToProps, null, null, { pure: false })(Menu)
|
function [dups, dupCounts, count, Sidx] = duplicates(S)
% detects duplicates in a string or cellstr vector.
% INPUT:
% S: a string/cellstr vector.
% OUTPUTS:
% dups: duplicated values.
% dupCounts: duplicate counts for each value in dups.
% Oveis Jamialahmadi, GU. Oct. 2020.
if nargin < 1
error('input is missing!')
elseif ~any(size(S) == 1)
error('only row/column vector!')
elseif ~isstring(S) && ~iscellstr(S)
S = string(S);
end
[Sunique, Sidx, Suidx] = unique(S, 'stable');
count = histcounts(Suidx,[1:numel(Sunique), inf])';
dups = Sunique(count > 1);
dupCounts = count(count > 1);
end % END
|
import React from 'react';
import { number, string, instanceOf } from 'prop-types';
import IssueCard from '../../../elements/IssueCard';
import styles from './IssueHeader.css';
const propTypes = {
issueNumber: number.isRequired,
name: string.isRequired,
date: instanceOf(Date).isRequired,
discipline: string.isRequired,
icon: string.isRequired,
hero: string.isRequired,
};
const IssueHeader = ({ issueNumber, name, date, discipline, icon, hero }) => (
<div className={styles.issueHeader}>
<IssueCard
className={styles.issueCard}
issueNumber={issueNumber}
name={name}
date={date}
discipline={discipline}
icon={icon}
/>
<div className={styles.issueHeaderInner}>
<img src={hero} className={styles.heroImage} alt={name} />
</div>
</div>
);
IssueHeader.propTypes = propTypes;
export default IssueHeader;
|
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkNumberToString.h"
#include "itkViewImage.h"
// #include "itkFFTPadPositiveIndexImageFilter.h"
#include "itkFFTPadImageFilter.h"
// Boundary Conditions:
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itkConstantBoundaryCondition.h"
#include "itkPeriodicBoundaryCondition.h"
// boost::program_options
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
namespace po = boost::program_options;
// boost::filesystem
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
template<typename ImageType>
void pad_image(
const std::string & inputImage,
const std::string & outputImage,
const std::string & boundaryConditionName,
const int sizeGreatestPrimeFactor,
bool visualize)
{
using ReaderType = itk::ImageFileReader< ImageType >;
auto reader = ReaderType::New();
reader->SetFileName( inputImage );
typename ImageType::Pointer handle = reader->GetOutput();
// using FFTPadFilterType = itk::FFTPadPositiveIndexImageFilter< ImageType >;
using FFTPadFilterType = itk::FFTPadImageFilter< ImageType >;
auto fftPadFilter = FFTPadFilterType::New();
fftPadFilter->SetInput(reader->GetOutput());
if(boundaryConditionName == "ZeroFluxNeumann")
{
// This is the default
}
else if(boundaryConditionName == "Constant")
{
using BoundaryCondition = itk::ConstantBoundaryCondition< ImageType, ImageType >;
BoundaryCondition boundaryCondition;
boundaryCondition.SetConstant(itk::NumericTraits<typename ImageType::PixelType>::ZeroValue());
fftPadFilter->SetBoundaryCondition(&boundaryCondition);
}
else if(boundaryConditionName == "Periodic")
{
using BoundaryCondition = itk::PeriodicBoundaryCondition< ImageType, ImageType >;
BoundaryCondition boundaryCondition;
fftPadFilter->SetBoundaryCondition(&boundaryCondition);
}
else
{
std::cerr << "Invalid boundary condition: " << boundaryConditionName << std::endl;
throw std::runtime_error( "Invalid boundary condition: " + boundaryConditionName);
}
if(sizeGreatestPrimeFactor != -1) {
fftPadFilter->SetSizeGreatestPrimeFactor(sizeGreatestPrimeFactor);
}
fftPadFilter->Update();
std::cout << " ------------" << std::endl;
fftPadFilter->Print(std::cout);
std::cout << " ------------" << std::endl;
handle = fftPadFilter->GetOutput();
auto sizeOriginal = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
auto sizeAfterPad = fftPadFilter->GetOutput()->GetLargestPossibleRegion().GetSize();
std::cout << "Image Padded" << std::endl;
std::cout << "Original Size:" << sizeOriginal << std::endl;
std::cout << "After Pad Size:" << sizeAfterPad << std::endl;
using WriterType = itk::ImageFileWriter< ImageType >;
auto writer = WriterType::New();
writer->SetFileName( outputImage );
writer->SetInput( fftPadFilter->GetOutput() );
try
{
std::cout << "Output in: " << outputImage << std::endl;
writer->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
if(visualize){
itk::ViewImage<ImageType>::View( reader->GetOutput(), "Input" );
itk::ViewImage<ImageType>::View( fftPadFilter->GetOutput(), "Padded Output: " + boundaryConditionName );
}
}
int main( int argc, char *argv[])
{
/*-------------- Parse command line -----------------------------*/
po::options_description general_opt ( "Allowed options are: " );
general_opt.add_options()
( "help,h", "display this message." )
( "input,i", po::value<std::string>()->required(), "Input image." )
( "outputFolder,o", po::value<std::string>()->required(), "Outputfolder path. A number of images will be generated depending on levels and bands." )
( "outputExtension,e", po::value<std::string>()->default_value("nrrd"), "Output extension." )
( "dimension,d", po::value<unsigned int>()->required(), "Use imageInfo if needed." )
( "sizeGreatestPrimeFactor,g", po::value<int>()->default_value(-1), "Specify the sizeGreatestPrimeFactor to pad the image. If -1 it will be computed internally. Example: Set to 2 for the output size to be power of 2." )
( "pixelType,p", po::value<std::string>()->required(), "Use imageInfo if needed." )
( "boundaryCondition,b", po::value<std::string>()->default_value("ZeroFluxNeumann"), "Boundary Condition." )
( "visualize,t", po::bool_switch()->default_value(false), "Visualize using vtk based viewer.");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, general_opt), vm);
if (vm.count ( "help" ) || argc<=1 )
{
std::cout << "Basic usage:\n" << general_opt << "\n";
return false;
}
po::notify ( vm );
} catch ( const std::exception& e ) {
std::cerr << e.what() << std::endl;
return 1;
}
const std::string inputImage = vm["input"].as<std::string>();
const std::string outputFolder = vm["outputFolder"].as<std::string>();
const std::string outputExtension = vm["outputExtension"].as<std::string>();
const unsigned int dimension = vm["dimension"].as<unsigned int>();
const int sizeGreatestPrimeFactor = vm["sizeGreatestPrimeFactor"].as<int>();
const std::string pixelType = vm["pixelType"].as<std::string>();
const std::string boundaryConditionName = vm["boundaryCondition"].as<std::string>();
const bool visualize = vm["visualize"].as<bool>();
// END PARSE
itk::NumberToString< double > n2s;
const fs::path inputImageStem_path = fs::path(inputImage).stem();
const fs::path outputFolder_path = fs::absolute(fs::path(outputFolder));
const std::string sizeGreatestPrimeFactorString =
(sizeGreatestPrimeFactor != -1) ? ("withFactor" + std::to_string(sizeGreatestPrimeFactor) ) : "";
const std::string appendString = "_fftPad" + boundaryConditionName + sizeGreatestPrimeFactorString;
const std::string outputImage = (outputFolder_path /
fs::path(inputImageStem_path.string() +
appendString + "." + outputExtension)).string();
if(pixelType == "double" ) {
if(dimension == 3) {
using ImageType = itk::Image<double, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<double, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else if(pixelType == "float" ) {
if(dimension == 3) {
using ImageType = itk::Image<float, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<float, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else if(pixelType == "unsigned char" ) {
if(dimension == 3) {
using ImageType = itk::Image<unsigned char, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<unsigned char, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else if(pixelType == "short" ) {
if(dimension == 3) {
using ImageType = itk::Image<short, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<short, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else if(pixelType == "int" ) {
if(dimension == 3) {
using ImageType = itk::Image<int, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<int, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else if(pixelType == "int" ) {
if(dimension == 3) {
using ImageType = itk::Image<int, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<int, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else if(pixelType == "short" ) {
if(dimension == 3) {
using ImageType = itk::Image<short, 3>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
} else if (dimension == 2) {
using ImageType = itk::Image<short, 2>;
pad_image<ImageType>(inputImage, outputImage, boundaryConditionName, sizeGreatestPrimeFactor, visualize);
}
} else {
std::cout << "PixelType: " << pixelType << " is not supported" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
package co.edu.uniquindio.proyecto_isw3.servicios.impl;
import co.edu.uniquindio.proyecto_isw3.dto.get.FacultadGetDTO;
import co.edu.uniquindio.proyecto_isw3.modelo.Facultad;
import co.edu.uniquindio.proyecto_isw3.repositorios.FacultadRepo;
import co.edu.uniquindio.proyecto_isw3.servicios.interfaces.FacultadService;
import lombok.AllArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@AllArgsConstructor
public class FacultadServiceImpl implements FacultadService {
private FacultadRepo facultadRepo;
private MessageSource ms;
@Override
@Transactional(readOnly = true)
public List<FacultadGetDTO> listar() throws Exception {
List<Facultad> facultades = facultadRepo.findAll();
List<FacultadGetDTO> facultadesGetDTO = new ArrayList<>();
if (facultades.isEmpty()) {
throw new Exception(ms.getMessage("facultad.lista.vacio", null, LocaleContextHolder.getLocale()));
}
for (Facultad f : facultades) {
facultadesGetDTO.add(convertir(f));
}
return facultadesGetDTO;
}
@Override
@Transactional(readOnly = true)
public Facultad buscar(String idFacultad) throws Exception {
validar(idFacultad);
return facultadRepo.findById(idFacultad).get();
}
private FacultadGetDTO convertir(Facultad facultad) {
return new FacultadGetDTO(
facultad.getIdFacultad(),
facultad.getNombre(),
facultad.getDescripcion()
);
}
private void validar(String idFacultad) throws Exception {
if(!facultadRepo.existsById(idFacultad)) {
throw new Exception(ms.getMessage("facultad.no.encontrada", new Object[]{idFacultad}, LocaleContextHolder.getLocale()));
}
}
}
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:gluten_cops/form_screens/addproduct_screen.dart';
class ProductsScreen extends StatefulWidget {
@override
_ProductsScreenState createState() => _ProductsScreenState();
}
class _ProductsScreenState extends State<ProductsScreen> {
int selectedButton = 0;
final Stream<QuerySnapshot> _allProductsStream =
FirebaseFirestore.instance.collection('products').snapshots();
TextEditingController _searchController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 50.0, left: 10.0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.black),
onPressed: () {
Navigator.pop(context);
},
),
const SizedBox(width: 10),
const Text(
"Ürünler",
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
),
),
],
),
),
const SizedBox(height: 20.0),
TextField(
controller: _searchController,
onChanged: (value) {
setState(() {});
},
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Ara',
),
),
const SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildButton('Tümü', 0, Colors.pink),
_buildButton('Glutenli', 1, Colors.pink),
_buildButton('Glutensiz', 2, Colors.green),
],
),
const SizedBox(height: 20.0),
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: _allProductsStream,
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Bir şeyler yanlış gitti: ${snapshot.error}');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Yükleniyor");
}
List<DocumentSnapshot> products = snapshot.data!.docs;
List<DocumentSnapshot> filteredProducts =
_filterProducts(products);
return ListView.builder(
itemCount: filteredProducts.length,
itemBuilder: (context, index) {
return _buildProductListTile(filteredProducts[index]);
},
);
},
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const AddProduct()),
);
},
child: const Icon(Icons.add),
backgroundColor: Colors.pink,
),
);
}
List<DocumentSnapshot> _filterProducts(List<DocumentSnapshot> products) {
String filter = '';
if (selectedButton == 1) {
filter = 'glutenli';
} else if (selectedButton == 2) {
filter = 'glutensiz';
}
return products.where((product) {
final productName = product['productName']?.toLowerCase() ?? '';
final productStatus = product['glutenStatus']?.toLowerCase() ?? '';
final searchText = _searchController.text.toLowerCase();
if (_searchController.text.isNotEmpty &&
!productName.contains(searchText)) {
return false;
}
if (selectedButton != 0 && productStatus != filter) {
return false;
}
return true;
}).toList();
}
Widget _buildProductListTile(DocumentSnapshot product) {
Map<String, dynamic> productData = product.data() as Map<String, dynamic>;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Card(
elevation: 5.0,
child: ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: productData.containsKey('imageUrl') &&
productData['imageUrl'] != null
? Image.network(
productData['imageUrl'],
fit: BoxFit.cover,
height: 60,
width: 60,
)
: const Icon(
Icons.image_not_supported,
color: Colors.grey,
size: 60,
),
),
title: Text(productData['productName']),
onTap: () {
_showProductDetailPopup(context, productData);
},
),
),
);
}
void _showProductDetailPopup(
BuildContext context, Map<String, dynamic> productData) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(productData['productName'], textAlign: TextAlign.center),
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: Image.network(
productData['imageUrl'] ?? '',
fit: BoxFit.cover,
height: 200.0,
),
),
SizedBox(height: 10),
Text(
'Gluten Durumu: ${productData['glutenStatus'] ?? 'Bilgi yok'}',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Kapat', style: TextStyle(color: Colors.pink)),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Widget _buildButton(String name, int index, Color color) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: selectedButton == index ? color : Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
),
onPressed: () {
setState(() {
selectedButton = index;
});
},
child: Text(
name,
style: TextStyle(color: Colors.white),
),
);
}
}
|
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/boring.css">
<style>
body {
background: #555;
}
.error {color: #FF0000;}
.success {color: #00FF00;}
.box
{
background: #888;
position: fixed; /* or absolute */
height: 370px;
width: 420px;
top: 50%;
left: 50%;
margin-top: -160px;
margin-left: -210px;
}
label { float: left; width: 150px; text-align: right; }
input[type=text] { width: 200px; }
input[type=password] { width: 200px; }
</style>
</head>
<body>
<div><a href='/'>Back</a></div>
<?php
session_start();
function validateInfo( $username, $password, $confirm_pass, $email, $tos )
{
if ( filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE )
{
return "Invalid email address";
}
if ( empty($username) )
{
return "Username is required";
}
else
{
if ( !preg_match( "/^[a-zA-Z0-9 ]*$/", $username ) )
{
return "Only letters and numbers allowed in username";
}
else {
$parse = explode( " ", $username );
$count = count( $parse );
if( $count != 1 && $count != 2 )
{
return "Username cannot be more than two names";
}
}
}
if ( empty( $password ) )
{
return "Password is required";
}
if( $password != $confirm_pass )
{
return "Passwords do not match";
}
if( $tos === FALSE )
{
return "You must agree to the Terms of Service";
}
return TRUE;
}
$genericErr = $username = $email = $firstname = $lastname = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = htmlspecialchars( $_POST["username"] );
$password = htmlspecialchars( $_POST["password"] );
$confirm_password = htmlspecialchars( $_POST["confirm_password"] );
$email = htmlspecialchars( $_POST["email"] );
$agree_to_tos = $_POST["agree_to_tos"] === "1";
$check_data = validateInfo( $username, $password, $confirm_password, $email, $agree_to_tos );
if( $check_data === TRUE )
{
$parse = explode( " ", $username );
$count = count( $parse );
if( $count == 1 )
{
$firstname = $parse[0];
$lastname = "Resident";
}
else if( $count == 2 )
{
$firstname = $parse[0];
$lastname = $parse[1];
}
if(!empty($firstname) && !empty($lastname) && !empty($password))
{
include_once "includes/accountmagic.php";
$create_info = "";
$create_success = createUser( $firstname, $lastname, $password, $email, $create_info );
if( $create_success === TRUE )
{
$_SESSION['user_id'] = $create_info;
$_SESSION['user_level'] = 0;
$_SESSION['user_name'] = $username;
header("Location: " . WebsiteURL);
exit();
}
else
{
$genericErr = $create_success;
}
}
}
else
{
$genericErr = $check_data;
}
}
?>
<div class="box" align="center">
<h2>OpenSim Signup Example</h2>
<form method="post" action="">
<label>Email Address:</label><input type="text" name="email" value="<?php echo $email; ?>">
<br><br>
<label>Username:</label><input type="text" name="username" value="<?php echo $username; ?>">
<br><br>
<label>Password:</label><input type="password" name="password" value="">
<br><br>
<label>Confirm Password:</label><input type="password" name="confirm_password" value="">
<br><br>
<input type="checkbox" name="agree_to_tos" value="1">I agree to the <a href='/tos' target="_blank">Terms of Service</a>
<br><br>
<span class="error"><?php echo $genericErr;?></span><br>
<br>
<input type="submit" name="submit" value="Create Account">
<br>
<br>
<a href='/login'>Already have an account?</a>
</form>
</div>
</body>
<footer class="footer">Copyright (c) 2019, Mobius Team<div class="bottom-right"><a href="https://github.com/Mobius-Team/">Mobius Team GitHub</a></div></footer>
</html>
|
+++
author = ""
title = "Ethical Issues in Health"
date = "2019-11-14"
description = "Structures of the Hip Bone."
tags = ["Masters", "Research Methods Applied to Prosthetic and Orthotic Science"]
categories = ["Masters", "Research Methods Applied to Prosthetic and Orthotic Science"]
series = ["University Journal"]
aliases = ["migrate-from-jekyl"]
+++
<font size="+7" color="orange"><center> Introduction </center></font>
---
<details>
<summary></summary>
### <mark>Ethics</mark>
- Ethics is a branch of philosophy
- Ethics is ‘the formal study of the principles on which moral rules and values are based’
- Morals refer to those beliefs about how people ‘ought’ to behave. These debates are about right and wrong, good and bad, and duty
- Morals are products of culture, linked to historical contexts.
<br>
### <mark>Morals vs Ethics</mark>
- “The **moral** question is, what should I do?, and the reply consists of proposing an action (or an omission).”
- **“Ethics** asks, why should I do it?: it positions itself at a secondary, contemplative level and the reply consists of an argument”
<br>
### <mark>Why do we need ethics in research?</mark>
The physician Hippocrates (5th century, B.C.E.)
Oath of Hippocrates.
“medical care should be practiced in such a way as to diminish the severity of the suffering that illness and disease bring in their wake, and the physician should be acutely aware of the limitations concerning the practical art of medicine and refrain from any attempt to go beyond such limitations accordingly” -> Taylor (2019)
<br>
### <mark>HCPC Code of Conduct</mark>
The Health and Care Professions Council (HCPC) is a regulator set up to protect the public. It regulates 16 professions including prosthetists / orthotists.
| The Code |
|---------------------------------------------------------------|
| Promote and protect the interests of service users and carers |
| Communicate appropriately and effectively; |
| Work within the limits of their knowledge and skills |
| Delegate appropriately |
| Respect confidentiality |
| Manage risk |
| Report concerns about safety |
| Be open when things go wrong |
| Be honest and trustworthy |
| Keep records of their work |
<br>
### <mark>Difference between health care ethics and research ethics</mark>
- “Once patients agree to be treated, they trust that the physician will act in their interest, or at least will do no harm”
- “In research, which is outside the beneficent context of the physician–patient relationship, this trust may be misplaced, because the physician's primary goal is not to treat; rather, it is to test a scientific hypothesis by following a protocol, regardless of the patient-subject's best interest” -> Shuster (1997)
<br>
### <mark>Ethics of Health Promotion</mark>
- “The ethics of health promotion involves the careful examination of the authority or legitimacy of health promoters. It asks us to explain and justify our choice [of intervention]” (Bunton & McDonald 2002, p.274)
- Raphael (2002) argues that “ethical health promotion requires explicit recognition of the interactions among ideologies, values, principles and rules of evidence” (p.355)
---
<br><br>
</details>
<font size="+7" color="orange"><center> Theories and Practices</center></font>
---
<details>
<summary></summary>
### <mark>Brief History of Research Ethics</mark>
- 1906 – Cholera Vaccine Trial
- Lack of informed consent
- 1947 – Nuremberg Code
- [The Nuremberg trial verdict results in the creation of the Nuremberg code](http://www.hhs.gov/ohrp/archive/nurcode.html)
- 1964 – Declaration of Helsinki
- [Statement of ethical principles for medical research involving human subjects](https://www.wma.net/wp-content/uploads/2016/11/DoH-Oct2013-JAMA.pdf)
- 1972 Tuskegee Syphilis Study
- [Study not well explained and treatment withheld](http://www.cdc.gov/tuskegee/timeline.htm)
- 1996 Good Clinical Practice
- [13 principles covering risks, rights of the individual, ethics, training, informed consent, handling of data](https://www.gov.uk/guidance/good-clinical-practice-for-clinical-trials)
- 2005 Research Governance Framework 2nd edition
- [Principles of good governance that apply to all research within the remit of the Secretary of State for Health](https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/139565/dh_4122427.pdf)
<br>
### <mark>The Function of Ethical Theory</mark>
- There is no correct ‘ethical formula’ for decision making and no single set of ‘right answers’ (Bunton & McDonald, 2002).
- It is not designed to provide answers…but to inform judgements to help people work out what course of action should be taken
- Most ethical theories fall into two types:
- Deontological
- Consequential
<br>
<font size="+4" color="orange"><center> Deontology</center></font>
---
<details>
<summary></summary>
- Deontology – comes from the Greek work deontos, meaning duty.
- Deontologists hold that we have a duty to act in accordance with certain universal moral rules.
- Duty
- Deontologists hold that there are universal moral rules that it is our duty to follow.
- Many of the philosophical discussions about the nature duty are based on Immanuel Kant’s ‘Categorical Imperative’ (Kant 1909 cited in Naidoo & Wills 1994)
<br>
### <mark>Kant's Theory</mark>
- Act as if your action in each circumstance is to become law for everyone, yourself included, in the future.
- Always treat human beings as ‘ends in themselves’ and never as merely ‘means’. A moral rule is one that respects all people.
<br>
### <mark>Duties incorporated in 'codes of practice'</mark>
- Practitioners have a:
- Duty to care
- Duty to be fair
- Duty to respect personal and group rights
- Duty to avoid harm
- Duty to respect confidentiality
- Duty to report (SHEPS 1997)
---
<br><br>
</details>
<font size="+4" color="orange"><center> Consequential/Utilitarianism</center></font>
---
<details>
<summary></summary>
- Consequential ethics are based on the premise that whether an action is right or wrong will depend on its end result.
- Consequentialism differs from deontology because it is concerned with the ends and not only the means.
- Utilitarianism is the most well known branch of consequentialism.
- The Utilitarianism principle is that a person should always act in such a way that will produce more good or benefits than disadvantages.
- E.G. John Stuart Mill & Jeremy Bentham aimed for ‘the greatest good or pleasure for the greatest number of people’.
<br>
### <mark>Limitations of Consequentialism</mark>
- If the aims of all actions is to achieve the greatest good, does this justify harm or injustice to a few if society benefits?
- Should the interests of the majority always take precedence over those of the individual?
---
<br><br>
</details>
<font size="+4" color="orange"><center> Simplification of Approaches</center></font>
---
<details>
<summary></summary>
- ‘Rule-based’
- As a rule is it wrong to interfere in someone's life?
Should we respect their privacy/personal liberty?
<br>
- ‘Consequence-based’
- Will it produce good consequences?
- What are ‘good consequences’? How can we know what they will be?
---
<br><br>
</details>
</details>
<font size="+7" color="orange"><center> The Four Principles of Biomedical Ethics</center></font>
---
<details>
<summary></summary>
| Principle | Description |
|------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| Respect for Persons/Autonomy | Acknowledge a person's right to make choices to hold views, and to take actions based on personal values and beliefs |
| Justice | Treat others equitably, distribute benefits/burdens fairly |
| Nonmaleficence (do no harm) | Obligation not to inflict harm intentionally. In medical ethics, the physician's guiding maxis is "First, do no harm" |
| Beneficence (do good) | Provide benefits to persons and contribute to their welfare. Refers to an action done for the benefit of others. |
“Every biomedical research project involving human subjects should be preceded by a careful assessment of predictable risks in comparison with foreseeable benefits to the subject or to others. Concern for the interests of the subject must always prevail over the interests of science or society” -> (Declaration of Helsinki 1975, cited in Singleton & McLaren 1995, p.118).
---
<br><br>
</details>
<font size="+7" color="orange"><center> Autonomy</center></font>
---
<details>
<summary></summary>
- Autonomy derives from the Greek word autonomous meaning self-rule.
- Autonomy is only constrained by:
- Reason and the ability to make rational choices
- The ability to understand one’s environment
- The ability to react to one’s environment
<br>
- In addition, a person needs to be free from pressures such as fear and want and have the personal and social circumstances to make any chosen action possible.
- Autonomy must, therefore, be thought of not as an absolute but as an attainable, to a greater or lesser extent.
- Not everyone has autonomy. When a person’s capacity for rationality is affected in some way, decisions are often taken on their behalf on the basis that ‘they do not know what’s best for them’.
- It was not until the 20th Century that women were deemed able to make a rational choice in a democratic vote.
- It was only in 1989 that the Children’s Act first recognized the rights and capacity of children to have a say in their care.
<br>
### <mark>Creating/respecting Autonomy</mark>
- Seedhouse (1988) makes a distinction between creating autonomy and respecting autonomy in working for health.
- Creating autonomy – is making an effort to improve the quality of a person’s ability to choose freely by trying to enhance what the person is able to do…often called empowerment
- Respecting autonomy – is agreeing to the wishes of the individual, whether or not you approve of their wishes.
<br>
### <mark>Justice</mark>
- Seedhouse (1988) states that ‘This is a question which is at least as difficult to provide an answer to as the question ‘What is health’? (p.108)
- Philosophers suggest three versions of justice:
- The fair distribution of scarce resources
- Respect for individual and group rights
- Following morally acceptable laws
<br>
- The formal principle of Justice is that ‘equals ought to be treated equally’
---
<br><br>
</details>
<font size="+7" color="orange"><center>Beneficence and non-maleficence</center></font>
---
<details>
<summary></summary>
- The principle of beneficence makes the point that ‘we should try to practice to do good and not evil, not merely that we should wish to do so’ (Seedhouse 1988 p.136)
<br>
- Frankena (1963) (cited in Seedhouse 1988), summed up the principle of beneficence as:
- One ought not to inflict evil or harm (what is bad)
- One ought to prevent evil or harm
- One ought to remove evil
- One ought to do or promote good
<br>
### <mark>Applying the Principle</mark>
Need to be clear about:
- What counts as good?
- What counts as evil
---
<br><br>
</details>
<font size="+7" color="orange"><center>Seedhouse - Ethical Grid</center></font>
---
<details>
<summary></summary>
- Developed to aid clinical decision making, with the layers helping support moral reasoning.
- It can help remind the clinician of the range of considerations which might affect his deliberation.
{{<figure src="/Other/Grid.jpg" position="center" style="border-radius: 8px;" caption="Ethical Grid" captionPosition="center" captionStyle="color: white;" >}}
<br>
### <mark>The Ethical Grid</mark>
- Designed to provide a structured way of thinking about something
- Based on Moral Theory
- It will rarely be necessary to consider a problem using every box, it is important to consider each situation in the light of each layer to engage in ‘moral reasoning’.
{{<figure src="/Other/grid.jpg" position="center" style="border-radius: 8px;" caption="Ethical Grid" captionPosition="center" captionStyle="color: white;" >}}
---
<br><br>
</details>
<font size="+7" color="orange"><center>Nolan Principles</center></font>
---
<details>
<summary></summary>
- This includes people who are elected or appointed to public office, nationally and locally, and all people appointed to work in:
- the civil service
- local government
- the police
- the courts and probation services
- non-departmental public bodies
- health, education, social and care services
<br>
- The principles also apply to all those in other sectors that deliver public services. They were first set out by Lord Nolan in 1995 and they are included in the Ministerial code.
1. Selflessness
2. Integrity
3. Objectivity
4. Accountability
5. Openness
6. Honesty
7. Leadership
[Link to principles](https://www.gov.uk/government/publications/the-7-principles-of-public-life)
---
<br><br>
</details>
<font size="+7" color="orange"><center>Public Health Ethics</center></font>
---
<details>
<summary></summary>
Lee & Zarowsky (2015) suggest three element for public health practitioners relating to ethics:
- the notions of “common” and “professional” morality,
- an understanding of the practice and content of modern public health and especially its practical, solution-focused orientation,
- an appreciation of the history of public health as integrally linked to evolving and contested views of the relationship between citizens, science and the state
[Link](http://publichealthreviews.biomedcentral.com/articles/10.1186/s40985-015-0004-1)
---
<br><br>
</details>
<font size="+7" color="orange"><center>Summary</center></font>
---
<details>
<summary></summary>
- Ethics often relies on a set of judgements based on moral areas, so there is often no single or universal way forward.
- Ethical guidance and codes in health are less set than some areas but the principles of ethics translate across all areas.
---
<br><br>
</details>
<font size="+7" color="orange"><center>References</center></font>
---
<details>
<summary></summary>
- Bunton R. & McDonald G. (2002) Health Promotion: disciplines, diversity and developments, 2nd edn, Routledge
- Naidoo & Wills (2000) Health Promotion (chapter 6)
- Nuffield Council On Bio-Ethics (2007) Public Health Ethical Issues http://www.nuffieldbioethics.org
- Ethical issues in global health http://www.who.int/ethics/topics/en/
- Global Health Ethics: key issues http://apps.who.int/iris/bitstream/handle/10665/164576/9789240694033_eng.pdf;jsessionid=C18FD48A42FFC4CB147E0C3DC3C6CE2D?sequence=1
- Arksey, H & Knight, P (1999) Interviewing for Social Scientists: An introductory Resource with examples
- Ramcharan, P & Cutcliffe, JR (2001) Judging the ethics of qualitative research: considering the "ethics as process" model
- Singleton, J & McLaren, S (1995) Ethical foundation of health care: responsibilities in decision making
- Royo-Bordonada MÁ, Román-Maestre B. Towards public health ethics. Public Health Rev. 2015;36:3. doi:10.1186/s40985-015-0005-0
- Hart, T (1971) The Inverse Care Law
Ruschmann (1980) Mandatory Motorcycle Helmet Laws in the Courts and in the Legislatures
- Shuster (1997) Fifty Years Later: The Significance of the Nuremberg Code. N Engl J Med 1997; 337:1436-1440 https://www.nejm.org/doi/full/10.1056/NEJM199711133372006
- Seedhouse (1988) Ethics: The heart of health care
- Taylor (2019) Health Care Ethics. The Internet Encyclopedia of Philosophy (IEP) (ISSN 2161-0002) https://www.iep.utm.edu/h-c-ethi/
</details>
|
import './App.css';
import React from 'react';
// 👇️ import Routes instead of Switch 👇️
import {
BrowserRouter as Router,
Route,
Link,
Routes,
} from 'react-router-dom';
export default function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
{/* 👇️ Wrap your Route components in a Routes component */}
<Routes>
<Route path="/about" element={<About />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
|
package com.example.mycity.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.mycity.model.Category
import com.example.mycity.model.Destination
@Composable
fun CategoryScreen(
onDestinationClick: (Destination) -> Unit,
destinations: List<Destination>,
modifier: Modifier = Modifier
) {
LazyColumn{
items(destinations) { destination ->
DestinationCard(
destination = destination,
onDestinationClick = onDestinationClick
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DestinationCard(
destination: Destination,
onDestinationClick: (Destination) -> Unit,
modifier: Modifier = Modifier
) {
Card (
elevation = CardDefaults.cardElevation(5.dp),
onClick = { onDestinationClick(destination) },
modifier = Modifier.padding(8.dp)
) {
Column (
modifier = Modifier
.fillMaxWidth()
.heightIn(100.dp)
) {
Text(
text = destination.name,
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(8.dp)
)
Text(
text = destination.description,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(
start = 8.dp,
end = 8.dp,
bottom = 8.dp
)
)
}
}
}
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gtest/gtest.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "nsIFile.h"
#include "nsDirectoryServiceDefs.h"
#include "nsComponentManagerUtils.h"
#include "buildid.h"
#include "buildid_section.h"
#include "mozilla/toolkit/library/buildid_reader_ffi.h"
#include "nsXPCOMPrivate.h"
#include "nsAppRunner.h"
#include <string>
using namespace mozilla;
#define WAIT_FOR_EVENTS \
SpinEventLoopUntil("BuildIDReader::emptyUtil"_ns, [&]() { return done; });
#if defined(XP_WIN)
# define BROKEN_XUL_DLL u"xul_broken_buildid.dll"_ns
# define CORRECT_XUL_DLL u"xul_correct_buildid.dll"_ns
# define MISSING_XUL_DLL u"xul_missing_buildid.dll"_ns
#elif defined(XP_MACOSX)
# define BROKEN_XUL_DLL u"libxul_broken_buildid.dylib"_ns
# define CORRECT_XUL_DLL u"libxul_correct_buildid.dylib"_ns
# define MISSING_XUL_DLL u"libxul_missing_buildid.dylib"_ns
#else
# define BROKEN_XUL_DLL u"libxul_broken_buildid.so"_ns
# define CORRECT_XUL_DLL u"libxul_correct_buildid.so"_ns
# define MISSING_XUL_DLL u"libxul_missing_buildid.so"_ns
#endif
class BuildIDReader : public ::testing::Test {
public:
nsresult getLib(const nsString& lib, nsAutoString& val) {
nsresult rv;
nsCOMPtr<nsIFile> file
#if defined(ANDROID)
= do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
rv = file->InitWithPath(u"/data/local/tmp/test_root/"_ns);
#else
;
rv = NS_GetSpecialDirectory(NS_GRE_BIN_DIR, getter_AddRefs(file));
#endif
if (!NS_SUCCEEDED(rv)) {
return rv;
}
rv = file->Append(u"gtest"_ns);
if (!NS_SUCCEEDED(rv)) {
return rv;
}
rv = file->Append(lib);
if (!NS_SUCCEEDED(rv)) {
return rv;
}
rv = file->GetPath(val);
return rv;
}
void testFromLib() {}
};
TEST_F(BuildIDReader, ReadCorrectBuildIdFromLib) {
nsAutoString xul;
nsresult rv = getLib(CORRECT_XUL_DLL, xul);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Unable to find correct lib "
<< NS_ConvertUTF16toUTF8(CORRECT_XUL_DLL).get();
nsCString installedBuildID;
nsCString sectionName(MOZ_BUILDID_SECTION_NAME);
rv = read_toolkit_buildid_from_file(&xul, §ionName, &installedBuildID);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Error reading from " << NS_ConvertUTF16toUTF8(CORRECT_XUL_DLL).get()
<< ": " << std::hex << static_cast<uint32_t>(rv);
EXPECT_EQ(installedBuildID, "12341201987654"_ns);
}
TEST_F(BuildIDReader, ReadIncorrectBuildIdFromLib) {
nsAutoString xul;
nsresult rv = getLib(BROKEN_XUL_DLL, xul);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Unable to find correct lib "
<< NS_ConvertUTF16toUTF8(CORRECT_XUL_DLL).get();
nsCString installedBuildID;
nsCString sectionName(MOZ_BUILDID_SECTION_NAME);
rv = read_toolkit_buildid_from_file(&xul, §ionName, &installedBuildID);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Error reading from " << NS_ConvertUTF16toUTF8(CORRECT_XUL_DLL).get()
<< ": " << std::hex << static_cast<uint32_t>(rv);
EXPECT_EQ(installedBuildID, "12345678765428Y38AA76"_ns);
}
TEST_F(BuildIDReader, ReadMissingBuildIdFromLib) {
nsAutoString xul;
nsresult rv = getLib(MISSING_XUL_DLL, xul);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Unable to find correct lib "
<< NS_ConvertUTF16toUTF8(CORRECT_XUL_DLL).get();
nsCString installedBuildID;
nsCString sectionName(MOZ_BUILDID_SECTION_NAME);
rv = read_toolkit_buildid_from_file(&xul, §ionName, &installedBuildID);
ASSERT_FALSE(NS_SUCCEEDED(rv))
<< "No error reading from " << NS_ConvertUTF16toUTF8(MISSING_XUL_DLL).get()
<< ": " << std::hex << static_cast<uint32_t>(rv);
EXPECT_EQ(installedBuildID, nsCString(""));
EXPECT_EQ(rv, NS_ERROR_NOT_AVAILABLE);
}
TEST_F(BuildIDReader, ReadFromMissingLib) {
nsAutoString xul;
nsresult rv = getLib(u"inexistent-lib.so"_ns, xul);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Unable to find correct lib "
<< NS_ConvertUTF16toUTF8(CORRECT_XUL_DLL).get();
nsCString installedBuildID;
nsCString sectionName(MOZ_BUILDID_SECTION_NAME);
rv = read_toolkit_buildid_from_file(&xul, §ionName, &installedBuildID);
ASSERT_FALSE(NS_SUCCEEDED(rv))
<< "No error reading from " << NS_ConvertUTF16toUTF8(MISSING_XUL_DLL).get()
<< ": " << std::hex << static_cast<uint32_t>(rv);
EXPECT_EQ(rv, NS_ERROR_INVALID_ARG);
}
TEST_F(BuildIDReader, ReadFromRealLib) {
nsAutoString xul;
nsresult rv = getLib(XUL_DLL u""_ns, xul);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Unable to find correct lib "
<< NS_ConvertUTF16toUTF8(XUL_DLL u""_ns).get();
nsCString installedBuildID;
nsCString realMozBuildID(std::to_string(MOZ_BUILDID).c_str());
ASSERT_TRUE(realMozBuildID.Length() == 14);
nsCString sectionName(MOZ_BUILDID_SECTION_NAME);
rv = read_toolkit_buildid_from_file(&xul, §ionName, &installedBuildID);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Error reading from " << NS_ConvertUTF16toUTF8(XUL_DLL u""_ns).get()
<< ": " << std::hex << static_cast<uint32_t>(rv);
EXPECT_EQ(installedBuildID, realMozBuildID);
}
TEST_F(BuildIDReader, ReadFromNSAppRunner) {
nsAutoString xul;
nsresult rv = getLib(XUL_DLL u""_ns, xul);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Unable to find correct lib "
<< NS_ConvertUTF16toUTF8(XUL_DLL u""_ns).get();
nsCString installedBuildID;
nsCString sectionName(MOZ_BUILDID_SECTION_NAME);
rv = read_toolkit_buildid_from_file(&xul, §ionName, &installedBuildID);
ASSERT_TRUE(NS_SUCCEEDED(rv))
<< "Error reading from " << NS_ConvertUTF16toUTF8(XUL_DLL u""_ns).get()
<< ": " << std::hex << static_cast<uint32_t>(rv);
nsCString realMozBuildID(PlatformBuildID());
ASSERT_TRUE(realMozBuildID.Length() == 14);
EXPECT_EQ(installedBuildID, realMozBuildID);
}
|
import React, { useState } from 'react';
import {
Card,
Input,
Button,
Typography,
} from "@material-tailwind/react";
import { Link, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
const SimpleRegistrationForm = () => {
const history = useHistory();
const [formData, setFormData] = useState({
owner_uname: '',
prod_desc: '',
item: '',
phone_no: '',
item_image: '',
});
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (event) => {
event.preventDefault();
fetch ('http://127.0.0.1:5000/create-item',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
.then ( (res) => {
if (!res.ok) {
throw new Error("item insertion failed ");
}
console.log("Item is added");
})
.catch( (e) => {
console.log(e.message);
})
history.push("/inventory");
};
return (
<div className=" w-full flex justify-center bg-blue-gray-100 p-4">
<Card className= 'contribute-section p-10 ' shadow={false}>
<Typography variant="h4" color="blue-gray">
Item Registration
</Typography>
<Typography color="gray" className="mt-1 font-normal">
Fill the form and upload the image of the item
</Typography>
<form className="mt-8 mb-2 w-80 max-w-screen-lg sm:w-96" onSubmit={handleSubmit}>
<div className="mb-1 flex flex-col gap-6">
<Typography variant="h6" color="blue-gray" className="-mb-4">
Your Name
</Typography>
<Input
required
name="owner_uname"
value={formData.owner_uname }
onChange={handleInputChange}
size="lg"
placeholder="Name"
className="!border-t-blue-gray-200 focus:!border-t-gray-900"
/>
<Typography variant="h6" color="blue-gray" className="-mb-4">
Item Name
</Typography>
<Input
required
name="item"
value={formData.item}
onChange={handleInputChange}
size="lg"
placeholder="Description"
className="!border-t-blue-gray-200 focus:!border-t-gray-900"
/>
<Typography variant="h6" color="blue-gray" className="-mb-4">
Description of the item
</Typography>
<Input
required
name="prod_desc"
value={formData.prod_desc}
onChange={handleInputChange}
size="lg"
placeholder="Description"
className="!border-t-blue-gray-200 focus:!border-t-gray-900"
/>
<Typography variant="h6" color="blue-gray" className="-mb-4">
Contact no.
</Typography>
<Input
required
name="phone_no"
value={formData.phone_no}
onChange={handleInputChange}
size="lg"
placeholder="1234567890"
className="!border-t-blue-gray-200 focus:!border-t-gray-900"
/>
<Typography variant="h6" color="blue-gray" className="-mb-4">
URL of the Image
</Typography>
<div>
<Input
required
name="item_image"
value={formData.item_image}
onChange={handleInputChange}
size="lg"
placeholder="https://image.png"
className="!border-t-blue-gray-200 focus:!border-t-gray-900"
/>
</div>
<a href="https://imgbb.com" target='_blank'><Button className='' style={{
width: "100px"
}} >Get URL</Button></a>
</div>
<Button type="submit" className=" " fullWidth>
Register
</Button>
</form>
</Card>
</div>
);
}
export default SimpleRegistrationForm;
|
---
date : 2022-09-30
time : 07:41
aliases :
- 如何有效學習
---
# Metadata
Status :: #note_grow <br>
Note Type :: #type/📘 <br>
---
# Evergreen
Question :: 主要訴說什麼觀點?
Answer ::
---
# Summary
---
# Note
學習的三步驟:
1. 進入[[學習如何學習 - 發散模式]]大概了解全局,了解認知到要學習的目標以及大方向,以閱讀來說就是先了解書本架構、目錄等
2. 進入[學習如何學習 - 專注模式](學習如何學習%20-%20專注模式.md),針對已經設定好的方向專注投入研究、閱讀
3. 積極回想,回想是最有效的記憶方式
結束後再重複執行以上步驟,千萬不要只運用一種模式學習,最有效的學習方式為在[學習如何學習 - 專注模式](學習如何學習%20-%20專注模式.md)以及[學習如何學習 - 發散模式](學習如何學習%20-%20發散模式.md)模式中進行切換
有效學習後下一步就是要有效記憶,沒有辦法留下記憶一切都是徒勞,以下有幾種方法可以加強記憶:
## 加強記憶
- 睡眠:好的睡眠可以讓樹突棘生長,也就可以讓記憶穩固
- 利用費曼學習法: 將自己所學的傳授給他人
- 為想記住的事物編一首歌曲
- 利用比喻,建立想記憶的事物以及其他類似事情之間的連結
- 做筆記
- 想像自己就是要學習的概念或事物
- 交錯練習
- 同時利用多個感官去學習,聽覺、嗅覺、觸覺等
- 換不同的環境學習
- 分散學習:將一個需要長時間學習的事物切成很多段,利用多段的時間去學習

其中較難理解的方法為交錯練習,交錯練習就是先學習這件事情的一個面向,學習完後再去學習另一個事物的一個面向,例如:先學習歷史,閱讀完後做英文習題,做完後再讀英文並且寫歷史題目,這麼做的原因在於可以迫使自己回想,讓記憶更加穩固
## 注意事項
- 學習最重要的還是主動,並且想出學習之後可以運用的方式以及場景,讓學習更有目標及意義會學習的更好
---
# 連結其他相關想法
這讓我了解到[閱讀整理 - 間歇高效率的三次閱讀法](Sources/Books/閱讀整理%20-%20間歇高效率的三次閱讀法.md)這種閱讀方式也是透過發散和集中的方式在學習
---
# 相關連結
up ::
same ::
down ::
|
# Add Functionality to the Radio Buttons
We will now add functionality to the radio buttons using the `on_clicked()` function. We will define two functions - `hzfunc()` and `colorfunc()` - that will be called when the radio buttons are clicked.
```python
def hzfunc(label):
hzdict = {'1 Hz': s0, '2 Hz': s1, '4 Hz': s2}
ydata = hzdict[label]
l.set_ydata(ydata)
fig.canvas.draw()
radio.on_clicked(hzfunc)
rax = fig.add_axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor)
radio2 = RadioButtons(
rax, ('red', 'blue', 'green'),
label_props={'color': ['red', 'blue', 'green']},
radio_props={
'facecolor': ['red', 'blue', 'green'],
'edgecolor': ['darkred', 'darkblue', 'darkgreen'],
})
def colorfunc(label):
l.set_color(label)
fig.canvas.draw()
radio2.on_clicked(colorfunc)
rax = fig.add_axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor)
radio3 = RadioButtons(rax, ('-', '--', '-.', ':'))
def stylefunc(label):
l.set_linestyle(label)
fig.canvas.draw()
radio3.on_clicked(stylefunc)
```
|
import React, { Fragment, useState } from "react";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";
import axios from "axios";
const Invitation = (props) => {
const { code_access, id } = useParams();
const [error, setError] = useState(null);
const [inputs, setInputs] = useState({});
const handleChange = (event) => {
const name = event.target.name;
const value = event.target.value;
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event) => {
event.preventDefault();
const newUserRoom = {
user_room: {
code_access: code_access,
room_id: id,
user: {
nickname: inputs.nickname
},
}
}
axios({
url: props.urlApi + 'user_rooms/add_user',
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
data: JSON.stringify(newUserRoom),
}).then((response) => {
if (response.data.status === 404) {
setError(response.data.messenger)
}else{
localStorage.setItem("nickname", newUserRoom.user_room.user.nickname);
window.location.href = `http://${window.location.host}/rooms/${id}`
}
});
showAlert()
}
function showAlert() {
console.log(error);
if (error) {
toast.error(error);
} else {
toast.success('Entrando na sala!');
}
}
return (
<Fragment>
<header className="py-5">
<div className="container">
<div className="text-center my-5"></div>
</div>
</header>
<div className="container col-2">
<form onSubmit={handleSubmit}>
<h1 className="h3 mb-3 fw-normal">Codigo de acesso: <span className="text-info">{code_access}</span></h1>
<div className="form-floating">
<input
type="text"
className="form-control"
id="floatingInput"
onChange={handleChange}
value={inputs.nickname || ''}
name="nickname"
/>
<label htmlFor="floatingInput">Novo apelido</label>
</div>
<br />
<button className="w-100 btn btn-lg btn-success" type="submit">
Aceitar convite
</button>
</form>
</div>
</Fragment>
);
};
export default Invitation;
|
import React from 'react';
import userEvent from '@testing-library/user-event';
import { act } from '@testing-library/react';
import '@testing-library/jest-dom';
import { PtsStatus } from '@vertis/schema-registry/ts-types-snake/auto/api/api_offer_model';
import type { FormContext } from 'auto-core/react/components/common/Form/types';
import type { FieldErrors } from 'auto-core/react/components/common/Form/fields/types';
import { renderComponent } from 'www-poffer/react/utils/testUtils';
import { offerFormPageContextMock } from 'www-poffer/react/contexts/offerFormPage.mock';
import { OfferFormFieldNames } from 'www-poffer/react/types/offerForm';
import type { OfferFormFields, OfferFormFieldNamesType } from 'www-poffer/react/types/offerForm';
import OfferFormCustomClearedField from './OfferFormCustomClearedField';
it('при смене типа ПТС на "без ПТС" выставит значение в true', async() => {
const initialValues = {
[OfferFormFieldNames.CUSTOM_NOT_CLEARED]: false,
[OfferFormFieldNames.PTS_STATUS]: PtsStatus.ORIGINAL,
};
const formApi = React.createRef<FormContext<OfferFormFieldNamesType, OfferFormFields, FieldErrors>>();
const { findByLabelText } = await renderComponent(<OfferFormCustomClearedField/>, { initialValues, formApi });
const checkbox = await findByLabelText(/Не растаможен/i) as HTMLInputElement;
expect(checkbox.checked).toBe(false);
await act(async() => {
formApi.current?.setFieldValue(OfferFormFieldNames.PTS_STATUS, PtsStatus.NO_PTS);
});
expect(checkbox.checked).toBe(true);
});
describe('при смене ПТС на не "без ПТС"', () => {
it('если инпут скрыт сбросит значение на false', async() => {
const initialValues = {
[OfferFormFieldNames.CUSTOM_NOT_CLEARED]: true,
[OfferFormFieldNames.PTS_STATUS]: PtsStatus.ORIGINAL,
};
const formApi = React.createRef<FormContext<OfferFormFieldNamesType, OfferFormFields, FieldErrors>>();
const { findByLabelText } = await renderComponent(<OfferFormCustomClearedField isHidden={ true }/>, { initialValues, formApi });
await act(async() => {
formApi.current?.setFieldValue(OfferFormFieldNames.PTS_STATUS, PtsStatus.DUPLICATE);
});
const checkbox = await findByLabelText(/Не растаможен/i) as HTMLInputElement;
expect(checkbox.checked).toBe(false);
});
it('если инпут не скрыт не будет трогать значение', async() => {
const initialValues = {
[OfferFormFieldNames.CUSTOM_NOT_CLEARED]: true,
[OfferFormFieldNames.PTS_STATUS]: PtsStatus.ORIGINAL,
};
const formApi = React.createRef<FormContext<OfferFormFieldNamesType, OfferFormFields, FieldErrors>>();
const { findByLabelText } = await renderComponent(<OfferFormCustomClearedField/>, { initialValues, formApi });
await act(async() => {
formApi.current?.setFieldValue(OfferFormFieldNames.PTS_STATUS, PtsStatus.DUPLICATE);
});
const checkbox = await findByLabelText(/Не растаможен/i) as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
});
it('при клике на чекбокс отсылается метрика', async() => {
const { findByLabelText } = await renderComponent(<OfferFormCustomClearedField/>);
const checkbox = await findByLabelText(/Не растаможен/i) as HTMLInputElement;
userEvent.click(checkbox);
expect(offerFormPageContextMock.sendFormLog).toHaveBeenCalledTimes(1);
expect(offerFormPageContextMock.sendFormLog).toHaveBeenCalledWith({ event: 'click', field: OfferFormFieldNames.CUSTOM_NOT_CLEARED });
});
|
---
layout: post
title: git上传
categories: [技术教程,新手教程]
tags: 教程
author: CKH
---
git的简单上传使用技巧
<!--more-->
# git简单上传使用技巧
## 1. 添加到暂存区
```
//将所有文件添加到暂存区
git add *
//也可以单独选择文件
git add test01.md
```
## 2. 添加到缓存区
```
//提交暂存区到本地仓库(缓存区),-m 说明信息
git commit -m "说明信息"
```
## 3.提交
```
//提交到指定分支
git push origin master
```
|
<div class="text-center">
<form class="form-signin">
<h1 class="h4 mb-2 login">Login do Cliente</h1>
<label for="inputEmail" class="sr-only">Email</label>
<input type="email"
id="inputEmail"
name="email"
placeholder="Informe o seu email"
class="form-control mb-2"
[ngClass] = "{
'is-invalid': email.invalid && (email.dirty || email.touched),
'is-valid': email.valid && (email.dirty || email.touched)
}"
[(ngModel)]="usuario.email"
#email="ngModel"
email
required
/>
<div class="invalid-feedback mb-2" *ngIf="email.invalid && (email.dirty || email.touched)">
<div *ngIf="email.errors.required">
Email é de preechimento obrigatorio
</div>
<div *ngIf="email.errors.email">
Email não está no formato correto
</div>
</div>
<label for="inputSenha"
class="sr-only">Senha</label>
<input type="password"
id="inputSenha"
name="senha"
placeholder="Senha"
class="form-control mb-2"
[(ngModel)]="usuario.senha"
[ngClass] ="{
'is-invalid':senha.invalid && (senha.dirty || senha.touched),
'is-valid':senha.valid && (senha.dirty || senha.touched)
}"
#senha = "ngModel"
required
/>
<div class="invalid-feedback mb-2" *ngIf="senha.invalid && (senha.dirty || senha.touched)">
<div *ngIf="senha.errors.required">
Senha é obrigatória!
</div>
</div>
<button class="btn btn-primary btn-block mb-2"
type="submit" (click)="entrar()" [disabled]="ativar_Spinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" *ngIf="ativar_Spinner" ></span>
Entrar
</button>
<div>Novo por aqui? <a [routerLink]='["/novo-usuario"]'>Cadastre-se</a></div>
<div class="alert alert-danger" *ngIf="mensagem">
{{ mensagem }}
</div>
<img src="../../../assets/img/quick-b-logo.jpg" title="Imagem do src do projeto" />
</form>
</div>
|
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:5000'); // Replace with your server URL
function App() {
const [message, setMessage] = useState('');
const [receivedMessage, setReceivedMessage] = useState('');
useEffect(() => {
socket.on('message', (data) => {
setReceivedMessage(data);
});
}, []);
const handleMessageSubmit = () => {
socket.emit('message', message);
setMessage('');
};
return (
<div>
<h1>Socket.io Example</h1>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={handleMessageSubmit}>Send</button>
<p>Received Message: {receivedMessage}</p>
</div>
);
}
export default App;
|
import { useRef, useState } from "react";
import { FaChevronLeft, FaChevronRight } from "react-icons/fa";
import SwiperCore, { Navigation } from "swiper/core";
import { Swiper, SwiperSlide } from "swiper/react";
import { ShopVoucher } from "../../../../lib/repo/shop-voucher.repo";
import { Spinner } from "../../../shared/utilities/misc";
import { VoucherDetailsDialog } from "../../../shared/voucher/voucher-details-dialog";
import { VoucherItem } from "../../../shared/voucher/voucher-item";
import { DAYS_OF_WEEK } from "../../../shared/voucher/voucher-list";
import { usePaymentContext } from "../providers/payment-provider";
SwiperCore.use([Navigation]);
export function PaymentVouchers(props) {
const { vouchers, setSelectedVoucher } = usePaymentContext();
const [openVoucherDetails, setOpenVoucherDetails] = useState<ShopVoucher>();
const navigationPrevRef = useRef(null);
const navigationNextRef = useRef(null);
if (!vouchers) return <></>;
if (vouchers.length == 0) return <></>;
return (
<div className="pb-8 bg-white">
<Swiper
className="px-4"
spaceBetween={24}
slidesPerView="auto"
grabCursor
navigation={{
prevEl: navigationPrevRef.current,
nextEl: navigationNextRef.current,
}}
>
<div
ref={navigationPrevRef}
className="absolute left-0 w-8 pl-0 pr-2 text-gray-600 transform -translate-y-1/2 bg-white border rounded-r-full shadow cursor-pointer h-9 top-1/2 flex-center group-hover:text-primary z-100"
>
<i className="text-lg">
<FaChevronLeft />
</i>
</div>
<div
ref={navigationNextRef}
className="absolute right-0 w-8 pl-2 pr-0 text-gray-600 transform -translate-y-1/2 bg-white border rounded-l-full shadow cursor-pointer h-9 top-1/2 flex-center group-hover:text-primary z-100"
>
<i className="text-lg">
<FaChevronRight />
</i>
</div>
{vouchers
.filter((item) => {
if (item.applyISODayOfWeek?.length === 0) {
return item;
}
return item.applyISODayOfWeek?.find((day) => {
// write minute 1 because data return from server is with 1 = sunday 7 = saturday [WIP]
let currentDay = parseInt(JSON.stringify(DAYS_OF_WEEK[new Date().getDay() - 1]?.key))
return day === currentDay;
});
// return item.applyISODayOfWeek?.find((day) => {
// return day === new Date().getDay();
// });
})
.map((item: ShopVoucher, index) => {
return (
<SwiperSlide key={index} className="w-full mt-4 xs:w-3/4 sm:w-2/3">
<VoucherItem
voucher={item}
onShowDetails={() => {
setSelectedVoucher(item);
setOpenVoucherDetails(item);
}}
onApply={() => {
setSelectedVoucher(item);
// checkVoucherDiscount(item.code);
// setOrderInput({ ...orderInput, promotionCode: item.code });
}}
/>
</SwiperSlide>
);
})}
</Swiper>
<VoucherDetailsDialog
voucher={openVoucherDetails}
isOpen={!!openVoucherDetails}
onClose={() => setOpenVoucherDetails(null)}
/>
</div>
);
}
|
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return null;
}
StringBuffer sb = new StringBuffer();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
if (temp == null) {
sb.append("#");
sb.append(" ");
} else {
sb.append(temp.val);
sb.append(" ");
queue.offer(temp.left);
queue.offer(temp.right);
}
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() == 0) {
return null;
}
String[] strs = data.split(" ");
TreeNode root = new TreeNode(Integer.valueOf(strs[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
for (int i = 1; i < strs.length; i++) {
TreeNode temp = queue.poll();
if (!strs[i].equals("#")) {
temp.left = new TreeNode(Integer.valueOf(strs[i]));
queue.offer(temp.left);
}
if (!strs[i + 1].equals("#")) {
temp.right = new TreeNode(Integer.valueOf(strs[i + 1]));
queue.offer(temp.right);
}
i++;
}
return root;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
StringBuffer sb = new StringBuffer();
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
if (temp != null) {
sb.append(temp.val);
sb.append("#");
queue.offer(temp.left);
queue.offer(temp.right);
} else {
sb.append(" ");
sb.append("#");
}
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() == 0) {
return null;
}
data = data.trim();
String[] strs = data.split("#");
TreeNode root = new TreeNode(Integer.valueOf(strs[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
for (int i = 1; i < strs.length; i++) {
TreeNode temp = queue.poll();
if (!strs[i].equals(" ")) {
temp.left = new TreeNode(Integer.valueOf(strs[i]));
queue.offer(temp.left);
}
if (i + 1 < strs.length && !strs[i + 1].equals(" ")) {
temp.right = new TreeNode(Integer.valueOf(strs[i + 1]));
queue.offer(temp.right);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stopwatch</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
#timer {
font-size: 36px;
margin-bottom: 20px;
}
#controls {
margin-top: 20px;
}
button {
font-size: 18px;
padding: 10px 20px;
margin: 0 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="timer">00:00:00</div>
<div id="controls">
<button onclick="startStopwatch()">Start</button>
<button onclick="stopStopwatch()">Stop</button>
<button onclick="resetStopwatch()">Reset</button>
</div>
<script>
let timer;
let startTime;
let elapsedTime = 0;
let isRunning = false;
function startStopwatch() {
if (!isRunning) {
startTime = Date.now() - elapsedTime;
timer = setInterval(updateTime, 1000);
isRunning = true;
}
}
function stopStopwatch() {
clearInterval(timer);
isRunning = false;
}
function resetStopwatch() {
clearInterval(timer);
elapsedTime = 0;
updateDisplay();
isRunning = false;
}
function updateTime() {
const currentTime = Date.now();
elapsedTime = currentTime - startTime;
updateDisplay();
}
function updateDisplay() {
const totalSeconds = Math.floor(elapsedTime / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
document.getElementById("timer").innerText =
`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
</script>
</body>
</html>
|
# scripts and templates
## Python
* [sys](https://docs.python.org/3/library/sys.html)
* [os](https://docs.python.org/3/library/os.html)
* [subprocess](https://docs.python.org/3/library/subprocess.html)
* [multiprocessing](https://docs.python.org/3/library/multiprocessing.html)
* [datetime](https://docs.python.org/3/library/datetime.html)
* [time](https://docs.python.org/3/library/time.html)
* [re](https://docs.python.org/3/library/re.html)
* [argparse](https://docs.python.org/3/library/argparse.html)
* [beautifulsoup4](https://pypi.org/project/beautifulsoup4/)
* BeautifulSoup
* [enum](https://docs.python.org/3/library/enum.html)
* [getmac](https://pypi.org/project/getmac/)
* [bibtexparser](https://pypi.org/project/bibtexparser/)
### Networking
* [scapy](https://pypi.org/project/scapy/)
* [mininet](https://pypi.org/project/mininet/)
* [pox](https://pypi.org/project/pox/)
* [pyshark](https://pypi.org/project/pyshark/)
* [requests](https://pypi.org/project/requests/)
### Databases
* [sqlite3](https://docs.python.org/3/library/sqlite3.html)
* [pyodbc](https://pypi.org/project/pyodbc/)
### Math
* [pandas](https://pypi.org/project/pandas/)
* [matplotlib](https://pypi.org/project/matplotlib/)
* matplotlib.pyplot
* [numpy](https://pypi.org/project/numpy/)
* [math](https://docs.python.org/3/library/math.html)
* [sklearn](https://pypi.org/project/sklearn/)
* sklearn.metrics
* r2_score
* [scipy](https://pypi.org/project/scipy/)
* scipy.optimize
* curve_fit
* [networkx](https://pypi.org/project/networkx/)
## Markdown
* [Obsidian Markdown Guide](https://help.obsidian.md/How+to/Format+your+notes)
* [GitHub Markdown Guide](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
## LaTeX and BibTeX
* [Overleaf LaTeX Guide](https://www.overleaf.com/learn)
* [ACM BibTeX Formatting](https://www.acm.org/publications/authors/bibtex-formatting)
|
import { Component, OnInit} from '@angular/core';
import { first } from 'rxjs/operators';
import { AlertService, DataService } from '@app/services';
import { ActivatedRoute, Router } from '@angular/router';
import { Establishment } from '@app/models/establishment.model';
import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";
import { TDocumentDefinitions } from 'pdfmake/interfaces';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
@Component({
selector: 'page-establishment-provider',
templateUrl: 'view-establishment.component.html',
styleUrls: ['view-establishment.component.scss']
})
export class ViewEstablishmentComponent implements OnInit{
id?: string;
establishment?: Establishment;
submitting = false;
loading = false;
elements: any = [];
constructor(private dataService: DataService, private alertService: AlertService,
private route: ActivatedRoute, private router: Router) {
}
ngOnInit(): void {
this.id = this.route.snapshot.params['id'];
this.loading = true;
if (this.id){
this.dataService.getEstablishmentById(this.id)
.pipe(first())
.subscribe((establ: any) =>{
let establishment = establ.getEstablishmentResponse.establishment;
if (establishment){
this.establishment = establishment;
this.setEstablishmentElements(this.establishment!);
this.loading = false;
}
});
}
}
deleteEstablishment() {
this.submitting = true;
this.dataService.deleteEstablishment(this.establishment)
.pipe(first())
.subscribe({
next: () => {
this.alertService.success('Establecimiento eliminado', { keepAfterRouteChange: true });
this.router.navigateByUrl('/establishments');
},
error: error => {
this.alertService.error('Error al eliminar el establecimiento, contacte con Administracion');
}});
}
setEstablishmentElements(establishment: Establishment){
console.log(establishment)
this.elements.push({icon : "pin_drop", name : "Direccion", value : establishment.address});
this.elements.push({icon : "description", name : "Descripción", value : establishment.description});
this.elements.push({icon : "info", name : "Estado", value : establishment.status?.identifier});
this.elements.push({icon : "calendar_today", name : "Fecha Creación", value : this.dataService.getLocalDateTimeFromUTCTime(establishment.creationDate!.replaceAll("\"",""))});
this.elements.push({icon : "calendar_today", name : "Fecha Actualización", value : this.dataService.getLocalDateTimeFromUTCTime(establishment.updateDate!.replaceAll("\"",""))});
this.elements.push({icon : "badge", name : "Usuario Creador", value : establishment.creatorUser?.name ? establishment.creatorUser.name : 'N/A'});
}
generatePDF() {
let docDefinition:TDocumentDefinitions = {
header: 'C#Corner PDF Header',
content: [
{
columns: [
[
{
qr: 'sdflkasdf', fit: 50
}
]
]
},
{
text: 'Información del Establecimiento',
style: 'header',
},
{
text: `Nombre: ${this.establishment?.name || 'N/A'}`,
margin: [0, 10],
},
{
text: `Dirección: ${this.establishment?.address || 'N/A'}`,
margin: [0, 5],
},
{
text: `Descripción: ${this.establishment?.description || 'N/A'}`,
margin: [0, 5],
},
{
text: `Fecha de Creación: ${this.establishment?.creationDate || 'N/A'}`,
margin: [0, 5],
},
{
text: `Fecha de Actualización: ${this.establishment?.updateDate || 'N/A'}`,
margin: [0, 5],
},
{
text: `Creador del Usuario: ${this.establishment?.creatorUser || 'N/A'}`,
margin: [0, 5],
},
{
text: `Estado: ${this.establishment?.status || 'N/A'}`,
margin: [0, 10],
}
],
styles: {
header: {
fontSize: 18,
bold: true,
margin: [0, 0, 0, 10],
},
},
};
// let docDefinition = {
// header: 'C#Corner PDF Header',
// content: 'Sample PDF generated with Angular and PDFMake for C#Corner Blog'
// };
pdfMake.createPdf(docDefinition).open();
}
}
|
#include <iostream>
using namespace std;
/**
* Output all even numbers in a given range.
*
* @param lower lower integer bound (a)
* @param upper upper integer bound (b)
*/
void output_even_integers(const int lower, const int upper)
{
for (int next_even = lower; next_even <= upper; next_even += 2) {
cout << next_even << "\n";
}
}
int main(int argc, char** argv)
{
// Check and parse command line args
if (argc < 3) {
cout << " Usage: ./even_gen [lower_bound] [upper_bound]" << "\n";
return 1;
}
// Assume all args are well formed (i.e., can be parsed as integers).
int lower_bound = atoi(argv[1]);
int upper_bound = atoi(argv[2]);
// The core even output logic
cout << "Range [" << lower_bound << ", " << upper_bound << "]" << "\n";
cout << "\n";
output_even_integers(lower_bound, upper_bound);
return 0;
}
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import fetch, { RequestInit } from 'node-fetch';
import { parsePort, stopwatch, timeout } from '../helpers';
import { CoreNodeFeeResponse } from '@stacks/stacks-blockchain-api-types';
import { ClarityValue, cvToHex } from '@stacks/transactions';
import { logger } from '../logger';
interface CoreRpcAccountInfo {
/** Hex-prefixed uint128. */
balance: string;
/** Hex-prefixed binary blob. */
balance_proof: string;
locked: string;
nonce: number;
/** Hex-prefixed binary blob. */
nonce_proof: string;
unlock_height: number;
}
interface CoreRpcInfo {
burn_block_height: number;
burn_consensus: string;
exit_at_block_height: number | null;
network_id: number;
parent_network_id: number;
peer_version: number;
server_version: string;
stable_burn_block_height: number;
stable_burn_consensus: string;
stacks_tip: string;
stacks_tip_burn_block: string;
stacks_tip_height: number;
unanchored_tip: string;
}
export interface CoreRpcPoxInfo {
contract_id: string;
pox_activation_threshold_ustx: number;
first_burnchain_block_height: number;
prepare_phase_block_length: number;
reward_phase_block_length: number;
reward_slots: number;
rejection_fraction: number;
total_liquid_supply_ustx: number;
current_cycle: {
id: number;
min_threshold_ustx: number;
stacked_ustx: number;
is_pox_active: boolean;
};
next_cycle: {
id: number;
min_threshold_ustx: number;
min_increment_ustx: number;
stacked_ustx: number;
prepare_phase_start_block_height: number;
blocks_until_prepare_phase: number;
reward_phase_start_block_height: number;
blocks_until_reward_phase: number;
ustx_until_pox_rejection: number;
};
/** @deprecated included for backwards-compatibility */
min_amount_ustx: number;
/** @deprecated included for backwards-compatibility */
prepare_cycle_length: number;
/** @deprecated included for backwards-compatibility */
reward_cycle_id: number;
/** @deprecated included for backwards-compatibility */
reward_cycle_length: number;
/** @deprecated included for backwards-compatibility */
rejection_votes_left_required: number;
/** @deprecated included for backwards-compatibility */
next_reward_cycle_in: number;
// Available in Stacks 2.1:
current_burnchain_block_height?: number;
contract_versions?: {
contract_id: string;
activation_burnchain_block_height: number;
first_reward_cycle_id: number;
}[];
}
export interface Neighbor {
network_id: number;
peer_version: number;
ip: string;
port: number;
public_key_hash: string;
authenticated: boolean;
}
interface ReadOnlyContractCallSuccessResponse {
okay: true;
result: string;
}
interface ReadOnlyContractCallFailResponse {
okay: false;
cause: string;
}
export type ReadOnlyContractCallResponse =
| ReadOnlyContractCallSuccessResponse
| ReadOnlyContractCallFailResponse;
interface CoreRpcNeighbors {
sample: Neighbor[];
inbound: Neighbor[];
outbound: Neighbor[];
}
type RequestOpts = RequestInit & { queryParams?: Record<string, string> };
export function getCoreNodeEndpoint(opts?: { host?: string; port?: number | string }) {
const host = opts?.host ?? process.env['STACKS_CORE_RPC_HOST'];
if (!host) {
throw new Error(`STACKS_CORE_RPC_HOST is not defined`);
}
const port = parsePort(opts?.port ?? process.env['STACKS_CORE_RPC_PORT']);
if (!port) {
throw new Error(`STACKS_CORE_RPC_PORT is not defined`);
}
return `${host}:${port}`;
}
export class StacksCoreRpcClient {
readonly endpoint: string;
constructor(opts?: { host?: string; port?: number | string }) {
this.endpoint = getCoreNodeEndpoint(opts);
}
createUrl(path: string, init?: RequestOpts) {
const url = new URL(`http://${this.endpoint}/${path}`);
if (init?.queryParams) {
Object.entries(init.queryParams).forEach(([k, v]) => url.searchParams.set(k, v));
}
return url.toString();
}
/**
* Try connecting to the endpoint until successful for timeout is reached.
* Throws an error if connection cannot be established.
* @param retryTimeout - milliseconds
*/
async waitForConnection(retryTimeout = 60000): Promise<void> {
const retryInterval = 2500; // 2.5 seconds
const timer = stopwatch();
let lastError: Error;
do {
try {
const info = await this.getInfo();
if (!info.stacks_tip_height || info.stacks_tip_height <= 0) {
throw new Error(`stacks_tip_height not >= 1`);
}
return;
} catch (error: any) {
lastError = error;
await timeout(retryInterval);
}
} while (timer.getElapsed() < retryTimeout);
throw lastError;
}
async fetchJson<T>(path: string, init?: RequestOpts): Promise<T> {
const resultString = await this.fetchText(path, init);
try {
const resultJson = JSON.parse(resultString);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return resultJson;
} catch (error) {
logger.error(error, `Error parsing json: "${resultString}"`);
throw error;
}
}
async fetchText(path: string, init?: RequestOpts): Promise<string> {
const url = this.createUrl(path, init);
const result = await fetch(url, init);
if (!result.ok) {
let msg = '';
try {
msg = await result.text();
} catch (error) {
// ignore error
}
throw new Error(`Response ${result.status}: ${result.statusText} fetching ${url} - ${msg}`);
}
try {
const resultString = await result.text();
return resultString;
} catch (error) {
logger.error(error, `Error reading response from ${url}`);
throw error;
}
}
async getInfo(): Promise<CoreRpcInfo> {
const result = await this.fetchJson<CoreRpcInfo>('v2/info');
return result;
}
async getPox(): Promise<CoreRpcPoxInfo> {
const result = await this.fetchJson<CoreRpcPoxInfo>('v2/pox');
return result;
}
async getAccount(
principal: string,
atUnanchoredChainTip = false,
indexBlockHash?: string
): Promise<CoreRpcAccountInfo> {
const requestOpts: RequestOpts = {
method: 'GET',
queryParams: {
proof: '0',
},
};
if (atUnanchoredChainTip) {
const info = await this.getInfo();
requestOpts.queryParams!.tip = info.unanchored_tip;
} else if (indexBlockHash) {
requestOpts.queryParams!.tip = indexBlockHash;
}
const result = await this.fetchJson<CoreRpcAccountInfo>(
`v2/accounts/${principal}`,
requestOpts
);
return result;
}
async getAccountNonce(principal: string, atUnanchoredChainTip = false): Promise<number> {
const nonces: number[] = [];
const lookups: Promise<number>[] = [
this.getAccount(principal, false).then(account => nonces.push(account.nonce)),
];
if (atUnanchoredChainTip) {
lookups.push(this.getAccount(principal, true).then(account => nonces.push(account.nonce)));
}
await Promise.allSettled(lookups);
if (nonces.length === 0) {
await lookups[0];
}
const nonce = Math.max(...nonces);
return nonce;
}
async getAccountBalance(principal: string): Promise<bigint> {
const account = await this.getAccount(principal);
const balance = BigInt(account.balance);
return balance;
}
async sendTransaction(serializedTx: Buffer): Promise<{ txId: string }> {
const result = await this.fetchJson<string>('v2/transactions', {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: serializedTx,
});
return {
txId: '0x' + result,
};
}
async sendReadOnlyContractCall(
contractAddress: string,
contractName: string,
functionName: string,
senderAddress: string,
functionArgs: ClarityValue[]
): Promise<ReadOnlyContractCallResponse> {
const body = {
sender: senderAddress,
arguments: functionArgs.map(arg => cvToHex(arg)),
};
return await this.fetchJson<ReadOnlyContractCallResponse>(
`v2/contracts/call-read/${contractAddress}/${contractName}/${functionName}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}
);
}
async getNeighbors(): Promise<CoreRpcNeighbors> {
const result = await this.fetchJson<CoreRpcNeighbors>(`v2/neighbors`, {
method: 'GET',
});
return result;
}
async getEstimatedTransferFee(): Promise<CoreNodeFeeResponse> {
const result = await this.fetchJson<CoreNodeFeeResponse>(`v2/fees/transfer`, {
method: 'GET',
});
return result;
}
}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:news/news_app/cubit/cubit.dart';
import 'package:news/news_app/cubit/states.dart';
import 'package:news/shared/components/components.dart';
class SearchScreen extends StatelessWidget {
var searchController = TextEditingController();
@override
Widget build(BuildContext context) {
return BlocConsumer<NewsCubit , NewsStates>(
listener: (context, state) {
},
builder: (context, state) {
var list = NewsCubit.get(context).search;
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: searchController,
keyboardType: TextInputType.text,
onFieldSubmitted: (value) {
print(value);
},
onChanged: (value) {
NewsCubit.get(context).getSearch(value);
},
validator: (value) {
if (value!.isEmpty) {
return 'Search must not be empty';
}
return null;
},
decoration: InputDecoration(
labelText: 'Search',
border: OutlineInputBorder(),
prefixIcon: Icon(
Icons.search,
),
),
),
),
Expanded(
child: articleBuilder(list, context , isSearch: true,)),
],
),
);
},
);
}
}
|
from abc import (
ABC,
abstractmethod,
)
from core.apps.customers.entities import CustomerEntity
from core.apps.products.entities.products import ProductEntity
from core.apps.products.entities.reviews import ReviewEntity
from core.apps.products.exceptions.reviews import ReviewInvalidRatingException
from core.apps.products.models.reviews import ReviewModel
class BaseReviewService(ABC):
@abstractmethod
def save_review(
self,
review: ReviewEntity,
customer: CustomerEntity,
product: ProductEntity,
) -> ReviewEntity:
pass
class ORMReviewService(BaseReviewService):
def save_review(
self,
review: ReviewEntity,
customer: CustomerEntity,
product: ProductEntity,
) -> ReviewEntity:
review_dto: ReviewModel = ReviewModel.from_entity(
review=review,
customer=customer,
product=product,
)
review_dto.save()
return review_dto.to_entity()
class BaseReviewValidatorService(ABC):
def validate(
self,
review: ReviewEntity,
customer: CustomerEntity | None = None,
product: ProductEntity | None = None,
):
pass
class ReviewRatingValidatorService(BaseReviewValidatorService):
def validate(
self,
review: ReviewEntity,
*args,
**kwargs,
):
# TODO: constants for range of rating
if not (1 <= review.rating <= 5):
raise ReviewInvalidRatingException(rating=review.rating)
class CompositeReviewValidatorService(BaseReviewValidatorService):
validators: list[BaseReviewValidatorService]
def validate(
self,
review: ReviewEntity,
customer: CustomerEntity | None = None,
product: ProductEntity | None = None,
):
for validator in self.validators:
validator.validate(review=review, customer=customer, product=product)
|
import React from "react";
import {HashRouter as Router, Redirect, Route, Switch} from "react-router-dom";
import Auth from "../routes/Auth";
import Home from "../routes/Home";
import Navigation from "./Navigation";
import Profile from "../routes/Profile";
const AppRouter= ({refreshUser, isLoggedIn, userObj}) => {
return (
<Router>
{isLoggedIn && <Navigation userObj={userObj} />}
<Switch>
{isLoggedIn ? (
<>
<Route exact path ="/">
<Home userObj={userObj} />
</Route>
<Route exact path ="/profile">
<Profile userObj={userObj} refreshUser={refreshUser} />
</Route>
<Redirect from="*" to="/" />
</>
) : (
<>
<Route exact path ="/">
<Auth />
</Route>
<Redirect from="*" to="/" />
</>
)}
</Switch>
</Router>
);
};
export default AppRouter;
|
import pymysql
import pandas as pd
from sqlalchemy import create_engine
from datetime import datetime
def preview_table_mysql(username, password, ip, port, db, table, limit):
mysql_settings = {
"host": ip,
"port": int(port),
"user": username,
"password": password,
"db": db,
"charset": "utf8"
}
mysql_db = pymysql.connect(**mysql_settings)
cursor = mysql_db.cursor(pymysql.cursors.DictCursor)
cursor.execute(f"SELECT * FROM {table} LIMIT {limit};")
results = cursor.fetchall()
for result in results:
for column_name,value in result.items():
if isinstance(value, datetime):
result[column_name] = value.isoformat()
return results
def query_table_mysql(username, password, ip, port, db, table, columns, start_time, end_time, time_column):
def generate_query(table, columns, start_time, end_time, time_column):
req_cols = ','.join(columns)
optional_fields = ''
if start_time is not None and end_time is not None and time_column is not None:
optional_fields = f"WHERE {time_column} BETWEEN '{start_time}' and '{end_time}'"
sql = f'SELECT {req_cols} FROM {table} {optional_fields};'
return sql
sql = generate_query(table, columns, start_time, end_time, time_column)
db_url = 'mysql+pymysql://%s:%s@%s:%s/%s' % (username, password, ip, port, db)
db_engine = create_engine(db_url)
df = pd.read_sql(sql, con=db_engine)
return df
def list_dbs_mysql(username, password, ip, port):
engine = create_engine("mysql+pymysql://%s:%s@%s:%s/" % (username, password, ip, port))
df = pd.read_sql("SHOW DATABASES;", con=engine)
return sorted(df.iloc[:,0].tolist())
def list_tables_mysql(username, password, ip, port, db):
engine = create_engine("mysql+pymysql://%s:%s@%s:%s/%s" % (username, password, ip, port, db))
df = pd.read_sql("SHOW TABLES", con=engine)
return sorted(df.iloc[:,0].tolist())
def list_columns_mysql(username, password, ip, port, db, table):
engine = create_engine("mysql+pymysql://%s:%s@%s:%s/%s" % (username, password, ip, port, db))
df = pd.read_sql("SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME`='%s'" % (db, table), con=engine)
return sorted(df['COLUMN_NAME'].tolist())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.