text
stringlengths
184
4.48M
import React from "react"; import { Grid, CircularProgress } from "@material-ui/core"; import { useSelector } from "react-redux"; //Allows you to extract data from the Redux store state, using a selector function. import Post from './Post/Post'; import useStyles from './styles'; const Posts = ({ setCurrentId}) => { const posts = useSelector((state) => state.posts ); // posts comes from Reducers(Redux) index.js const classes = useStyles(); // MATERIALUI STYLE FROM STYLE.JS >> MATERIALUI console.log(posts); return ( !posts.length ? <CircularProgress /> : ( // check if we have posts, else CircularProgress(loading..). <Grid className={classes.container} container alignItems="stretch" spacing={3}> {posts.map((post) => ( <Grid key={post._id} item xs={12} sm={6}> <Post post={post} setCurrentId={setCurrentId}/> </Grid> ))} </Grid> ) ); } export default Posts;
<?php namespace App\Controllers; use App\Models\AuthModel; class Auth extends BaseController { protected $AuthModel; protected $session; public function __construct() { $this->session = \Config\Services::session(); $this->AuthModel = new AuthModel(); } public function valid_register() { $data = [ 'nama_lengkap' => $this->request->getVar('nama_lengkap'), 'username' => $this->request->getVar('username'), 'email' => $this->request->getVar('email'), 'alamat' => $this->request->getVar('alamat'), 'password' => $this->request->getVar('password'), 'confirm' => $this->request->getVar('confirm'), 'foto' => 'default.jpg' ]; // cek apakah password dan ulangi password sama if ($data['password'] != $data['confirm']) { session()->setFlashdata('pesan', 'Password dan Ulangi Password tidak sama'); return redirect()->to('/register'); } // enkripsi password $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT); $token = bin2hex(random_bytes(10)); $email = \Config\Services::email(); $email->setTo($data['email']); $email->setFrom('[email protected]', 'SourcePicture'); $email->setSubject('Registrasi Akun'); $email->setMessage('Selamat Datang ' . $data['username'] . ' di SourcePicture, akun anda berhasil dibuat. Silahkan Activasi akun anda dengan klik link berikut :' . base_url() . 'auth/activate/' . $token); $email->send(); // simpan ke database $this->AuthModel->save([ 'nama_lengkap' => $data['nama_lengkap'], 'username' => $data['username'], 'email' => $data['email'], 'alamat' => $data['alamat'], 'password' => $data['password'], 'foto' => $data['foto'], 'active' => $token, ]); // Arahkan ke halaman login session()->setFlashdata('login', 'Anda berhasil mendaftar, silahkan cek email anda untuk aktivasi akun'); return redirect()->to('/login'); } public function activate($token) { if ($token) { $user = $this->AuthModel->where(['active' => $token])->first(); if ($user) { $this->AuthModel->save([ 'id_user' => $user['id_user'], 'active' => 'true' ]); session()->setFlashdata('aktif', 'Akun berhasil diaktivasi'); return redirect()->to('/login'); } else { session()->setFlashdata('token', 'Token tidak ditemukan'); return redirect()->to('/login'); } } else { session()->setFlashdata('token', 'Token tidak ditemukan'); return redirect()->to('/login'); } } public function valid_login() { $data = [ 'username' => $this->request->getVar('username'), 'password' => $this->request->getVar('password'), ]; $user = $this->AuthModel->where(['username' => $data['username']])->first(); // cek apakah username ada if ($user) { // cek apakah password benar if (password_verify($data['password'], $user['password'])) { if ($user['active'] == 'true') { session()->set([ 'id_user' => $user['id_user'], 'username' => $user['username'], 'nama_lengkap' => $user['nama_lengkap'], 'email' => $user['email'], 'alamat' => $user['alamat'], 'password' => $user['password'], 'foto' => $user['foto'], 'logged_in' => TRUE ]); session()->set($data); return redirect()->to('/home'); } else { session()->setFlashdata('pesan', 'Akun belum diaktivasi'); return redirect()->to('/login'); } } else { session()->setFlashdata('pesan', 'Password salah.'); return redirect()->to('/login'); } } else { session()->setFlashdata('pesan', 'Username tidak ditemukan.'); return redirect()->to('/login'); } } }
import React from 'react'; import Button from '../Button/Button'; import {jsx} from '@emotion/core'; const BeatsControl = ({defaultValue, updateValue}) => { const [currentValue, setCurrentValue] = React.useState(defaultValue); function addOne() { const newValue = currentValue + 1; setCurrentValue(newValue); updateValue(newValue); } function subtractOne() { const newValue = currentValue - 1; setCurrentValue(newValue); updateValue(newValue); } return ( <div css={{ display: 'flex', flexDirection: 'column', }} > <div css={{ display: 'flex', }} > <Button onClick={subtractOne} variant={'small'}> - </Button> <input value={currentValue} css={{width: '2em'}}></input> <Button onClick={addOne}>+</Button> </div> <div css={{textAlign: 'center'}}> <span>repeat</span> </div> </div> ); }; export default BeatsControl;
# Secret Management This cluster is set up to use sealed-secrets. This allows for SealedSecrets to appears in GitHub and be provisioned via Flux. Creating a SealedSecret will automatically create a secret for use in the cluster. Sealed secrets need to be created via command line tool called `kubeseal` Sealed secrets are also tied to the cluster, so if a cluster is created, I won't be able to decrpyt them in the future. # Namespace-wide secrets ## 1. Create a secret Note: scope here is `namespace-wide` ```sh # Change secret value # Change namespace name echo -n superdupersecret | kubeseal --raw --namespace default --scope namespace-wide ``` Copy the output. ## 2. Build a `SealedSecret` for use within a namespace This will be bound to the namespace ```yaml apiVersion: bitnami.com/v1alpha1 kind: SealedSecret metadata: name: mysecret # change secret name namespace: default # change namespace name annotations: sealedsecrets.bitnami.com/namespace-wide: "true" spec: encryptedData: mysecretKey: AgBy3i4OJSWK+PiTySYZZA9rO43cGDEq..... # Add encrypted value here ``` # Cluster-wide secrets ## 1. Build a `SealedSecret for cluster-wide use ```sh echo -n supersecret | kubeseal --raw --scope cluster-wide ``` ## 2. Deploy ```yaml apiVersion: bitnami.com/v1alpha1 kind: SealedSecret metadata: name: mysecret # change secret name annotations: sealedsecrets.bitnami.com/cluster-wide: "true" spec: encryptedData: mysecretKey: AgBy3i4OJSWK+PiTySYZZA9rO43cGDEq..... # Add encrypted value here ```
import React from 'react'; import { Form , Table, Layout ,Breadcrumb , Input , Select , Icon , Button , Popconfirm , Menu} from '../../base/components/AntdComp'; let { Header , Sider , Content } = Layout; let MItem = Menu.Item; import { base_columns , base_config } from '../consts/BaseData'; import MTable from '../../base/components/TableComp'; import { Enum } from '../../base/consts/Enum.js' let Option = Select.Option; class BaseDataComp extends React.Component{ constructor(props){ super(props); this.state = { searchPm:{ "page":1, "pageSize":20, }, searchType : 1, //搜索条件的类型 filterList:"" //左边列表的筛选条件 } } componentDidMount(){ this.props.handleRefresh(this.state.searchPm); } createColumns(type) { const columns = [...base_columns, { title: "操作", render: (text, record)=><div> <a onClick={()=>this.props.getRecord(record.countryCode)}>编辑</a>&nbsp; <Popconfirm title={ <div> <h5>确定要删除该数据吗?</h5> </div> } onConfirm={() => this.props.handleDelete(record.countryCode)}> <a href="#">删除</a> </Popconfirm> </div>, key: "action" }]; return [...base_config[type].columns , ...columns]; } handleSearch = ()=>{ let { baseType , form , searchPm } = this.props; let fields = form.getFieldsValue(); let pm = {...searchPm}; pm[base_config[baseType].fields.code] = fields.searchType === "1"? fields.code_name : ""; pm[base_config[baseType].fields.name] = fields.searchType === "2"? fields.code_name : ""; pm["status"] = fields.searchType === "3" ? fields.status : "0"; this.props.handleRefresh(pm); } changeSearchType = (type)=>{ if(type === "3"){ this.setState({searchType : 2}); }else{ this.setState({searchType : 1}); } } filterList = (val)=>{ this.setState({filterList:val}); } resetSearch = ()=>{ this.props.form.resetFields(); this.props.resetFlagFun(false); } render(){ let { baseType , dataSource , selectType , handleRefresh ,tableLoading , addDialog ,resetFlag , paging} = this.props; let { getFieldDecorator } = this.props.form; let result_columns = this.createColumns(baseType); if(resetFlag){ this.resetSearch(); } return (<div> <div className="base-data-container"> <div className="base-data-header"> <Form layout="vertical" className="search"> <Form.Item className="search-type search-item"> { getFieldDecorator("searchType",{ initialValue: "1", })( <Select onChange={this.changeSearchType} style={{height:30}} > <Option value="1">编码</Option> <Option value="2">名称</Option> <Option value="3">状态</Option> </Select> ) } </Form.Item> <div className={this.state.searchType === 1 ? "search-show" : "search-hide"}> <Form.Item className="search-content search-item" visible={this.state.searchType === 1}> { getFieldDecorator("code_name",{ initialValue: "", })( <Input.Search placeholder="输入编码/名称搜索" onSearch={this.handleSearch} style={{height:30}} /> ) } </Form.Item> </div> <div className={this.state.searchType === 2 ? "search-show" : "search-hide"}> <Form.Item className="search-status search-item"> { getFieldDecorator("status",{ initialValue: Enum.dataStatus[0].catCode, })( <Select style={{height:30}} > { Enum.dataStatus.map((option)=>{ return (<Option key={option.catCode}>{option.catName}</Option>); }) } </Select> ) } </Form.Item> </div> <Form.Item> <Button type="primary" onClick={this.handleSearch}>查询</Button> </Form.Item> </Form> <div className="btns"> <Button className="btn" type="primary" onClick={()=>addDialog(true)}>{`新增${base_config[baseType].c_name}`}</Button> </div> </div> <div className="base-data-content"> <div className="base-data-nav" style={{background:"#fff"}}> <Input onPressEnter={(e)=>this.filterList(e.target.value)} style={{height:20}} placeholder="请输入..." /> <Menu> { base_config.map((item,index)=>{ if(item.c_name.indexOf(this.state.filterList) > -1){ return (<MItem key={index}><a onClick={()=>selectType(index)}>{item.c_name}</a></MItem>) } }) } </Menu> </div> <div className="base-data-table"> <MTable dataSource={dataSource} cols={result_columns} pageOnChange={handleRefresh} rowKey="countryCode" loading={tableLoading} colsChanged={result_columns} paging={paging} /> </div> </div> </div> </div>); } } export default Form.create()(BaseDataComp);
import logging import os from typing import Iterable, List import pytest from opensearchpy import OpenSearch from core.external_search import ExternalSearchIndex, SearchIndexCoverageProvider from core.model import ExternalIntegration, Work from tests.fixtures.database import DatabaseTransactionFixture from tests.mocks.search import SearchServiceFake class ExternalSearchFixture: """ These tests require opensearch to be running locally. If it's not, or there's an error creating the index, the tests will pass without doing anything. Tests for opensearch are useful for ensuring that we haven't accidentally broken a type of search by changing analyzers or queries, but search needs to be tested manually to ensure that it works well overall, with a realistic index. """ integration: ExternalIntegration db: DatabaseTransactionFixture search: OpenSearch _indexes_created: List[str] def __init__(self): self._indexes_created = [] self._logger = logging.getLogger(ExternalSearchFixture.__name__) @classmethod def create(cls, db: DatabaseTransactionFixture) -> "ExternalSearchFixture": fixture = ExternalSearchFixture() fixture.db = db fixture.integration = db.external_integration( ExternalIntegration.OPENSEARCH, goal=ExternalIntegration.SEARCH_GOAL, url=fixture.url, settings={ ExternalSearchIndex.WORKS_INDEX_PREFIX_KEY: "test_index", ExternalSearchIndex.TEST_SEARCH_TERM_KEY: "test_search_term", }, ) fixture.search = OpenSearch(fixture.url, use_ssl=False, timeout=20, maxsize=25) return fixture @property def url(self) -> str: env = os.environ.get("SIMPLIFIED_TEST_OPENSEARCH") if env is None: raise OSError("SIMPLIFIED_TEST_OPENSEARCH is not defined.") return env def record_index(self, name: str): self._logger.info(f"Recording index {name} for deletion") self._indexes_created.append(name) def close(self): for index in self._indexes_created: try: self._logger.info(f"Deleting index {index}") self.search.indices.delete(index) except Exception as e: self._logger.info(f"Failed to delete index {index}: {e}") # Force test index deletion self.search.indices.delete("test_index*") self._logger.info("Waiting for operations to complete.") self.search.indices.refresh() return None def default_work(self, *args, **kwargs): """Convenience method to create a work with a license pool in the default collection.""" work = self.db.work( *args, with_license_pool=True, collection=self.db.default_collection(), **kwargs, ) work.set_presentation_ready() return work def init_indices(self): client = ExternalSearchIndex(self.db.session) client.initialize_indices() @pytest.fixture(scope="function") def external_search_fixture( db: DatabaseTransactionFixture, ) -> Iterable[ExternalSearchFixture]: """Ask for an external search system.""" """Note: You probably want EndToEndSearchFixture instead.""" data = ExternalSearchFixture.create(db) yield data data.close() class EndToEndSearchFixture: """An external search system fixture that can be populated with data for end-to-end tests.""" """Tests are expected to call the `populate()` method to populate the fixture with test-specific data.""" external_search: ExternalSearchFixture external_search_index: ExternalSearchIndex db: DatabaseTransactionFixture def __init__(self): self._logger = logging.getLogger(EndToEndSearchFixture.__name__) @classmethod def create(cls, transaction: DatabaseTransactionFixture) -> "EndToEndSearchFixture": data = EndToEndSearchFixture() data.db = transaction data.external_search = ExternalSearchFixture.create(transaction) data.external_search_index = ExternalSearchIndex(transaction.session) return data def populate_search_index(self): """Populate the search index with a set of works. The given callback is passed this fixture instance.""" # Create some works. if not self.external_search.search: # No search index is configured -- nothing to do. return # Add all the works created in the setup to the search index. SearchIndexCoverageProvider( self.external_search.db.session, search_index_client=self.external_search_index, ).run() self.external_search.search.indices.refresh() @staticmethod def assert_works(description, expect, actual, should_be_ordered=True): """Verify that two lists of works are the same.""" # Get the titles of the works that were actually returned, to # make comparisons easier. actual_ids = [] actual_titles = [] for work in actual: actual_titles.append(work.title) actual_ids.append(work.id) expect_ids = [] expect_titles = [] for work in expect: expect_titles.append(work.title) expect_ids.append(work.id) # We compare IDs rather than objects because the Works may # actually be WorkSearchResults. expect_compare = expect_ids actual_compare = actual_ids if not should_be_ordered: expect_compare = set(expect_compare) actual_compare = set(actual_compare) assert ( expect_compare == actual_compare ), "%r did not find %d works\n (%s/%s).\nInstead found %d\n (%s/%s)" % ( description, len(expect), ", ".join(map(str, expect_ids)), ", ".join(expect_titles), len(actual), ", ".join(map(str, actual_ids)), ", ".join(actual_titles), ) def expect_results( self, expect, query_string=None, filter=None, pagination=None, **kwargs ): """Helper function to call query_works() and verify that it returns certain work IDs. :param ordered: If this is True (the default), then the assertion will only succeed if the search results come in in the exact order specified in `works`. If this is False, then those exact results must come up, but their order is not what's being tested. """ if isinstance(expect, Work): expect = [expect] should_be_ordered = kwargs.pop("ordered", True) hits = self.external_search_index.query_works( query_string, filter, pagination, debug=True, **kwargs ) query_args = (query_string, filter, pagination) self._compare_hits(expect, hits, query_args, should_be_ordered, **kwargs) def expect_results_multi(self, expect, queries, **kwargs): """Helper function to call query_works_multi() and verify that it returns certain work IDs. :param expect: A list of lists of Works that you expect to get back from each query in `queries`. :param queries: A list of (query string, Filter, Pagination) 3-tuples. :param ordered: If this is True (the default), then the assertion will only succeed if the search results come in in the exact order specified in `works`. If this is False, then those exact results must come up, but their order is not what's being tested. """ should_be_ordered = kwargs.pop("ordered", True) resultset = list( self.external_search_index.query_works_multi(queries, debug=True, **kwargs) ) for i, expect_one_query in enumerate(expect): hits = resultset[i] query_args = queries[i] self._compare_hits( expect_one_query, hits, query_args, should_be_ordered, **kwargs ) def _compare_hits(self, expect, hits, query_args, should_be_ordered=True, **kwargs): query_string, filter, pagination = query_args results = [x.work_id for x in hits] actual = ( self.external_search.db.session.query(Work) .filter(Work.id.in_(results)) .all() ) if should_be_ordered: # Put the Work objects in the same order as the IDs returned # in `results`. works_by_id = dict() for w in actual: works_by_id[w.id] = w actual = [ works_by_id[result] for result in results if result in works_by_id ] query_args = (query_string, filter, pagination) self.assert_works(query_args, expect, actual, should_be_ordered) if query_string is None and pagination is None and not kwargs: # Only a filter was provided -- this means if we pass the # filter into count_works() we'll get all the results we # got from query_works(). Take the opportunity to verify # that count_works() gives the right answer. count = self.external_search_index.count_works(filter) assert count == len(expect) def close(self): for index in self.external_search_index.search_service().indexes_created(): self.external_search.record_index(index) self.external_search.close() @pytest.fixture(scope="function") def end_to_end_search_fixture( db: DatabaseTransactionFixture, ) -> Iterable[EndToEndSearchFixture]: """Ask for an external search system that can be populated with data for end-to-end tests.""" data = EndToEndSearchFixture.create(db) try: yield data except Exception: raise finally: data.close() class ExternalSearchFixtureFake: integration: ExternalIntegration db: DatabaseTransactionFixture search: SearchServiceFake external_search: ExternalSearchIndex @pytest.fixture(scope="function") def external_search_fake_fixture( db: DatabaseTransactionFixture, ) -> ExternalSearchFixtureFake: """Ask for an external search system that can be populated with data for end-to-end tests.""" data = ExternalSearchFixtureFake() data.db = db data.integration = db.external_integration( ExternalIntegration.OPENSEARCH, goal=ExternalIntegration.SEARCH_GOAL, url="http://does-not-exist.com/", settings={ ExternalSearchIndex.WORKS_INDEX_PREFIX_KEY: "test_index", ExternalSearchIndex.TEST_SEARCH_TERM_KEY: "a search term", }, ) data.search = SearchServiceFake() data.external_search = ExternalSearchIndex( _db=db.session, custom_client_service=data.search ) return data
import React, { useState, useEffect } from 'react'; import EducatorNavBar from './EducatorComponents/EducatorSideBar'; import { useAuth } from '../contexts/AuthContext'; import { useDarkMode } from '../contexts/DarkMode'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; import { FaPlus, FaTrash, FaEye } from 'react-icons/fa'; import { toast } from 'react-toastify'; import AddCourseModal from './course/CreateCourse'; import styled from 'styled-components'; const CourseCard = styled.div` width: 100%; padding: 16px; border: 1px solid ${(props) => (props.$isDarkMode ? '#2d2d2d' : '#e0e0e0')}; border-radius: 8px; display: flex; flex-direction: row; align-items: center; background-color: ${(props) => (props.$isDarkMode ? '#1a1a1a' : '#fff')}; color: ${(props) => (props.$isDarkMode ? '#cad2c5' : '#333')}; transition: transform 0.3s, box-shadow 0.3s; cursor: pointer; margin-bottom: 16px; min-height: 200px; /* Ensure uniform height */ &:hover { transform: translateY(-5px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } img { width: 100px; height: 100px; object-fit: cover; border-radius: 8px; margin-right: 16px; } .course-info { flex-grow: 1; h3 { font-size: 1.25rem; font-weight: 600; margin-bottom: 8px; } .description { max-height: 4.5rem; /* 3 lines */ overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; white-space: normal; } } .course-actions { display: flex; flex-direction: column; align-items: flex-end; .action-icons { display: flex; flex-direction: row; align-items: center; margin-top: 8px; .icon { margin-left: 16px; cursor: pointer; &:hover { color: ${(props) => (props.$isDarkMode ? '#ff6b6b' : '#ff0000')}; } } } } `; function EducatorPage() { const { user, isLoading } = useAuth(); const { isDarkMode, toggleDarkMode } = useDarkMode(); // Accessing dark mode context const navigate = useNavigate(); const [courses, setCourses] = useState([]); const [showConfirmDialog, setShowConfirmDialog] = useState(false); const [courseToDelete, setCourseToDelete] = useState(null); const [isAddCourseModalOpen, setIsAddCourseModalOpen] = useState(false); const fetchCourses = async () => { if (!user || !user.token) { return; } try { const headers = { Authorization: `Bearer ${user.token}` }; const response = await axios.get(`/api/Courses/educator/${user.id}`, { headers }); const coursesData = response.data; const fetchCountsPromises = coursesData.map(async (course) => { const viewCountResponse = await axios.get(`/api/Courses/${course.id}/visit-count`); const purchaseCountResponse = await axios.get(`/api/Courses/${course.id}/purchase-count`); return { ...course, viewCount: viewCountResponse.data, purchaseCount: purchaseCountResponse.data, }; }); const coursesWithCounts = await Promise.all(fetchCountsPromises); setCourses(coursesWithCounts); } catch (error) { console.error('Error fetching courses:', error); toast.error('Failed to fetch courses'); } }; useEffect(() => { if (!user || isLoading) return; if (user.role !== "Educator") { navigate("/"); // Redirect to home or another appropriate page return; } fetchCourses(); }, [user, isLoading, navigate]); const handleAddCourse = () => { setIsAddCourseModalOpen(true); }; const handleModifyCourse = (courseId) => { navigate(`/educator/course/${courseId}`); }; const handleRemoveCourse = async () => { if (!courseToDelete) return; try { await axios.delete(`/api/Courses/${courseToDelete.id}`, { headers: { Authorization: `Bearer ${user.token}`, }, params: { educator: user.id, }, }); toast.success('Course removed successfully'); setCourses((prevCourses) => prevCourses.filter((course) => course.id !== courseToDelete.id)); } catch (error) { console.error('Error removing course:', error); toast.error('Failed to remove course'); } finally { setCourseToDelete(null); setShowConfirmDialog(false); } }; const showConfirmDeletion = (course) => { setCourseToDelete(course); setShowConfirmDialog(true); }; const hideConfirmDeletion = () => { setShowConfirmDialog(false); setCourseToDelete(null); }; const currencyFormatter = new Intl.NumberFormat('fr-TN', { style: 'currency', currency: 'TND', minimumFractionDigits: 2, }); if (isLoading) { return <div>Loading...</div>; } if (!user || user.role !== "Educator") { return <div>Unauthorized access. Redirecting...</div>; } return ( <div className={`flex min-h-screen ${isDarkMode ? 'bg-[#253237]' : 'bg-[#FAFAFA]'} text-${isDarkMode ? '[#CAD2C5]' : '[#333333]'}`}> <EducatorNavBar isDarkMode={isDarkMode} toggleTheme={toggleDarkMode} /> <div className={`flex-grow p-8 max-w-6xl mx-auto p-8 rounded-lg`}> <div className={`flex justify-between items-center mb-8 sticky top-0 z-10 p-4 rounded-lg ${isDarkMode ? 'bg-[#1A2D34]' : 'bg-[#E0E0E0]'}`}> <h1 className="text-4xl font-bold">{'Your Added Courses'}</h1> <button onClick={handleAddCourse} className={`px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700 flex items-center justify-center`}> <FaPlus className="mr-2" /> Add Course </button> </div> {courses.length > 0 ? ( <ul className="space-y-4"> {courses.map((course) => ( <CourseCard key={course.id} onClick={() => handleModifyCourse(course.id)} $isDarkMode={isDarkMode}> {course.courseImage && ( <img src={course.courseImage} alt={course.title} /> )} <div className="course-info"> <h3>{course.title}</h3> <div className="description"> {course.description} </div> <p>Price: {currencyFormatter.format(course.price)}</p> <div className="flex items-center space-x-4"> <div className="flex items-center text-green-500"> <FaPlus className="mr-1" /> Purchases: {course.purchaseCount} </div> <div className="flex items-center text-blue-500"> <FaEye className="mr-1" /> Views: {course.viewCount} </div> </div> </div> <div onClick={(e) => { e.stopPropagation(); showConfirmDeletion(course); }} className="course-actions"> <FaTrash className="icon" title="Delete" /> </div> </CourseCard> ))} </ul> ) : ( <p className="text-center"> No courses available </p> )} </div> {showConfirmDialog && ( <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75"> <div className={`p-6 rounded-lg ${isDarkMode ? 'bg-[#253237]' : 'bg-white'}`}> <h3 className="text-lg font-medium mb-4">Confirm Deletion</h3> <p className="mb-4">Are you sure you want to delete this course?</p> <div className="flex justify-end space-x-4"> <button className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600" onClick={handleRemoveCourse}>Delete</button> <button className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700" onClick={hideConfirmDeletion}>Cancel</button> </div> </div> </div> )} <AddCourseModal isOpen={isAddCourseModalOpen} onClose={() => setIsAddCourseModalOpen(false)} refreshCourses={fetchCourses} isDarkMode={isDarkMode} /> </div> ); } export default EducatorPage;
import { Icon } from '@iconify/react'; import moment from 'moment'; import React from 'react' import styled from 'styled-components'; import Avatar from '../../components/Avatar'; import Tag from '../../components/Tag'; import { BookType, OrderType } from '../../interfaces'; import { genStatusOrder, ORDER_STATUS } from '../../utils'; import { currencyFormat } from '../../utils/format'; type Props = { data: Array<BookType>; handleDetail: (id: string) => void; } type Type = | "start" | "end" | "left" | "right" | "center" | "justify" | "match-parent"; const TableCell = styled.td` padding: 10px; `; const TableCellHead = styled.th` padding: 10px; `; function BaseTableBook({ data, handleDetail }: Props) { const textAlign = (value: Type) => value; const header = [ { name: "ID", width: "5%", textAlign: textAlign("center"), }, { name: "Khách hàng", width: "25%", textAlign: textAlign("left"), }, { name: "Tổng tiền", width: "10%", textAlign: textAlign("center"), }, { name: "Thời gian đặt bàn", width: "15%", textAlign: textAlign("center"), }, { name: "Thời gian nhận bàn", width: "15%", textAlign: textAlign("center"), }, { name: "Số người", width: "10%", textAlign: textAlign("center"), }, { name: "Trạng thái", width: "10%", textAlign: textAlign("center"), }, { name: "Hành động", width: "10%", textAlign: textAlign("right"), }, ]; return ( <table className="mt-4 w100_per bg_white box_shadow_card border_radius_3"> <thead className="bg_ddd"> <tr> {header.map((item, index) => ( <TableCellHead key={index} className="font_family_regular font14" style={{ width: item.width, textAlign: item.textAlign, }} > {item.name} </TableCellHead> ))} </tr> </thead> <tbody> {data.map((item, index) => ( <tr className="border_top_gray_1px" key={index}> <TableCell style={{ width: header.at(0)?.width, textAlign: header.at(0)?.textAlign, }} > {index + 1} </TableCell> <TableCell style={{ width: header.at(1)?.width, textAlign: header.at(1)?.textAlign, }} > <div className='d-flex align-items-center' > <Avatar size={42} url={item?.customer?.avatar} shape="circle" /> <div className='ml_10px'> <div className='font14 font_family_bold_italic'>{item?.customer?.name}</div> <div className='font12 font_family_bold_italic mt-2 color_888'>SĐT: {item?.customer?.phone}</div> </div> </div> </TableCell> <TableCell style={{ width: header.at(2)?.width, textAlign: header.at(2)?.textAlign, }} > {currencyFormat(item?.totalPrice)} </TableCell> <TableCell style={{ width: header.at(3)?.width, textAlign: header.at(3)?.textAlign, }} > {moment(new Date()).format(`DD/MM/YYYY HH:mm`)} </TableCell> <TableCell style={{ width: header.at(4)?.width, textAlign: header.at(4)?.textAlign, }} >{moment(new Date()).format(`DD/MM/YYYY HH:mm`)} </TableCell> <TableCell style={{ width: header.at(5)?.width, textAlign: header.at(5)?.textAlign, }} > {item?.quantityCustomer} </TableCell> <TableCell className='font_family_bold_italic' style={{ width: header.at(6)?.width, textAlign: header.at(6)?.textAlign, }} > <Tag color={genStatusOrder(item.status).color} name={genStatusOrder(item.status).name} /> </TableCell> <TableCell style={{ width: header.at(7)?.width, textAlign: header.at(7)?.textAlign, }} > { item.status === ORDER_STATUS.USING && <button onClick={() => handleDetail(item?.id)} className="btn p-0 mr_5px" title='Thanh toán' > <Icon className="icon20x20 color_primary" icon="dashicons:money-alt" /> </button> } <button onClick={() => handleDetail(item?.id)} className="btn p-0 mr_5px" title='Xem thông tin' > <Icon className="icon20x20 color_888" icon="akar-icons:eye" /> </button> </TableCell> </tr> ))} </tbody> </table> ) } export default React.memo(BaseTableBook)
package com.nuriggum.nuriframe.security.config; import com.nuriggum.nuriframe.security.filter.CustomAuthenticationFilter; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class WebSecurityConfig { private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; private final CustomAuthenticationFailureHandler customAuthenticationFailureHandler; private final CustomLoginAuthenticationEntryPoint authenticationEntryPoint; private final AuthenticationConfiguration authenticationConfiguration; private final CustomAccessDeniedHandler accessDeniedHandler; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() .cors().disable() .authorizeHttpRequests(request -> request .antMatchers("/login").permitAll() .antMatchers("/user/register").permitAll() .anyRequest().permitAll()) // .antMatchers("/").authenticated() // .anyRequest().authenticated()) .logout().disable() .addFilterBefore(ajaxAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .exceptionHandling(config -> config .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler)); return http.build(); } @Bean public CustomAuthenticationFilter ajaxAuthenticationFilter() throws Exception { CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(); customAuthenticationFilter.setAuthenticationManager(authenticationManager()); customAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler); customAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler); SecurityContextRepository contextRepository = new HttpSessionSecurityContextRepository(); customAuthenticationFilter.setSecurityContextRepository(contextRepository); return customAuthenticationFilter; } @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = require("express"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const UserModel_1 = require("../database/models/UserModel"); const router = (0, express_1.Router)(); router.post('/login', async (req, res) => { if (!req.body.email || !req.body.password) { return res.status(400).json({ message: 'All fields must be filled' }); } const { email, password } = req.body; const user = await UserModel_1.default.findOne({ where: { email } }); if (!user) { return res.status(401).json({ message: 'Incorrect email or password' }); } const flag = await bcrypt.compare(password, user === null || user === void 0 ? void 0 : user.dataValues.password); if (flag) { const token = jwt.sign(user === null || user === void 0 ? void 0 : user.dataValues, 'jwt_secret', { algorithm: 'HS256' }); res.status(200); res.json({ token }); } if (!flag) { return res.status(401).json({ message: 'Incorrect email or password' }); } }); router.get('/login/validate', async (req, res) => { const token = req.headers.authorization; const flag = await jwt.verify(token, 'jwt_secret'); req.body.user = flag; return res.status(200).json({ role: req.body.user.role }); }); exports.default = router; //# sourceMappingURL=user.js.map
import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { add_to_search_index } from "../components/SearchBlock/quantumSearch"; function ProductForm({ quantumAuth, productData }) { // State variables to manage form input values const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [image, setImage] = useState(""); const [unit, setUnit] = useState(""); const [price, setPrice] = useState(""); // Access the navigation function from React Router const navigate = useNavigate(); // Event handler functions to update state on input changes const handleNameChange = (event) => { const value = event.target.value; setName(value); }; const handleDescriptionChange = (event) => { const value = event.target.value; setDescription(value); }; const handleImageChange = (event) => { const value = event.target.value; setImage(value); }; const handleUnitChange = (event) => { const value = event.target.value; setUnit(value); }; const handlePriceChange = (event) => { const value = event.target.value; setPrice(value); }; useEffect(() => { const fetchProductForEdit = async () => { if (productData) { setName(productData.name); setDescription(productData.description); setImage(productData.image); setUnit(productData.unit); setPrice(productData.price.toString()); } }; fetchProductForEdit(); }, [productData]); const handleSubmit = async (event) => { event.preventDefault(); const vendorName = quantumAuth.getAuthentication().account.fullname; const data = { name: name, description: description, image: image, unit: unit, price: parseFloat(price), vendor_name: vendorName }; let productUrl = `${quantumAuth.baseUrl}/api/products`; let method = "POST"; if (productData) { productUrl += `/${productData.id}`; method = "PUT"; } const fetchConfig = { method: method, credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }; const response = await fetch(productUrl, fetchConfig); if (response.ok) { const prod = await response.json(); await add_to_search_index(prod, quantumAuth); navigate("/vendor/product"); } }; return ( <div className="row services "> <div className="offset-3 col-6"> <div className="shadow p-4 mt-4 mb-4"> <h1 className="px-2">{productData ? "Edit" : "Create"} a Product</h1> <form onSubmit={handleSubmit} id="create-location-form"> <div className="form-floating mb-3"> <input value={name} onChange={handleNameChange} placeholder="YYYY-MM-DD" required type="text" name="name" id="name" className="form-control" /> <label htmlFor="name">Name</label> </div> <div className="form-floating mb-3"> <input value={description} onChange={handleDescriptionChange} placeholder="description" required type="text" name="description" id="description" className="form-control" /> <label htmlFor="description">Description</label> </div> <div className="form-floating mb-3"> <input value={image} onChange={handleImageChange} placeholder="image" required type="text" name="image" id="image" className="form-control" /> <label htmlFor="image">Image</label> </div> <div className="form-floating mb-3"> <input value={unit} onChange={handleUnitChange} placeholder="unit" required type="text" name="unit" id="unit" className="form-control" /> <label htmlFor="unit">Unit</label> </div> <div className="form-floating mb-3"> <input value={price} onChange={handlePriceChange} placeholder="price" required type="text" name="price" id="price" className="form-control" /> <label htmlFor="price">Price</label> </div> <button className="btn btn-primary">Create</button> </form> </div> </div> </div> ); } export default ProductForm;
import json import subprocess from enum import Enum from typing import Any class CommandType(Enum): BASH = 0 GDB = 1 WRITE = 2 END = 3 class Command(): cmd_str: str cmd_type: CommandType params: list[str] = [] def __init__(self, cmd_raw: str, use_gdb: bool): if cmd_raw.upper().startswith("BASH"): self.cmd_str = cmd_raw[len("BASH COMMAND:"):].strip() self.cmd_type = CommandType.BASH elif cmd_raw.upper().startswith("GDB"): self.cmd_str = cmd_raw[len("GDB COMMAND:"):].strip() self.cmd_type = CommandType.GDB elif cmd_raw.upper().startswith("WRITE"): self.cmd_str = cmd_raw[len("WRITE"):].strip() self.cmd_type = CommandType.WRITE elif cmd_raw.upper().startswith("FINISH!"): self.cmd_type = CommandType.END else: raise ValueError("GPT response not of valid type") def execute(self) -> Any: kwargs = { "capture_output": True, "text": True, } if self.cmd_type == CommandType.BASH: kwargs["shell"] = True response = subprocess.run(self.cmd_str, **kwargs) return response.stdout
import '@wangeditor/editor/dist/css/style.css' // 引入 css import React, { useState, useEffect } from 'react' import { Editor, Toolbar } from '@wangeditor/editor-for-react' import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor' import styles from './index.less' import { Button, Form, Input, message, Typography } from 'antd' import { v4 as uuidv4 } from 'uuid'; import { addNewsByPaperId } from '@/services/admin/newsController' import { useNavigate } from '@umijs/max' const { Title } = Typography function addNews() { const navigate = useNavigate() // editor 实例 const [editor_cn, setEditor_cn] = useState<IDomEditor | null>(null) // TS 语法 const [editor_en, setEditor_en] = useState<IDomEditor | null>(null) // 编辑器内容 const [html_cn, setHtml_cn] = useState('<p>hello</p>') const [html_en, setHtml_en] = useState('<p>hello</p>') const [title_cn, setTitle_cn] = useState<string>() const [title_en, setTitle_en] = useState<string>() // 模拟 ajax 请求,异步设置 html useEffect(() => { setTimeout(() => { setHtml_cn('<h1 style="text-align: center;">中文标题</h1><hr/><p>新闻内容</p>') setHtml_en('<h1 style="text-align: center;">Title EN-US</h1><hr/><p>news content</p>') }, 500) }, []) // 工具栏配置 const toolbarConfig: Partial<IToolbarConfig> = {} toolbarConfig.excludeKeys = ['group-video'] useEffect(() => { console.log(toolbarConfig); }) // 编辑器配置 const editorConfig: Partial<IEditorConfig> = { placeholder: '请输入内容...', MENU_CONF: { uploadImage: { server: '/api/uploadPic', // form-data fieldName ,默认值 'wangeditor-uploaded-image' fieldName: 'image', // 单个文件的最大体积限制,默认为 2M maxFileSize: 5 * 1024 * 1024, // 5M // 最多可上传几个文件,默认为 100 maxNumberOfFiles: 20, // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 [] allowedFileTypes: ['image/*'], // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。 // meta: { // token: 'xxx', // otherKey: 'yyy' // }, // 将 meta 拼接到 url 参数中,默认 false metaWithUrl: false, // 自定义增加 http header headers: { 'authorization': `Bearer ${sessionStorage.getItem('token')}` }, // 跨域是否传递 cookie ,默认为 false //withCredentials: true, // 超时时间,默认为 10 秒 timeout: 5 * 1000, // 5 秒 } } } // 及时销毁 editor ,重要! useEffect(() => { return () => { if (editor_cn == null) return editor_cn.destroy() setEditor_cn(null) } }, [editor_cn]) useEffect(() => { return () => { if (editor_en == null) return editor_en.destroy() setEditor_cn(null) } }, [editor_en]) function insertText() { if (editor_cn == null) return editor_cn.insertText(' hello ') } function printHtml() { if (editor_cn == null) return console.log(editor_cn.getHtml()) } const onClick = async () => { if (!title_cn || !title_en) { message.error('请填写标题') return } const paperId = uuidv4() let data = { news_cn: { paperId: paperId, text: html_cn, title: title_cn }, news_en: { paperId: paperId, text: html_en, title: title_en } } const resData = await addNewsByPaperId(data) console.log(resData); if (resData.success) { message.success('提交成功') navigate('/admin/news') return } message.error('提交失败请重试') } return ( <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center',alignItems:'center' }}> <Title>添加新闻</Title> <div className={styles.container}> <div className={styles.left}> <Form style={{ margin: "20px 20px" }}> <Form.Item label="中文标题" name="title_cn" rules={[{ required: true, message: '请输入中文标题!' }]}> <Input style={{ maxWidth: "600px" }} onChange={(e) => setTitle_cn(e.target.value)}></Input> </Form.Item> </Form> <div style={{ border: '1px solid #ccc', zIndex: 100, minHeight: '800px' }}> <Toolbar editor={editor_cn} defaultConfig={toolbarConfig} mode="default" style={{ borderBottom: '1px solid #ccc' }} /> <Editor defaultConfig={editorConfig} value={html_cn} onCreated={setEditor_cn} onChange={editor => setHtml_cn(editor.getHtml())} mode="default" style={{ overflowY: 'hidden' }} /> </div> </div> <div className={styles.right}> <Form style={{ margin: "20px 20px" }}> <Form.Item label="英文标题" name="title_en" rules={[{ required: true, message: '请输入英文标题!' }]}> <Input style={{ maxWidth: "600px" }} onChange={(e) => setTitle_en(e.target.value)}></Input> </Form.Item> </Form> <div style={{ border: '1px solid #ccc', zIndex: 100, minHeight: '800px' }}> <Toolbar editor={editor_en} defaultConfig={toolbarConfig} mode="default" style={{ borderBottom: '1px solid #ccc' }} /> <Editor defaultConfig={editorConfig} value={html_en} onCreated={setEditor_en} onChange={editor => setHtml_en(editor.getHtml())} mode="default" style={{ overflowY: 'hidden' }} /> </div> </div> </div> <Button type="primary" style={{ margin: "30px 0" }} onClick={() => onClick()}>提交</Button> </div> ) } export default addNews
import React, { useState, useEffect, useRef } from 'react'; import { DataTable } from 'primereact/datatable'; import { Column } from 'primereact/column'; import { Button } from 'primereact/button'; import { InputText } from 'primereact/inputtext'; import { useTranslation } from 'react-i18next'; import { FilterMatchMode, FilterOperator } from 'primereact/api'; import { useHistory } from "react-router-dom"; import { PartnerService } from '../../service/PartnerService'; import { SplitButton } from 'primereact/splitbutton'; import { Fieldset } from 'primereact/fieldset'; import { InputSwitch } from 'primereact/inputswitch'; import { Toast } from 'primereact/toast'; import { Dialog } from 'primereact/dialog'; import { MultiSelect } from 'primereact/multiselect'; import { Dropdown } from 'primereact/dropdown'; import { InputNumber } from 'primereact/inputnumber'; import { NewPartnerDialogue } from '../../pages/dialogues/NewPartnerDialogue'; export const PartnerListPage = () => { const { t, i18n } = useTranslation(); const toast = useRef(null); let history = useHistory(); const [partnerList, setPartnerList] = useState([]); const [newPartnerDialog, setNewPartnerDialog] = useState(false); const [deletePartnerDialog, setDeletePartnerDialog] = useState(false); const [selectedPartnerIndex, setSelectedPartnerIndex] = useState(null); const [selectedPartner, setSelectedPartner] = useState({}); const [loading, setLoading] = useState(true); const [filters, setFilters] = useState({ 'global': { value: null, matchMode: FilterMatchMode.CONTAINS } }); const partnerService = new PartnerService(); useEffect(() => { partnerService.getPartners().then(data => { setPartnerList(data); setLoading(false) }); }, []); const filtersMap = { 'filters': { value: filters, callback: setFilters }, }; const renderHeader = (filtersKey) => { const filters = filtersMap[`${filtersKey}`].value; return ( <span className="p-input-icon-left"> <i className="pi pi-search" /> <InputText type="search" value={filters['global'].value || ''} onChange={(e) => onGlobalFilterChange(e, filtersKey)} placeholder={t('search')} /> </span> ); } const header1 = renderHeader('filters'); const onGlobalFilterChange = (event, filtersKey) => { const value = event.target.value; let filters = { ...filtersMap[filtersKey].value }; filters['global'].value = value; filtersMap[filtersKey].callback(filters); } const deleteButtonTemplate = (rowData, info) => { return <div className="flex justify-content-end"><Button icon="pi pi-trash" className="p-button-rounded p-button-warning" onClick={() => { setDeletePartnerDialog(true); setSelectedPartnerIndex(info.rowIndex) }} /> </div>; } const deletePartner = () => { setLoading(true); let partners = [...partnerList]; partnerService.deletePartnerById(partners[selectedPartnerIndex].id) .then(data => { setPartnerList(partners); setLoading(false); setDeletePartnerDialog(false); }); partners.splice(selectedPartnerIndex, 1); } const categoryBody = (rowData) => { return <span >{t(rowData.category)}</span>; } const genderBodyTemplate = (rowData) => { return <span >{t(rowData.customerGender)}</span>; }; const hideDialog = () => { setDeletePartnerDialog(false); setNewPartnerDialog(false); } const detailsButtonItems = (partnerId) => [ { label: t('staff_list'), icon: 'pi pi-users', command: () => { history.push('/admin/partners-staff-list/'+partnerId) }, }, { label: t('settings'), icon: 'pi pi-cog', command: () => { history.push('/admin/partners-settings/'+partnerId) } }, { label: t('photos'), icon: 'pi pi-images', command: () => { history.push('/admin/partners-photos') } }, { label: t('invoices'), icon: 'pi pi-money-bill', command: () => { history.push('/admin/partners-invoices') } }, { label: t('use_panel'), icon: 'pi pi-window-maximize', command: () => { history.push('/admin/partners-use-panel') } } ]; const deletePartnerDialogFooter = ( <React.Fragment> <Button label={t('no')} icon="pi pi-times" className="p-button-text" onClick={hideDialog} /> <Button label={t('yes')} icon="pi pi-check" className="p-button-text" onClick={deletePartner} /> </React.Fragment> ); const editButtonTemplate = (rowData) => { return ( <div className="flex justify-content-end"> <SplitButton label={t('edit')} model={detailsButtonItems(rowData.id)} onClick={(e)=>clickEditButton(e)} /> </div> ); } const clickEditButton = (e) => { history.push({pathname: e.value.to + e.param, state: e}); } return ( <div> <div className="card"> <div className="grid"> <div className="flex justify-content-start flex-wrap card-container col"> <h2><b>{t('partners')}</b></h2> </div> <div className="flex justify-content-end flex-wrap card-container col"> <Button label={t('add_new_partner')} icon="pi pi-plus" style={{ padding: '.45rem 1rem', marginBottom: "1rem", marginLeft: '1rem' }} className="p-button-success" onClick={() => setNewPartnerDialog(true)} /> </div> </div> <DataTable paginator value={partnerList} responsiveLayout="scroll" header={header1} filters={filters} onFilter={(e) => setFilters(e.filters)} rows={20} paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" rowsPerPageOptions={[20, 50, 100]} loading={loading} emptyMessage={t('no_records_found')} currentPageReportTemplate={t('Showing {first} to {last} of {totalRecords} entries')}> <Column field="name" header={t('partner')} sortable ></Column> <Column field="city" header={t('city')} sortable ></Column> <Column field="district" header={t('district')} sortable ></Column> <Column field="category" body={categoryBody} header={t('category')} sortable filter></Column> <Column field="customerGender" body={genderBodyTemplate} header={t('customer_gender')} sortable filter></Column> <Column header="" body={deleteButtonTemplate}></Column> <Column header="" body={editButtonTemplate}></Column> </DataTable> </div> <Dialog visible={deletePartnerDialog} style={{ width: '450px' }} header={t('confirm')} modal footer={deletePartnerDialogFooter} onHide={hideDialog}> <div className="confirmation-content"> <i className="pi pi-exclamation-triangle mr-3" style={{ fontSize: '2rem' }} /> {<span>{t('confirm_delete')}</span>} </div> </Dialog> <NewPartnerDialogue visible={newPartnerDialog} partner={selectedPartner} onHide={hideDialog}></NewPartnerDialogue> </div> ); }
{% url 'login' as login %} {% url 'signup' as signup %} {% url 'cart:cart' as cart %} <nav class="navbar navbar-expand-md bg-dark navbar-dark"> <a href="{% url 'index' %}" class="navbar-brand">D'Mare Store</a> <button type="button" name="button" class="navbar-toggler navbar-toggler-rigth" data-toggle="collapse" data-target="#navbarop"> <span class="navbar-toggler-icon"></span> </button> <div id="navbarop" class="navbar-collapse collapse hide"> <ul class="navbar-nav"> <li class="nav-item {% if request.path == cart %} active {% endif %}"> <a class="nav-link" href="{{ cart }}">Mi carrito <span class="fas fa-shopping-cart"></span></a> </li> </ul> <ul class="nav navbar-nav ml-auto"> {% if user.is_authenticated %} <li class="navbar-item"> <a href="{% url 'logout' %}" class="nav-link"> <span class="fa-solid fa-right-from-bracket"></span> Log Out</a> </li> {% else %} <!--request.path nos permite ver en que ruta estamos para así activar el icono de la ruta actual --> <li class="navbar-item {% if request.path == login %}active{% endif %}"> <a href="{{ login }}" class="nav-link"><span class="fas fa-user"></span> Login</a> </li> <li class="navbar-item {% if request.path == signup %}active{% endif %}"> <a href="{{ signup }}" class="nav-link"><span class="fa-solid fa-user-plus"></span> Sing Up</a> </li> {% endif %} </ul> </div> </nav>
import tensorflow as tf import tensorflow_probability as tfp from deeprl.tensorflow import models FLOAT_EPSILON = 1e-8 # A2C, TRPO, PPO class DetachedScaleGaussianPolicyHead(tf.keras.Model): def __init__(self, loc_activation='tanh', dense_loc_kwargs=None, log_scale_init=0., scale_min=1e-4, scale_max=1., distribution=tfp.distributions.MultivariateNormalDiag): super().__init__() self.loc_activation = loc_activation if dense_loc_kwargs is None: dense_loc_kwargs = models.default_dense_kwargs() self.dense_loc_kwargs = dense_loc_kwargs self.log_scale_init = log_scale_init self.scale_min = scale_min self.scale_max = scale_max self.distribution = distribution def initialize(self, action_size): self.loc_layer = tf.keras.layers.Dense( action_size, self.loc_activation, **self.dense_loc_kwargs) log_scale = [[self.log_scale_init] * action_size] self.log_scale = tf.Variable(log_scale, dtype=tf.float32) def call(self, inputs): loc = self.loc_layer(inputs) batch_size = tf.shape(inputs)[0] scale = tf.math.softplus(self.log_scale) + FLOAT_EPSILON scale = tf.clip_by_value(scale, self.scale_min, self.scale_max) scale = tf.tile(scale, (batch_size, 1)) return self.distribution(loc, scale) # MPO class GaussianPolicyHead(tf.keras.Model): def __init__( self, loc_activation='tanh', dense_loc_kwargs=None, scale_activation='softplus', scale_min=1e-4, scale_max=1, dense_scale_kwargs=None, distribution=tfp.distributions.MultivariateNormalDiag ): super().__init__() self.loc_activation = loc_activation if dense_loc_kwargs is None: dense_loc_kwargs = models.default_dense_kwargs() self.dense_loc_kwargs = dense_loc_kwargs self.scale_activation = scale_activation self.scale_min = scale_min self.scale_max = scale_max if dense_scale_kwargs is None: dense_scale_kwargs = models.default_dense_kwargs() self.dense_scale_kwargs = dense_scale_kwargs self.distribution = distribution def initialize(self, action_size): self.loc_layer = tf.keras.layers.Dense(action_size, self.loc_activation, **self.dense_loc_kwargs) self.scale_layer = tf.keras.layers.Dense(action_size, self.scale_activation, **self.dense_scale_kwargs) def call(self, inputs): loc = self.loc_layer(inputs) scale = self.scale_layer(inputs) scale = tf.clip_by_value(scale, self.scale_min, self.scale_max) return self.distribution(loc, scale) class Actor(tf.keras.Model): def __init__(self, encoder, torso, head): super().__init__() self.encoder = encoder self.torso = torso self.head = head def initialize( self, observation_space, action_space, observation_normalizer=None ): self.encoder.initialize(observation_normalizer) self.head.initialize(action_space.shape[0]) def call(self, *inputs): out = self.encoder(*inputs) out = self.torso(out) return self.head(out)
import { burgerConstructorReducer, initialData } from "./burger-constructior"; import { AllInitialTypes, IIngredient } from "../../../types"; import { ADD_BUN, ADD_INGREDIENT, DEL_INGREDIENT, DROP_CONSTRUCTOR, SORT_INGREDIENTS } from "../../actions/burger-constructor"; import { currentBunData, currentIngredientData } from "../../../utils/constants"; describe("Check burger constructor", () => { it("should return initialState", () => { expect(burgerConstructorReducer(undefined, {} as AllInitialTypes)).toEqual(initialData); }); it("ADD_BUN", () => { const state = burgerConstructorReducer(initialData, { type: ADD_BUN, bun: currentBunData }); expect(state.bun).toBe(currentBunData); }); it("ADD_INGREDIENT", () => { const state = burgerConstructorReducer(initialData, { type: ADD_INGREDIENT, item: currentIngredientData }); expect(state.items.find(item => item._id === currentIngredientData._id)).not.toBe(undefined); }); it("DEL_INGREDIENT", () => { const state = burgerConstructorReducer(initialData, { type: DEL_INGREDIENT, id: '1' }); expect(state.items.find(item => item._id === '1')).toBe(undefined); }); it("SORT_INGREDIENTS", () => { const state = burgerConstructorReducer(initialData, { type: SORT_INGREDIENTS, dragIndex: 1, hoverIndex: 1 }); expect(state.bun).not.toBe({}); expect(state.items).not.toHaveLength(0); }); it("DROP_CONSTRUCTOR", () => { const state = burgerConstructorReducer(initialData, { type: DROP_CONSTRUCTOR, }); expect(state.bun).toStrictEqual({} as IIngredient); expect(state.items).toStrictEqual([]); }); });
--- title: Remote-Debugging des AEM SDK description: Der lokale Schnellstart des AEM SDK ermöglicht das Remote-Java-Debugging von Ihrer IDE aus, sodass Sie die Live-Code-Ausführung in AEM schrittweise durchführen können, um den genauen Ausführungsfluss zu überblicken. jira: KT-5251 topic: Development feature: Developer Tools role: Developer level: Beginner, Intermediate thumbnail: 34338.jpeg exl-id: beac60c6-11ae-4d0c-a055-cd3d05aeb126 duration: 452 source-git-commit: af928e60410022f12207082467d3bd9b818af59d workflow-type: tm+mt source-wordcount: '270' ht-degree: 100% --- # Remote-Debugging des AEM SDK >[!VIDEO](https://video.tv.adobe.com/v/34338?quality=12&learn=on) Der lokale Schnellstart des AEM SDK ermöglicht das Remote-Java-Debugging von Ihrer IDE aus, sodass Sie die Live-Code-Ausführung in AEM schrittweise durchführen können, um den genauen Ausführungsfluss zu überblicken. Um einen Remote-Debugger mit AEM zu verbinden, muss der lokale Schnellstart des AEM SDK mit bestimmten Parametern (`-agentlib:...`) ausgeführt werden, sodass die IDE eine Verbindung herstellen kann. ``` $ java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar aem-author-p4502.jar ``` + AEM SDK unterstützt nur Java 11 + `address` gibt den Port an, auf den AEM für Remote-Debugging-Verbindungen lauscht, und kann in einen beliebigen verfügbaren Port auf dem lokalen Entwicklungs-Computer geändert werden. + Der letzte Parameter (z. B. `aem-author-p4502.jar`) ist die AEM SKD-Schnellstart-JAR. Dies kann entweder der AEM Author-Service (`aem-author-p4502.jar`) oder der AEM Publish-Service (`aem-publish-p4503.jar`) sein. ## Anweisungen zur IDE-Einrichtung Die meisten Java-IDEs bieten Unterstützung für das Remote-Debugging von Java-Programmen, jedoch variieren die genauen Einrichtungsschritte jeder IDE. Die genauen Schritte finden Sie in den Anweisungen zum Remote-Debugging Ihrer IDE. Normalerweise erfordern IDE-Konfigurationen Folgendes: + Der Host, auf den beim lokalen Schnellstart des AEM SDKs gelauscht wird, d. h. `localhost`. + Der Port, auf den beim lokalen Schnellstart des AEM SDKs für die Remote-Debugging-Verbindung gelauscht wird, welches der Port ist, der vom `address`-Parameter beim Ausführen des lokalen Schnellstarts des AEM SDKs angegeben wird. + Gelegentlich müssen die Maven-Projekte, die den Quell-Code für Remote-Debugging bereitstellen, angegeben werden. Dies sind die Maven-Projekt-Projekte des OSGi-Pakets. ### Einrichten von Anweisungen + [Einrichten des VS-Code-Java-Remote-Debuggers](https://code.visualstudio.com/docs/java/java-debugging) + [Einrichten des IntelliJ-IDEA-Remote-Debuggers](https://www.jetbrains.com/help/idea/tutorial-remote-debug.html) + [Einrichten des Eclipse-Remote-Debuggers](https://javapapers.com/core-java/java-remote-debug-with-eclipse/)
import {createSlice, createAsyncThunk} from "@reduxjs/toolkit"; import api from "../../api/api"; export const get_customers = createAsyncThunk( "chat/get_customers", async (id, {rejectWithValue, fulfillWithValue}) => { try { const {data} = await api.get(`/chat/seller/get-customers/${id}`, { withCredentials: true, }); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const get_customer_message = createAsyncThunk( "chat/get_customer_message", async (id, {rejectWithValue, fulfillWithValue}) => { try { const accessToken = localStorage.getItem("accessToken"); const {data} = await api.post( `/chat/seller/get-customer-message/${id}`, {accessToken}, { withCredentials: true, } ); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const send_message_to_customer = createAsyncThunk( "chat/send_message_to_customer", async (info, {rejectWithValue, fulfillWithValue}) => { try { const {data} = await api.post( `/chat/seller/send-message-to-customer`, info, { withCredentials: true, } ); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const get_sellers = createAsyncThunk( "chat/get_sellers", async (_, {rejectWithValue, fulfillWithValue}) => { try { const {data} = await api.get(`/chat/admin/get-sellers`, { withCredentials: true, }); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const send_message_seller_admin = createAsyncThunk( "chat/send_message_seller_admin", async (info, {rejectWithValue, fulfillWithValue}) => { try { const {data} = await api.post(`/chat/message-send-seller-admin`, info, { withCredentials: true, }); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const get_admin_message = createAsyncThunk( "chat/get_admin_message", async (receiverId, {rejectWithValue, fulfillWithValue}) => { try { const {data} = await api.get(`/chat/get-admin-message/${receiverId}`, { withCredentials: true, }); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const get_seller_message = createAsyncThunk( "chat/get_seller_message", async (receiverId, {rejectWithValue, fulfillWithValue}) => { try { const accessToken = localStorage.getItem("accessToken"); const {data} = await api.post( `/chat/get-seller-message`, {accessToken}, { withCredentials: true, } ); return fulfillWithValue(data); } catch (error) { return rejectWithValue(error.response.data); } } ); export const chatReducer = createSlice({ name: "chat", initialState: { successMessage: "", errorMessage: "", loader: false, customers: [], messages: [], activeCustomer: [], activeSeller: [], messageNotification: [], activeAdmin: "", friends: [], seller_admin_messages: [], currentSeller: {}, currentCustomer: {}, sellers: [], }, reducers: { clearMessage: (state, action) => { state.errorMessage = ""; state.successMessage = ""; }, updateMessage: (state, action) => { state.messages = [...state.messages, action.payload]; }, updateCustomer: (state, action) => { state.activeCustomer = [...state.activeCustomer, ...action.payload]; }, updateAdminMessage: (state, action) => { state.seller_admin_messages = [ ...state.seller_admin_messages, action.payload, ]; }, updateSellerMessage: (state, action) => { state.seller_admin_messages = [ ...state.seller_admin_messages, action.payload, ]; }, activeStatus_update: (state, action) => { state.activeAdmin = action.payload.status; }, }, extraReducers: (builder) => { builder.addCase(get_customers.fulfilled, (state, action) => { state.customers = action.payload.customers; }); builder.addCase(get_customer_message.fulfilled, (state, action) => { state.messages = action.payload.messages; state.currentCustomer = action.payload.currentCustomer; }); builder.addCase(send_message_to_customer.fulfilled, (state, action) => { let tempFriends = state.customers; let index = tempFriends.findIndex( (i) => i.friendId === action.payload.message.receiverId ); while (index > 0) { let temp = tempFriends[index]; tempFriends[index] = tempFriends[index - 1]; tempFriends[index - 1] = temp; index--; } state.customers = tempFriends; state.messages = [...state.messages, action.payload.message]; state.successMessage = "Send message success"; }); builder.addCase(get_sellers.fulfilled, (state, action) => { state.sellers = action.payload.sellers; }); builder.addCase(send_message_seller_admin.fulfilled, (state, action) => { state.seller_admin_messages = [ ...state.seller_admin_messages, action.payload.message, ]; let tempFriends = state.sellers; let index = tempFriends.findIndex( (i) => i._id === action.payload.message.receiverId ); while (index > 0) { let temp = tempFriends[index]; tempFriends[index] = tempFriends[index - 1]; tempFriends[index - 1] = temp; index--; } state.sellers = tempFriends; state.successMessage = "Send message success"; }); builder.addCase(get_admin_message.fulfilled, (state, action) => { state.seller_admin_messages = action.payload.messages; state.currentSeller = action.payload.currentSeller; }); builder.addCase(get_seller_message.fulfilled, (state, action) => { state.seller_admin_messages = action.payload.messages; }); }, }); export default chatReducer.reducer; export const { clearMessage, updateMessage, updateCustomer, updateAdminMessage, updateSellerMessage, activeStatus_update, } = chatReducer.actions;
// Biblioteca do Display LCD #include <LiquidCrystal.h> int inches = 0; int cm = 0; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.begin(16, 2); lcd.setCursor(2, 0); lcd.print("NAVAR M M N"); lcd.setCursor(0, 1); lcd.print("HC-SR04 + LCD"); delay(2000); pinMode(7, INPUT); pinMode(8, INPUT); lcd.clear(); } void loop() { lcd.clear(); cm = 0.01723 * readUltrasonicDistance(7, 8); lcd.setCursor(0, 0); lcd.print("Distancia em"); lcd.setCursor(0, 1); lcd.print("Centimetro: "); lcd.print(cm); delay(100); } long readUltrasonicDistance(int triggerPin, int echoPin) { pinMode(triggerPin, OUTPUT); // Clear the trigger digitalWrite(triggerPin, LOW); delayMicroseconds(2); // Sets the trigger pin to HIGH state for 10 microseconds digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); pinMode(echoPin, INPUT); // Reads the echo pin, and returns the sound wave travel time in microseconds return pulseIn(echoPin, HIGH); }
import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observable, catchError } from "rxjs"; import { ResourceService } from "src/app/core/services/resource.service"; import { BasicInformation } from "./models/basic-information"; import { Response } from "src/app/core/models/response"; @Injectable({ providedIn: 'root' }) export class RequestBasicInformationRepository extends ResourceService { constructor(http: HttpClient) { super(http) } getResourceUrl(): string { return 'request' } getBasicInformation(id: number): Observable<BasicInformation> { return this.http .get<BasicInformation>(this.APIUrl + `/${id}` + '/basic-information') .pipe(catchError((err) => { throw new Error('Error', err.message) })) } addBasicInformation(id: number, resource: BasicInformation): Observable<any> { return this.http .post(this.APIUrl + `/${id}` + '/basic-information', resource) .pipe(catchError((err) => { throw new Error('Error', err.message) })) } }
<template> <nav class="navbar orange lighten-1"> <div class="nav-wrapper"> <div class="navbar-left"> <a href="#" @click.prevent="$emit('clickOnMenu')"> <i class="material-icons black-text">dehaze</i> </a> <span class="black-text"> {{ date | fDate('date time') }} </span> </div> <ul class="right hide-on-small-and-down"> <li> <a class="dropdown-trigger black-text input-field" href="#" data-target="dropdown" tabindex="1" ref="dropDownBtn" > {{ getUserInfo.name }} <i class="material-icons right">arrow_drop_down</i> </a> <ul id='dropdown' class='dropdown-content'> <li> <router-link to="/profile" class="black-text"> <i class="material-icons">account_circle</i>Профиль </router-link> </li> <li class="divider" tabindex="-1"></li> <li> <a href="#" class="black-text" @click.prevent="logout"> <i class="material-icons">assignment_return</i>Выйти </a> </li> </ul> </li> </ul> </div> </nav> </template> <script> import { mapActions, mapGetters } from 'vuex'; import fDate from '@/filters/fDate'; export default { name: 'Navbar', data: () => ({ date: new Date(), interval: undefined, dropDown: undefined, }), computed: { ...mapGetters(['getUserInfo']), }, methods: { ...mapActions(['signOut']), logout() { this.signOut() .then(() => { this.$router.push('/login?message=logout'); }); }, }, filters: { fDate, }, mounted() { this.interval = setInterval(() => { this.date = new Date(); }, 1000); const el = this.$refs.dropDownBtn; this.dropDown = window.M.Dropdown.init(el, { constrainWidth: false, }); }, beforeDestroy() { if (this.interval) { clearInterval(this.interval); } if (this.dropDown) { this.dropDown.destroy(); } }, }; </script> <style scoped> </style>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Controller</title> <link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css"> <style type="text/css"> .todo { padding: 10px 0; border-bottom: 1px solid #BFBFBF; cursor: move; } .todo:last-child { border-bottom: none; } </style> </head> <body ng-app="todoApp"> <div class="container" ng-controller="TodoCtrl" ng-init="init()"> <div class="hero-unit"> <h1>Todo</h1> </div> <!-- notes 1. directive 'avatar' on the div replaces the internal content with its template 2. input maps to the model 3. ng-click invokes the function --> <div avatar></div> <input type="text" placeholder="Add a todo" ng-model="todos.new_todo.title" /> <button class="btn" ng-click="todos.new_todo.save()">Add</button> <div style="max-width: 340px; padding: 8px 0;" class="well"> <ul class="nav nav-list" sorter> <!-- Some notes 1. the attribute data-title will be used lated in the sorter directive 2. ng-repeat loops thru the list 3. ng-click marks it complete and removes the item --> <li class="todo" data-title='{{todo.attributes.title}}' ng-repeat="todo in todos.list"> <input type="checkbox" ng-click="todos.complete(todo)" /> <span ng-bind="todo.attributes.title"/> </li> </ul> </div> </div> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script> <script type="text/javascript" src="../static/js/angular.min.js"></script> <script type="text/javascript" src="../static/js/fulltodo.js"></script> <script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.17.min.js"></script>
import { NextApiRequest, NextApiResponse } from "next"; import { getSession } from "next-auth/react"; import prisma from "../../../utils/prisma"; import { sessionAndMethodAreValid } from "../../../utils/api"; import { ERROR_CODES } from "../../../utils/constants"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const session = await getSession({ req }); if (!sessionAndMethodAreValid(req, res, session, "GET")) { return; } const { groupId } = req.query; if (!groupId || typeof groupId !== "string") { return res .status(400) .json({ success: false, error_type: ERROR_CODES.queryInvalid }); } // TODO: check the user is part of the group // (otherwise you can get any group's tasks, // as long as you have the groupId) let tasks = undefined; try { tasks = await prisma.task.findMany({ where: { group: { id: groupId } }, orderBy: [ { dueDate: "asc", }, { name: "asc", }, ], }); } catch (e) { console.error(e); } if (!tasks) { return res .status(500) .json({ success: false, error_type: ERROR_CODES.databaseUnkownError }); } return res.status(200).json({ success: true, data: tasks }); }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:task/controller/home_controller.dart'; import 'package:task/widgets/grid_item.dart'; import 'package:task/widgets/home_title.dart'; class HomeBody extends StatefulWidget { const HomeBody({super.key}); @override State<HomeBody> createState() => _HomeBodyState(); } class _HomeBodyState extends State<HomeBody> { final ScrollController _scrollController = ScrollController(); bool _isTitleVisible = false; final controller = Get.put(HomeController()); @override void initState() { super.initState(); _scrollController.addListener(() { if (_scrollController.position.pixels >= 43) { if (!_isTitleVisible) { setState(() { _isTitleVisible = true; }); } } else { if (_isTitleVisible) { setState(() { _isTitleVisible = false; }); } } }); } @override Widget build(BuildContext context) { return NestedScrollView( controller: _scrollController, headerSliverBuilder: (context, innerBoxIsScrolled) { return [ SliverAppBar( expandedHeight: 115, pinned: true, backgroundColor: Colors.white, elevation: 0, toolbarHeight: _isTitleVisible ? 70 : 50, centerTitle: true, leading: SizedBox(), flexibleSpace: Padding( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 10, ), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ IconButton( onPressed: () {}, icon: Icon( Icons.card_travel, size: 28, ), ), IconButton( onPressed: () {}, icon: Icon( Icons.person, size: 28, ), ), _isTitleVisible ? const SizedBox() : IconButton( onPressed: () {}, icon: Icon( Icons.favorite, size: 28, ), ), _isTitleVisible ? Hero( tag: 'form1', child: SizedBox( height: 45, width: 200, child: ClipRRect( borderRadius: BorderRadius.circular(40), child: TextFormField( decoration: InputDecoration( border: InputBorder.none, filled: true, fillColor: Colors.grey.shade200, hintText: 'Search for products'), ), ), ), ) : const SizedBox(), _isTitleVisible ? const SizedBox() : const Spacer(), IconButton( onPressed: () { controller.scaffoldKey.currentState!.openDrawer(); }, icon: const Icon( Icons.menu, ), ), ], ), !_isTitleVisible ? Hero( tag: 'form1', child: SizedBox( height: 45, width: double.infinity, child: ClipRRect( borderRadius: BorderRadius.circular(40), child: TextFormField( decoration: InputDecoration( border: InputBorder.none, filled: true, fillColor: Colors.grey.shade200, hintText: 'Search for products', ), ), ), ), ) : const SizedBox() ], ), ), ), ]; }, body: SingleChildScrollView( physics: const NeverScrollableScrollPhysics(), child: Column( children: [ const HomeTitle(), Padding( padding: const EdgeInsetsDirectional.symmetric( horizontal: 30, vertical: 10, ), child: GridView.builder( physics: const BouncingScrollPhysics(), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( childAspectRatio: 1, crossAxisSpacing: 20, mainAxisSpacing: 20, mainAxisExtent: 150, crossAxisCount: 2, ), itemBuilder: (context, index) { return const GridItem(); }, shrinkWrap: true, itemCount: 8, ), ), ], ), ), ); } @override void dispose() { _scrollController.dispose(); super.dispose(); } }
#include "Problem_1003.h" using namespace std; #include <iostream> #include <unordered_map> typedef struct tagFibbValue { int iZero = { }; int iOne = { }; tagFibbValue operator+(tagFibbValue tSrc) { tagFibbValue tTemp = { }; tTemp.iZero = iZero + tSrc.iZero; tTemp.iOne = iOne + tSrc.iOne; return tTemp; } } FIBV; unordered_map<int, FIBV> mapFibb1003; FIBV Calc_Fibb_1003(int iN) { auto iter = mapFibb1003.find(iN); if (iter != mapFibb1003.end()) { return iter->second; } else { if (iN == 0) return FIBV{ 1, 0 }; else if (iN == 1) return FIBV{ 0, 1 }; else { FIBV tFibv = Calc_Fibb_1003(iN - 1) + Calc_Fibb_1003(iN - 2); mapFibb1003.emplace(iN, tFibv); return tFibv; } } } int CProblem_1003::Solve_Problem() { int iNumTC = { }; cin >> iNumTC; for (int iIndex = 0; iIndex < iNumTC; ++iIndex) { int iNumFibb = { }; cin >> iNumFibb; FIBV iFibv = Calc_Fibb_1003(iNumFibb); cout << iFibv.iZero << " " << iFibv.iOne << '\n'; } return 0; }
@keras_export("keras.backend.concatenate") @tf.__internal__.dispatch.add_dispatch_support @doc_controls.do_not_generate_docs def concatenate(tensors, axis=-1): """Concatenates a list of tensors alongside the specified axis. Args: tensors: list of tensors to concatenate. axis: concatenation axis. Returns: A tensor. Example: >>> a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = tf.constant([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) >>> tf.keras.backend.concatenate((a, b), axis=-1) <tf.Tensor: shape=(3, 6), dtype=int32, numpy= array([[ 1, 2, 3, 10, 20, 30], [ 4, 5, 6, 40, 50, 60], [ 7, 8, 9, 70, 80, 90]], dtype=int32)> """ if axis < 0: rank = ndim(tensors[0]) if rank: axis %= rank else: axis = 0 if py_all(is_sparse(x) for x in tensors): return tf.compat.v1.sparse_concat(axis, tensors) elif py_all(isinstance(x, tf.RaggedTensor) for x in tensors): return tf.concat(tensors, axis) else: return tf.concat([to_dense(x) for x in tensors], axis)
'use client'; import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import Drawer from '@mui/material/Drawer'; import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import List from '@mui/material/List'; import Divider from '@mui/material/Divider'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; import ChevronRightIcon from '@mui/icons-material/ChevronRight'; import ListItem from '@mui/material/ListItem'; import ListItemButton from '@mui/material/ListItemButton'; import ListItemText from '@mui/material/ListItemText'; import AddLocationIcon from '@mui/icons-material/AddLocation'; import AirlineStopsIcon from '@mui/icons-material/AirlineStops'; import TravelExploreIcon from '@mui/icons-material/TravelExplore'; import LoginIcon from '@mui/icons-material/Login'; import LogoutIcon from '@mui/icons-material/Logout'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; import { useSession } from 'next-auth/react'; import { SnackbarProvider } from 'notistack'; const drawerWidth = 240; interface MenuListItem { name: string; icon: JSX.Element; href: string; } const MenuList: MenuListItem[] = [ { name: 'Locations', icon: <AddLocationIcon />, href: '/locations' }, { name: 'Trips', icon: <AirlineStopsIcon />, href: '/trips' }, { name: 'Explore', icon: <TravelExploreIcon />, href: '/explore' }, { name: 'Logout', icon: <LogoutIcon />, href: '/signin' }, { name: 'Sign in', icon: <LoginIcon />, href: '/signin' }, ]; const Main = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })<{ open?: boolean; }>(({ theme, open }) => ({ flexGrow: 1, // padding: theme.spacing(3), transition: theme.transitions.create('margin', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginLeft: `-${drawerWidth}px`, ...(open && { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, }), })); interface AppBarProps extends MuiAppBarProps { open?: boolean; } const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })<AppBarProps>(({ theme, open }) => ({ transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { width: `calc(100% - ${drawerWidth}px)`, marginLeft: `${drawerWidth}px`, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }), })); const DrawerHeader = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, justifyContent: 'flex-end', })); export default function SideNav({ children }: React.PropsWithChildren) { const theme = useTheme(); const { data: session } = useSession(); const [open, setOpen] = React.useState(false); const pathname = usePathname(); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); }; const isSelected = (href: string) => pathname === href; return ( <SnackbarProvider autoHideDuration={3000}> <Box sx={{ display: 'flex' }}> <AppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ mr: 2, ...(open && { display: 'none' }) }} > <MenuIcon /> </IconButton> </Toolbar> </AppBar> <Drawer sx={{ width: drawerWidth, flexShrink: 0, '& .MuiDrawer-paper': { width: drawerWidth, boxSizing: 'border-box', }, }} variant="persistent" anchor="left" open={open} > <DrawerHeader> <IconButton onClick={handleDrawerClose}> {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </DrawerHeader> <Divider /> <List> {MenuList.filter(({ name }) => { if (name === 'Logout' && !session) { return false; } return !(name === 'Sign in' && session); }).map(({ name, icon, href }, _index) => ( <Link key={name} href={href}> <ListItem key={name} disablePadding> <ListItemButton selected={isSelected(href)}> {icon} <ListItemText primary={name} /> </ListItemButton> </ListItem> </Link> ))} </List> </Drawer> <Main open={open}> <DrawerHeader /> {children} </Main> </Box> </SnackbarProvider> ); }
- Angular is a TypeScript-based open-source framework to build client side application. It is a great choice for SPAs. - Angular follows modular approach which helps in write reusable code. - Development in angular is quicker and easier and also unit testable. - It follows Component based approach.Every angular component is a mainly TypeScript class.Where HTML and CSS files are its extra attachments. Component class : handles data and functionality. HTML template : determines the UI. styles : define the look and feel. - Components define areas of responsibility in the UI, that let you reuse sets of UI functionality. - An Angular application comprises a tree of components, in which each Angular component has a specific purpose and responsibility. - Setting up the Local Environment and Workspace 1) install node.js : 2) node -v , npm -v : Angular requires Node.js version 10.9.0 or later. 2) npm install -g @angular/cli : Install Angular CLI 3) ng version : To check installed Angular CLI version 4) ng new my-app : Create a workspace and initial application 5) cd my-app , ng serve / npm start : Run the application (http://localhost:4200/) - Project Structure : my-angular-app node_modules package.json // contains dependencies and dev dependencies src index.html main.ts // enty point to bootstrap App module and set app env styles.css // to add global styles app app.component.ts // root component app.component.html app.component.css app.module.ts // root module custom-componets - ng generate component home : To create and register angular component,you have to provide metadata to your typescript class. @Component Decorator = View (HTML) + Code (Typescript Class : Data & Methods) + CSS metadata @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) - Three ways to specify selectors : 1) selector: 'app-home' && <app-home></app-home> 2) selector: '.app-home' && <div class="app-home"></div> 3) selector: '[app-home]' && <div app-home></div> - Inline template : template : "<div> Hello </div>" OR template :`<div> Hello </div>` (for multiple lines) - Inline styles : styles : [`div { color : red}`] - Angular lifecycle : * component instance has a lifecycle that starts when Angular instantiates the component class and renders the component view along with its child views. * Lifecycle continues with change detection, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed. * The lifecycle ends when Angular destroys the component instance and removes its rendered template from the DOM. * Directives have a similar lifecycle, as Angular creates, updates, and destroys instances in the course of execution. * You can respond to events in the lifecycle of a component or directive by implementing one or more of the lifecycle hook interfaces. * Lifecycle event sequence : * After your application instantiates a component or directive by calling its constructor, Angular calls the hook methods you have implemented at the appropriate point in the lifecycle of that instance. 1) ngOnChanges() : * Respond when Angular sets or resets data-bound input properties ("attribute" of component selector) * The method receives a SimpleChanges object of current and previous property values. * It will be Called before ngOnInit() (if the component has bound inputs) and whenever one or more data-bound input properties change. 2) ngOnInit() : * Initialize the directive or component after Angular first displays the data-bound properties and sets the directive or component's input properties. 3) ngDoCheck() : * Detect and act upon changes that Angular can't or won't detect on its own. * Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on the first run. 4) ngAfterContentInit() : * Respond after Angular projects external content into the component's view, or into the view that a directive is in. * Called once after the first ngDoCheck() 5) ngAfterContentChecked() : * Respond after Angular checks the content projected into the directive or component. * Called after ngAfterContentInit() and every subsequent ngDoCheck() 6) ngAfterViewInit() : * Respond after Angular initializes the component's views and child views, or the view that contains the directive. * Called once after the first ngAfterContentChecked() 7) ngAfterViewChecked() : * Respond after Angular checks the component's views and child views, or the view that contains the directive. * Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked() 8) ngOnDestroy() : * Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks. * Called immediately before Angular destroys the directive or component. - Template interpolation : * It is used to bind data from class (ts) to template (html). e.g {{ userName }} , {{ "Welcome " + userName }} , {{ getFullName() }} , {{ count + 1 }} , {{ userName.length }} , {{ userName.toUpperCase() }} * Interpolation can not be used for assignment. e.g {{ name = "Vishal" }} * You can not use global javascript variables direclty inside interpolation. e.g {{ window.location.href }} - Property binding / Data binding : (Component Class -> HTML Template) * Attribute and Properties are not the same. Attributes are defined by HTML. However, Properties are defined by DOM (Document Object Model) * Attributes initialize DOM properties and then they are done. Attributes value can not change once they are initialized. * Properties value however can change. * Using property binding in angular, we can bind value to property of DOM element. e.g <input type="text" [id]="myId" > or <input type="text" bind-id="myId" > * The same we can bind with interpolation. e.g <input type="text" id="{{myId}}" > However, interpolation only works with string value (limitation) e.g <input type="text" disabled="{{isDisabled}}" > // will not work * Interpolation {{ }} lets you render the property value as text; property binding [ ] lets you use the property value in a template expression. * Data binding (Property binding) in Angular refers to binding the data in the component instance to the HTML template.Any changes to the data automatically get updated in the view. * One way databinding : <input type="text" [value]="userName" > or <input type="text" [ngModel]="userName" > or <app-address-card [user]="userFromAppComp" /> - CSS Class binding : 1) Class binding : <div [class]="succClassFromComp"></div> (Without class binding : <div class="text-success"></div> ) 2) Conditionally apply single class : <div [class.text-danger]="hasError"></div> (text-danger class will be applied if hasError comp property is true) 3) Conditionally apply multiple class : <div [ngClass]="cssClassObj"></div> , cssClassObj = {text-success : !this.hasError , text-special : this.hasSpecial } - CSS Style binding : used to bind inline style to html element 1) <div [style.color]="'red'"></div> OR <div [style.color]="colorFromComp"></div> 2) <div [style.color]="hasError ? 'red' : 'green'"></div> 3) <div [ngStyle]="styleObjFromComp"></div> , styleObjFromComp = {color : "red" , fontStyle : "italic" } - If you will add style details in component's css file. It will be applied on that component only.The [property] selector is used in CSS to style elements that have that particular property. e.g <div property></div> or <div _ngcontent-c1></div> by which angualr handle styling to be apply to that particular component's elelent only - To add global styling, add it into src/style.css file. - Event binding : ( HTML template -> Component Class ) 1) <button (click)="eventHandler($event)" >Click</button> (in html) // $event optional eventHandler(event: any) { // method logic } (in component ts file) 2) <button (click)="greetMessage=''">Clear</button> // without Event Handler - Template reference variable : * It is used to access DOM elements and its properties. <input #myInput type="text"> <button (click)="logMessage(myInput.value)" > Log </button> - Two way databinding : (Property + Event Binding) * <input type="text" [(ngModel)]="userName" > // Syntax : [(ngModel)] or <app-address-card [(user)]="userFromAppComp" /> * To use ngModel directive for databinding, You have to import "FormsModule" in app.module.ts file. - Structural directives : * Use to add/remove HTML elements. 1) *ngFor directive is used to iterator over array e.g <div *ngFor="let phoneNo of user.phone; index as i; first as f; last as l; odd as o; even as e"> {{ i + 1 }} {{ phoneNo }} </div> 2) *ngIf directive is used for conditional check e.g <div *ngIf="user.phone.length > 0; else elseBlock"> User Details </div> OR <div *ngIf="displayName; then thenBlock; else elseBlock;"></div> <ng-template #elseBlock> <h2>Else block content<h2> </ng-template> 3) ngSwitch : <div [ngSwitch]="color"> <div *ngSwitchCase="'red'"> Red Color </div> <div *ngSwitchCase="'blue'"> Blue Color </div> <div *ngSwitchCaseDefault> Select again </div> </div> - Component Interaction : 1) @Input decorator : * @Input is used to bind "attribute" of component selector. It can be used to pass data from parent comp to child comp. e.g <app-address-card userName="Vishal Gana"></app-address-card> (in parent comp html file) OR <app-address-card [userName]="userNameFromParentComp"></app-address-card> @Input('userName') userName: string; (in child comp ts file). * This userName value can't be used inside constructor of ts class. as Angular will populate component's attrribute value after object creation of component. However we can use it inside ngOnInit life cycle method. 2) @Output decorator : * @Output is used to notify parent from child. e.g 1) Inside child : @Output() childEvent = new EventEmitter(); onChildCompBtnClick(){ this.childEvent.emit(this.childData); // child comp logic } <button (click)="onChildCompBtnClick()" >Child Click </button> OR <button (click)="childEvent.emit(childData)" >Child Click </button> 2) Inside parent : <child-comp (childEvent)="onEventFromChildToParent($event)" ></child-comp> onEventFromChildToParent(name: string){ // parent comp logic } - Built in pipe : 1) <h2> {{ name | lowercase }} </h2> 2) <h2> {{ name | upperrcase }} </h2> 3) <h2> {{ name | titlecase }} </h2> 4) <h2> {{ name | slice:3 }} </h2> OR <h2> {{ name | slice:3:7 }} </h2> 5) <h2> {{ employee | json }} </h2> 6) <h2> {{ 5.67 | number:'2.2-3' }} </h2> // 05.67 7) <h2> {{ 0.25 | percent }} </h2> // 25% 8) <h2> {{ 0.25 | currency }} </h2> // $0.25 OR <h2> {{ 0.25 | currency:'EUR' }} </h2> OR <h2> {{ 0.25 | currency:'EUR':'code' }} </h2> 9) <h2> {{ date | date:'short' }} </h2> OR <h2> {{ date | date:'shortDate' }} </h2> OR <h2> {{ date | date:'shortTime' }} </h2> ng g pipe truncate : to create custom pipe - Angular module : * ng generate module view : to create new module * ng generate component view/view-component : to create new component in specific module (Here it is view module) * If you are creating new module and you want to allow its usage in other module also than you have to export it's component e.g exports: [ViewModuleComponent] and in dependent module you have to import that module e.g imports : [ViewModule] - Angular services : * Angluar service is a class with a specific purpose. It can be used to share data, implement application logic, external interaction. * ng generate service test : to create new service * @Component() : Angular component, @NgModule() : Angular module, @Injectable() : Angular service * To use service in your module,Befeor Angular 6, You have to explicitly decalre it inside module.ts file. e.g providers: [TestService]. Here, We don't have to declare it for it's child modules also.(global service space). After Angular 6 , you can declare it using @Injectable({ providedIn : 'root' }) annotation * The providers property of @NgModule lets you specify the services or providers that you want to declare for your Angular App. * To use service inside component, You have to define it inside constructor.Angular will automatically inject Service dependency. e.g constructor(private testService: TestService) { } * @Injectable() in service is must required if our service has dependency on another service. * Built in HttpClient service : * To use built in HttpClient service, you have to import HttpClientModule. * Observables : A sequence of items that arrives aynchronously over time. HTTP call - sinlge Item (HTTP response) 1) EmployeeService : getEmployees() : Observable<IEmployee[]> { return this.http.get<IEmployee[]>(this.url) .pipe(catchError(this.errorHandler)); } errorHandler(error : HttpErrorResponse){ return throwError(error.message || "Server Error"); } 2) EmployeeDetails comp : employees: Employee[] = []; ngOnInit(){ this.employeeService.getEmployees() .subscribe( (data: any) => this.employees = data , error => this.errorMsg = error ); } 3) Employee model : constructor(public id: number, public name: string, public age: number) {} - ng new routing-demo --routing : to create new project with routing support - URL based routing + Component based routing 1) Define your route URLs 2) Create Angular components for each view (one for each route) 3) Configure Angular to map route URLs to components - // Routing config in app-routing.module.ts const routes: Route[] = [ { path: '', redirectTo: '/home' , pathMatch: 'full' }, // for default routing OR { path: '', component: HomeComponent }, { path: 'home', component: HomeComponent }, { path: 'settings', component: SettingsComponent, children : [ // child route. add <router-outlet></router-outlet> in settings component's html file also { path: '', redirectTo: 'profile' , pathMatch: 'full' }, { path: 'profile', component: SettingsProfileComponent }, { path: 'contacts', component: SettingsContactsComponent }, { path: 'contacts/:contactId', component: ContactComponent }, { path: '**', component : PageNotFoundComponent } // for error handling ] }, { path: '**', component : PageNotFoundComponent } // for error handling ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } - In html file you have to add <router-outlet></router-outlet> to render routing view - for routing link you can use : <a *ngFor="let route of routes" [routerLink]="route.url"> {{ route.linkName }} </a> OR <a routerLink="home" routerLinkActive="activeClass">Home</a> // hardcoded value OR <a [routerLink]="homeLink">Home</a> // value from ts file OR <a [routerLink]="['contacts', contactId">Settings</a> - Router service : to navigate from code with router parameter e.g { path: 'departments/:id', component: DeptDetailComponent } onDeptSelect(dept){ // Inside dept list comp this.router.navigate(["/departments",dept.id]); // provide Router service dependency inside constructor } - ActivatedRoute service : contains information about the route, its parameters, and additional data associated with the route. ngOnInit() { // Inside dept detail comp this.activatedRoute.paramMap.sbscribe((params : ParamMap) => { let id = params.get("id"); this.deptId = id; }); } - ng build is used to build and package angular app into dist folder which can later be hosted using http-server. Here we don't need ng serve to start the app. 1) ng build or ng build --prod (AOT:Ahead of time compilation) 2) npm install http-server -g (one time) 3) http-server dist/my-app/ - Angular Forms : 1) Tempalte driven forms : * Most of the code and logic reside in the componet template (html) . It is similar to Angular JS forms. * It uses two way databinding with ngModel. * Have to import FormsModule. * Automatically tracks the form and form elements state and validity. * Unit testing is a challenge. * Redability decreases with complex forms and validation. Hence, suitable for simple scenarios. * in html Directive : ngForm, ngModel, ngModelGroup (to create sub group within the form) , ngSubmit * When ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions. * Track control state and validity : State Class if true Class if false Property if true Property if false The control has been visited. ng-touched ng-untouched touched untouched The control's value has changed. ng-dirty ng-pristine dirty pristine The control's value is valid. ng-valid ng-invalid valid invalid 2) Reative forms (Model driven) : * Most of the code and logic resides in the component class (ts file). * No two way binding. * have to import ReactiveFormsModule. * Well suited for complex scenarios. * Provide support for Dynamic form fields. * Can do custom and Dynamic/Conditional validation. To add dynamic validation, formGroup refrence shoud be created inside ngOnInit method. * Unit testing is possible. * in ts , class : FormGroup, FormControl OR using FormBuilder service, Validators, AbstractControl (for custom validator), FormArray (to maintain dynamic list of control) * in html, Directive : formGroup , formControlName, formGroupName (to create sub group within the form) , formArrayName * In cross field custom validator function input 'control' parameter doesn't refer to individual form control instead it refers to form group refrence. - Tempalte Driven Forms Example : <div class="container-fluid mb-5"> <h1>User Enrollment Form</h1> <form #userFormRef="ngForm" *ngIf="!isUserFormSubmitted" (ngSubmit)="onUserFormSubmit()" novalidate> <div class="form-group mb-3"> <input type="text" name="userName" #userNameRef="ngModel" [(ngModel)]="user.userName" [class.is-invalid]="userNameRef.touched && userNameRef.invalid" class="form-control" placeholder="Name" required> <small class="text-danger" [class.d-none]="userNameRef.untouched || userNameRef.valid">User Name is required</small> </div> <div class="form-group mb-3"> <input type="number" name="phone" #phoneRef="ngModel" [(ngModel)]="user.phone" [class.is-invalid]="phoneRef.touched && phoneRef.invalid" class="form-control" pattern="^[1-9]{1}[0-9]{9}$" placeholder="Phone" required> <div *ngIf="phoneRef.errors && (phoneRef.touched || phoneRef.invalid)"> <small class="text-danger" *ngIf="phoneRef.errors.required">Phone number is required</small> <small class="text-danger" *ngIf="phoneRef.errors.pattern">Phone number must be 10 digits</small> </div> </div> <div class="form-group mb-3"> <select name="topic" #topicRef="ngModel" [(ngModel)]="user.topic" [class.is-invalid]="topicRef.touched && isTopicHasErr" (blur)="validateTopic(topicRef.value)" (change)="validateTopic(topicRef.value)" class="form-select"> <option value="default">I am interested in</option> <option *ngFor="let topic of topics">{{topic}}</option> </select> <small class="text-danger" [class.d-none]="topicRef.untouched || !isTopicHasErr">Please select a topic</small> </div> <div ngModelGroup="address"> <div class="form-group mb-3"> <input type="text" class="form-control" name="city" [(ngModel)]="user.address.city" placeholder="City"> </div> <div class="form-group mb-3"> <input type="text" class="form-control" name="postalCode" [(ngModel)]="user.address.postalCode" placeholder="Postal Code"> </div> </div> <button type="submit" [disabled]="userFormRef.form.invalid || isTopicHasErr" class="btn btn-primary">Submit</button> </form> <div class="alert alert-success" *ngIf="successMsg"> {{successMsg}} </div> <div class="alert alert-danger" *ngIf="errorMsg"> {{errorMsg}} </div> </div - Reactive Forms Example : <div class="container-fluid"> <h2>User Registration Form</h2> <form [formGroup]="registratrionForm" *ngIf="!isFormSubmitted" (ngSubmit)="onRegistrationFormSubmit()"> <div class="form-group mb-3"> <input formControlName="userName" [class.is-invalid]="userNameRef.invalid && userNameRef.touched" type="text" class="form-control" placeholder="Username"> <div *ngIf="userNameRef.invalid && userNameRef.touched"> <small class="text-danger" *ngIf="userNameRef.errors?.required">Username is required</small> <small class="text-danger" *ngIf="userNameRef.errors?.minlength">Username must be atleast 3 characters</small> <small class="text-danger" *ngIf="userNameRef.errors?.forbiddenName">{{userNameRef.errors?.forbiddenName.value}} Username not allowed</small> <!-- using custom validator --> </div> </div> <div class="form-group mb-3"> <button (click)="addAlternateEmail()" class="btn btn-secondary btn-sm m-2" type="button">Add Email</button> <input formControlName="email" type="email" [class.is-invalid]="emailRef.invalid && emailRef.touched" class="form-control" placeholder="Email"> <small class="text-danger" [class.d-none]="emailRef.valid || emailRef.untouched">Email is required</small> <div formArrayName="alternateEmails" *ngFor="let email of alternateEmailsRef.controls; let i=index"> <!-- Dynamic form field --> <input [formControlName]="i" type="email" class="form-control my-1" placeholder="Alternate Email"> </div> </div> <div class="form-check mb-3"> <input formControlName="subscribe" type="checkbox" class="form-check-input"> <label class="form-check-label">Send me promotional offers</label> </div> <div class="form-group mb-3"> <input formControlName="password" type="password" [class.is-invalid]="registratrionForm.get('password').invalid && registratrionForm.get('password').touched" class="form-control" placeholder="Password"> <small class="text-danger" [class.d-none]="registratrionForm.get('password').valid || registratrionForm.get('password').untouched">Password is required</small> </div> <div class="form-group mb-3"> <input formControlName="confirmPassword" type="password" [class.is-invalid]="registratrionForm.errors?.passwordMismatch" class="form-control" placeholder="Confirm Password"> <small class="text-danger" *ngIf="registratrionForm.errors?.passwordMismatch">Password Mismatch</small> <!-- using cross field custom validator --> </div> <div formGroupName="address"> <div class="form-group mb-3"> <input formControlName="city" type="text" class="form-control" placeholder="City"> </div> <div class="form-group mb-3"> <input formControlName="postalCode" type="text" class="form-control" placeholder="Postal Code"> </div> </div> <button [disabled]="registratrionForm.invalid" class="btn btn-primary" type="submit">Register</button> </form> <div class="alert alert-success" *ngIf="successMsg"> {{successMsg}} </div> <div class="alert alert-danger" *ngIf="errorMsg"> {{errorMsg}} </div> </div> export class ReactiveFormsComponent implements OnInit { registratrionForm: any; isFormSubmitted = false; successMsg: string = ""; errorMsg: string = ""; constructor( private _formBuilder: FormBuilder, private _userRegistrationService: UserRegistrationService ) {} ngOnInit(): void { this.registratrionForm = this._formBuilder.group( { userName: ["Default Value", [Validators.required, Validators.minLength(3), forbiddenNameValidator] ], email: [""], subscribe: [false], password: ["", Validators.required], confirmPassword: [""], address: this._formBuilder.group({ city: [""], state: [""], postalCode: [""] }), alternateEmails: this._formBuilder.array([]) }, { validator: passwordValidator } // cross field validation ); this.registratrionForm.get("subscribe") // Dynamic/Conditional validation .valueChanges.subscribe((checkedValue: boolean) => { const emailRef: FormControl = this.registratrionForm.get("email"); if (checkedValue) { emailRef.setValidators(Validators.required); } else { emailRef.clearValidators(); } emailRef.updateValueAndValidity(); }); } loadAPIData() { //this.registratrionForm.setValue({ // 1) to set values to all form controls this.registratrionForm.patchValue({ // 2) to set values to selective form controls userName: "Vihan", email: "[email protected]", }); } get userNameRef() { return this.registratrionForm.get("userName"); } get alternateEmailsRef() { return this.registratrionForm.get("alternateEmails") as FormArray; } addAlternateEmail() { this.alternateEmailsRef.push(this._formBuilder.control("")); } onRegistrationFormSubmit() { console.log(this.registratrionForm.value); } } - Angular Authentication : - Angular Material : * UI component library. * Provides us with components to build awesome user interfaces in quick time. * Implementation of Google's material design specification. * To add Angular Material into project : ng add @angular/material * Pending from sidenav - How can we make multiple projects share node_modules directory ? 1) Main directory (e.g Angular_Projects) should look like this Angular_Projects node_modules Project1 Project2 2) Open the file Project1/angular.json and change the $schema value to "./../node_modules/@angular/cli/lib/config/schema.json" 3) Create empty node_modules folder inside each project (e.g Project1) directory - How to update angular-cli ? 1) For Global package npm uninstall -g angular-cli npm cache clean npm install -g angular-cli@latest 2) Local project package rmdir /s /q node_modules dist tmp npm install --save-dev angular-cli@latest npm install ng init - express-server for api : * create folder e.g express-server * npm init --yes (to create package.json file) * npm install --save express body-parser cors * create server.js file and write below code : const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const port = 3000; const app = express(); app.use(bodyParser.json()); app.use(cors()); app.get("/", (req, res) => { res.send("Hello from express server!"); }); app.listen(port, () => { console.log(`Express server running on http://localhost:${port}`); }); * node server (to start express server) - setInterval is a javascript API that lets you run a function at regular time intervals. setInterval( () => { console.log("Hello") } , 2000); - Commands : node -v and npm -value // to verify node and npm installed or not npm install -g @angular/cli // To install angular CLI globally ng version // to check the installed angular CLI version ng new first-project // to create new project ng new second-proj --style=scss // to create new project with scss CSS format ng serve // to start angualr application on http://localhost:4200/ ng serve --port 4201 // to start angualr application on diffrent port ng serve --configuration production // to start angualr application with prod mode ng generate component hello-world // to create new component ng g c hello-word // to create new component (short format) ng g c employee -it -is // to create comp with inline template and css ng g c employee --skipTests // to skip test file ng generate module view // to create new module ng g c view/view-component // to create new component in specific module (Here it is view module) ng generate service test // to create new service ng build or ng build --prod // to build and package angualr app in one folder (dist) which can be deploy independently (without angular CLI) npm install http-server -g // to install http-server which can be used to host local directory. http-server dist/first-project/ // to run http-server to host application ng new routing-demo --routing // to create new project with routing support ng g class blog-post // to create new class ng g pipe truncate // to create new pipe ng g interceptor auth // to create new interceptor ng test // to execute test cases ng test --code-coverage // to execute test cases with code coverage ng add @angular/material // to add angular material into project npm i --save express body-parser cors // to install express (web server) and body-parser (Middleware to handle form data such as User registration/login) ------------------------------------------------------------------------------------ * Angular interview questions : https://www.interviewbit.com/angular-interview-questions/ https://intellipaat.com/blog/interview-question/angular-interview-questions/ https://github.com/sudheerj/angular-interview-questions#what-is-angular-framework
// // Hike.swift // TrailTales // // Created by Raphaël Payet on 11/09/2023. // import SwiftUI import RealmSwift final class Hike: Object, ObjectKeyIdentifiable { // MARK: - Properties @Persisted(primaryKey: true) var _id: ObjectId @Persisted var ownerId = "" @Persisted var name: String = "" @Persisted var location: String = "" @Persisted var distance: String = "" @Persisted var difficulty: HikeDifficulty = .medium @Persisted var coverPhoto: Data? // TODO: Add multiple photo support // @Persisted var photos = List<Data>() @Persisted var durationInS: Double = 0.0 @Persisted var date: Date? // MARK: - Initialization convenience init(name: String, location: String, distance: String, difficulty: HikeDifficulty, ownerId: String, durationInS: Double, date: Date? = nil) { self.init() self.name = name self.location = location self.distance = distance self.difficulty = difficulty self.ownerId = ownerId self.durationInS = durationInS self.date = date } } enum HikeDifficulty: String, PersistableEnum, Equatable, CaseIterable { case veryEasy, easy, medium, hard, veryHard var label: String { switch self { case .veryEasy: return NSLocalizedString("Very Easy", comment: "Very Easy Difficulty") case .easy: return NSLocalizedString("Easy", comment: "Easy Difficulty") case .medium: return NSLocalizedString("Medium", comment: "Medium Difficulty") case .hard: return NSLocalizedString("Hard", comment: "Hard Difficulty") case .veryHard: return NSLocalizedString("Very Hard", comment: "Very Hard Difficulty") } } var badgeColor: Color { switch self { case .veryEasy: return .greenish case .easy: return .blueish case .medium: return .yellowish case .hard: return .brownish case .veryHard: return .red } } } /// Represents a collection of hikes. final class HikesGroup: Object, ObjectKeyIdentifiable { /// The unique ID of the HikesGroup. `primaryKey: true` declares the /// _id member as the primary key to the realm. @Persisted(primaryKey: true) var _id: ObjectId /// The collection of Items in this group. @Persisted var items = RealmSwift.List<HikesGroup>() /// Store the user.id as the ownerId so you can query for the user's objects with Flexible Sync @Persisted var ownerId = "" }
import { Grid, Typography } from "@mui/material"; import Property from "./Property"; import { propertyList } from "../../assets/propertyList"; import { Grow } from "@mui/material"; import { CurrentLocationProvider, useCurrentLocation } from "../../context/useCurrentLocation"; interface PropertyListType { guestNumber: number; } const PropertyList = ({ guestNumber}: PropertyListType) => { const {currentLocation} = useCurrentLocation() const filteredProperties = propertyList.filter( (item) => item.bedCount >= guestNumber && currentLocation === `${item.city}, ${item.state}` ); console.log(currentLocation) return ( <Grid container spacing={2}> {filteredProperties.length === 0 ? ( <Typography sx={{p: 2}}>No properties found</Typography> ) : ( filteredProperties.map((item, index) => ( <Grow in timeout={1000 + index * 700}> <Grid item xs={12} sm={4} key={item.id}> <Property src={item.src} name={item.name} bedCount={item.bedCount} roomType={item.roomType} rating={item.rating} superHost={item.superHost} /> </Grid> </Grow> )) )} </Grid> ); }; export default PropertyList;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>nav bar</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <style> img{ width: 400px; height: 350px; } </style> </head> <body> <nav class="navbar navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand">Navbar</a> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </nav> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar scroll</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarScroll"> <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Courses</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About me</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarScrollingDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Link </a> <ul class="dropdown-menu" aria-labelledby="navbarScrollingDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled">Link</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Pesquisa here" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> <div class="carousel-inner"> <div class="carousel-item active"> <img src="nature.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="menu.jpg" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="saudavel.jpg" class="d-block w-100" alt="..."> </div> </div> </div> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Launch static backdrop modal </button> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Understood</button> </div> </div> </div> </div> <button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="Popover title" data-bs-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button> <script> var popover = new bootstrap.Popover(document.querySelector('.example-popover'), { container: 'body' }) </script> <div class="toast-container"> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img src="..." class="rounded me-2" alt="..."> <strong class="me-auto">Bootstrap</strong> <small class="text-muted">just now</small> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> See? Just like this. </div> </div> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img src="..." class="rounded me-2" alt="..."> <strong class="me-auto">Bootstrap</strong> <small class="text-muted">2 seconds ago</small> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel"></div> <div class="toast-body"> tomorrow i am here practice about us!!! <h3></h3> Heads up, toasts will stack automatically </div> </div> </div> </body> </html>
import { useEffect, useState } from "react"; import { useAppDispatch } from "../.."; import { TTodo, complete, editTodo } from "../../store/todosSlice"; import styles from "./todo-item.module.css"; const TodoItem: React.FunctionComponent<TTodo> = (item: TTodo) => { const dispatch = useAppDispatch(); const [checkedTodo, setCheckedTodo] = useState<boolean>(false); const hadleCheckedChange = (item: TTodo) => { dispatch(complete(item)); }; const handleChange = (event: React.ChangeEvent<HTMLInputElement>, item: TTodo) => { if (item.done === false) { dispatch(editTodo({ ...item, text: event.target.value })); } }; useEffect(() => { if(item.done === true) { setCheckedTodo(true) } if(item.done === false) { setCheckedTodo(false) } },[item.done]) return ( <li className={styles.list__item} key={item.id}> <input type="checkbox" data-cy='todo-checkbox' name='checkbox' id={item.id} onChange={() => hadleCheckedChange(item)} checked={checkedTodo}/> <label htmlFor={item.id} className={styles.list__item__check}> <input type="text" value={item.text} className={!item.done ? styles.list__item__text : `${styles.list__item__text} ${styles.list__item__text_done}`} onChange={(e) => handleChange(e, item)} /> </label> </li> ); }; export default TodoItem;
import { Link, useNavigate } from "react-router-dom"; import { useEffect, useState } from "react"; import { useUsers } from "../context/UserContext"; import { useAuth } from "../context/AuthContext"; function Users() { const { getUsers, users, deleteUser } = useUsers(); const { user, logout } = useAuth(); const navigate = useNavigate(); const [currentPage, setCurrentPage] = useState(1); // Estado para almacenar la página actual const [searchTerm, setSearchTerm] = useState(""); // Estado para almacenar el término de búsqueda const [selectedAgency, setSelectedAgency] = useState(""); // Estado para almacenar la agencia seleccionada const [selectedStatus, setSelectedStatus] = useState(""); // Estado para almacenar el estado seleccionado const [selectedRole, setSelectedRole] = useState(""); // Estado para almacenar el rol seleccionado const usersPerPage = 10; // Número de usuarios por página useEffect(() => { getUsers(); }, []); const handleDeleteClick = (userId) => { const confirmDelete = window.confirm( "¿Estás seguro de que quieres eliminar este usuario?" ); if (confirmDelete) { if (user.id === userId) { deleteUser(userId); setTimeout(() => { navigate("/"); logout(); }, 1000); } deleteUser(userId); } }; // Filtrar usuarios según el término de búsqueda, agencia, estado y rol seleccionados const filteredUsers = users.filter((user) => user.username.toLowerCase().includes(searchTerm.toLowerCase()) && (!selectedAgency || user.agencia.toLowerCase().includes(selectedAgency.toLowerCase())) && (!selectedStatus || user.estado === selectedStatus) && (!selectedRole || user.rol.toLowerCase().includes(selectedRole.toLowerCase())) ); // Calcular el total de páginas para los usuarios filtrados const totalPages = Math.ceil(filteredUsers.length / usersPerPage); // Lógica para calcular los índices de inicio y fin de los usuarios en la página actual const indexOfLastUser = currentPage * usersPerPage; const indexOfFirstUser = indexOfLastUser - usersPerPage; const currentUsers = filteredUsers.slice(indexOfFirstUser, indexOfLastUser); // Obtener la lista de agencias existentes para la selección const agencies = [...new Set(users.map(user => user.agencia))]; // Obtener la lista de roles existentes para la selección const roles = [...new Set(users.map(user => user.rol))]; return ( <div className="flex justify-center p-4 "> <div className="w-full md:w-3/4 lg:w-4/5 xl:w-3/4 bg-white rounded-lg shadow-md "> <h1 className="text-center rounded-lg bg-blue-900 font-bold text-white py-2 relative" style={{ fontSize: "30px" }} > Usuarios <Link to="/register" className="bg-blue-400 text-white hover:bg-blue-500 px-3 rounded-full absolute top-1/2 transform -translate-y-1/2 right-4 flex items-center justify-center" style={{ width: "36px", height: "36px" }} > + </Link> </h1> {/* Campos de búsqueda */} <div className="p-4 flex justify-between"> <input type="text" placeholder="Buscar por username..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-1/3 px-3 py-2 border border-gray-300 focus:outline-none focus:border-blue-500 rounded-lg mr-2" /> <select value={selectedAgency} onChange={(e) => setSelectedAgency(e.target.value)} className="w-1/3 px-3 py-2 border border-gray-300 focus:outline-none focus:border-blue-500 rounded-lg mr-2" > <option value="">Ninguna Agencia...</option> {agencies.map((agency, index) => ( <option key={index} value={agency}> {agency} </option> ))} </select> <select value={selectedRole} onChange={(e) => setSelectedRole(e.target.value)} className="w-1/3 px-3 py-2 border border-gray-300 focus:outline-none focus:border-blue-500 rounded-lg" > <option value="">Ningun Rol...</option> {roles.map((role, index) => ( <option key={index} value={role}> {role} </option> ))} </select> </div> <div className="my-2 overflow-x-auto rounded-lg"> <table className="w-full border-collapse rounded-lg"> {/* Encabezado de la tabla */} <thead> <tr className="bg-blue-900 text-white"> <th className="py-2 text-center">Username</th> <th className="py-2 text-center">Correo electronico</th> <th className="py-2 text-center">Rol</th> <th className="py-2 text-center">Agencia</th> <th className="py-2 text-center">Estado</th> <th className="py-2 text-center">Acciones</th> </tr> </thead> {/* Cuerpo de la tabla */} <tbody> {currentUsers.map((place) => ( <tr key={place._id}> <td className="text-center border border-blue-100"> {place.username} </td> <td className="text-center border border-blue-100"> {place.email} </td> <td className="text-center border border-blue-100"> {place.rol} </td> <td className="text-center border border-blue-100"> {place.agencia} </td> <td className="text-center border border-blue-100"> {place.estado === true ? "Activo" : "Desactivo"} </td> <td className="flex justify-center items-center border border-blue-100"> <Link to={`/users/${place._id}`} className="bg-blue-500 font-bold hover:bg-blue-400 text-white py-1 px-2 rounded-lg mr-2" > Editar </Link> <button className="bg-red-500 font-bold hover:bg-red-400 text-white py-1 px-2 rounded-lg" onClick={() => handleDeleteClick(place._id)} > Eliminar </button> </td> </tr> ))} </tbody> </table> {/* Controles de paginación */} <div className="flex justify-center mt-4"> {/* Botón para ir a la página anterior */} {currentPage !== 1 && ( <button className="bg-blue-500 font-bold hover:bg-blue-400 text-white py-2 px-4 rounded-lg mr-2" onClick={() => setCurrentPage(currentPage - 1)} > Anterior </button> )} {/* Botón para ir a la página siguiente */} {indexOfLastUser < filteredUsers.length && ( <button className="bg-blue-500 font-bold hover:bg-blue-400 text-white py-2 px-4 rounded-lg" onClick={() => setCurrentPage(currentPage + 1)} > Siguiente </button> )} </div> {/* Mostrar el total de páginas */} <p className="text-center text-sm text-gray-500 mt-2"> Página {currentPage} de {totalPages} </p> </div> </div> </div> ); } export default Users;
// // UploadVideoEntryViewModelUnitTests.swift // JournalBuddyUnitTests // // Created by Julian Worden on 8/25/23. // import AVFoundation import Combine @testable import JournalBuddy import Photos import XCTest @MainActor final class UploadVideoEntryViewModelUnitTests: XCTestCase { var sut: UploadVideoEntryViewModel! var cancellables = Set<AnyCancellable>() var videoEntryIsSavingExpectation: XCTestExpectation! var videoEntryWasSavedExpectation: XCTestExpectation! var videoEntryIsUploadingExpectation: XCTestExpectation! var videoEntryWasUploadedExpectation: XCTestExpectation! var videoEntryWasCreatedNotificationExpectation: XCTNSNotificationExpectation! override func setUp() { videoEntryIsSavingExpectation = XCTestExpectation( description: "viewState updated to .videoEntryIsSavingToDevice." ) videoEntryWasSavedExpectation = XCTestExpectation( description: "viewState updated to .videoEntryWasSavedToDevice." ) videoEntryIsUploadingExpectation = XCTestExpectation( description: "viewState updated to .videoEntryIsUploading." ) videoEntryWasUploadedExpectation = XCTestExpectation( description: "viewState updated to .videoEntryWasUploaded." ) videoEntryWasCreatedNotificationExpectation = XCTNSNotificationExpectation( name: .videoEntryWasCreated ) } override func tearDown() { sut = nil cancellables = Set<AnyCancellable>() videoEntryIsSavingExpectation = nil videoEntryWasSavedExpectation = nil videoEntryIsUploadingExpectation = nil videoEntryWasUploadedExpectation = nil videoEntryWasCreatedNotificationExpectation = nil } func test_OnInit_DefaultValuesAreCorrect() { initializeSUTWith(databaseServiceError: nil, authServiceError: nil) XCTAssertEqual(sut.viewState, .displayingView) XCTAssertEqual(sut.recordedVideoURL, Bundle.main.url(forResource: "TestVideo", withExtension: "mov")!) XCTAssertFalse(sut.saveVideoToDevice) XCTAssertTrue(sut.videoWasSelectedFromLibrary) } // Consider adding commented code into a new VideoPlayerViewModel in the future // func test_VideoPlayerCurrentItemLengthInSeconds_ReturnsExpectedValue() { // initializeSUTWith(databaseServiceError: nil, authServiceError: nil) // let expectation = XCTestExpectation(description: "The video's length was retrieved") // // waitForVideoPlayerReadyToPlayStatus { // if self.sut.videoPlayerCurrentItemLengthInSeconds == 2 { // expectation.fulfill() // } // } // // wait(for: [expectation], timeout: 3) // } // func test_OnVideoPlayerPlayButtonTapped_VideoPlayerStartsPlaying() { // initializeSUTWith(databaseServiceError: nil, authServiceError: nil) // let expectation = XCTestExpectation(description: "Video player is playing.") // sut.player // .publisher(for: \.timeControlStatus) // .sink { timeControlStatus in // if timeControlStatus == .playing { // expectation.fulfill() // } // } // .store(in: &cancellables) // // waitForVideoPlayerReadyToPlayStatus { // self.sut.videoPlayerPlayButtonTapped() // } // // wait(for: [expectation], timeout: 3) // } // // func test_OnVideoPlayerPauseButtonTapped_VideoPlayerPauses() { // initializeSUTWith(databaseServiceError: nil, authServiceError: nil) // let expectation = XCTestExpectation(description: "Video player is paused.") // // waitForVideoPlayerReadyToPlayStatus { // self.sut.videoPlayer.play() // self.sut.videoPlayerPauseButtonTapped() // XCTAssertEqual(self.sut.videoPlayer.timeControlStatus, .paused) // expectation.fulfill() // } // // wait(for: [expectation], timeout: 3) // } // // func test_OnVideoPlayerRestartButtonTapped_VideoPlayerRestartsAndPlays() { // initializeSUTWith(databaseServiceError: nil, authServiceError: nil) // let expectation = XCTestExpectation(description: "Video player restarted and played successfully.") // // waitForVideoPlayerReadyToPlayStatus { // self.sut.videoPlayer.play() // DispatchQueue.main.asyncAfter(deadline: .now() + 5) { // self.sut.videoPlayerRestartButtonTapped() // // DispatchQueue.main.asyncAfter(deadline: .now() + 3) { // XCTAssertEqual( // self.sut.videoPlayer.currentTime().seconds, // 3, // accuracy: 0.5, // "The video player should start over from the very beginning." // ) // XCTAssertEqual( // self.sut.videoPlayer.timeControlStatus, // .playing, // "After restarting the video player should automatically start playing again." // ) // expectation.fulfill() // } // } // } // // wait(for: [expectation], timeout: 10) // } // // func test_OnSeekVideoPlayer_VideoPlayerSeeks() { // initializeSUTWith(databaseServiceError: nil, authServiceError: nil) // let expectation = XCTestExpectation(description: "Video player did seek 5 seconds into the video.") // // waitForVideoPlayerReadyToPlayStatus { // Task { // await self.sut.seekVideoPlayer(to: 5) // // XCTAssertEqual(self.sut.videoPlayer.currentTime().seconds, 5) // expectation.fulfill() // } // } // // wait(for: [expectation], timeout: 3) // } func test_OnUploadButtonTappedWithSaveToDeviceEnabled_SavingAndUploadingCompleteSuccessfully() async { initializeSUTWith(databaseServiceError: nil, authServiceError: nil) sut.saveVideoToDevice = true subscribeToViewStateUpdates() await sut.uploadButtonTapped(photoLibrary: MockPHPhotoLibrary(errorToThrow: nil)) await fulfillment( of: [ videoEntryIsSavingExpectation, videoEntryWasSavedExpectation, videoEntryIsUploadingExpectation, videoEntryWasUploadedExpectation, videoEntryWasCreatedNotificationExpectation ], timeout: 3, enforceOrder: true ) } func test_OnUploadButtonTappedWithSaveToDeviceEnabled_VideoDoesNotStartUploadingWhenSavingErrorIsThrown() async throws { initializeSUTWith(databaseServiceError: nil, authServiceError: nil) sut.saveVideoToDevice = true subscribeToViewStateUpdates() sut.$viewState .sink { viewState in switch viewState { case .videoEntryIsUploading, .videoEntryWasUploaded: XCTFail("An error should have been thrown during saving and uploading shouldn't have started.") default: break } } .store(in: &cancellables) await sut.uploadButtonTapped(photoLibrary: MockPHPhotoLibrary(errorToThrow: TestError.general)) // Give the view model the chance to set uploading-related view states. Test will fail if this happens try await Task.sleep(seconds: 3) XCTAssertEqual(sut.viewState, .error(message: TestError.general.localizedDescription)) } func test_OnUploadButtonTappedWithSaveToDeviceDisabled_SavingToDeviceDoesNotOccurAndUploadingIsSuccessful() async { initializeSUTWith(databaseServiceError: nil, authServiceError: nil) subscribeToViewStateUpdates() sut.$viewState .sink { viewState in switch viewState { case .videoEntryIsSavingToDevice, .videoEntryWasSavedToDevice: XCTFail("The video entry shouldn't be getting saved to the device.") default: break } } .store(in: &cancellables) await sut.uploadButtonTapped(photoLibrary: MockPHPhotoLibrary(errorToThrow: nil)) await fulfillment( of: [ videoEntryIsUploadingExpectation, videoEntryWasUploadedExpectation, videoEntryWasCreatedNotificationExpectation ], timeout: 3, enforceOrder: true ) } func test_OnUploadButtonTapped_ErrorViewStateIsSetWhenUploadingFails() async { initializeSUTWith(databaseServiceError: TestError.general, authServiceError: nil) await sut.uploadButtonTapped() XCTAssertEqual(sut.viewState, .error(message: TestError.general.localizedDescription)) } func initializeSUTWith(databaseServiceError: Error?, authServiceError: Error?) { sut = UploadVideoEntryViewModel( isTesting: true, recordedVideoURL: Bundle.main.url(forResource: "TestVideo", withExtension: "mov")!, videoWasSelectedFromLibrary: true, databaseService: MockDatabaseService(errorToThrow: databaseServiceError), authService: MockAuthService(errorToThrow: authServiceError) ) } func subscribeToViewStateUpdates() { sut.$viewState .sink { viewState in switch viewState { case .videoEntryIsSavingToDevice: self.videoEntryIsSavingExpectation.fulfill() case .videoEntryWasSavedToDevice: self.videoEntryWasSavedExpectation.fulfill() case .videoEntryIsUploading: self.videoEntryIsUploadingExpectation.fulfill() case .videoEntryWasUploaded: self.videoEntryWasUploadedExpectation.fulfill() default: break } } .store(in: &cancellables) } // func waitForVideoPlayerReadyToPlayStatus(completion: @escaping () -> Void) { // sut.videoPlayer // .publisher(for: \.currentItem?.status) // .sink { status in // if status == .readyToPlay { // completion() // } // } // .store(in: &cancellables) // } }
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Post, Group from .forms import PostForm def index(request): latest = Post.objects.all()[:11] return render(request, 'index.html', {'posts': latest}) def group_posts(request, slug): group = get_object_or_404(Group, slug=slug) posts = group.posts.all()[:12] return render(request, 'group.html', {'group': group, 'posts': posts}) @login_required def new_post(request): form = PostForm(request.POST or None) if request.method == 'POST' and form.is_valid(): post = form.save(commit=False) post.author = request.user form.save() return redirect('index') return render(request, 'new.html', {'form': form})
class PeopleController < ApplicationController before_action :set_person, only: [:show, :edit, :update, :destroy] # GET /people # GET /people.json def index @people = Person.all end # GET /people/1 # GET /people/1.json def show end # GET /people/new def new @person = Person.new @genders = ["male", "female", "neuter"] @castes = Animal.all #["open", "obc", "nt", "sc", "st", "vj"] end # GET /people/1/edit def edit end # POST /people # POST /people.json def create @person = Person.new(person_params) p"*** would like to get details of params = #{person_params}" p "i got ur birthdateis = #{@person.birthdate}" p "Acceptance = #{@person.terms}" respond_to do |format| if @person.save format.html { redirect_to @person, notice: 'Person was successfully created.' } format.json { render :show, status: :created, location: @person } else @genders = ["male", "female", "neuter"] @castes = Animal.all format.html { render :new } format.json { render json: @person.errors, status: :unprocessable_entity } end end end # PATCH/PUT /people/1 # PATCH/PUT /people/1.json def update respond_to do |format| if @person.update(person_params) format.html { redirect_to @person, notice: 'Person was successfully updated.' } format.json { render :show, status: :ok, location: @person } else format.html { render :edit } format.json { render json: @person.errors, status: :unprocessable_entity } end end end # DELETE /people/1 # DELETE /people/1.json def destroy p"I am in the destroy method" @person.destroy respond_to do |format| format.html { redirect_to people_url, notice: 'Person was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_person @person = Person.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def person_params params.require(:person).permit(:name, :address, :gender, :age, :country, :state, :city, :is_disable, :birthdate, :caste, :terms, skills: []) end end
class Product < ActiveRecord::Base has_many :reviews has_many :users, through: :reviews def leave_review(user, star_rating, comment) if user.is_a?(User) && star_rating.is_a?(Integer) && comment.is_a?(String) Review.create( star_rating: star_rating, comment: comment, user_id: user.id, product_id: self.id ) else "Please check the data types of your user/star_rating and/or comment" end end def print_all_reviews self .reviews .map do |review| puts "Review for #{self.name} by #{review.user.name}: #{review.star_rating}. #{review.comment}" end .compact end def average_rating self.reviews.map { |review| review.star_rating.to_f }.sum / self.reviews.count end end
<template> <div class="videoPopup"> <div :class="playing ? 'avatar active' : 'avatar'" @click.prevent="play"> <img :src="post.image_url" :alt="post.title"> <span class="icon"><i class="icon-right-dir"></i></span> <iframe width="560" height="315" :src="videoEmbed" frameborder="0" allowfullscreen></iframe> </div> <div class="title" v-text="post.title"></div> </div> </template> <script> import {mapState} from 'vuex' export default { props: ['id'], data() { return { playing: false }; }, created() { this.$store.dispatch('fetchDetails', this.id); }, computed: { videoEmbed() { return this.post.video ? this.post.video.path + '?autoplay=1' : ''; }, ...mapState({ post: state => state.mainStore.details }) }, methods: { play() { let theHref = $('iframe').attr('src'); $('iframe').attr('src', theHref + ";autoplay=1"); this.playing = true; }, } } </script>
import { mocked } from 'ts-jest/utils'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import {Router} from 'react-router-dom'; import {createMemoryHistory} from 'history'; import { fetchCategories } from '../../../../../services/Category.services'; import RestaurantFilter from '../RestaurantFilter.component'; import Category from '../../../../../services/Category.model'; import CategoryContext from '../../../contexts/RestaurantCategory/RestaurantCategory.context'; import categoriesResponseJson from "../../../../../../dependencies/stubby/mocks/response/categories_response.json"; import Error from '../../../../../services/Error.model'; import { showWarning } from '../../../../../services/Notification.service'; jest.mock('../../../../../services/Category.services'); jest.mock('../../../../../services/Notification.service'); let mockedFetchCategories: any let mockedShowWarning: any beforeEach(() => { jest.clearAllMocks(); mockedFetchCategories = mocked(fetchCategories); mockedShowWarning = mocked(showWarning); }); it('should list category empty list on component', async () => { mockedFetchCategories.mockImplementationOnce(() => Promise.resolve( [] )); const history = createMemoryHistory(); render( <Router history={history}> <RestaurantFilter /> </Router> ); const categoriesSelect = await waitFor(() => screen.getByTestId('select-category')) as HTMLSelectElement; expect(categoriesSelect.childElementCount).toEqual(1); const defaultOption = categoriesSelect.children[0] as HTMLOptionElement; expect(defaultOption.text).toEqual('Selecione uma categoria'); expect(defaultOption.value).toEqual(''); expect(defaultOption.selected).toBeTruthy(); }); it('should list category list on component', async () => { mockedFetchCategories.mockImplementationOnce(() => Promise.resolve( categoriesResponseJson.data as Category [] )); const history = createMemoryHistory(); render( <Router history={history}> <RestaurantFilter /> </Router> ); const categoriesSelect = await waitFor(() => screen.getByTestId('select-category')) as HTMLSelectElement; expect(categoriesSelect.childElementCount).toEqual(6); const defaultOption = categoriesSelect.children[0] as HTMLOptionElement; expect(defaultOption.text).toEqual('Selecione uma categoria'); expect(defaultOption.value).toEqual(''); expect(defaultOption.selected).toBeTruthy(); const pizzeriaOption = categoriesSelect.children[1] as HTMLOptionElement; expect(pizzeriaOption.text).toEqual('Pizzaria'); expect(pizzeriaOption.value).toEqual('pizza'); expect(pizzeriaOption.selected).toBeFalsy(); const hamburguerOption = categoriesSelect.children[2] as HTMLOptionElement; expect(hamburguerOption.text).toEqual('Hambúrguer'); expect(hamburguerOption.value).toEqual('hamburguer'); expect(hamburguerOption.selected).toBeFalsy(); const japaneseOption = categoriesSelect.children[3] as HTMLOptionElement; expect(japaneseOption.text).toEqual('Japonesa'); expect(japaneseOption.value).toEqual('japonesa'); expect(japaneseOption.selected).toBeFalsy(); const vegetarianOption = categoriesSelect.children[4] as HTMLOptionElement; expect(vegetarianOption.text).toEqual('Vegetariana'); expect(vegetarianOption.value).toEqual('vegetariana'); expect(vegetarianOption.selected).toBeFalsy(); const brazilianOption = categoriesSelect.children[5] as HTMLOptionElement; expect(brazilianOption.text).toEqual('Brasileira'); expect(brazilianOption.value).toEqual('brasileira'); expect(brazilianOption.selected).toBeFalsy(); }); it('should select category and change state selected', async () => { mockedFetchCategories.mockImplementationOnce(() => Promise.resolve( categoriesResponseJson.data as Category [] )); const categoryState = { category: '', setCategory: jest.fn(), }; const history = createMemoryHistory(); render( <CategoryContext.Provider value={ categoryState }> <Router history={history}> <RestaurantFilter /> </Router> </CategoryContext.Provider> ); await waitFor(() => { fireEvent.change(screen.getByTestId('select-category'), { target: { value: 'pizza' } }); expect(categoryState.setCategory).toHaveBeenCalledWith('pizza'); }); const categoriesSelect = screen.getByTestId('select-category') as HTMLSelectElement; expect(categoriesSelect.childElementCount).toEqual(6); const defaultOption = categoriesSelect.children[0] as HTMLOptionElement; expect(defaultOption.text).toEqual('Selecione uma categoria'); expect(defaultOption.value).toEqual(''); expect(defaultOption.selected).toBeFalsy(); const pizzeriaOption = categoriesSelect.children[1] as HTMLOptionElement; expect(pizzeriaOption.text).toEqual('Pizzaria'); expect(pizzeriaOption.value).toEqual('pizza'); expect(pizzeriaOption.selected).toBeTruthy(); const hamburguerOption = categoriesSelect.children[2] as HTMLOptionElement; expect(hamburguerOption.text).toEqual('Hambúrguer'); expect(hamburguerOption.value).toEqual('hamburguer'); expect(hamburguerOption.selected).toBeFalsy(); const japaneseOption = categoriesSelect.children[3] as HTMLOptionElement; expect(japaneseOption.text).toEqual('Japonesa'); expect(japaneseOption.value).toEqual('japonesa'); expect(japaneseOption.selected).toBeFalsy(); const vegetarianOption = categoriesSelect.children[4] as HTMLOptionElement; expect(vegetarianOption.text).toEqual('Vegetariana'); expect(vegetarianOption.value).toEqual('vegetariana'); expect(vegetarianOption.selected).toBeFalsy(); const brazilianOption = categoriesSelect.children[5] as HTMLOptionElement; expect(brazilianOption.text).toEqual('Brasileira'); expect(brazilianOption.value).toEqual('brasileira'); expect(brazilianOption.selected).toBeFalsy(); }); it('should show warning message when fetch get error', async () => { mockedFetchCategories.mockImplementationOnce(() => Promise.reject( new Error("0001", "Error fetch categories") )); mockedShowWarning.mockImplementationOnce((message: string) => { expect(message).toEqual('Error fetch categories'); }); const history = createMemoryHistory(); render( <Router history={history}> <RestaurantFilter /> </Router> ); const categoriesSelect = await waitFor(() => screen.getByTestId('select-category')) as HTMLSelectElement; expect(categoriesSelect.childElementCount).toEqual(1); const defaultOption = categoriesSelect.children[0] as HTMLOptionElement; expect(defaultOption.text).toEqual('Selecione uma categoria'); expect(defaultOption.value).toEqual(''); expect(defaultOption.selected).toBeTruthy(); });
#include <iostream> #include "Login.h" #include "inputProcessor.h" #include "List.h" #include "Buy.h" #include "Refund.h" #include "AddCredit.h" #include "Profiles.h" #include "Create.h" #include "Delete.h" #include "Sell.h" #include <string> using namespace std; string userAccountsFilePath; string gameCollectionFilePath; string availableGamesFilePath; string dailyTransactionFilePath; int main(int argc, char* argv[]){ if (argc != 5) { cout << "Invalid number of arguments" << endl; return 1; } userAccountsFilePath = "../Test Files/AvailableAccounts/" + string(argv[1]); availableGamesFilePath = "../Test Files/AvailableGames/" + string(argv[2]); gameCollectionFilePath = "../Test Files/GameCollection/" + string(argv[3]); dailyTransactionFilePath = "../Test Files/DailyTransaction/" + string(argv[4]); Login login; List list; inputProcessor ip; Buy buy(login); Refund refund(login); AddCredit addCredit(login); Profiles profiles(login); Create create; Delete deleting(login); Sell sell(login); string input; cout << "Welcome to GameFlow!" << endl; // Welcome message do { //Login loop, meant to ensure that the user logs in before proceeding cout << "Please enter Login Command:" << endl; getline(cin, input); if (ip.ignoreCase(input, "exit")){ exit(0); } } while (!login.isLogin(input)); while (!login.isLoggedIn()){ // Username loop, ensure user enters a valid username before proceeding cout << "Please enter a valid username:" << endl; getline(cin, input); if (ip.ignoreCase(input, "exit")){ exit(0); } login.loginUser(input); } cout << "Welcome, " << login.getUserLevel() << " User: " << login.getCurrentUser() << endl; // Once logged in, appropriate welcome message is displayed cout << "Your current credit balance is: " << login.getUserCredit() << endl; while (login.isLoggedIn()) { // Command loop, will continue to prompt user for commands until they logout do { cout << "Please enter a valid command. (Options: " << ip.getCommands(login.getUserLevel()) << ")"<< endl; getline(cin, input); } while (!ip.isValidInput(input, login.getUserLevel())); if (ip.ignoreCase(input, "logout")){ login.logoutUser(); } else if (ip.ignoreCase(input, "list")){ list.displayList(); } else if (ip.ignoreCase(input, "create")){ create.createUser(); } else if (ip.ignoreCase(input, "delete")){ deleting.deleteUser(); } else if (ip.ignoreCase(input, "buy")){ buy.buyGame(); } else if(ip.ignoreCase(input, "sell")){ sell.sellGame(); } else if (ip.ignoreCase(input, "refund")){ refund.refundTransaction(); } else if (ip.ignoreCase(input, "AddCredit")){ addCredit.addCreditCommand(); } else if (ip.ignoreCase(input, "Profiles")) { cout << "List of Current Users: " << endl << "-------------------" << endl; profiles.listProfiles(); } } return 0; }
--- index: 5 module: module_2 task: headlight_check previous: speed_record_challenge next: emergency_light --- # Lesson 8. Headlight check ## Lesson objective Learn about the `setup()` function and how to control LED using the `lineRobot` library. ## Introduction In previous lessons, you learned about functions for controlling the robot's movement. Now, let's check the robot's headlights to learn about the `setup()` function in Arduino Wiring. ## Block of theory In the Wiring language for Arduino, every program has two functions: `setup()` and `loop()` The `setup()` function runs **only once** after the program starts. Inside this function, you can write code to execute other functions or to initialize variables. The `turnOnHeadlight()` function turns on the LED. The `turnOffHeadlight` function turns off the LED. The `turnOnHeadlightForSecond()` function turns on the LED on the robot for exactly one second. ## Task Write a program for the robot to turn on Headlights for 3 seconds. Hint: you can do this by two ways: using `delay()` or `turnOnHeadlightForSecond()` ## Conclusion Congratulations! Now you know about one of the fundamental functions in Arduino programs and can control the LED on the robot.
"use client"; import { zodResolver } from "@hookform/resolvers/zod"; import { SubmitHandler, useForm } from "react-hook-form"; import * as z from "zod"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { FormUserType, UserType } from "@/types"; import { FC } from "react"; const FormSchema = z.object({ name: z .string() .min(1, { message: "Name is required", }) .min(3, { message: "Please enter at least 3 characters." }), email: z .string() .min(1, { message: "Email is required", }) .email(), gender: z.string().min(1, { message: "Gender is required", }), status: z.string().min(1, { message: "Status is required", }), }); interface FormUserProps { submit: SubmitHandler<z.infer<typeof FormSchema>>; isEditing: boolean; initialValues: FormUserType; isLoading: boolean; } const FormUser: FC<FormUserProps> = ({ submit, isEditing, isLoading, initialValues, }) => { const form = useForm<z.infer<typeof FormSchema>>({ resolver: zodResolver(FormSchema), defaultValues: initialValues, }); if (isLoading) { return <div>loading ..</div>; } return ( <div className="flex flex-col items-center py-6"> <Form {...form}> <form onSubmit={form.handleSubmit(submit)} className="w-2/3 space-y-6"> <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input placeholder="Input name" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="email" render={({ field }) => ( <FormItem> <FormLabel>Email</FormLabel> <FormControl> <Input placeholder="Input email" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <div className="flex items-center gap-8"> <FormField control={form.control} name="gender" render={({ field }) => ( <FormItem> <FormLabel>Gender</FormLabel> <Select onValueChange={field.onChange} defaultValue={field.value} > <FormControl> <SelectTrigger> <SelectValue placeholder="Select gender" /> </SelectTrigger> </FormControl> <SelectContent> <SelectItem value="male">Male</SelectItem> <SelectItem value="female">Female</SelectItem> </SelectContent> </Select> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="status" render={({ field }) => ( <FormItem> <FormLabel>Status</FormLabel> <Select onValueChange={field.onChange} defaultValue={field.value} > <FormControl> <SelectTrigger> <SelectValue placeholder="Select status" /> </SelectTrigger> </FormControl> <SelectContent> <SelectItem value="active">Active</SelectItem> <SelectItem value="inactive">Inactive</SelectItem> </SelectContent> </Select> <FormMessage /> </FormItem> )} /> </div> <Button type="submit" className="mt-6"> {isLoading ? "Please wait..." : isEditing ? "Update user" : "Add new user"} </Button> </form> </Form> </div> ); }; export default FormUser;
package com.refrigeratorthief.reciperecommendservice.dto.comment.controllerDto; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; import com.refrigeratorthief.reciperecommendservice.domain.user.User; import com.refrigeratorthief.reciperecommendservice.dto.comment.serviceDto.CommentUpdateServiceRequestDto; import lombok.*; @Setter @Getter @Builder @NoArgsConstructor @AllArgsConstructor @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public class CommentUpdateRequestControllerDto { private Integer id; private String content; private String userId; public CommentUpdateServiceRequestDto toServiceDto() { return CommentUpdateServiceRequestDto.builder() .id(id) .content(content) .user(User.builder().id(userId).build()) .build(); } }
import React, { useEffect, useState } from "react" import Header from "../../components/header" import { StyledHomePage, StyledContainer, StyledUpperPart, } from "./styles" import Footer from "../../components/footer" import { getDataApi } from "../../requests/shop" import { PaginatedItems } from "./components/Pagintaion" export const HomePage = () => { const [products, setProducts] = useState([]) useEffect(() => { const getData = async () => { const { data } = await getDataApi(); setProducts(data); } getData(); }, []) return ( <StyledHomePage> <Header /> <StyledContainer> <StyledUpperPart> <p>{products.length ?? 0} listings shown</p> </StyledUpperPart> {!!products.length ? <PaginatedItems itemsPerPage={9} products={products} /> : null} <Footer /> </StyledContainer> </StyledHomePage> ) } export default HomePage
// // File.swift // // // Created by Sushant Jugran on 27/02/24. // import Foundation class PaypalAPIClient: PaypalAPIClientProtocol { var baseURLString: String private var baseURL: URL { if let url = URL(string: baseURLString) { return url } else { fatalError() } } init(baseURLString: String) { self.baseURLString = baseURLString } func getOrderId() async throws -> String? { let url = self.baseURL.appendingPathComponent("orders") var request = URLRequest(url: url) request.httpMethod = "POST" let (data, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data") } guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else { fatalError("Error while parsing data") } return (json["id"] as? String) } func captureOrder(orderId: String) async throws { guard let url = URL(string: "https://tabby-aeolian-ophthalmologist.glitch.me//api/orders/\(orderId)/capture") else {return} var request = URLRequest(url: url) request.httpMethod = "POST" let (_, response) = try await URLSession.shared.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data") } return } }
package BJ.Gold.G1; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; public class BJ_17472_다리만들기2 { private static BufferedReader br; private static StringTokenizer st; private static int[] dy = {-1, 1, 0, 0}; private static int[] dx = {0, 0, -1, 1}; private static int N; private static int M; private static int cnt; private static int[][] matrix; private static boolean[][] visited; private static int[] island; private static int[] p; private static PriorityQueue<Edge> q; private static String input1 = "7 8\r\n" + "0 0 0 0 0 0 1 1\r\n" + "1 1 0 0 0 0 1 1\r\n" + "1 1 0 0 0 0 0 0\r\n" + "1 1 0 0 0 1 1 0\r\n" + "0 0 0 0 0 1 1 0\r\n" + "0 0 0 0 0 0 0 0\r\n" + "1 1 1 1 1 1 1 1"; private static String input2 = "7 7\r\n" + "1 1 1 0 1 1 1\r\n" + "1 1 1 0 1 1 1\r\n" + "1 1 1 0 1 1 1\r\n" + "0 0 0 0 0 0 0\r\n" + "1 1 1 0 1 1 1\r\n" + "1 1 1 0 1 1 1\r\n" + "1 1 1 0 1 1 1"; public static void main(String[] args) throws Exception { init(); islandCheck(); for(int[] iArr : matrix) { System.out.println(Arrays.toString(iArr)); } System.out.println(); setEdge(); for(Edge e : q) { System.out.println(e.start + " : " + e.end + " : " + e.weight); } System.out.println(); System.out.println(findMst()); } private static void init() throws Exception { System.setIn(new FileInputStream("input.txt")); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(input2.getBytes()))); st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); matrix = new int[N][M]; visited = new boolean[N][M]; for(int y = 0; y < N; y++) { st = new StringTokenizer(br.readLine()); for(int x = 0; x < M; x++) { matrix[y][x] = Integer.parseInt(st.nextToken()); } } } private static void islandCheck() { cnt = 0; for(int y = 0; y < N; y++) { for(int x = 0; x < M; x++) { if(visited[y][x] || matrix[y][x] == 0) continue; islandConnect(y, x, ++cnt); } } } private static void islandConnect(int y, int x, int num) { if(visited[y][x] || matrix[y][x] == 0) return; visited[y][x] = true; matrix[y][x] = num; for(int i = 0; i < 4 ; i++) { int Y = y + dy[i]; int X = x + dx[i]; if(Y < 0 || Y >= N || X < 0 || X >= M) continue; islandConnect(Y, X, num); } } private static class Edge implements Comparable<Edge>{ public int start; public int end; public int weight; public Edge(int start, int end, int weight) { super(); this.start = start; this.end = end; this.weight = weight; } @Override public int compareTo(Edge o) { return this.weight - o.weight; } } private static void setEdge() { q = new PriorityQueue<>(); for(int y = 0; y < N; y++) { int prev = 0; int curr = 0; for(int x = 0; x < M; x++) { curr = x; if(matrix[y][curr] == 0) continue; if(prev == 0) { prev = x; continue; } if(prev == curr) { continue; } if(curr - prev > 2) { q.offer(new Edge(matrix[y][prev], matrix[y][curr], curr - prev - 1)); } prev = curr; } } for(int x = 0; x < M; x++) { int prev = 0; int curr = 0; for(int y = 0; y < N; y++) { curr = y; if(matrix[curr][x] == 0) continue; if(prev == 0) { prev = y; continue; } if(prev == curr) { continue; } if(curr - prev > 2) { q.offer(new Edge(matrix[prev][x], matrix[curr][x], curr - prev - 1)); } prev = curr; } } } private static int findMst() { int ans = 0; p = new int[cnt + 1]; for(int i = 1; i < (cnt + 1); i++) p[i] = i; for(Edge e : q) { int px = findSet(e.start); int py = findSet(e.end); if(px == py) continue; unionSet(px, py); ans += e.weight; } System.out.println(Arrays.toString(p)); int prev = p[1]; for(int i = 2; i < cnt; i++) { if(prev != p[i]) return -1; } return ans; } private static void unionSet(int px, int py) { p[py] = px; } private static int findSet(int x) { if(p[x] == x) return x; return p[x] = findSet(p[x]); } }
import classNames from 'classnames'; import { BsArrowRight, BsChevronRight } from 'react-icons/bs'; import React, { useRef } from 'react'; import LzLink from './link'; interface IProps { leftIcon?: any; rightIcon?: any; isDisabled?: boolean; ghost?: boolean; asLink?: string; children: React.ReactNode; variant?: string; size?: string; className?: string; onClick?: () => void; } const LzButton = ({ leftIcon, isDisabled, rightIcon, ghost, asLink, children, variant = 'pri', size = 'sm', className, ...rest }: IProps) => { const linkRef = useRef<HTMLElement>(null); const variants: any = { pri: 'lz-btn-pri', sec: 'lz-btn-sec', gho: 'lz-btn-gho', }; const sizes: any = { sm: 'lz-btn-sm', md: 'lz-btn-md', lg: 'lz-btn-lg', }; interface IconProp { [index: string]: React.ReactNode } const icon: IconProp = { arrow: <BsArrowRight className="text-current" />, chevron: <BsChevronRight className="text-current" /> }; const handleClick = () => { rest?.onClick?.(); if (asLink) linkRef.current?.click(); }; if (ghost) { return ( <div tabIndex={0} role="button" className="flex items-center space-x-2 group" {...rest} onClick={handleClick}> <span className="whitespace-pre paragraph-1-s xl:paragraph-3-s text-neu-700">{children}</span> { rightIcon && ( rightIcon === 'chevron' ? <BsChevronRight fill="text-neu-700" className="duration-200 transform group-hover:translate-x-1" /> : rightIcon === 'arrow' ? <BsArrowRight fill="text-neu-700" className="duration-200 transform group-hover:translate-x-1" /> : null ) } {asLink && <LzLink ref={linkRef} to={asLink} className='m-0 sr-only' />} </div> ); } return ( <> <button disabled={isDisabled} {...rest} onClick={handleClick} className={classNames('lz-btn group whitespace-pre', sizes[size], className, variants[variant])}> { leftIcon && ( <span> {leftIcon && icon[leftIcon] || leftIcon} </span> ) } <span className={classNames('block', { 'ml-2': leftIcon, 'mr-2': rightIcon })}> {children} </span> { rightIcon && ( <span> {rightIcon && icon[rightIcon] || rightIcon} </span> ) } </button> {asLink && <LzLink ref={linkRef} to={asLink} className='!m-0 sr-only' />} </> ); }; export default LzButton;
import React from 'react'; import { useRef, useState, useEffect, useCallback} from "react"; import Webcam from "react-webcam"; import * as faceapi from 'face-api.js'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'; export const Top = () => { //show all cameras by deviceid const [deviceId, setDeviceId] = React.useState<string>(""); const [devices, setDevices] = React.useState<MediaDeviceInfo[]>([]); const videoConstraints = { width: 720, height: 360, facingMode: "user", deviceId: deviceId }; const handleDevices = (mediaDevices:MediaDeviceInfo[]) => { setDevices(mediaDevices.filter((item) => item.kind === "videoinput")); }; React.useEffect( () => { navigator.mediaDevices.enumerateDevices().then(handleDevices); }, [handleDevices] ); const [isCaptureEnable, setCaptureEnable] = useState<boolean>(false); const webcamRef = useRef<Webcam>(null); //face-api model const [expressions, setExpressions] = React.useState({ angry: 0, disgusted: 0, fearful: 0, happy: 0, neutral: 0, sad: 0, surprised: 0 }); const [modelsLoaded, setModelsLoaded] = React.useState<boolean>(false); const loadModels = async () => { Promise.all([ faceapi.nets.tinyFaceDetector.loadFromUri('/models'), faceapi.nets.faceLandmark68Net.loadFromUri('/models'), faceapi.nets.faceRecognitionNet.loadFromUri('/models'), faceapi.nets.faceExpressionNet.loadFromUri('/models'), ]).then(() => { faceDetection(); }) } const faceDetection = () => { setInterval(async () => { if(webcamRef.current) { const webcamCurrent = webcamRef.current as any; if(webcamCurrent.video.readyState === 4) { const video = webcamCurrent.video; const detections = await faceapi.detectAllFaces (video,new faceapi.TinyFaceDetectorOptions()) .withFaceLandmarks() .withFaceExpressions(); if(detections.length > 0) { const exp = detections[0].expressions; console.log(exp); setExpressions(exp); const nextChartData = defaultChartData; const data = [ exp.angry , exp.disgusted , exp.fearful , exp.happy , exp.neutral , exp.sad , exp.surprised ]; for(var i:number = 0;i < 7;++i ) { nextChartData[i].data = data[i]; } setChartData(nextChartData); } } } },1000); }; useEffect(() => { loadModels(); },[]); //chart settings const labels:string[] = ["angry" ,"disgusted", "fearful", "happy", "neutral", "sad", "surprised"]; const defaultChartData = [ { expression: 'angry', data:0, fullMark: 1, index: 0 }, { expression: 'disgusted', data:0, fullMark: 1, index: 1 }, { expression: 'fearful', data:0, fullMark: 1, index: 2 }, { expression: 'happy', data:0, fullMark: 1, index: 3 }, { expression: 'neutral', data:0, fullMark: 1, index: 4 }, { expression: 'sad', data:0, fullMark: 1, index: 5 }, { expression: 'surprised', data:0, fullMark: 1, index: 6 }, ]; const [chartData, setChartData] = React.useState(defaultChartData); return ( <> <header> <h1>表情評価</h1> </header> {isCaptureEnable || ( <button onClick={() => setCaptureEnable(true)}>開始</button> )} {isCaptureEnable && ( <> <div> <button onClick={() => setCaptureEnable(false)}>終了</button> </div> <div> <Webcam audio={false} width={540} height={360} ref={webcamRef} screenshotFormat="image/jpeg" videoConstraints={videoConstraints} /> </div> <div> {devices.map((device, key) => ( <button key={device.deviceId} onClick={() => setDeviceId(device.deviceId)} > {device.label || `Device ${key + 1}`} </button> ))} </div> <div style={{height:"200px",width:"60%"}}> <ResponsiveContainer width="100%" height="100%"> <LineChart width={500} height={300} data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="expression" /> <YAxis /> <Tooltip /> <Line type="monotone" dataKey="data" stroke="#8884d8" activeDot={{ r: 8 }} /> </LineChart> </ResponsiveContainer> </div> </> )} </> ); } export default Top;
import { ApiProperty } from '@nestjs/swagger'; import { TransactionTypeEnum } from '@shared/database/financial/enums/transaction-type.enum'; import { IsEnum, IsNotEmpty, IsNumber, Min } from 'class-validator'; export class CreateTransactionBodyDto { @ApiProperty({ description: 'Account ID', minimum: 1, example: 4225, }) @IsNotEmpty() @IsNumber() @Min(1) accountId: number; @ApiProperty({ description: 'Transaction type', enum: TransactionTypeEnum, example: TransactionTypeEnum.DEBIT, }) @IsNotEmpty() @IsEnum(TransactionTypeEnum) type: TransactionTypeEnum; @ApiProperty({ description: 'Transaction amount', minimum: 0.01, example: 1500.34, }) @IsNotEmpty() @IsNumber() @Min(0.01) amount: number; }
import unittest from domain.domainFilm import Film from repository.repoFilm import repoFilm class TestFilm(unittest.TestCase): def test_film_initialization(self): film_id = 1 titlu = "Inception" descriere = "A mind-bending movie" gen = "Sci-Fi" film = Film(film_id, titlu, descriere, gen) self.assertEqual(film.get_film_id(), film_id) self.assertEqual(film.get_titlu(), titlu) self.assertEqual(film.get_descriere(), descriere) self.assertEqual(film.get_gen(), gen) def test_setters(self): film = Film(1, "Inception", "A mind-bending movie", "Sci-Fi") new_id = 2 new_titlu = "Interstellar" new_descriere = "Exploring space and time" new_gen = "Sci-Fi" film.set_film_id(new_id) film.set_titlu(new_titlu) film.set_descriere(new_descriere) film.set_gen(new_gen) self.assertEqual(film.get_film_id(), new_id) self.assertEqual(film.get_titlu(), new_titlu) self.assertEqual(film.get_descriere(), new_descriere) self.assertEqual(film.get_gen(), new_gen) def test_str_method(self): film = Film(1, "Inception", "A mind-bending movie", "Sci-Fi") expected_str = 'Filmul este Inception , genul este Sci-Fi , descrierea este : A mind-bending movie' self.assertEqual(str(film), expected_str) class TestRepoFilm(unittest.TestCase): def test_adauga_film(self): repo = repoFilm() titlu = "Inception" descriere = "A mind-bending movie" gen = "Sci-Fi" repo.adauga_film(titlu, descriere, gen) films = repo.get_all_films() self.assertEqual(len(films), 1) added_film = films[0] self.assertEqual(added_film.get_titlu(), titlu) self.assertEqual(added_film.get_descriere(), descriere) self.assertEqual(added_film.get_gen(), gen) def test_sterge_film(self): repo = repoFilm() repo.adauga_film("Inception", "A mind-bending movie", "Sci-Fi") repo.adauga_film("Interstellar", "Exploring space and time", "Sci-Fi") repo.sterge_film(1) films = repo.get_all_films() self.assertEqual(len(films), 1) remaining_film = films[0] self.assertEqual(remaining_film.get_titlu(), "Interstellar") self.assertEqual(remaining_film.get_descriere(), "Exploring space and time") self.assertEqual(remaining_film.get_gen(), "Sci-Fi") def test_modifica_film(self): repo = repoFilm() repo.adauga_film("Inception", "A mind-bending movie", "Sci-Fi") repo.adauga_film("Interstellar", "Exploring space and time", "Sci-Fi") repo.modifica_film(1, "Memento", "A psychological thriller", "Thriller") films = repo.get_all_films() modified_film = films[0] self.assertEqual(modified_film.get_titlu(), "Memento") self.assertEqual(modified_film.get_descriere(), "A psychological thriller") self.assertEqual(modified_film.get_gen(), "Thriller") def test_search_film_by_id(self): repo = repoFilm() repo.adauga_film("Inception", "A mind-bending movie", "Sci-Fi") repo.adauga_film("Interstellar", "Exploring space and time", "Sci-Fi") film = repo.search_film_by_id(2) self.assertEqual(film.get_titlu(), "Interstellar") self.assertEqual(film.get_descriere(), "Exploring space and time") self.assertEqual(film.get_gen(), "Sci-Fi") def test_search_film_by_titlu(self): repo = repoFilm() repo.adauga_film("Inception", "A mind-bending movie", "Sci-Fi") repo.adauga_film("Interstellar", "Exploring space and time", "Sci-Fi") film = repo.search_film_by_titlu("Inception") self.assertEqual(film.get_film_id(), 1) self.assertEqual(film.get_descriere(), "A mind-bending movie") self.assertEqual(film.get_gen(), "Sci-Fi") if __name__ == '__main__': unittest.main()
""" Class to manage background images for polar plotting """ import gc # garbage collection import logging import os import sys import cartopy import cartopy.feature as cfeature import cartopy.io.img_tiles as cimgt import matplotlib.pyplot as plt # plotting functions import numpy as np import pyproj from matplotlib import colormaps from matplotlib.colors import LinearSegmentedColormap from netCDF4 import Dataset # pylint: disable=E0611 from PIL import Image from pyproj import Transformer from skimage import exposure # from scikit-image from clev2er.utils.areas.areas import Area from clev2er.utils.dems.dems import Dem # DEM reading log = logging.getLogger(__name__) # pylint: disable=unpacking-non-sequence # pylint: disable=too-many-lines # pylint: disable=too-many-arguments # pylint: disable=too-many-locals # pylint: disable=too-many-statements # pylint: disable=too-many-branches # pylint: disable=too-few-public-methods # dict of available plot background names and test areas all_backgrounds = { "basic_land": "ais", "cartopy_stock": ["ais", "arctic"], "cartopy_stock_ocean": ["ais", "arctic"], "arcgis_shaded_relief": ["ais", "arctic"], "google_satellite": "canadianlake_woods", "bluemarble": ["ais", "arctic"], "natural_earth_cbh": ["ais", "arctic"], "natural_earth_cbh_oceanmasked": ["ais", "arctic"], "natural_earth_cbh_ocean": ["ais", "arctic"], "natural_earth_gray": ["ais", "arctic"], "natural_earth1": ["ais", "arctic"], "stamen": ["ais", "arctic"], "natural_earth_faded": ["ais", "arctic"], "moa": ["ais", "vostok_centre"], "cpom_dem": "ais", "awi_gis_dem": "greenland", "arcticdem_1km": "arctic", "rema_dem_1km": "ais", "grn_s1_mosaic": "greenland", "hillshade": ["ais", "greenland"], "ant_iceshelves": "ais", "ibcso_bathymetry": "ais", "ibcao_bathymetry": "arctic", } all_background_resolutions = ["low", "medium", "high", "vhigh", "vvhigh"] # all_backgrounds = {"google_satellite": 'canadianlake_woods',} class Background: """class to handle background images""" def __init__(self, name, area): """class initialization Args: name (str): background name area (str): area name from clev2er.utils.areas.areas """ if isinstance(area, str): self.thisarea = Area(area) elif isinstance(area, Area): self.thisarea = area if name is None: name = self.thisarea.background_image if name not in all_backgrounds: log.error("background name not valid %s", name) sys.exit(1) self.name = name self.moa_image = None self.moa_zimage = None def load( self, ax, # axis to display background dataprj, # cartopy coordinate reference system (crs) alpha=None, # transparency of background (0..1). If None Area.background_image_alpha resolution=None, # resolution str for backgrounds that have this option include_features=True, # cartopy features to overlay for backgrounds that include this # option hillshade_params=None, # dict of hillshade parameters for use with the # 'hillshade' background zorder=None, # zorder number to use to display background cmap=None, # colormap to use for backgrounds that support different colourmaps ): """ param: ax : axis param: dataprj : cartopy coordinate reference system (crs) param: background: replace default background image (thisarea.background_image) for plot with one of the available backgrounds cartopy_stock : stock image for Cartopy, uses a downgraded natural earth image. Only one resolution cartopy_stock_ocean : stock image for Cartopy with land blanked out in a single colour. Only one resolution arcgis_shaded_relief : resolution (low, medium, default is high) : : ArcGIS World Shaded Relief tiles google_satellite : resolution (low, medium, high, vhigh, vvhigh (default) bluemarble : resolution (low, medium, high) : NASA Blue Marble world image natural_earth_cbh : resolution (low, medium, default is high): Cross Blended Hypso with Shaded Relief and Water https://www.naturalearthdata.com/downloads/50m-raster-data/50m-cross-blend-hypso/ natural_earth_cbh_oceanmasked : resolution (low, medium, default is high) : as for natural_earth_cbh, but with oceans set to white natural_earth_cbh_ocean : resolution (low, medium, high) natural_earth_gray : resolution (low, medium, high): Gray Earth with Shaded Relief, Hypsography, and Ocean Bottom : https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/raster/GRAY_50M_SR_OB.zip natural_earth1 : resolution (low, medium, default is high): Natural Earth I with Shaded Relief and Water : https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/raster/NE1_50M_SR_W.zip stamen : resolution (low, medium, default is high):terrain-background http://maps.stamen.com/terrain-background/#12/37.7706/-122.3782 natural_earth_faded basic_land : resolution (low, medium, high) : basic ocean and land plot moa : MODIS Mosaic of Antarctica 2008-2009 (MOA2009) Image Map at 750m resolution, gray scale cpom_dem : CPOM Antarctic DEM at 1km resolution, gray scale hillshade : hillshade_params={"azimuth": f,”pitch": f,”dem": “str”,”alpha": f} ant_iceshelves ibcso_bathymetry ibcao_bathymetry awi_gis_dem : Greenland DEM from AWI 2014 grn_s1_mosaic : resolution (low, medium, high, vhigh) arcticdem_1km : ArcticDEM at 1km resolution rema_dem_1km : REMA Antarctic DEM at 1km resolution ' param: resolution : 'low', 'medium','high','vhigh','vvhigh', if None, self.thisarea.background_image_resolution is used alpha: set the background transparency (alpha), 0..1. If None, self.thisarea.background_image_alpha is used :return: """ # Select background image to use. Default is from cpom.areas.Area.background_image if not self.name: if isinstance(self.thisarea.background_image, list): self.name = self.thisarea.background_image[0] else: self.name = self.thisarea.background_image if not resolution: if isinstance(self.thisarea.background_image_resolution, list): resolution = self.thisarea.background_image_resolution[0] else: resolution = self.thisarea.background_image_resolution if not alpha: if isinstance(self.thisarea.background_image_alpha, list): alpha = self.thisarea.background_image_alpha[0] else: alpha = self.thisarea.background_image_alpha print("-------------------------------------------------------------") print(f"Background: {self.name}") log.info("resolution=%s", resolution) print("alpha=", alpha) # Most background files are stored here (unless they are too big) os.environ["CARTOPY_USER_BACKGROUNDS"] = ( os.environ["CPOM_SOFTWARE_DIR"] + "/cpom/resources/backgrounds/" ) if self.name == "cartopy_stock": print("Loading cartopy stock background") ax.stock_img() return if self.name == "cartopy_stock_ocean": print("Loading cartopy stock background") ax.stock_img() # blank out land with single colour (default land feature colour) ax.add_feature(cfeature.LAND, zorder=5) return if self.name == "arcgis_shaded_relief": print("Loading arcgis background") url = ( "https://server.arcgisonline.com/ArcGIS/rest/services" "/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}.jpg" ) image = cimgt.GoogleTiles(url=url) if resolution == "low": ax.add_image(image, 2, zorder=0) elif resolution == "medium": ax.add_image(image, 4, zorder=0) else: ax.add_image(image, 8, zorder=0) elif self.name == "google_satellite": print("Loading google_satellite tiles background") image = cimgt.GoogleTiles(style="satellite") if resolution == "low": print("Adding Google Earth Satellite background at low res") ax.add_image(image, 2, alpha=alpha) elif resolution == "medium": print("Adding Google Earth Satellite background at medium res") ax.add_image(image, 4, alpha=alpha) elif resolution == "high": print("Adding Google Earth Satellite background at high res") ax.add_image(image, 8, alpha=alpha) elif resolution == "vhigh": print("Adding Google Earth Satellite background at high res") ax.add_image(image, 12, alpha=alpha) elif resolution == "vvhigh": print("Adding Google Earth Satellite background at high res") ax.add_image(image, 14, alpha=alpha) else: print("Adding Google Earth Satellite background at very high res") ax.add_image(image, 14, alpha=alpha) elif self.name == "bluemarble": print("Loading bluemarble background") if resolution == "low": ax.background_img(name="blue_marble", resolution="low") elif resolution == "medium": ax.background_img(name="blue_marble", resolution="medium") else: ax.background_img(name="blue_marble", resolution="high") elif self.name == "natural_earth_cbh": print("Loading natural_earth cbh background : ", resolution) if resolution == "low": ax.background_img(name="natural_earth_cbh", resolution="low") elif resolution == "medium": ax.background_img(name="natural_earth_cbh", resolution="medium") else: ax.background_img(name="natural_earth_cbh", resolution="high") elif self.name == "natural_earth_cbh_oceanmasked": print("Loading natural_earth cbh oceanmasked background : ", resolution) if resolution == "low": ax.background_img(name="natural_earth_cbh_oceanmasked", resolution="low") elif resolution == "medium": ax.background_img(name="natural_earth_cbh_oceanmasked", resolution="medium") else: ax.background_img(name="natural_earth_cbh_oceanmasked", resolution="high") elif self.name == "natural_earth_cbh_ocean": print("Loading natural_earth cbh background") if resolution == "low": ax.background_img(name="natural_earth_cbh", resolution="low") elif resolution == "medium": ax.background_img(name="natural_earth_cbh", resolution="medium") else: ax.background_img(name="natural_earth_cbh", resolution="high") ax.add_feature(cfeature.LAND, zorder=5) elif self.name == "natural_earth_gray": print("Loading natural_earth_gray background") if resolution == "low": ax.background_img(name="natural_earth_gray", resolution="low") elif resolution == "medium": ax.background_img(name="natural_earth_gray", resolution="medium") else: ax.background_img(name="natural_earth_gray", resolution="high") elif self.name == "natural_earth1": print("Loading natural_earth1 background") if resolution == "low": ax.background_img(name="natural_earth_1", resolution="low") elif resolution == "medium": ax.background_img(name="natural_earth_1", resolution="medium") else: ax.background_img(name="natural_earth_1", resolution="high") elif self.name == "stamen": print("Loading stamen:terrain-background background") stamen_terrain = cimgt.Stamen("terrain-background") if resolution == "low": ax.add_image(stamen_terrain, 2, zorder=0) # 8 is high res, 4, 1 lower elif resolution == "medium": ax.add_image(stamen_terrain, 4, zorder=0) # 8 is high res, 4, 1 lower else: ax.add_image(stamen_terrain, 8, zorder=0) # 8 is high res, 4, 1 lower elif self.name == "natural_earth_faded": print("Loading natural_earth_faded background") # Add a semi-transparent white layer to fade the background ax.add_feature( cfeature.NaturalEarthFeature( "physical", "land", "10m", edgecolor="none", facecolor="whitesmoke" ), zorder=1, alpha=0.4, ) ax.background_img(name="natural_earth_cbh_oceanmasked", resolution="medium") elif self.name == "basic_land": print("Loading basic_land background") # ax.stock_img() ax.set_facecolor("#F2F7FF") land_color = cfeature.COLORS["land"] land_color = "#F5F5F5" if resolution == "low": land = cfeature.NaturalEarthFeature( "physical", "land", "110m", edgecolor="face", facecolor=land_color, ) elif resolution == "medium": land = cfeature.NaturalEarthFeature( "physical", "land", "50m", edgecolor="face", facecolor=land_color, ) elif resolution == "high": land = cfeature.NaturalEarthFeature( "physical", "land", "10m", edgecolor="black", facecolor=land_color, ) else: land = cfeature.NaturalEarthFeature( "physical", "land", "110m", edgecolor="face", facecolor=land_color, ) ax.add_feature(land, zorder=0) elif self.name == "moa": # ------------------------------------------------------------------------------------- # Load CPOM Antarctic 1km DEM # ------------------------------------------------------------------------------------- print("----------------------------------------------------------") # new_img = plt.imread(moa_image) moa_image_file = ( os.environ["CPDATA_DIR"] + "/SATS/OPTICAL/MODIS/MOA2009/750m/moa750_2009_hp1_v1.1.tif" ) print("reading MOA 750m Antarctic image..") print(moa_image_file) self.moa_image = Image.open(moa_image_file) print("processing MOA image...") ncols, nrows = self.moa_image.size zimage = np.array(self.moa_image.getdata()).reshape((nrows, ncols)) self.moa_zimage = np.flip(zimage, 0) ximage = np.linspace(-3174450.0, 2867550.0, 8056, endpoint=True) yimage = np.linspace(-2816675.0, 2406325.0, 6964, endpoint=True) minimagex = ximage.min() minimagey = yimage.min() imagebinsize = 750.0 imagebinsize_km = imagebinsize / 1000.0 # Plot MOA if self.thisarea.hemisphere == "north": print("Can not plot Antarctic MOA background in Northern Hemisphere") sys.exit() # Get tie point prj = pyproj.CRS("epsg:3031") wgs_prj = pyproj.CRS("epsg:4326") # WGS84 if self.thisarea.specify_by_centre: c_x, c_y = self.thisarea.latlon_to_xy( self.thisarea.centre_lat, self.thisarea.centre_lon ) xll = c_x - ((self.thisarea.width_km * 1000) / 2) yll = c_y - ((self.thisarea.height_km * 1000) / 2) else: tie_point_lonlat_to_xy_transformer = Transformer.from_proj( wgs_prj, prj, always_xy=True ) xll, yll = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) image_bin_offset_x = int((xll - minimagex) / imagebinsize) image_bin_offset_y = int((yll - minimagey) / imagebinsize) zimage = self.moa_zimage[ image_bin_offset_y : image_bin_offset_y + int(self.thisarea.height_km / imagebinsize_km), image_bin_offset_x : image_bin_offset_x + int(self.thisarea.width_km / imagebinsize_km), ] ximage = ximage[ image_bin_offset_x : image_bin_offset_x + int(self.thisarea.width_km / imagebinsize_km) ] yimage = yimage[ image_bin_offset_y : image_bin_offset_y + int(self.thisarea.height_km / imagebinsize_km) ] x_grid, y_grid = np.meshgrid(ximage, yimage) zimage = exposure.equalize_adapthist(zimage) thiscmap = plt.cm.get_cmap("Greys_r") print("pcolormesh") plt.pcolormesh(x_grid, y_grid, zimage, cmap=thiscmap, shading="auto", transform=dataprj) elif self.name == "cpom_dem": print("----------------------------------------------------------") print("reading CS2 DEM..") demfile = ( os.environ["CPDATA_DIR"] + "/SATS/RA/DEMS/ant_cpom_cs2_1km/nc/ant_cpom_cs2_1km.nc" ) nc_dem = Dataset(demfile) xdem = nc_dem.variables["x"][:] ydem = nc_dem.variables["y"][:] zdem = nc_dem.variables["z"][:] print("DEM zdem shape ", zdem.data.shape) print("DEM xdem.min,xdem.max= ", xdem.min(), xdem.max()) print("DEM ydem.min,ydem.max= ", ydem.min(), ydem.max()) print("----------------------------------------------------------") mindemx = xdem.min() mindemy = ydem.min() # Get tie point prj = pyproj.CRS("epsg:3031") wgs_prj = pyproj.CRS("epsg:4326") # WGS84 tie_point_lonlat_to_xy_transformer = Transformer.from_proj(wgs_prj, prj, always_xy=True) if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - mindemx) / 1000.0) dem_bin_offset_y = int((yll - mindemy) / 1000.0) print("dem_bin_offset =", dem_bin_offset_x, dem_bin_offset_y) dem_bin_offset_x = max(dem_bin_offset_x, 0) dem_bin_offset_y = max(dem_bin_offset_y, 0) zdem = np.flip(zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km), ] xdem = xdem[dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km)] ydem = np.flip(ydem) ydem = ydem[dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km)] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = plt.cm.get_cmap("Greys", 48) thiscmap.set_bad(color="aliceblue") ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", vmin=self.thisarea.min_elevation - 50.0, vmax=self.thisarea.max_elevation + 50.0, transform=dataprj, ) elif self.name == "hillshade": print(f"Loading background : {self.name}") # Define default hill shade params for southern hemisphere def_hillshade_params = { "azimuth": 235.0, "pitch": 45.0, "dem": "awi_ant_1km", "alpha": 0.3, } # Define default hill shade params for northern hemisphere if self.thisarea.hemisphere == "north": def_hillshade_params = { "azimuth": 140.0, "pitch": 45.0, "dem": "awi_grn_1km", "alpha": 0.3, } if self.thisarea.hillshade_params is not None: def_hillshade_params.update(self.thisarea.hillshade_params) if hillshade_params is not None: def_hillshade_params.update(hillshade_params) print("background hillshade params: ", def_hillshade_params) thisdem = Dem(def_hillshade_params["dem"]) print("Applying hillshade to DEM..") thisdem.hillshade( azimuth=def_hillshade_params["azimuth"], pitch=def_hillshade_params["pitch"], ) # convert dem elevations to hill shaded values (0..256) print("done..") # Get lower left x,y coordinates of area in m if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = thisdem.lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = thisdem.lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - thisdem.mindemx) / thisdem.binsize) dem_bin_offset_y = int((yll - thisdem.mindemy) / thisdem.binsize) dem_bin_offset_x = max(dem_bin_offset_x, 0) dem_bin_offset_y = max(dem_bin_offset_y, 0) zdem = np.flip(thisdem.zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km * 1e3 / thisdem.binsize), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km * 1e3 / thisdem.binsize), ] xdem = thisdem.xdem[ dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km * 1e3 / thisdem.binsize) ] ydem = np.flip(thisdem.ydem) ydem = ydem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km * 1e3 / thisdem.binsize) ] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = colormaps["Greys"] if cmap: thiscmap = cmap # thiscmap.set_bad(color="aliceblue") ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", vmin=np.nanmin(zdem), vmax=np.nanmax(zdem), transform=dataprj, alpha=def_hillshade_params["alpha"], zorder=zorder if zorder else None, ) del thisdem gc.collect() # this background applies a white ice shelf layer elif self.name == "ant_iceshelves": print(f"Loading background : {self.name}") # Define default hill shade params for southern hemisphere def_hillshade_params = { "azimuth": 235.0, "pitch": 45.0, "dem": "awi_ant_1km_floating", "alpha": 1.0, } print("background hillshade params: ", def_hillshade_params) thisdem = Dem(def_hillshade_params["dem"]) thisdem.hillshade( azimuth=def_hillshade_params["azimuth"], pitch=def_hillshade_params["pitch"], ) # convert dem elevations to hill shaded values (0..256) # Get lower left x,y coordinates of area in m if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = thisdem.lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = thisdem.lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - thisdem.mindemx) / thisdem.binsize) dem_bin_offset_y = int((yll - thisdem.mindemy) / thisdem.binsize) zdem = np.flip(thisdem.zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km * 1e3 / thisdem.binsize), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km * 1e3 / thisdem.binsize), ] xdem = thisdem.xdem[ dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km * 1e3 / thisdem.binsize) ] ydem = np.flip(thisdem.ydem) ydem = ydem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km * 1e3 / thisdem.binsize) ] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = LinearSegmentedColormap.from_list( "white_viridis", [ (0, "#808080"), (1, "#ffffff"), ], N=256, ) if cmap: thiscmap = cmap ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", vmin=np.nanmin(zdem), vmax=np.nanmax(zdem), transform=dataprj, alpha=def_hillshade_params["alpha"], zorder=zorder if zorder else None, ) # Antarctic bathymetry from IBCSO v2, available in 'low','medium','high' resolutions elif self.name == "ibcso_bathymetry": bgfile = ( f'{os.environ["CPDATA_DIR"]}/RESOURCES/' f"backgrounds/IBCSO_v2_bed_RGB_{resolution}.npz" ) print(f"Loading background : {self.name} : {bgfile}") try: print("Loading IBCSO_v2_bed_RGB topo map background..") data = np.load(bgfile, allow_pickle=True) zdem = data["zdem"] x_grid = data["X"] y_grid = data["Y"] except IOError: log.error("Could not read %s", bgfile) sys.exit(f"Could not read {bgfile}") thiscmap = plt.cm.get_cmap("Blues_r", 8) ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", alpha=alpha, vmin=np.nanmin(zdem), vmax=np.nanmax(zdem), transform=dataprj, ) # Arctic bathymetry from IBCAO_v4.2 elif self.name == "ibcao_bathymetry": print(f"Loading background : {self.name}") bgfile = ( f'{os.environ["CPDATA_DIR"]}/RESOURCES/backgrounds/' f"IBCAO_v4.2_bathymetry_{resolution}.npz" ) try: print("Loading IBCAO_v4.2 topo map background..") data = np.load(bgfile, allow_pickle=True) zdem = data["zdem"] x_grid = data["X"] y_grid = data["Y"] except IOError: log.error("Could not read %s", bgfile) base_cmap = colormaps["Blues"].reversed() new_colors = base_cmap(np.linspace(0, 1, 8)) thiscmap = LinearSegmentedColormap.from_list("custom_blues", new_colors) ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", alpha=alpha, vmin=np.nanmin(zdem), vmax=np.nanmax(zdem), transform=dataprj, ) elif self.name == "awi_gis_dem": print(f"Loading background : {self.name}") thisdem = Dem("awi_grn_1km") if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = thisdem.lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = thisdem.lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - thisdem.mindemx) / thisdem.binsize) dem_bin_offset_y = int((yll - thisdem.mindemy) / thisdem.binsize) zdem = np.flip(thisdem.zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km), ] xdem = thisdem.xdem[dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km)] ydem = np.flip(thisdem.ydem) ydem = ydem[dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km)] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = plt.cm.get_cmap("Greys", 48) ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", vmin=self.thisarea.min_elevation - 50.0, vmax=self.thisarea.max_elevation + 50.0, transform=dataprj, ) elif self.name == "grn_s1_mosaic": if resolution == "low": demfile = ( os.environ["CPDATA_DIR"] + "/RESOURCES/backgrounds/greenland/S1_mosaic_v2_1km.tiff" ) binsize = 1000 # 1000m grid resolution elif resolution == "medium": demfile = ( os.environ["CPDATA_DIR"] + "/RESOURCES/backgrounds/greenland/S1_mosaic_v2_500m.tiff" ) binsize = 500 # 500m grid resolution elif resolution == "high": demfile = ( os.environ["CPDATA_DIR"] + "/RESOURCES/backgrounds/greenland/S1_mosaic_v2_200m.tiff" ) binsize = 200 # 200m grid resolution elif resolution == "vhigh": demfile = ( os.environ["CPDATA_DIR"] + "/RESOURCES/backgrounds/greenland/S1_mosaic_v2_100m.tiff" ) binsize = 100 # 100m grid resolution print("Loading S1 Sigma0 Mosaic background..") print(demfile) im = Image.open(demfile) print("opened") ncols, nrows = im.size print("ncols, nrows: ", ncols, nrows) zdem = np.array(im.getdata(0)).reshape((nrows, ncols)) # Set void data to Nan # void_data = np.where(zdem == -9999) # if np.any(void_data): # zdem[void_data] = np.nan # self.zdem = np.flip(self.zdem,0) xdem = np.linspace(-660050.000, 859950.000, ncols, endpoint=True) ydem = np.linspace(-3380050.000, -630050.000, nrows, endpoint=True) ydem = np.flip(ydem) mindemx = xdem.min() mindemy = ydem.min() # Get tie point prj = pyproj.CRS("epsg:3413") wgs_prj = pyproj.CRS("epsg:4326") # WGS84 tie_point_lonlat_to_xy_transformer = Transformer.from_proj(wgs_prj, prj, always_xy=True) if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - mindemx) / binsize) dem_bin_offset_y = int((yll - mindemy) / binsize) dem_bin_offset_x = max(dem_bin_offset_x, 0) dem_bin_offset_y = max(dem_bin_offset_y, 0) zdem = np.flip(zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km * 1e3 / binsize), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km * 1e3 / binsize), ] xdem = xdem[ dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km * 1e3 / binsize) ] ydem = np.flip(ydem) ydem = ydem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km * 1e3 / binsize) ] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = plt.cm.get_cmap("Greys", 48) thiscmap.set_bad(color="aliceblue") ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", # vmin=self.thisarea.min_elevation - 50., # vmax=self.thisarea.max_elevation + 50., transform=dataprj, ) elif self.name == "arcticdem_1km": demfile = ( os.environ["CPDATA_DIR"] + "/SATS/RA/DEMS/arctic_dem_1km/arcticdem_mosaic_1km_v3.0.tif" ) print("Loading ArcticDEM 1km Greenland DEM..") print(demfile) im = Image.open(demfile) ncols, nrows = im.size zdem = np.array(im.getdata()).reshape((nrows, ncols)) # Set void data to Nan void_data = np.where(zdem == -9999) if np.any(void_data): zdem[void_data] = np.nan # self.zdem = np.flip(self.zdem,0) xdem = np.linspace(-4000000.000, 3400000.000, ncols, endpoint=True) ydem = np.linspace(-3400000.000, 4100000.000, nrows, endpoint=True) ydem = np.flip(ydem) mindemx = xdem.min() mindemy = ydem.min() binsize = 1e3 # 1km grid resolution in m # Get tie point prj = pyproj.CRS("epsg:3413") wgs_prj = pyproj.CRS("epsg:4326") # WGS84 tie_point_lonlat_to_xy_transformer = Transformer.from_proj(wgs_prj, prj, always_xy=True) if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - mindemx) / 1000.0) dem_bin_offset_y = int((yll - mindemy) / 1000.0) dem_bin_offset_x = max(dem_bin_offset_x, 0) dem_bin_offset_y = max(dem_bin_offset_y, 0) zdem = np.flip(zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km), ] xdem = xdem[dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km)] ydem = np.flip(ydem) ydem = ydem[dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km)] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = plt.cm.get_cmap("Greys", 48) thiscmap.set_bad(color="aliceblue") ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", vmin=self.thisarea.min_elevation - 50.0, vmax=self.thisarea.max_elevation + 50.0, transform=dataprj, ) elif self.name == "rema_dem_1km": demfile = ( os.environ["CPDATA_DIR"] + "/SATS/RA/DEMS/rema_1km_dem/REMA_1km_dem_filled_uncompressed.tif" ) print("Loading REMA 1km DEM ..") print(demfile) im = Image.open(demfile) ncols, nrows = im.size zdem = np.array(im.getdata()).reshape((nrows, ncols)) # Set void data to Nan void_data = np.where(zdem == -9999) if np.any(void_data): zdem[void_data] = np.nan # self.zdem = np.flip(self.zdem,0) xdem = np.linspace(-2700000.0, 2800000.0, ncols, endpoint=True) ydem = np.linspace(-2200000.0, 2300000.0, nrows, endpoint=True) ydem = np.flip(ydem) mindemx = xdem.min() mindemy = ydem.min() binsize = 1e3 # 1km grid resolution in m # Get tie point prj = pyproj.CRS("epsg:3031") # Polar Stereo - South -71S wgs_prj = pyproj.CRS("epsg:4326") # WGS84 tie_point_lonlat_to_xy_transformer = Transformer.from_proj(wgs_prj, prj, always_xy=True) if self.thisarea.specify_plot_area_by_lowerleft_corner: xll, yll = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.llcorner_lon, self.thisarea.llcorner_lat ) else: xc, yc = tie_point_lonlat_to_xy_transformer.transform( self.thisarea.centre_lon, self.thisarea.centre_lat ) xll = xc - (self.thisarea.width_km * 1e3) / 2 yll = yc - (self.thisarea.height_km * 1e3) / 2 dem_bin_offset_x = int((xll - mindemx) / 1000.0) dem_bin_offset_y = int((yll - mindemy) / 1000.0) dem_bin_offset_x = max(dem_bin_offset_x, 0) dem_bin_offset_y = max(dem_bin_offset_y, 0) zdem = np.flip(zdem, 0) zdem = zdem[ dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km), dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km), ] xdem = xdem[dem_bin_offset_x : dem_bin_offset_x + int(self.thisarea.width_km)] ydem = np.flip(ydem) ydem = ydem[dem_bin_offset_y : dem_bin_offset_y + int(self.thisarea.height_km)] x_grid, y_grid = np.meshgrid(xdem, ydem) thiscmap = plt.cm.get_cmap("Greys", 64) thiscmap.set_bad(color="aliceblue") max_elevation = self.thisarea.max_elevation if self.thisarea.max_elevation: max_elevation = self.thisarea.max_elevation ax.pcolormesh( x_grid, y_grid, zdem, cmap=thiscmap, shading="auto", vmin=self.thisarea.min_elevation - 50.0, vmax=max_elevation + 50.0, transform=dataprj, ) if include_features: if self.thisarea.add_lakes_feature: lakes = cartopy.feature.NaturalEarthFeature( "physical", "lakes", scale="10m", edgecolor="lightslategray", facecolor="powderblue", ) ax.add_feature(lakes, zorder=1) if self.thisarea.add_rivers_feature: rivers = cartopy.feature.NaturalEarthFeature( "physical", "rivers_lake_centerlines", scale="10m", edgecolor="b", facecolor="none", ) ax.add_feature(rivers, linewidth=1.0, zorder=1) if self.thisarea.add_country_boundaries: # country boundaries country_bodr = cartopy.feature.NaturalEarthFeature( category="cultural", name="admin_0_boundary_lines_land", scale="50m", facecolor="none", edgecolor="k", ) ax.add_feature( country_bodr, linestyle="--", linewidth=0.8, edgecolor="k", zorder=1 ) # USA/Canada if self.thisarea.add_province_boundaries: # province boundaries provinc_bodr = cartopy.feature.NaturalEarthFeature( category="cultural", name="admin_1_states_provinces_lines", scale="50m", facecolor="none", edgecolor="k", ) ax.add_feature(provinc_bodr, linestyle="--", linewidth=0.6, edgecolor="k", zorder=1) print("-------------------------------------------------------------")
import React from "react"; import { format } from "date-fns"; function Shift({ navigation, shifts, editable, invalidShiftIds }) { function getDays(item) { if ( format(new Date(item.start), "EEE do LLL") !== format(new Date(item.end), "EEE do LLL") ) { return ( <> <span>Across Days:</span> <span>{format(new Date(item.start), "EEE do LLL")}</span> <span>{format(new Date(item.end), "EEE do LLL")}</span> </> ); } else { return ( <> <span>{format(new Date(item.start), "EEE do LLL")}</span> </> ); } } return ( <div w="100%"> {shifts.map((item, index) => { return ( <div borderColor="myBorderGray" style={{ paddingLeft: "4px", paddingRight: "4px", marginLeft: "4px", marginRight: "4px", textAlign: "left", }} > <div className="v-stack"> <span style={{ fontWeight: "700" }}>{item.position}</span> <div className="h-stack" style={{ justifyContent: "space-between", }} > <div className="v-stack" style={{ color: "#4b5563" }}> {getDays(item)} </div> <div className="v-stack" style={{ color: "#4b5563" }}> <span>{format(new Date(item.start), "p")}</span> <span>{format(new Date(item.end), "p")}</span> </div> </div> </div> </div> ); })} </div> ); } export default Shift;
/* Approach 1 :- Iterative */ class Solution { public: double myPow(double x, int n) { if(n==0) { return 1; } if(n==1) { return x; } if(n==-1) { return (double)1/x; } if(n<0) { n=abs(n); x=1/x; } double res=1.0; long long N=n; long long i=1; while(i<=N) { res*=x; if(i*2<N) /* Optimisation step ie. if double the current power is less than the required power then double the result */ { i=(i*2)+1; res*=res; } else { i++; } } return res; } }; /* Approach 2 :- Recursive */ class Solution { public: double myPow(double x, int n) { if(x==1||n==0) { return (double)1; } else if(n==1) { return x; } else if(n==-2147483648) { return (double)0; } else if(x==-1&&n%2==0) { return (double)1; } else if(x==-1&&n%2==1) { return (double)-1; } else if(n<0) { n*=-1; x=1.00/x; } return x*pow(x,n-1); } };
<%= form_for(@category, :html => { :class => "form-horizontal listing", :multipart => true }) do |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2> <ul> <% @category.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="form-group"> <%= f.label :name %><br> <%= f.text_field :name, class: "form-control" %> </div> <div class="form-group"> <%= f.file_field :image, class: "form-control" %> </div> <div class="form-group"> <%= f.submit nil, :class => 'btn btn-primary' %> <%= link_to t('.cancel', :default => t("helpers.links.cancel")), categories_path, :class => 'btn btn-default' %> </div> <% end %>
using FluentAssertions; using Xunit; namespace ServiceRadar.Application.Common.ApplicationUser.Tests; public class CurrentUserTests { [Fact] public void IsInRole_WithMatchingRole_ShouldReturnTrue() { // Arrange var currentUser = new CurrentUser("1", "[email protected]", new List<string> { "Admin", "User" }); // Act var isInRole = currentUser.IsInRole("Admin"); // Assert isInRole.Should().BeTrue(); } [Fact] public void IsInRole_WithNonMatchingRole_ShouldReturnFalse() { // Arrange var currentUser = new CurrentUser("1", "[email protected]", new List<string> { "Admin", "User" }); // Act var isInRole = currentUser.IsInRole("Redactor"); // Assert isInRole.Should().BeFalse(); } [Fact] public void IsInRole_WithNonMatchingCaseRole_ShouldReturnFalse() { // Arrange var currentUser = new CurrentUser("1", "[email protected]", new List<string> { "Admin", "User" }); // Act var isInRole = currentUser.IsInRole("admin"); // Assert isInRole.Should().BeFalse(); } }
getBtn.addEventListener("click", getTodos); postBtn.addEventListener("click", postTodo); putBtn.addEventListener("click", putTodo); deleteBtn.addEventListener("click", deleteTodo); const getBtn = document.getElementById("get-btn"); const postBtn = document.getElementById("post-btn"); const putBtn = document.getElementById("put-btn"); const deleteBtn = document.getElementById("delete-btn"); getBtn.addEventListener("click", getTodos); postBtn.addEventListener("click", postTodo); putBtn.addEventListener("click", putTodo); deleteBtn.addEventListener("click", deleteTodo); function postTodo() { axios .post("https://crudcrud.com/api/e56bd73358e0445a99f0c7436156f25d/todo", { title: "Learn Axios", completed: false, }) .then((res) => console.log(res)) .catch((err) => console.log(err)); } function getTodos() { axios .get("https://crudcrud.com/api/e56bd73358e0445a99f0c7436156f25d/todo") .then((res) => console.log(res.data)) .catch((err) => console.log(err)); } function putTodo() { axios .put( "https://crudcrud.com/api/e56bd73358e0445a99f0c7436156f25d/todo/65dee9cc72109f03e8c7f3ad", { title: "Learn Axios", completed: true, } ) .then((res) => console.log(res)) .catch((err) => console.log(err)); } function deleteTodo() { axios .delete( "https://crudcrud.com/api/e56bd73358e0445a99f0c7436156f25d/todo/65dee9d672109f03e8c7f3af" ) .then((res) => console.log(res.data)) .catch((err) => console.log(err)); }
Встречающиеся термины и понятия: Software Development Life Cycle – SDLC – жизненный цикл разработки ПО Software Testing Life Cycle – STLC – жизненный цикл тестирования ПО SDLC methodologies – методологии SDLC, способы создания программного продукта. Build – (в программировании) – сборка, конечный результат, подготовленный для использования информационный продукт. Increment – инкремент продукта, новый, потенциально рабочий продукт, решающий бизнес-проблему, который получается в результате итерации. Sprint – итерация разработки, отрезок времени для выполнения определенной части работы. Backlog – набор, список задач для выполнения. Product Backlog – бэклог продукта, требования, список всех желаемых возможностей продукта. Что такое разработка ПО (SDLC)? Software development life cycle – цикл разработки программного обеспечения, включающий в себя мероприятия и процессы с момента принятия решения о создании программного продукта до его полного изъятия из эксплуатации. SDLC состоит из следующих этапов: 1) возникает идея 2) на основании этой идеи формируются требования 3) на основании требований производится работа над дизайном продукта 4) идет его разработка 5) проводится его тестирование 6) установка в окружение, где продукт будет работать, и его дальнейшее обслуживание. Тестирование не существует в изоляции, оно занимает свое место в каждом цикле разработки программного обеспечения. Дефекты могут возникнуть на любом этапе SDLC, при этом, в зависимости от этапа, цена исправления дефекта будет отличаться в разы. Дефект, обнаруженный на этапе разработки требований, исправляется намного быстрее и дешевле, например, самим автором требований без привлечения дополнительных людей, а вот если он обнаружен уже после релиза, то цена исправления максимально высока. Поэтому тестировщик должен подключаться еще на этапе разработки и сбора требований, несмотря на то, что больше всего багов возникает на стадии разработки ПО. Уже на этапе формирования требований тестировщик ревьюит, находит некачественные требования. На этапе дизайна он тестирует шаблон на соответствие требованиям (проводит Usability testing). На этапе разработки тестирует UI (user interface), backend и т.д. На этапе непосредственного тестирования - выполняет тестирование, а на этапе внедрения проводит приемочное тестирование. Разработка ПО реализуется с помощью разных методологий (моделей). Модели реализации процесса разработки представляют собой целые системы принципов, а также совокупность идей, понятий, методов, способов и средств, определяющих стиль разработки продукта. Знание и понимание моделей позволяет тестовой команде лучше спланировать и максимально эффективно определить, какое тестирование, когда и в каком объеме будет проводиться, какие ресурсы под него выделить и т.д. Поэтому знание моделей SDLC очень важно для тестировщика. Сами модели бывают очень различные, начиная от самых простых и быстрых, когда время выхода продукта на рынок играет ключевое значение, до суперсложных, когда основным фактором является качество и надежность. Рассмотрим виды этих моделей. В ISTQB все модели разработки делятся на 2 группы: 1) последовательные (sequential) - стадии выполняются строго последовательно друг за другом и каждая следующая стадия начинается только после окончания предыдущей. К таким относится самая древняя модель - каскадная (Waterfall model), а также V-модель 2) итеративные (iterative, включают многократное повторение одних и тех же стадий разработки) и инкрементальные (incremental, содержат функциональное наполнение, которое наращивается с каждой итерацией). Самыми популярными являются: · Итеративная модель · Концепция Agile Waterfall model Waterfall – водопадная (каскадная) модель, где этапы последовательно следуют друг за другом: 1.Этап – анализ требований, полностью завершается, когда составлен список требований к ПО. 2. Этап дизайна. Архитекторы проектируют ПО, строят его архитектуру из требований, создают документы, подробно описывающие для программистов способ и план реализации указанных требований. 3. Этап разработки. После того как проектирование полностью выполнено, разработчики кодируют архитектуру, выполняется интеграция отдельных компонентов, разрабатываемых различными командами программистов. 4. Этап тестирования идет после того как реализация и интеграция завершены. Производится тестирование и отладка продукта; тестировщики берут build, тестируют его, устраняются все недочеты, появившиеся на предыдущих стадиях 5. Этап выкладки ПО – программный продукт внедряется и обеспечивается его поддержка. Плюсы: - стабильность требований в течение всего SDLC, - определенность и понятность этапов модели и простота ее применения, - возможность планировать сроки выполнения и соответствующие ресурсы - этапы четко определены с самого начала, а результат ПО предсказуем. Минусы: - низкая гибкость в управлении проектом, пока не завершен один этап, переход к следующему невозможен, - этапы изолированы, невозможно провести изменения их результатов для устранения возникающих проблем, - пользователи не могут убедиться в качестве разрабатываемого продукта до окончания всего процесса разработки, - невозможность предоставить заказчику результат, пока не завершен весь проект. Сегодня она редко используется. Что такое V-модель? V-модель – это модель, где каждому этапу разработки ставится соответствующий уровень тестирования. Она направлена на тщательное тестирование продукта, который находится еще на стадии проектирования, что позволяет привлекать тестировщиков как можно раньше, буквально как только первые черновики требований уже готовы. Стадия тестирования проводится одновременно с соответствующей стадией разработки. Стадии разработки идут сверху вниз (на рисунке они слева), а тестовые уровни расположены снизу вверх (справа): На этапе написания бизнес-требований предлагается продумать приемочное тестирование, проверку системы с точки зрения конечного пользователя. На этапе разработки функциональных требований к системе (системных требований) необходимо спланировать системные тесты, проверяющие систему целиком - от начала до конца. На этапе архитектуры (дизайна) системы продумываем интеграционные тесты, проверяющие взаимодействие компонентов друг с другом. На этапе реализации (кодирования) пишутся unit-тесты на конкретный модуль/компонент системы и проводится модульное тестирование. Каждое требование тестируется в нужное время. Используется при разработке систем с важным бесперебойным функционирование, например, для интегрированного ПО для механизмов управления аварийными подушками безопасности в транспортных средствах. Данная модель показывает, что тестирование - это не только процесс выполнения тестов, но это целый комплекс мероприятий, в том числе анализ требований/документации и подготовка к тестированию. Плюсы: - тестовые активности идут параллельно разработке, что сильно экономит время и способствует более качественой коммуникации внутри команды, например, на этапе acceptance testing тестировщик плотно взаимодействует с аналитиками, которые пишут требования для продукта - требования четко определены и фиксированы - проводится тщательное тестирование продукта, снижаются риски, т.к. тестировщики привлекаются на самых ранних этапах Минусы: - все-таки это последовательная модель, она неповоротлива к различного рода изменениям. А требования к бизнесу постоянно меняются, и если меняется какое-то требование к продукту, то приходится повторять все стадии от начала до конца - время на активность по подготовке к какому-либо уровню тестирования строго ограничено временем соответствующей стадии разработки. Например, мы должны сделать подготовку к системному тестированию пока идет стадия написания требований для нашей системы, что не всегда удобно и эффективно. Поэтому тестировщики жестко привязаны к какому-то конретному уровню тестирования и лишены гибкости в нахождении максимально эффективного подхода к тестированию. Итеративная модель Iterative model – это поэтапная модель с промежуточным контролем. Она подразумевает поэтапную разработку продукта стадиями которые многократно (итеративно) повторяются. Межэтапные корректировки позволяют учитывать реально существующее взаимовлияние результатов разработки на различных этапах, время жизни каждого из этапов растягивается на весь период разработки. Определяются группы функций, потом они проектируются, создаются и тестируются все вместе в серии циклов. Каждая итерация - это работающее программное обеспечение, которое наращивает в себе функциональность. Iterative model включает в себя: 1. Начальный этап – планирование. Определяются все основные требования к проекту, они подразделяются на более и менее важные. 2. Проводится разработка системы по принципу приращений, так, чтобы разработчик мог использовать данные, полученные в ходе разработки ПО. Проводится анализ и проектирование продукта по итерациям и его последующая реализация. Каждая итерация представляет собой «мини-каскад», который имеет такой же процесс: анализ требований - планирование (проектирование) - разработка (реализация) - тестирование - демонстрация и внедрение. Рисунок взят с сайта https://bytextest.ru/2017/12/21/iterative-model/ То есть, берется одна какая-то небольшая часть функционала на итерацию (неделя, 2 недели, месяц), по окончании итерации эта часть должна быть полностью закончена, ее можно поставлять клиенту, получить от него фидбэк, уточнить требования для следующих компонентов. Затем занимаются разработкой следующей части системы. Процесс повторяется до тех пор, пока не будут выполнены все требования, определенные на начальном этапе. Дефекты, найденные на одной итерации, легко поправить в следующей. Таким образом, итеративная модель – это процесс простой реализации четко определенных и понятных требований к программе и доработки некоторых деталей тех пор, пока продукт не будет полностью реализован. Она характерна при разработке сложных и комплексных систем, для которых имеется четкое видение (как со стороны заказчика, так и со стороны разработчика) того, что собой должен представлять конечный результат, а также требуется ранний вывод продукта на рынок. Плюсы: - разработка происходит быстрее, не нужно сразу писать все требования на каждую функциональность, как в предыдущих моделях. Заказчик видит результаты уже после внедрения первой версии, т.к. первые части системы являются прототипом системы в целом, и можно сразу получить отзывы от клиента о проделанной работе, изменить требования к разработке - затраты, которые получаются в связи с изменением требований пользователей, уменьшаются; - у клиента есть возможность быстро получить и освоить продукт. Минусы: - не все продукты могут быть выпущены с минимальной функциональностью, для крупной сложной платформы наличие минимального набора функциональностей для того, чтобы она была выпущен - очень существенно; - менеджеры должны постоянно измерять прогресс процесса; - добавление новых компонентов в структуру может привести к ухудшению продукта, ведь постоянные изменения нарушают структуру системы, в связи с чем часто требуется дополнительное время и деньги; - надо хорошо продумать регрессионное тестирование, ведь объем функуциональностей будет наращиваться с каждой итерацией, следовательно библиотека с регрессионным тестированием будет расти и надо быть аккуратным в планировании регрессионного тестирования в этом случае; Agile модель Считается, что концепция Agile была разработана и создана под влиянием каскадной, итеративной и V-моделей. ISTQB приводит Agile методологию в качестве итерстивной и икрементальной модели. Условные правила, по которым Agile должен работать, записаны в Agile манифесте, который был создан в 2001 году: - Люди и взаимодействие важнее процессов и инструментов - Работающий продукт важнее исчерпывающей документации - Сотрудничество с заказчиком важнее согласования условий контракта - Готовность к изменениям важнее следования первоначальному плану Agile модель подразумевает активное общение и сотрудничество между всеми участниками проекта. Основу этой гибкой методологии составляет разбиение проектов на небольшие задачи – User story (пользовательские истории). Согласно приоритетности задачи решают в рамках коротких двухнедельных циклов (итераций). Структура модели имеет итеративный цикл: Каждая итерация представляет собой небольшой объем работы, который необходимо выполнить в течение определенного периода времени – спринта (sprint). Длятся спринты от 1 до 2-х недель. Есть 2 реализации Agile – Scrum и Kanban Scrum характеризуется фиксированными сроками, предусмотрены четко организованные периоды работы с конкретными задачами на период. Данный метод подразумевает несколько шагов: 1. Составляется Product Backlog, в котором находятся требования. Из него будут браться задачи, оцениваться и выполняться. 2. Осуществляется Sprint Planning – планирование на реализацию некоторого количества задач, которые обязаны сделать в конце спринта. На Agile-доске рассталяются приоритеты по каждому требованию к продукту (большую роль играет владелец продукта, который собирает пожелания к продукту для оценки командой бэклога). Планируются спринты на реализацию выбранных задач. 3. Sprint Backlog – перемещение сюда набора задач (требований) из Product Backlog, выбранных для выполнения в текущем спринте. 4. Проведение Sprint Execution – разработка этих требований, результаты которых обсуждаются на еженедельных совещаниях 5. Осуществление Sprint Review – завершение задач, обзор рабочих частей продукта. На этом этапе уже имеется Potentially Shippable Increment – потенциальный продукт, который можно выпустить, конечный этап задачи. 6. Sprint Retrospective – анализ спринта, обсуждение проблемы и поиск решения после каждого спринта. Полученный план изменения внедряется на следующем спринте. Клиенту доставляется часть проекта, которая была завершена во время спринта, на проверку и обсуждение. И так итерация повторяется: берется из Product Backlog следующая задача, оценивается и выполняется. Kanban – второй подход к реализации методологии Agile. Предполагает обсуждение производительности в режиме реального времени и полную прозрачность рабочих процессов. Характеризуется отсутствием зафиксированных требований и зафиксированного проекта, задачи команда ставит сама себе и работает по принципу самоорганизации. Для отслеживания достижений и процесса в Kanban используют доски – элемент управления, который наглядно показывает уровень выполнения задач. Backlog – обязательно приоритезированный, задачи стоят в порядке приоритета. Из него берется задача в To Do, реализовывается (In Progress, Testing), потом переводится в Done.
import { inject, injectable } from 'tsyringe'; import { Car } from '@modules/cars/infra/typeorm/entities/Car'; import { ICarsRepository } from '@modules/cars/repositories/ICarsRepository'; import { ICategoriesRepository } from '@modules/cars/repositories/ICategoriesRepository'; import { AppError } from '@shared/errors/AppError'; interface IRequest { name: string; description: string; dailyRate: number; licensePlate: string; fineAmount: number; brand: string; categoryId: string; } @injectable() class CreateCarUseCase { constructor( @inject('CarsRepository') private carsRepository: ICarsRepository, @inject('CategoriesRepository') private categoriesRepository: ICategoriesRepository, ) {} public async execute({ name, description, brand, categoryId, dailyRate, fineAmount, licensePlate, }: IRequest): Promise<Car> { const category = await this.categoriesRepository.findById(categoryId); if (!category) { throw new AppError('Category does not exist', 404); } const carAlreadyExists = await this.carsRepository.findByLicensePlate( licensePlate, ); if (carAlreadyExists) { throw new AppError('Car already exists'); } const car = await this.carsRepository.create({ brand, categoryId, dailyRate, description, name, fineAmount, licensePlate, specifications: [], }); return car; } } export { CreateCarUseCase };
package hotel.xy.com.hotel.utils.http; import com.alibaba.fastjson.JSON; import java.io.IOException; import java.util.concurrent.Executor; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Response; /** * Created by lsy on 18/8/17. */ public class OkHttpUtils { public static final long DEFAULT_MILLISECONDS = 10_000L; private volatile static OkHttpUtils mInstance; private OkHttpClient mOkHttpClient; private Platform mPlatform; public OkHttpUtils(OkHttpClient okHttpClient) { if (okHttpClient == null) { mOkHttpClient = new OkHttpClient(); } else { mOkHttpClient = okHttpClient; } mPlatform = Platform.get(); } public static OkHttpUtils initClient(OkHttpClient okHttpClient) { if (mInstance == null) { synchronized (OkHttpUtils.class) { if (mInstance == null) { mInstance = new OkHttpUtils(okHttpClient); } } } return mInstance; } public static OkHttpUtils getInstance() { return initClient(null); } public Executor getDelivery() { return mPlatform.defaultCallbackExecutor(); } public OkHttpClient getOkHttpClient() { return mOkHttpClient; } public static GetBuilder get() { return new GetBuilder(); } public static PostStringBuilder postString() { return new PostStringBuilder(); } public static PostFileBuilder postFile() { return new PostFileBuilder(); } public static PostFormBuilder post() { return new PostFormBuilder(); } public static OtherRequestBuilder put() { return new OtherRequestBuilder(METHOD.PUT); } public static HeadBuilder head() { return new HeadBuilder(); } public static OtherRequestBuilder delete() { return new OtherRequestBuilder(METHOD.DELETE); } public static OtherRequestBuilder patch() { return new OtherRequestBuilder(METHOD.PATCH); } public void execute(final RequestCall requestCall, final OnRequest callback) { final int id = requestCall.getOkHttpRequest().getId(); requestCall.getCall().enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, final IOException e) { sendFailResultCallback(call, e, callback, id); } @Override public void onResponse(final Call call, final Response response) { try { if (call.isCanceled()) { sendFailResultCallback(call, new IOException("Canceled!"), callback, id); return; } if (!response.isSuccessful()) { sendFailResultCallback(call, new IOException("request failed , reponse's code is : " + response.code()), callback, id); return; } Object o = JSON.parseObject(response.body().string(), requestCall.getOkHttpRequest().result); Object tag = call.request().tag(); sendSuccessResultCallback(o, callback, id, tag); } catch (Exception e) { sendFailResultCallback(call, e, callback, id); } finally { if (response.body() != null) response.body().close(); } } }); } public void executeDownLoad(final RequestCall requestCall, final FileCallBack callback) { final int id = requestCall.getOkHttpRequest().getId(); requestCall.getCall().enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, final IOException e) { callback.fail(call, e); } @Override public void onResponse(final Call call, final Response response) { callback.saveFile(response, id); } }); } public void sendFailResultCallback(final Call call, final Exception e, final OnRequest callback, final int id) { if (callback == null) return; mPlatform.execute(new Runnable() { @Override public void run() { callback.onFail(call, e, id); } }); } public void sendSuccessResultCallback(final Object object, final OnRequest callback, final int id, final Object tag) { if (callback == null) return; mPlatform.execute(new Runnable() { @Override public void run() { callback.onSuccess(object, id, null == tag ? "" : tag.toString()); } }); } public void cancelTag(Object tag) { for (Call call : mOkHttpClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : mOkHttpClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } } public static class METHOD { public static final String HEAD = "HEAD"; public static final String DELETE = "DELETE"; public static final String PUT = "PUT"; public static final String PATCH = "PATCH"; } }
import { Component, OnInit, Output, EventEmitter} from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder } from '@angular/forms'; import { BibleinfoProviderService } from '../bibleinfo-provider.service'; @Component({ selector: 'app-chapter-navbar', templateUrl: './app-chapter-navbar.html', styleUrls: ['./app-chapter-navbar.css'], }) export class AppChapterNavbar implements OnInit { @Output() changeToNextBook: EventEmitter<any> = new EventEmitter(); @Output() changeToNextChapter: EventEmitter<any> = new EventEmitter(); @Output() changeToPreviousBook: EventEmitter<any> = new EventEmitter(); @Output() changeToPreviousChapter: EventEmitter<any> = new EventEmitter(); indexOfBook: number = 0; chapters: number[] = []; // array of numbers to iterate with ngFor on template maxChapters: number | null = 50; // number of all chapters in chosen Book bibleInfo = this.bibleInfoService.BibleInfo; selectForm = this.formBuilder.group({ bookName: 50, // Value to set deafult book chapters: 0, }); constructor( private router: Router, private bibleInfoService: BibleinfoProviderService, private formBuilder: FormBuilder, ) {} nextBook() { this.changeToNextBook.emit(); } nextChapter() { this.changeToNextChapter.emit(); } goToPreviousBook() { this.changeToPreviousBook.emit(); } goToPreviousChapter() { this.changeToPreviousChapter.emit(); } // Get index of current selected chapter getIndex(event:any ):void { this.indexOfBook = event.target!["selectedIndex"]; } // Use index of current selected chapter to navigate through bible navigate(value: number | string): void { let indexOfChapter: number | string = +value; indexOfChapter = indexOfChapter - 1; this.router.navigateByUrl('bible/'+ this.indexOfBook + '/' + indexOfChapter); } // Use number of chapters from observable to create array of numbers that we use in template in order // to display them with ngFor createSelectChapters(): number[] { let array: number[] = []; for(let i = 1; i <= this.maxChapters!; i++) { array.push(i); } return array; } ngOnInit(): void { // Subscribe to select input to get number of all the chapters of each book specified in the service this.selectForm.get('bookName')?.valueChanges.subscribe(chapters => { this.maxChapters = chapters; this.chapters = this.createSelectChapters(); this.selectForm.get('chapters')?.setValue(1); }); this.chapters = this.createSelectChapters(); } }
/** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ //import './bootstrap'; //import { createApp } from 'vue'; window.Vue = require('vue').default; window.axios = require('axios'); //import Vue from 'vue' //import Buefy from 'buefy' // import 'buefy/dist/buefy.css' //QR Scanner //import VueQrcodeReader from "vue-qrcode-reader"; //for QR CODE Generation //import VueQrcode from '@chenfengyuan/vue-qrcode'; const files = require.context('./', true, /\.vue$/i) files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)) /** * Next, we will create a fresh Vue application instance. You may then begin * registering components with the application instance so they are ready * to use in your application's views. An example is included for you. */ //const app = createApp({}); //import ExampleComponent from './components/ExampleComponent.vue'; //app.component('example-component', ExampleComponent); const app = new Vue({ el: '#app', }); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // Object.entries(import.meta.glob('./**/*.vue', { eager: true })).forEach(([path, definition]) => { // app.component(path.split('/').pop().replace(/\.\w+$/, ''), definition.default); // }); /** * Finally, we will attach the application instance to a HTML element with * an "id" attribute of "app". This element is included with the "auth" * scaffolding. Otherwise, you will need to add an element yourself. */ //app.mount('#app');
// // ViewModel.swift // YouOn // // Created by Айдимир Магомедов on 22.03.2023. // import Foundation protocol ViewModelProtocol { func errorHandler(_ error: Error) } protocol MainViewModelDelegate: AnyObject { func onPlayerFileAppeared(title: String?, author: String?) } protocol MainViewModelProtocol: ViewModelProtocol { func onPopupRightSwipe() func onPopupLeftSwipe() var player: MusicPlayerProtocol? { get } var router: MainRouterProtocol? { get } var delegate: MainViewModelDelegate? { get set } } class MainViewModel: MainViewModelProtocol { var player: MusicPlayerProtocol? var router: MainRouterProtocol? weak var delegate: MainViewModelDelegate? init() { NotificationCenter.default.addObserver(self, selector: #selector(updateValue), name: NotificationCenterNames.playedSong, object: nil) } @objc private func updateValue() { delegate?.onPlayerFileAppeared(title: player?.currentFile.value?.title, author: player?.currentFile.value?.author) } func errorHandler(_ error: Error) { router?.showAlert(title: "Error", error: error, msgWithError: nil, action: nil) } func onPopupRightSwipe() { player?.playPrevious() } func onPopupLeftSwipe() { player?.playNext() } }
#include "../headers/spellCard.h" SpellCard::SpellCard(std::string name, int manaCost, int type, int damage) : Card(std::move(name), manaCost, type), damage(damage) {} int SpellCard::getDamage() const { return damage; } std::shared_ptr<Card> SpellCard::clone() const { return std::make_shared<SpellCard>(name, manaCost, type, damage); } bool SpellCard::playCard(Board &board, bool friendly) { std::cout << "Who do you want to target with this spell?" << std::endl; std::cout << "0 - Opponent\n" << std::endl; std::cout << "i - the ith enemy minion from left\n" << std::endl; std::string answer; std::cin >> answer; while (not isNumber(answer)) { std::cout << "Please enter a valid number" << std::endl; std::cin >> answer; } int idx = stoi(answer); while (idx < OPPONENT_TARGET || (friendly && idx > (int)board.getEnemyMinions().size()) || (!friendly && idx > (int)board.getFriendlyMinions().size())) { std::cout << "Invalid target chosen. Try again." << std::endl; std::cin >> answer; while (not isNumber(answer)) { std::cout << "Please enter a valid number" << std::endl; std::cin >> answer; } idx = stoi(answer); } if (idx == OPPONENT_TARGET) { return true; } idx--; board.damageMinion(idx, damage, !friendly); return false; }
package com.example.demo.service; import com.example.demo.data.entity.Car; import com.example.demo.data.entity.ParkingGarage; import com.example.demo.data.entity.ParkingSlot; import com.example.demo.exception.NotFoundException; import com.example.demo.exception.WrongInputException; import com.example.demo.service.impl.CarServiceImpl; import com.example.demo.service.impl.ParkingGarageServiceImpl; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; @SpringBootTest @Sql({"/createTablesInDb.sql", "/insertGarageIntoDb.sql"}) @ActiveProfiles("test") public class CarServiceImplIT { private final CarServiceImpl carService; private final ParkingGarageServiceImpl parkingGarageService; @Autowired public CarServiceImplIT(CarServiceImpl carService, ParkingGarageServiceImpl parkingGarageService) { this.carService = carService; this.parkingGarageService = parkingGarageService; } @Test @Transactional public void should_return_car_IT() { Car expectedCar = new Car(); expectedCar.setModel("200"); expectedCar.setBrand("Audi"); expectedCar.setParkingStarted(LocalDateTime.now()); expectedCar.setLicensePlate("abc123"); carService.create(expectedCar); Car actualCar = carService.findById(1L); Assertions.assertEquals(expectedCar, actualCar); } @Test @Transactional public void should_return_updated_car_IT() { Car expectedCar = new Car(); expectedCar.setBrand("Audi"); expectedCar.setLicensePlate("abc123"); carService.create(expectedCar); expectedCar.setBrand("Toyota"); carService.updateById(1L, expectedCar); Car actualCar = carService.findById(1L); Assertions.assertEquals(expectedCar, actualCar); } @Test @Transactional public void should_return_wrong_input_exception_IT() { Car expectedCar = new Car(); expectedCar.setLicensePlate("abc123"); carService.create(expectedCar); WrongInputException wrongInputException = Assertions.assertThrows(WrongInputException.class, () -> carService.create(expectedCar)); String expectedMessage = "Car with license plate \"abc123\" already exist."; String actualMessage = wrongInputException.getMessage(); Assertions.assertEquals(expectedMessage, actualMessage); } @Test @Transactional public void should_return_not_found_exception_IT() { ParkingGarage actualGarage = parkingGarageService.findById(1L); ParkingSlot actualSlot = actualGarage.getParkingSlots().get(0); Car expectedCar = new Car(); expectedCar.setLicensePlate("abc123"); expectedCar.setParkingSlot(actualSlot); carService.create(expectedCar); carService.deleteById(1L); NotFoundException notFoundException = Assertions.assertThrows(NotFoundException.class, () -> carService.findById(1L)); String expectedMessage = "Car with ID \"1\" not found."; String actualMessage = notFoundException.getMessage(); Assertions.assertEquals(expectedMessage, actualMessage); } }
import React from 'react' import './CheckoutProduct.css' import { useStateValue } from './StateProvider' function CheckoutProduct({id , image,title,price,rating}) { const [{basket} , dispatch] = useStateValue(); console.log(id , image,title,price,rating); const removeFromBasket = () =>{ // remove item from basket dispatch({ type: "REMOVE_FROM_BASKET", id:id, }); } return ( <div className="checkoutProduct" > <img className="checkoutProduct__image" src={image} /> <div className="checkoutProduct__info"> <p className="checkoutProduct__title">{title}</p> <p className="checkoutProduct__price"> <small>$</small> <strong>{price}</strong> </p> <div className="checkoutProduct__rating"> { Array(rating) .fill() .map((_,i)=> ( <p>&#11088; </p> )) } </div> <button onClick={removeFromBasket}>Remove from Cart</button> </div> </div> ) } export default CheckoutProduct
import { Box, Button, HStack, Image, Link, VStack } from '@chakra-ui/react'; import React from 'react'; import { ReactComponent as Logo } from '../../assets/DecorateKarlo-logo.svg'; class Banner extends React.Component { constructor(props) { super(props); this.state = { categories: [], }; } componentDidMount() { // Uncomment when categories are added to the backend fetch('http://localhost/api/category/all') .then((res) => res.json()) .then((data) => { console.log(data); this.setState({ categories: data }); }); } render() { return ( <VStack bg="red" width="100%" height="100vh" borderBottom="2px" backgroundImage={require('../../assets/banner-image.png')} backgroundSize='cover' backgroundPosition='center center' backgroundRepeat='no-repeat' align="center" justify="center" spacing="50px" > <Logo /> <Title>Beautify Your Homes</Title> <Button backgroundColor="white" textColor="blackAlpha" variant="solid" size="lg" width="300px" borderRadius="50" > <Link href="/categories">SHOP BY CATEGORIES</Link> </Button> <HStack spacing="50px"> {this.state.categories.map((category) => ( <Link key={category.id} href={`/category/${category.id}`} color="white" fontSize="4xl" fontFamily="heading" > {category.category_name} </Link> ))} </HStack> </VStack> ) } } export default Banner; class Title extends React.Component { render() { return ( <Box color="white" fontSize="7xl" fontFamily="heading" fontWeight="bold" textAlign="center" > {this.props.children} </Box> ) } }
function [refinedModel, summary] = refinementPipeline(model, microbeID, infoFilePath, inputDataFolder, translateModels) % This function runs the semi-automatic refinement pipeline on a draft % reconstruction generated by the KBase pipeline or a previously refined % reconstruction. % % USAGE: % % [refinedModel, summary] = refinementPipeline(modelIn, microbeID, infoFilePath, inputDataFolder, translateModels) % % INPUTS % model COBRA model structure to refine % microbeID ID of the reconstructed microbe that serves as the % reconstruction name and to identify it in input tables % infoFilePath File with information on reconstructions to refine % inputDataFolder Folder with input tables with experimental data and % databases that inform the refinement process % translateModels Boolean indicating whether to translate models if they % are in KBase nomenclature (default: true) % % OUTPUTS % refinedModel COBRA model structure refined through AGORA pipeline % summary Structure with description of performed refineemnt % % .. Authors: % - Almut Heinken and Stefania Magnusdottir, 2016-2021 % read the file with organism information infoFile = readInputTableForPipeline(infoFilePath); if ~any(strcmp(infoFile(:,1),microbeID)) warning('No organism information provided. The pipeline will not be able to curate the reconstruction based on gram status.') end tol=0.0000001; % load complex medium constraints = readtable('ComplexMedium.txt', 'Delimiter', 'tab'); constraints=table2cell(constraints); constraints=cellstr(string(constraints)); % Load reaction and metabolite database database=loadVMHDatabase; % translate model if not specified otherwise if nargin < 5 translateModels=true; end %% special case: two biomass reactions in model (bug in KBase?) if length(intersect(model.rxns,{'bio1','bio2'}))==2 model=removeRxns(model,'bio2'); end % if legacy biomass reactions need to be propagated lBio=intersect(model.rxns,{'biomassGramNeg_expanded','biomassGramPos_expanded'}); if ~isempty(lBio) biomassReaction=lBio{1}; else biomassReaction=model.rxns{strncmp(model.rxns,'bio',3)}; end if isempty(biomassReaction) error('Biomass objective function could not be found in the model!') end %% Translate to VMH if it is an untranslated KBase model if translateModels [model,notInTableRxns,notInTableMets] = translateKBaseModel2VMHModel(model,biomassReaction,database); if ~isempty(notInTableRxns) summary.('untranslatedRxns') = notInTableRxns; end if ~isempty(notInTableMets) summary.('untranslatedMets') = notInTableMets; end end %% add some reactions that need to be in every reconstruction essentialRxns={'DM_atp_c_','sink_PGPm1[c]','EX_nh4(e)','NH4tb','Kt1r'}; if ~find(strcmp(model.mets,'pi[e]')) essentialRxns=horzcat(essentialRxns,{'EX_pi(e)','PIabc'}); end for i=1:length(essentialRxns) model = addReaction(model, essentialRxns{i}, 'reactionFormula', database.reactions{find(ismember(database.reactions(:, 1), essentialRxns{i})), 3}, 'geneRule', 'essentialGapfill'); end %% prepare summary file summary.('conditionSpecificGapfill') = {}; summary.('targetedGapfill') = {}; summary.('relaxFBAGapfill') = {}; %% Refinement steps % The following sections include the various refinement steps of the pipeline. % The different functions may have to be run multiple times as the solutions and % reactions added in one section may influence the result of a previously run % section. % _*IMPORTANT:* Note that reactions added in a refinement step may influence % the results of other steps. It is therefore important to run each refinement % step more than once in order to make sure that all functionalities are captured. % This is especially important for steps testing for reconstruction quality._ %% Rebuild biomass objective function for organisms that do not have cell wall [model,removedBioComp,addedReactionsBiomass]=rebuildBiomassReaction(model,microbeID,biomassReaction,database,infoFile); summary.('removedBioComp') = removedBioComp; summary.('addedReactionsBiomass') = addedReactionsBiomass; %% Refine genome annotations [model,addAnnRxns,updateGPRCnt]=refineGenomeAnnotation(model,microbeID,database,inputDataFolder); summary.('addAnnRxns') = addAnnRxns; summary.('updateGPRCnt') = updateGPRCnt; %% perform refinement based on experimental data [model,summary] = performDataDrivenRefinement(model, microbeID, biomassReaction, database, inputDataFolder, summary); %% Reconnect blocked reactions and perform gapfilling to enable growth % connect specific pathways [resolveBlocked,model]=connectRxnGapfilling(model,database); summary.('resolveBlocked') = resolveBlocked; % run gapfilling tools to enable biomass production [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,biomassReaction, biomassReaction,'max',database); summary.('conditionSpecificGapfill') = union(summary.('conditionSpecificGapfill'),condGF); summary.('targetedGapfill') = union(summary.('targetedGapfill'),targetGF); summary.('relaxFBAGapfill') = union(summary.('relaxFBAGapfill'),relaxGF); %% Anaerobic growth-may need to run twice [model,oxGapfillRxns,anaerGrowthOK] = anaerobicGrowthGapfill(model, biomassReaction, database); summary.('anaerobicGapfillRxns') = oxGapfillRxns; summary.('anaerobicGrowthOK') = anaerGrowthOK; if ~anaerGrowthOK [model,oxGapfillRxns,anaerGrowthOK] = anaerobicGrowthGapfill(model, biomassReaction, database); end summary.('anaerobicGapfillRxns') = union(summary.('anaerobicGapfillRxns'),oxGapfillRxns); summary.('anaerobicGrowthOK') = anaerGrowthOK; %% gapfilling for growth on complex medium [AerobicGrowth, AnaerobicGrowth] = testGrowth(model, biomassReaction); if AnaerobicGrowth(1,2) < tol % apply complex medium model = useDiet(model,constraints); % run gapfilling tools to enable biomass production if no growth on % complex medium [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,biomassReaction, biomassReaction,'max',database); summary.('conditionSpecificGapfill') = union(summary.('conditionSpecificGapfill'),condGF); summary.('targetedGapfill') = union(summary.('targetedGapfill'),targetGF); summary.('relaxFBAGapfill') = union(summary.('relaxFBAGapfill'),relaxGF); end %% Stoichiometrically balanced cycles [model, deletedRxns, addedRxns, gfRxns] = removeFutileCycles(model, biomassReaction, database); summary.('futileCycles_addedRxns') = unique(addedRxns); summary.('futileCycles_deletedRxns') = unique(deletedRxns); summary.('futileCycles_gapfilledRxns') = unique(gfRxns); %% Remove unneeded reactions % Delete gap-filled reactions by KBase/ ModelSEED that are no longer needed [model,deletedSEEDRxns]=deleteSeedGapfilledReactions(model,biomassReaction); summary.('deletedSEEDRxns')=deletedSEEDRxns; %% Delete unused reactions that are leftovers from KBase pipeline % Delete transporters without exchanges [model, transportersWithoutExchanges] = findTransportersWithoutExchanges(model); summary.('transportersWithoutExchanges') = transportersWithoutExchanges; % Delete unused exchange reactions [model, unusedExchanges] = findUnusedExchangeReactions(model); summary.('unusedExchanges') = unusedExchanges; %% Perform any gapfilling still needed % in rare cases: gapfilling for anaerobic growth or growth on complex medium still needed for i=1:2 [AerobicGrowth, AnaerobicGrowth] = testGrowth(model, biomassReaction); if AerobicGrowth(1,2) < tol % apply complex medium model = useDiet(model,constraints); % run gapfilling tools to enable biomass production [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,biomassReaction,biomassReaction,'max',database); summary.('conditionSpecificGapfill') = union(summary.('conditionSpecificGapfill'),condGF); summary.('targetedGapfill') = union(summary.('targetedGapfill'),targetGF); summary.('relaxFBAGapfill') = union(summary.('relaxFBAGapfill'),relaxGF); end if AnaerobicGrowth(1,1) < tol [model,oxGapfillRxns,anaerGrowthOK] = anaerobicGrowthGapfill(model, biomassReaction, database); summary.('anaerobicGapfillRxns') = union(summary.('anaerobicGapfillRxns'),oxGapfillRxns); summary.('anaerobicGrowthOK') = anaerGrowthOK; end end %% Nutrient requirements % Needs to be done after deleting Seed-gapfilled reactions but before removing duplicate reactions % Needs to be run repeatedly for some models summary.('addedMismatchRxns')={}; summary.('deletedMismatchRxns')={}; for i = 1:6 [growsOnDefinedMedium,~] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction,inputDataFolder); if growsOnDefinedMedium==0 [model, addedMismatchRxns, deletedMismatchRxns] = curateGrowthRequirements(model, microbeID, database, inputDataFolder); summary.('addedMismatchRxns') = union(summary.('addedMismatchRxns'),addedMismatchRxns); summary.('deletedMismatchRxns') = union(summary.('deletedMismatchRxns'),deletedMismatchRxns); else break end end summary.('definedMediumGrowth')=growsOnDefinedMedium; %% remove duplicate reactions % Will remove reversible reactions of which an irreversible version is also % there but keep the irreversible version. modelTest = useDiet(model,constraints); [modelRD, removedRxnInd, keptRxnInd] = checkDuplicateRxn(modelTest); % test if the model can still grow FBA=optimizeCbModel(modelRD,'max'); if FBA.f > tol summary.('deletedDuplicateRxns') = model.rxns(removedRxnInd); model=modelRD; else modelTest=model; toRM={}; for j=1:length(removedRxnInd) modelRD=removeRxns(modelTest,model.rxns(removedRxnInd(j))); modelRD = useDiet(modelRD,constraints); FBA=optimizeCbModel(modelRD,'max'); if FBA.f > tol modelTest=removeRxns(modelTest, model.rxns{removedRxnInd(j)}); toRM{j}=model.rxns{removedRxnInd(j)}; else modelTest=removeRxns(modelTest, model.rxns{keptRxnInd(j)}); toRM{j}=model.rxns{keptRxnInd(j)}; end end summary.('deletedDuplicateRxns') = toRM; model=removeRxns(model,toRM); end %% remove reactions that were present in draft reconstructions but should not be present according to comparative genomics [model,rmUnannRxns]=removeUnannotatedReactions(model,microbeID,biomassReaction,growsOnDefinedMedium,inputDataFolder); summary.('removedUnannotatedReactions') = rmUnannRxns; %% double-check if gap-filled reactions are really needed anymore % If growth on a defined medium was achieved, use the constrained model [model,summary]=doubleCheckGapfilledReactions(model,summary,biomassReaction,microbeID,database,growsOnDefinedMedium, inputDataFolder); %% Need to repeat experimental data gap-fill because some reactions may be removed now that were there before % perform refinement based on experimental data [model,summary] = performDataDrivenRefinement(model, microbeID, biomassReaction, database, inputDataFolder, summary); %% enable growth on defined medium if still needed [growsOnDefinedMedium,constrainedModel] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction,inputDataFolder); if growsOnDefinedMedium==0 [model, addedMismatchRxns, deletedMismatchRxns] = curateGrowthRequirements(model, microbeID, database, inputDataFolder); summary.('addedMismatchRxns') = union(summary.('addedMismatchRxns'),addedMismatchRxns); summary.('deletedMismatchRxns') = union(summary.('deletedMismatchRxns'),deletedMismatchRxns); [growsOnDefinedMedium,constrainedModel] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction,inputDataFolder); if growsOnDefinedMedium summary.('definedMediumGrowth')=growsOnDefinedMedium; else [model, addedMismatchRxns, deletedMismatchRxns] = curateGrowthRequirements(model, microbeID, database, inputDataFolder); summary.('addedMismatchRxns') = union(summary.('addedMismatchRxns'),addedMismatchRxns); summary.('deletedMismatchRxns') = union(summary.('deletedMismatchRxns'),deletedMismatchRxns); end [growsOnDefinedMedium,constrainedModel] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction,inputDataFolder); if growsOnDefinedMedium==0 % last resort: gap-filling based on relaxFBA [model,addedMismatchRxns] = untargetedGapFilling(model,'max',database,1,1,1); summary.('addedMismatchRxns') = union(summary.('addedMismatchRxns'),addedMismatchRxns); end end %% debug models that cannot grow if coupling constraints are implemented (rare cases) [model,addedCouplingRxns] = debugCouplingConstraints(model,biomassReaction,database); summary.('addedCouplingRxns') = addedCouplingRxns; %% remove futile cycles if any remain [atpFluxAerobic, atpFluxAnaerobic] = testATP(model); if atpFluxAnaerobic>100 % if models can grow on defined medium, this will be abolishd in some % cases -> need to use the constrained model as input [growsOnDefinedMedium,constrainedModel] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction,inputDataFolder); if isnumeric(growsOnDefinedMedium) && growsOnDefinedMedium==1 [model, deletedRxns, addedRxns, gfRxns] = removeFutileCycles(model, biomassReaction, database,{},constrainedModel); else [model, deletedRxns, addedRxns, gfRxns] = removeFutileCycles(model, biomassReaction, database); end summary.('futileCycles_addedRxns') = union(summary.('futileCycles_addedRxns'),unique(addedRxns)); summary.('futileCycles_deletedRxns') = union(summary.('futileCycles_deletedRxns'),unique(deletedRxns)); summary.('futileCycles_gapfilledRxns') = union(summary.('futileCycles_gapfilledRxns'),unique(gfRxns)); end %% perform growth gap-filling if still needed % tmp fix if isfield(model,'C') model=rmfield(model,'C'); model=rmfield(model,'d'); end [AerobicGrowth, AnaerobicGrowth] = testGrowth(model, biomassReaction); if AerobicGrowth(1,2) < tol % apply complex medium model = useDiet(model,constraints); % run gapfilling tools to enable biomass production [model,condGF,targetGF,relaxGF] = runGapfillingFunctions(model,biomassReaction,biomassReaction,'max',database); summary.('conditionSpecificGapfill') = union(summary.('conditionSpecificGapfill'),condGF); summary.('targetedGapfill') = union(summary.('targetedGapfill'),targetGF); summary.('relaxFBAGapfill') = union(summary.('relaxFBAGapfill'),relaxGF); end %% remove duplicate reactions-needs repetition for some microbes % Will remove reversible reactions of which an irreversible version is also % there but keep the irreversible version. % use defined medium if possible, otherwise complex medium if growsOnDefinedMedium==1 [~,modelTest] = testGrowthOnDefinedMedia(model, microbeID, biomassReaction,inputDataFolder); else modelTest = useDiet(model,constraints); end [modelRD, removedRxnInd, keptRxnInd] = checkDuplicateRxn(modelTest); % test if the model can still grow FBA=optimizeCbModel(modelRD,'max'); if FBA.f > tol summary.('deletedDuplicateRxns') = model.rxns(removedRxnInd); model=modelRD; else modelTest=model; toRM={}; for j=1:length(removedRxnInd) modelRD=removeRxns(modelTest,model.rxns(removedRxnInd(j))); modelRD = useDiet(modelRD,constraints); FBA=optimizeCbModel(modelRD,'max'); if FBA.f > tol modelTest=removeRxns(modelTest, model.rxns{removedRxnInd(j)}); toRM{j}=model.rxns{removedRxnInd(j)}; else modelTest=removeRxns(modelTest, model.rxns{keptRxnInd(j)}); toRM{j}=model.rxns{keptRxnInd(j)}; end end summary.('deletedDuplicateRxns') =union(summary.('deletedDuplicateRxns'),toRM); model=removeRxns(model,toRM); end %% Delete sink for petidoglycan if not needed modelTest = removeRxns(model, 'sink_PGPm1[c]'); FBA = optimizeCbModel(modelTest, 'max'); if FBA.f>tol model= modelTest; end %% addd refinement descriptions to model.comments field model = addRefinementComments(model,summary); %% rebuild model model = rebuildModel(model,database,biomassReaction); %% constrain sink reactions model.lb(find(strncmp(model.rxns,'sink_',5)))=-1; %% add periplasmatic space if ~isempty(infoFilePath) if any(strcmp(infoFile(:,1),microbeID)) model = createPeriplasmaticSpace(model,microbeID,infoFile); end end %% end the pipeline refinedModel = model; end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Завдання 2</title> <style> #color-sample { width: 250px; height: 70px; margin: 10px; } </style> </head> <body> <div id="color-sample"></div> <script> /* Завдання Виправте сценарій таким чином, щоб крім зміни кольору div#color-sample в пааграфі під div виводилося повідомлення Колір: #000000 Де #000000 - це значення, кольору фону елементу div#color-sample */ function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } let colorSampleDiv = document.querySelector("#color-sample"); colorSampleDiv.style.backgroundColor = getRandomColor(); colorSampleDiv.innerHTML=`<br><br><br><br>колір:` + `${getRandomColor()}<br>` </script> </body> </html>
package com.hanati.team1.parsers; import com.hanati.team1.src.players.entities.Player; import com.hanati.team1.src.players.repository.PlayerRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class PlayerParser implements Parsable{ private final BaseParser baseParser; private final PlayerRepository playerRepository; @Override public void parse() throws Exception { baseParser.parse( "Player.csv", playerRepository, (csvRecord, list) -> { Player player = new Player(); player.setPlayerId(Long.parseLong(csvRecord.get(0))); player.setPlayerName(csvRecord.get(1)); player.setPlayerNation(csvRecord.get(2)); player.setPlayerBirth(baseParser.toLocalDateTime(csvRecord.get(3))); player.setPlayerHeight(Integer.parseInt(csvRecord.get(4))); player.setPlayerWeight(Integer.parseInt(csvRecord.get(5))); player.setPlayerProfile(csvRecord.get(6)); player.setPlayerYouth(csvRecord.get(7)); player.setPlayerStatus(Integer.parseInt(csvRecord.get(8))); String playerVision = csvRecord.get(9); if(!playerVision.equals("null")) player.setPlayerVision(playerVision); String playerEffort = csvRecord.get(10); if(!playerEffort.equals("null")) player.setPlayerEffort(playerEffort); String playerAdvantage = csvRecord.get(11); if(!playerAdvantage.equals("null")) player.setPlayerAdvantage(playerAdvantage); String playerVideo = csvRecord.get(12); if(!playerVideo.equals("null")) player.setPlayerVideo(playerVideo); list.add(player); } ); } }
import { Outlet } from "react-router-dom"; import Header from "../Header/Header"; import Sidebar from "../Sidebar/Sidebar"; import "./Layout.css"; import { useState } from "react"; import { PropTypes } from "prop-types"; const Layout = ({ menuUpdated }) => { const [sidebarOpen, setSidebarOpen] = useState(false); const toggleSidebar = () => { setSidebarOpen(!sidebarOpen); }; return ( <> <Header onMenuClick={toggleSidebar} menuIsOpen={sidebarOpen} /> <div className={`wrapper_content ${!sidebarOpen ? "" : "move-content"}`}> <Sidebar isOpen={sidebarOpen} menuUpdated={menuUpdated} /> <div className="content"> <Outlet /> </div> </div> </> ); }; Layout.propTypes = { menuUpdated: PropTypes.bool.isRequired, }; export default Layout;
public class OceanbaseCreateTableTest_rangePartition3 extends MysqlTest { public void test_0() throws Exception { String sql="CREATE TABLE employees ( " + "id INT NOT NULL, " + "fname VARCHAR(30), "+ "lname VARCHAR(30), "+ "hired DATE NOT NULL DEFAULT '1970-01-01', "+ "separated DATE NOT NULL DEFAULT '9999-12-31', "+ "job_code INT NOT NULL, store_id INT NOT NULL "+ ") PARTITION BY RANGE (job_code) "+ "( PARTITION p0 VALUES LESS THAN (100), "+ "PARTITION p1 VALUES LESS THAN (1000), "+ "PARTITION p2 VALUES LESS THAN (10000) "+ ")"; MySqlStatementParser parser=new MySqlStatementParser(sql); List<SQLStatement> stmtList=parser.parseStatementList(); SQLStatement stmt=stmtList.get(0); { String result=SQLUtils.toMySqlString(stmt); Assert.assertEquals("CREATE TABLE employees (" + "\n\tid INT NOT NULL," + "\n\tfname VARCHAR(30),"+ "\n\tlname VARCHAR(30),"+ "\n\thired DATE NOT NULL DEFAULT '1970-01-01',"+ "\n\tseparated DATE NOT NULL DEFAULT '9999-12-31',"+ "\n\tjob_code INT NOT NULL,"+ "\n\tstore_id INT NOT NULL"+ "\n)"+ "\nPARTITION BY RANGE (job_code) ("+ "\n\tPARTITION p0 VALUES LESS THAN (100),"+ "\n\tPARTITION p1 VALUES LESS THAN (1000),"+ "\n\tPARTITION p2 VALUES LESS THAN (10000)"+ "\n)",result); } { String result=SQLUtils.toMySqlString(stmt,SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); Assert.assertEquals("create table employees (" + "\n\tid INT not null," + "\n\tfname VARCHAR(30),"+ "\n\tlname VARCHAR(30),"+ "\n\thired DATE not null default '1970-01-01',"+ "\n\tseparated DATE not null default '9999-12-31',"+ "\n\tjob_code INT not null,"+ "\n\tstore_id INT not null"+ "\n)"+ "\npartition by range (job_code) ("+ "\n\tpartition p0 values less than (100),"+ "\n\tpartition p1 values less than (1000),"+ "\n\tpartition p2 values less than (10000)"+ "\n)",result); } Assert.assertEquals(1,stmtList.size()); MySqlSchemaStatVisitor visitor=new MySqlSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("orderBy : " + visitor.getOrderByColumns()); Assert.assertEquals(1,visitor.getTables().size()); Assert.assertEquals(7,visitor.getColumns().size()); Assert.assertEquals(0,visitor.getConditions().size()); } }
<script> import router from '../../../router/router.js' import { UserContext } from '../../../stores/UserContext.js' export default{ props:{ }, data(){ return{ email:"", password:"", validPassword:false, validEmail:false, EmailMessage: "" , passwordMessage: "" , responseFail:"" } }, methods:{ goRegister(){ router.push("/public/register") }, async login() { try { const userStore = UserContext(); const response = await fetch('https://bfbslaravel-production.up.railway.app/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: this.email, password: this.password }), }); if (response.ok) { const data = await response.json() console.log(data); userStore.setId(data.user.id) userStore.setName(data.user.name) userStore.setEmail(data.user.email) userStore.setToken(data.token) if(data.user.admin !== 1){ userStore.setAdmin(false) }else{ userStore.setAdmin(true) } router.push("/private/myRoutines") } else { throw new Error('Error en el login') } } catch (error) { this.responseFail = "Credenciales invalidas" setTimeout(() => { this.responseFail = "" }, 10000); } }, sendForm(e){ e.preventDefault() this.checkPassword() this.checkEmail() if(this.validEmail && this.validPassword){ this.login() } }, checkEmail(){ if(this.email.trim() === "" ){ this.emailMessage = "Este campo no puede estar vacío." return this.validEmail = false }else if(this.email.length < 4 ){ this.emailMessage ="El email debe tener al menos 4 caracteres." return this.validEmail = false } this.emailMessage = "" this.validEmail = true }, checkPassword(){ if(this.password.trim() === "" ){ this.passwordMessage = "Este campo no puede estar vacío." return this.validPassword = false } if(this.password.length < 3) { this.passwordMessage = "La contraseña debe tener al menos 3 caracteres." return this.validPassword = false } this.passwordMessage = "" this.validPassword = true }, goBack() { this.$router.go(-1) } }, watch:{ email: function () { this.checkEmail() }, password: function () { this.checkPassword() }, } } </script> <template> <main> <section class="login_imgpart"> <p class="login_imgpart__title">¡HOLA DE NUEVO!</p> <div class="login_imgpart__registerPart"> <p>¿NO TIENES CUENTA TODAVÍA?</p> <button @click="goRegister">REGISTRATE</button> </div> </section> <section class="login"> <p>LOGIN</p> <form class="login_form"> <span class="error-message">{{ responseFail }}</span> <label for="email" class="hidden_label">Email</label> <input v-model="email" type="text" id="email" name="email" placeholder="Email"> <span :class=" validEmail ? 'accept-message' : 'error-message' " >{{ emailMessage }}</span> <label for="password" class="hidden_label">Contraseña</label> <input v-model="password" type="password" id="password" name="password" placeholder="Contraseña"> <span :class=" validPassword ? 'accept-message' : 'error-message' " >{{ passwordMessage }}</span> <button @click="sendForm">ENTRA</button> <p @click="goBack" class="goBack_btn">Atrás</p> </form> </section> </main> </template> <style scoped> @import url('https://fonts.googleapis.com/css2?family=Goldman:wght@400;700&display=swap'); .error-message { color: red; font-size: 12px; width: 200px; text-align: center; } .hidden_label{ user-select: none; color: transparent; } .accept-message { color: green; font-size: 12px; width: 200px; text-align: center; } .goBack_btn{ font-size: 14px; color:rgba(19, 169, 73, 1); border-bottom: 2px solid rgba(19, 169, 73, 1); cursor: pointer; margin-top: 20px; } main{ display: flex; flex-direction: row; width: 100%; background-color: rgb(3, 3, 3, 1); height: 100vh; } .login_imgpart { display: flex; align-items: center; flex-direction: column; width: 50%; background-image: url(../../../assets/images/fondo_login.png); background-size:cover; background-repeat: no-repeat; background-position: center; color: white; font-family: "Goldman", sans-serif; font-size: 60px; font-style: normal; font-weight: 400; } .login { display: flex; align-items: center; flex-direction: column; width: 50%; color: white; font-family: "Goldman", sans-serif; font-size: 40px; font-style: normal; font-weight: 400; margin-top: 150px; } .login_form{ display: flex; align-items: center; flex-direction: column; margin-top: 5vh; } .login_form input{ border: none; color:white; background-color: rgb(3, 3, 3, 1); border-bottom: 1px solid white; padding-bottom: 10px; margin-bottom: 20px; margin-top: 20px; } .login_form button{ width: 180px; color:white; background-color: rgba(19, 169, 73, 1); border-radius: 10px; height: 40px; border: none; font-family: "Goldman", sans-serif; font-style: normal; font-size: 20px; margin-top: 50px; } .login_form button:hover{ border: 1px solid white; color:rgb(3, 3, 3, 1); background-color: rgba(19, 169, 73, 1); } .login_form input::placeholder{ color:white; font-family: "Goldman", sans-serif; font-style: normal; font-size: 16px; } .login_imgpart__title{ margin-top: 20px; display: flex; align-items: center; justify-content: start; flex-direction: column; font-size: 25px; width: 90%; height: 60%; font-family: "Goldman", sans-serif; font-size: 30px; font-style: normal; font-weight: 400; text-align: center; } .login_imgpart__registerPart{ display: flex; align-items: center; justify-content: center; flex-direction: column; font-size: 15px; gap: 30px; } .login_imgpart__registerPart button{ width: 180px; border: 0.5px solid white; background-color: rgb(3, 3, 3, 1); color: white; border-radius: 10px; height: 40px; font-family: "Goldman", sans-serif; font-style: normal; font-size: 16px; } .login_imgpart__registerPart button:hover{ border: 0.5px solid rgb(3, 3, 3, 1); background-color: white; color: rgb(3, 3, 3, 1); } input:focus{ outline: none; } @media screen and (max-width:540px){ .login_imgpart{ display: none; } .login{ width: 100%; } } </style>
package com.shamniestate.shamniestate.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.appcompat.content.res.AppCompatResources; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.shamniestate.shamniestate.databinding.ItemSearchResultLayBinding; import com.shamniestate.shamniestate.models.PropertyModel; import java.util.List; public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder> { private final Context context; private final List<PropertyModel.PropertyData> data; public SearchResultAdapter(Context context, List<PropertyModel.PropertyData> data) { this.context = context; this.data = data; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(ItemSearchResultLayBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { if (data.get(position) != null) { PropertyModel.PropertyData current = data.get(position); holder.binding.textName.setText(current.getPropertyTitle()); holder.binding.textAddress.setText(" in " + current.getCityName()); // if (current.getPropertyFurnishingStatus().equalsIgnoreCase("0")) // holder.binding.textRooms.setText("Unfurnished Property"); // else // holder.binding.textRooms.setText("Furnished Property"); holder.binding.textRooms.setText(current.getNoOfBedroom() + " BHK"); Glide.with(context).load(current.getPropertyImage()) .placeholder(AppCompatResources.getDrawable(context, com.denzcoskun.imageslider.R.drawable.loading)) .into(holder.binding.imageProperty); holder.binding.textPrice.setText("₹ " + current.getPropertyMaxPrice()); holder.binding.textPricePerUnit.setText("@ " + current.getPropertyPricePerUnit() + "/ " + current.getAreaUnitType()); holder.binding.textArea.setText(current.getMaxUnitArea() + " " + current.getAreaUnitType()); holder.binding.textPincode.setText("Pincode: " + current.getPropertyZipCode()); holder.binding.textLocality.setText(current.getLocalityName()); holder.binding.textPropertyCode.setText("Property Code: " + current.getPropertyCode()); holder.binding.recyclerView.setAdapter(new SearchResultAmenityAdapter(context, current.getAmenitiesDataArrayList())); holder.binding.recyclerView.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)); } } @Override public int getItemCount() { return data.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { public ItemSearchResultLayBinding binding; public ViewHolder(@NonNull ItemSearchResultLayBinding binding) { super(binding.getRoot()); this.binding = binding; } } }
return { -- NOTE: Code Autocompletion { "hrsh7th/nvim-cmp", event = "InsertEnter", dependencies = { { "saadparwaiz1/cmp_luasnip" }, { "hrsh7th/cmp-nvim-lsp" }, { "hrsh7th/cmp-path" }, }, config = function() local cmp = require("cmp") cmp.setup({ snippet = { expand = function(args) vim.snippet.expand(args.body) end, }, completion = { completeopt = "menu,menuone,noinsert" }, -- NOTE: Autocomplete Keymaps mapping = cmp.mapping.preset.insert({ -- Select the [n]ext item ["<C-n>"] = cmp.mapping.select_next_item(), ["<Tab>"] = cmp.mapping.select_next_item(), -- Select the [p]revious item ["<C-p>"] = cmp.mapping.select_prev_item(), ["<S-Tab>"] = cmp.mapping.select_prev_item(), -- Scroll the documentation window [b]ack / [f]orward ["<C-b>"] = cmp.mapping.scroll_docs(-4), ["<C-f>"] = cmp.mapping.scroll_docs(4), -- Accept ([y]es) the completion. ["<C-y>"] = cmp.mapping.confirm({ select = true }), ["<CR>"] = cmp.mapping.confirm({ select = true }), -- Manually trigger a completion from nvim-cmp. ["<C-Space>"] = cmp.mapping.complete({}), }), sources = { { name = "nvim_lsp" }, { name = "path" }, { name = "buffer" }, }, }) end, }, }
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; export abstract class HttpService { private API_URL = environment.API_URL; private headers = new HttpHeaders().set('Content-Type', 'application/json'); constructor(protected httpClient: HttpClient) { } get(endpoint: string, params: any): Observable<any> { return this.httpClient.get( this.API_URL + endpoint, { headers: this.headers, params: params } ); } post(endpoint: string, body: any): Observable<any> { return this.httpClient.post( this.API_URL + endpoint, body, { headers: this.headers } ); } put(endpoint: string, body: any) { return this.httpClient.put( this.API_URL + endpoint, body, { headers: this.headers } ); } delete(endpoint: string) { return this.httpClient.delete( this.API_URL + endpoint, { headers: this.headers } ); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Vote</title> <script src="/assets/vue.js"></script> <script src="/assets/axios.min.js"></script> <script src="/assets/lodash.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script src="/assets/vue-router.js"></script> </head> <body> <div id="app"> <router-view></router-view> </div> <script> var api = axios.create({ baseURL: "/api" }); var Index = { template: ` <div> <div v-if="user"> <h2>欢迎,<img :src="user.avatar" style="width:40px;height:40px;"> {{user.name}}</h2> <button @click="logout">退出</button> <router-link to="/create">创建投票</router-link> </div> <div v-else> <router-link to="/login">登录</router-link> <router-link to="/register">注册</router-link> </div> </div> `, data() { return { user: null }; }, methods: { async logout() { await api.get("/logout"); this.user = null; } }, async mounted() { let response = await api.get("/userInfo"); let data = response.data; if (data.code == 1) { this.user = data.user; } } }; var CreateVote = { template: ` ` }; var ViewVote = { template: ` ` }; var Register = { template: ` <div> <h3>注册</h3> <input placeholder="用户名" type="text" v-model="name"> <input placeholder="电子邮箱" type="email" v-model="email"> <input type="file" placeholder="头像" accept=".jpg, .jpeg, .png" @change="uploadAvatar"> <input placeholder="密码" type="password" v-model="pwd"> <button @click="register">注册</button> </div> `, methods: { async register() { let data = new FormData(); data.append("name", this.name); data.append("pwd", this.pwd); data.append("email", this.email); data.append("avatar", this.avatar); let response = (await api.post("/register", data)).data; if (response.code == 1) { this.$router.push("/"); } else { alert(response.msg); } }, uploadAvatar(e) { this.avatar = e.target.files[0]; } }, data() { return { name: "", email: "", pwd: "", avatar: "", avatar: "" }; } }; var Login = { template: ` <div> <h3>登陆</h3> <input placeholder="用户名" type="text" v-model="Info.name"> <input placeholder="密码" type="password" v-model="Info.pwd"> <button @click="login">登陆</button> <div> <router-link to="/forgot">忘记密码</router-link> </div> </div> `, methods: { async login() { let req = (await api.post("/login", this.Info)).data; if (req.code == 1) { alert(req.msg); // this.msg = req.msg // this.code = req.cod this.$router.push("/"); } else { alert(req.msg); } // try { // await api.post('/login', this.Info) // }catch(e) { // alert(e.response.data.msg) // } } }, data() { return { Info: { name: "", pwd: "" } // msg: "", // code: "", }; } }; var Forgot = { template: ` <div> 请输入您注册时的邮箱:<br/> <input type='text' v-model="Info.email"> <button @click="changePass">确定</button> </div> `, methods: { async changePass() { let res = (await api.post("/forgot", this.Info)).data; if (res.code == 1) { alert(res.msg); this.$router.push("/"); } else { alert(res.msg); } } }, data() { return { Info: { email: "" } }; } }; var ChangePass = { template: ` <div> 重置密码 <input type="password" v-model="Info.pwd"> <button @click="change">确定</button> </div> `, async mounted() { let res = (await api.get("/changePass/" + this.$route.params.token)) .data; if (res.code == -1) { alert(res.msg); this.$router.push("/"); } }, methods: { async change() { let res = (await api.post( "/changePass/" + this.$route.params.token, this.Info )).data; alert(res.msg); this.$router.push("/"); } }, data() { return { Info: { pwd: "" } }; } }; var CreateVote = { template: ` <div id="app"> <h2>创建投票</h2> <div><input type="text" placeholder="标题" v-model="voteInfo.title" required></div> <div><input type="text" placeholder="问题描述" v-model="voteInfo.desc"></div> <div v-for="(option, idx) of voteInfo.options"> <input type="text" v-model="voteInfo.options[idx]" :placeholder="'选项'+ (idx + 1)" > <button @click="voteInfo.options.splice(idx, 1)">-</button> </div> <div><button @click="voteInfo.options.push('')">添加选项</button></div> <div>截止时间: <input type="datetime-local" v-model="voteInfo.deadline"></div> <div>匿名投票: <label>是<input type="radio" v-model="voteInfo.anonymous" value="1"></label> <label>否<input type="radio" v-model="voteInfo.anonymous" value="0" checked></label> </div> <div> <select v-model="voteInfo.singleSelect"> <option value="1">单选</option> <option value="0">多选</option> </select> </div> <button @click="submit">创建投票</button> </div> `, data() { return { voteInfo: { title: "", desc: "", options: ["", ""], deadline: new Date(Date.now() + 86400000) .toISOString() .slice(0, 16), anonymous: "0", singleSelect: "1" } }; }, methods: { async submit() { let res = (await api.post("/vote", this.voteInfo)).data; if (res.code) { alert(res.msg); this.$router.push("/vote/" + res.id); } else { alert(res.msg); } } } }; var ViewVote = { template: ` <div id="app"> <div> <h1>{{voteInfo.title}}</h1> <h3>{{voteInfo.desc}}</h3> </div> <ul class="options" style="cursor: pointer;"> <li @click="(code == 0) && vote(option.id)" v-for="option in options"> {{option.content}} {{code == 1 ? '/' +summary[option.id].length+'票' : ''}} <div v-if="code==1" class="ratio" style="height:3px; background-color: red;" :style="{width:ratioSummary[option.id] * 100 + '%'}"></div> </li> </ul> </div> `, watch: { $route(to, from) { this.init() } }, async mounted() { this.init() }, computed: { summary() { let obj = _.mapValues(_.keyBy(this.options, "id"), () => []); return { ...obj, ..._.groupBy(this.voteups, "optionid") }; }, ratioSummary() { return _.mapValues(this.summary, val => { if (val.length == 0) return 0; return val.length / this.voteups.length; }); } }, methods: { async init() { // let query = location.search // .slice(1) // .split("&") // .reduce((obj, pair) => { // var [key, val] = pair.split("="); // obj[key] = val; // return obj; // }, {}); var id = this.$route.params.id let res = await api.get("/vote/" + id); console.log(res) let data = res.data; console.log(data); this.code = data.code; if (this.code == 1) { this.voteups = data.voteups; console.log(data.voteups); //this.socket = io('ws://www.xx.com/voteVue.html') this.socket = io(); this.socket.on("new vote", data => { console.log(data); this.voteups.push(data.data.voteups); }); } this.voteInfo = data.voteInfo; this.options = data.options; }, async vote(optionid) { let req = await api.post("/voteup", { optionid, voteid: this.voteInfo.id }); let data = req.data; console.log(req); if (data.code != 0) { if (data.code == 1) { this.code = data.code; this.voteups = data.voteups; alert("投票成功"); } else { alert("您已投过"); } } else { alert("你还未登录"); setTimeout(() => { location.href = "/"; }, 3000); } } }, data() { return{ voteInfo: {}, options: [], voteups: [], code: 0 } } }; var router = new VueRouter({ routes: [ { path: "/", component: Index }, { path: "/create", component: CreateVote }, { path: "/vote/:id", component: ViewVote }, { path: "/login", component: Login }, { path: "/register", component: Register }, { path: "/changePass/:token", component: ChangePass }, { path: "/forgot", component: Forgot } ] }); var app = new Vue({ el: "#app", router }); </script> </body> </html>
import { createEnv } from "@t3-oss/env-nextjs"; import { z } from "zod"; export const env = createEnv({ server: { GOOGLE_CLIENT_ID: z.string().min(1), GOOGLE_CLIENT_SECRET: z.string().min(1), GITHUB_CLIENT_ID: z.string().min(1), GITHUB_CLIENT_SECRET: z.string().min(1), EMAIL_SERVER_HOST: z.string().min(1), EMAIL_SERVER_PORT: z.string().min(1).default("0"), EMAIL_SERVER_USER: z.string().min(1), EMAIL_SERVER_PASSWORD: z.string().min(1), EMAIL_FROM: z.string().min(1), NEXTAUTH_SECRET: process.env.NODE_ENV === "production" ? z.string().min(1) : z.string().min(1).optional(), NEXTAUTH_URL: z.preprocess( // This makes Vercel deployments not fail if you don't set NEXTAUTH_URL // Since NextAuth.js automatically uses the VERCEL_URL if present. (str) => process.env.VERCEL_URL ?? str, // VERCEL_URL doesn't include `https` so it cant be validated as a URL process.env.VERCEL ? z.string() : z.string().url(), ), }, client: {}, runtimeEnv: { NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET, NEXTAUTH_URL: process.env.NEXTAUTH_URL, GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET, EMAIL_SERVER_HOST: process.env.EMAIL_SERVER_HOST, EMAIL_SERVER_PORT: process.env.EMAIL_SERVER_PORT, EMAIL_SERVER_USER: process.env.EMAIL_SERVER_USER, EMAIL_SERVER_PASSWORD: process.env.EMAIL_SERVER_PASSWORD, EMAIL_FROM: process.env.EMAIL_FROM, }, skipValidation: !!process.env.CI || !!process.env.SKIP_ENV_VALIDATION, });
# Jornada <div align="center"> <img width=80% src="https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/assets/112354693/2e82b97f-8cba-4bc1-8883-ac81c8957023"> </div> - **Studio:** D&A - AWS - **Squad:** 3 - **Turma:** T1-NOV-23 <hr> # Sobre mim <div align="center"> <img width=50% src="https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/assets/112354693/b363b8f2-d9c5-466b-aceb-8204802daa6b"> </div> <br> - **Nome:** Ednaldo Luiz de Lira Júnior - **Endereço:** Recife - PE - **Hobbies:** Programar pra mim é mais que uma profissão, é um hobbie e também sou interessado por Astronomia e temas sobre o Universo. - **Formação:** Análise e Desenvolvimento de Sistemas - **Status:** Cursando 4º Período - **Experiência:** Desenvolvedor Back-end Júnior Java - 2 meses - **Projetos em Destaque:** Realizo projetos pessoais e em equipe com frequência, aonde já atuei tanto com desenvolvimento Back-end e Front-end. Posso destacar: **[To-Day-list](https://github.com/EdnaldoLuiz/to-day-list)**, **[HelpUp](https://github.com/EdnaldoLuiz/HELP_UP_PROJECT)**, **[TaskMe-CRUD](https://github.com/EdnaldoLuiz/TaskMe-CRUD)** - **Tecnologias:** <div align="center"> <img src="https://skillicons.dev/icons?i=java,spring,git,mysql,angular" /> </div> - **Mais sobre mim:** <div align="center"> [![Portfolio](https://img.shields.io/badge/Portfolio-%23000000.svg?style=for-the-badge&logo=vercel&logoColor=#FF7139)](https://ednaldo-luiz.vercel.app/projetos) [![LinkedIn](https://img.shields.io/badge/linkedin-%230077B5.svg?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/ednaldoluiz) </div> --- # Sprints ## Sprint 1 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-1)** **Responsavel:** Luis Gustavo Tomaz Silva **[→](https://github.com/gus-phys)** ![](https://progress-bar.dev/100/) - [x] Linux para desenvolvedores - [x] Git e GitHub do básico ao avançado - [x] Exercícios 1/10 ## Sprint 2 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-2)** **Responsavel:** Daniel Dalmas de Oliveira **[→](https://www.linkedin.com/in/danieldalmas)** ![](https://progress-bar.dev/100/) - [x] SQL para análise de dados - [x] Big Data fundamentos 3.0 - [x] Exercícios 2/10 ## Sprint 3 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-3)** ![](https://progress-bar.dev/100/) **Responsavel:** Guilherme Konishi Yoshihara **[→](https://www.linkedin.com/in/guilherme-konishi)** - [x] Python - [x] Exercícios 3/10 ## Sprint 4 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-4)** ![](https://progress-bar.dev/100/) **Responsavel:** Carlos Eduardo **[→](https://www.linkedin.com/in/carlos-eduardo-f-souza-a834961bb/)** - [x] Python Funcional - [x] Docker para Desenvolvedores - [x] Estatística Descritiva com Python - [x] Exercícios 4/10 ## Sprint 5 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-5)** ![](https://progress-bar.dev/100/) **Responsavel:** Avner Dal Bosco **[→](https://br.linkedin.com/in/avnerdalbosco)** - [x] 3 Cursos AWS Partner - [x] Curso Exam Prep AWS - [x] AWS Cloud Quest - [x] Exercícios 5/10 ## Sprint 6 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-6)** ![](https://progress-bar.dev/100/) **Responsavel:** Decio Michellis Neto **[→](https://www.linkedin.com/in/décio-michellis-neto-884868208)** - [x] 13 Cursos AWS Skill Builder - [x] Exercícios 6/10 ## Sprint 7 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-7)** ![](https://progress-bar.dev/100/) **Responsavel:** Gabriel de Lima Arruda **[→](https://www.linkedin.com/in/gabriel-arruda-7b0b61223)** - [x] Curso Hadoop - [x] Curso Apache Pyspark - [x] Exercícios 7/10 - [x] Desafio final 1/4 ## Sprint 8 **[→]()** ![](https://progress-bar.dev/100/) **Responsavel:** Gabriel de Lima Arruda **[→](https://www.linkedin.com/in/gabriel-arruda-7b0b61223)** - [x] Exercícios 8/10 - [x] Desafio final 2/4 ## Sprint 9 **[→]()** ![](https://progress-bar.dev/100/) **Responsavel:** Isabela Ramos Braga Novaes Romeu **[→](https://www.linkedin.com/in/isabelaromeu)** - [x] Exercícios 9/10 - [x] Desafio final 3/4 ## Sprint 10 **[→]()** ![](https://progress-bar.dev/100/) **Responsavel:** Telma **[→]()** - [x] Exercícios 10/10 - [x] Curso Quicksight - [x] Desafio final 4/4 --- # Outros ## Cultura Ágil e Segurança **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/cultura-agil-e-seguranca)** ![](https://progress-bar.dev/100/) - [x] Métodos ágeis de A a Z - [x] Segurança em Aplicações WEB ## Conteúdo Complementar **[→]()** ![](https://progress-bar.dev/0/) --- # Meu aprendizado ## Sprint 1 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-1)** > Durante a Sprint 1 eu pude aprender coisas novas que serão uteis na minha jornada e melhorar em temas que eu já conhecia, apesar de já usar o Git e o Linux, pude me aprofundar mais descobrindo comandos novos para agregar na minha carreira. Mas meu aprendizado não se resumiu apenas a conteúdo técnico, acredito que meu maior ganho foi usar a metodologia Scrum e poder desenvolver minhas softskills interagindo com meus colegas da bolsa e com o instrutor Luis Gustavo, a minha forma de se relacionar com as pessoas é algo que sempre busco melhorar. ### Aprendizados - Softskills - Scrum - Git - Linux --- ## Sprint 2 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-2)** > Durante essa Sprint eu puder ter uma imersão no mundo de dados dando passos mais longos, meu conhecimento em SQL era básico e pude me aprofundar mais conhecendo querys avançadas, mas ainda tenho muito que aprender e isso me motiva. Tive a oportunidade de realizar um curso da DSA sobre Big Data, aonde foi meu primeiro contato com dados e conceitos usados na engenharia de dados, desde que ingressei no mundo de TI sempre estive focado em engenharia de software, mas dessa vez pude sair dessa bolha e conhecer novos temas, e confesso que adorei. Gostaria de agradecer muito ao Daniel que foi o responsavel por essa sprint, que sempre esteve ajudando tirando duvidos no privado do Teams e nas dailies, ter um feedback sobre seu desenvolvimento é muito importante ### Aprendizados - SQL - PgAdmin - Big Data - DBeaver - Softskills --- ## Sprint 3 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-3)** > Durante esta Sprint, pude aprofundar-me mais em Python, conhecendo desde a sua sintaxe até as suas principais vantagens na área de dados. Foi uma Sprint um pouco longa, então precisei levar um pouco mais de tempo para absorver todo o conhecimento, mas estou realizando projetos além dos exercícios para poder fixar melhor o conteúdo. Gostaria de agradecer ao responsável por esta Sprint, o Guilherme, que sempre esteve me ajudando com as minhas dúvidas nos exercícios e nas entregas. ### Aprendizados - Python - Algoritimos - Estrutura de dados - ETL com Python --- ## Sprint 4 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-4)** > Eu Gostei bastante dessa Sprint, acredito que o conteúdo dela foi o meu Favorito, pelo fato de já estar com muita vontade de reforçar meu aprendizado com Docker, eu já realizei um curso de Docker na Alura mas fiquei com a sensação que não fixei bem tudo que aprendi, mas durante essa Sprint essa sensação foi embora, pude criar containers de diversos modos a realização do exercícios foram coisas que me ajudaram bastante. Gostaria de agradecer ao Carlos que sempre esteve respondendo as minhas dúvidas e curiosidades e aos otimos conselhos dados durante essa Sprint. ### Aprendizados - Python - Dockerhub - Docker e Containers - Kubernetes - Estatísticas - Organização --- ## Sprint 5 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-5)** > Essa Sprint foi muito diferente das outras de uma forma positiva, a metodologia de ensino mudou mas adorei realizar cursos no AWS Skill Builder, já que essa é uma das minhas metas para 2024 vou aproveitar bastante os cursos da plataforma e do AWS Educate buscando realizar o maximo de cursos possivel. Gostaria de agradecer ao Avner por ter sempre se disponibilizado a ajudar o pessoal com problemas no console e pelas dailies separadas por Squads. ### Aprendizados - Cloud - Conceitos AWS - Console AWS - Parceiros AWS --- ## Sprint 6 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-6)** > Essa Sprint foi bastante evolutiva como um complemento da Sprint anterior, podendo avançar mais ainda nos principais serviços da AWS para dados e ter uma visão do que será necessario para o desafio final e tambem conhecer mais na pratica o ambiente da AWS pelos exercicios promovidos pela Sprint. Gostaria de agradecer ao Decio por ter explicado alguns serviços da AWS nas dailies, que foi um diferencial que notei em relação as outras Sprints e sem dúvidas ajudou bastante a min e ao pessoal ### Aprendizados - AWS Quicksight - AWS Redshift - Fundamentos do Data Analytics na AWS - Conceitos AWS - Console AWS --- ## Sprint 7 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-7)** > Essa Sprint foi o maior ponto de entrada para o mundo de Big Data, eu pude conhecer alguns dos serviços mais famosos no mundo de dados e bastante requisitados em grandes empresas e utilizar novamente serviços no ambiente da AWS como o Glue, Lake formation, IAM e outros, e tambem pude dar inicio ao principal desafio do programa de bolsas, reforçando os conhecimentos em Python e Docker. ### Aprendizados - Hadoop - MapReduce - Pyspark - Big Data - AWS Glue --- ## Sprint 8 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-8)** > Como nessa sprint não tivemos cursos foi o momento para dedicar meus estudos para a certificação da AWS, realizando os cursos adicionais na Udemy e alguns exames para a prova. Assim como o material da sprint 8 com os videos no Youtube sobre os serviços da AWS necessarios para a sprint. ### Aprendizados - Apache Spark - AWS Quicksight - AWS Athena - AWS Glue --- ## Sprint 9 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-9)** > Como nessa sprint não tivemos cursos foi o momento para dedicar meus estudos para a certificação da AWS, realizando os cursos adicionais na Udemy e alguns exames para a prova. E tambem aprofundar meus estudos na modelagem de dados com o DBeaver e seus conceitos. A Isabela foi bastante clara de forma detalhada sobre o que deveria ser entregue e a quantidade de dailies proposta separadamente foi maior, ponto bastante positivo em minha opinião ### Aprendizados - DBeaver - Modealgem Relacional - Modealgem Dimensional - AWS Glue - S3 --- ## Sprint 10 **[→](https://github.com/EdnaldoLuiz/AWS-Cloud-Data-Engineering-Compass-UOL/tree/main/sprint-10)** > Essa foi a Sprint final, eu só tenho a agradecer essa oportunidade de aprendizado que me foi dada, não são muitos que tem essa chance, sou grato imensamente pela Compass ter sido a minha primeira oportunidade, e irei levar todo esse aprendizado e experiencia para a minha vida, nunca é um adeus :) ### Aprendizados - Quicksight - AWS - Athena - S3 ---
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <title>{% block title %}My Site{% endblock %}</title> <style> body { font-family: Arial, sans-serif; } </style> </head> <body> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand rounded" href="#">PixelVision</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item bg-primary rounded mx-4 my-1"> <a class="nav-link text-white" aria-current="page" href="/">Home</a> </li> {% if user.is_authenticated %} <li class="nav-item bg-primary rounded mx-4 my-1"> <a class="nav-link text-white" href="/profile">Account</a> </li> <li class="nav-item bg-primary rounded mx-4 my-1"> <a class="nav-link text-white" href="/images">Images</a> </li> <li class="nav-item bg-primary rounded mx-4 my-1"> <a class="nav-link text-white" href="/password_change">Change Password</a> </li> {%else%} <li class="nav-item bg-primary rounded mx-4 my-1"> <a class="nav-link text-white" href="/about">About</a> </li> <li class="nav-item bg-primary rounded mx-4 my-1"> <a class="nav-link text-white" href="/signup">Sign Up</a> </li> {%endif%} </ul> {% if user.is_authenticated %} <span class="navbar-text mx-4 my-1 text-dark border border-dark rounded-4 p-2">Welcome, {{user.username}}</span> <form class="d-flex" role="search" method="get" action="/logout"> <button class="btn btn-outline-primary" type="submit">Logout</button> </form> {%else%} <form class="d-flex my-1" role="search" method="get" action="/login"> <button class="btn btn-outline-primary" type="submit">Login</button> </form> {% endif %} </div> </div> </nav> {% block content %}<h1 class="text-center m-5 border border-dark">Page Content</h1>{% endblock %} <footer class="bg-light mt-5"> <div class="container"> <div class="row"> <div class="col-md-4 p-3"> <h5>Contact Us</h5> <p>Email: [email protected]</p> <p>Phone: +91 8938943158</p> </div> <div class="col-md-4 p-3"> <h5>Quick Links</h5> <ul class="list-unstyled "> <li><a class="text-decoration-none text-dark text-decoration-underline" href="/">Home</a></li> <li><a class="text-decoration-none text-dark text-decoration-underline" href="/about">About</a></li> <li><a class="text-decoration-none text-dark text-decoration-underline" href="/profile">Account</a></li> <li><a class="text-decoration-none text-dark text-decoration-underline" href="/images">Images</a></li> </ul> </div> <div class="col-md-4 p-3"> <h5>Follow Us</h5> <a href="#"><i class="fab fa-facebook text-dark"></i></a> <a href="#"><i class="fab fa-twitter"></i></a> <a href="#"><i class="fab fa-linkedin"></i></a> </div> </div> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </body> </html>
package com.kochipek.noteapp.View; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import androidx.recyclerview.widget.GridLayoutManager; import com.kochipek.noteapp.Adapter.NoteAdapter; import com.kochipek.noteapp.R; import com.kochipek.noteapp.SharedPreferencesHelper; import com.kochipek.noteapp.ViewModel.NotesViewModel; import com.kochipek.noteapp.databinding.FragmentNotesFeedBinding; import java.util.ArrayList; public class NotesFeedFragment extends Fragment { private FragmentNotesFeedBinding binding; private NoteAdapter adapter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = FragmentNotesFeedBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Check if the user is enter the app for the first time if (!SharedPreferencesHelper.isTutorialCompleted(requireActivity())) { startShowcaseWalkthrough(); } NotesViewModel notesViewModel = new ViewModelProvider(requireActivity()).get(NotesViewModel.class); NavController navController = NavHostFragment.findNavController(NotesFeedFragment.this); adapter = new NoteAdapter(new ArrayList<>(), (MainActivity) requireActivity()); // Initialize adapter with empty list binding.lowButton.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { binding.highButton.setChecked(false); binding.dateButton.setChecked(false); notesViewModel.lotToHigh.observe(getViewLifecycleOwner(), notes -> adapter.updateNotes(notes)); } }); binding.highButton.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { binding.lowButton.setChecked(false); binding.dateButton.setChecked(false); notesViewModel.highToLow.observe(getViewLifecycleOwner(), notes -> adapter.updateNotes(notes)); } }); binding.dateButton.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { binding.lowButton.setChecked(false); binding.highButton.setChecked(false); notesViewModel.filterbydate.observe(getViewLifecycleOwner(), notes -> adapter.updateNotes(notes)); } }); notesViewModel.getAllNotes.observe(getViewLifecycleOwner(), notes -> { adapter.updateNotes(notes); if (notes.isEmpty()) { binding.noNotes.setVisibility(View.VISIBLE); binding.imageView2.setVisibility(View.VISIBLE); binding.recyclerView.setVisibility(View.GONE); } else { binding.recyclerView.setVisibility(View.VISIBLE); binding.noNotes.setVisibility(View.GONE); binding.imageView2.setVisibility(View.GONE); binding.recyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2)); binding.recyclerView.setAdapter(adapter); } }); binding.floatingActionButton.setOnClickListener(v -> navController.navigate(R.id.action_notesFeedFragment_to_addNoteFragment)); } private void startShowcaseWalkthrough() { ((MainActivity) requireActivity()).startShowcaseWalkthrough(); SharedPreferencesHelper.setTutorialCompleted(requireContext(), true); // Marking tutorial as completed } }
#' Compute Entropy Index #' #' @param .data [tibble][tibble::tibble-package] #' @param .cols [`tidy-select`](https://tidyselect.r-lib.org/reference/language.html) #' Columns to compute the measure with. Must be at least 2 columns. If more than 2, treats #' first column as first group and sum of other columns as second. #' @param .name name for column with entropy index. Leave missing to return a vector. #' @param .comp Default is FALSE. FALSE returns the sum, TRUE returns the components. #' #' @return a [tibble][tibble::tibble-package] or numeric vector if .name missing #' @export #' #' @md #' @concept evenness #' @examples #' data("de_county") #' ds_entropy(de_county, c(pop_white, starts_with('pop_'))) #' ds_entropy(de_county, starts_with('pop_'), 'entropy') ds_entropy <- function(.data, .cols, .name, .comp = FALSE){ .cols <- rlang::enquo(.cols) if (missing(.name)) { .name <- 'v_index' ret_t <- FALSE } else { ret_t <- TRUE } sub <- .data %>% drop_sf() %>% dplyr::select(!!.cols) if (ncol(sub) <= 1) { stop('.cols refers to a single column') } sub <- sub %>% dplyr::rowwise() %>% dplyr::mutate(.total = sum(dplyr::c_across(everything()))) %>% dplyr::ungroup() .T <- sum(sub$.total) .P <- sum(sub[[1]])/.T .E <- .P * plog (1/.P) + (1 - .P) * plog (1/(1 - .P)) out <- sub %>% dplyr::mutate(.p = pick_n(1)/.data$.total, .e = .data$.p * plog (1/.data$.p) + (1 - .data$.p) * plog (1/(1 - .data$.p))) %>% rowwise_if(.comp) %>% dplyr::mutate(!!.name := sum(.data$.total * (.E * .data$.e))/(.E * .T) ) %>% dplyr::pull(!!.name) if (ret_t) { .data %>% dplyr::mutate(!!.name := out) %>% relocate_sf() } else { out } } #' @rdname ds_entropy #' @param ... arguments to forward to ds_entropy from entropy #' @export entropy <- function(..., .data = dplyr::across(everything())) { ds_entropy(.data = .data, ...) }
<div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-block"> <h2 class="card-title">Adicionando sócio</h2> <h4 class="card-subtitle" style="margin-bottom: 30px;"> Informe pelo menos um sócio, que será o responsável pela empresa. </h4> <div class="clear"></div> <p>Os campos marcados com <b>(*)</b> são de preenchimento obrigatório.</p> <form novalidate [formGroup]="formSocio" (ngSubmit)="formSocio_submit(content)"> <div class="col-lg-12"> <div class="form-group" [ngClass]="{ 'has-danger': cpf.invalid && (cpf.dirty || cpf.touched), 'has-success': cpf.valid && (cpf.dirty || cpf.touched) }"> <label class="titulo-input">CPF (*)</label> <input type="text" class="form-control" formControlName="cpf" placeholder="Digite apenas números" [textMask]="{mask: cpfMask}" required> <div class="form-control-feedback" *ngIf="cpf.errors && (cpf.dirty || cpf.touched)"> <p *ngIf="cpf.errors.required">Você precisa informar o CPF para continuar.</p> </div> </div> </div> <div class="col-lg-12"> <div class="form-group" [ngClass]="{ 'has-danger': nome.invalid && (nome.dirty || nome.touched), 'has-success': nome.valid && (nome.dirty || nome.touched) }"> <label class="titulo-input">Nome (*)</label> <input type="text" class="form-control" formControlName="nome" placeholder="Digite no nome do sócio" required> <div class="form-control-feedback" *ngIf="nome.errors && (nome.dirty || nome.touched)"> <p *ngIf="nome.errors.required">Informe o nome do sócio que será adicionado.</p> </div> </div> </div> <div class="row" class="col-lg-6"> <div class="form-actions"> <button type="submit" [disabled]="!formSocio.valid" class="btn btn-success"><i class="fa fa-check"></i> Adicionar</button> </div> </div> </form> <h4 class="margin">Sócios já adicionados</h4> <div class="alert" *ngIf="itensOut == null || itensOut == ''"> Ainda não existem sócios cadastrados. </div> <div class="item" *ngFor="let item of itensOut; let i = index"> <div class="excluir" title="Retirar sócio da lista" (click)="item_delete(i)">X</div> {{item.nome}} <div class="subtitulo">{{item.cpf}}</div> </div> </div> </div> </div> </div> <!-- modal --> <div class="row"> <div class="col-md-6"> <ng-template #content let-c="close" let-d="dismiss"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{tituloOut}}</h4> <button type="button" class="close" aria-label="Close" (click)="d('Cross click')"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>{{mensagemOut}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" (click)="c('Close click')">{{botaoOut}}</button> </div> </div> </ng-template> </div> </div>
<?php /** * Class: CookieManager * Version: 0.3 * This class handle cookie information. * TODO - Remove the global $Cookie variable * * requires: * - none. * */ namespace igotweb_wp_mp_links\igotweb\fwk\model\manager; use igotweb_wp_mp_links\igotweb\fwk\model\bean\Request; class CookieManager { private $siteContext; public function __construct(Request $request) { $this->siteContext = $request->getSiteContext(); } /* * private function: getCookieKey * This function returns the key used in cookie * based on the application short name. * * parameters: * - key - the original key. * return: * - cookieKey - the cookie key. */ private function getCookieKey($key) { $cookieKey = $key; if($this->siteContext != NULL) { $cookieKey = $this->siteContext->getApplication()->getShortName() . "_" .$key; } return $cookieKey; } /* * function: put * This function put the string in cookie with its key. * * parameters: * - $key : the key of the object to put in cookie. * - $object : the object to put in cookie. * return: * - none. */ public function put($key,$object,$expire = 0, $path = "", $domain = "", $secure = false) { // We get the cookie key $key = $this->getCookieKey($key); if(is_object($object) || is_array($object)) { $object = serialize($object); } setcookie($key,$object,$expire,$path,$domain,$secure); } /* * function: get * This function get object in cookie linked to the key. * * parameters: * - $key : the key of the object to get in cookie. * return: * - the object linked to the key. */ public function get($key) { // We get the cookie key $key = $this->getCookieKey($key); $object = @$_COOKIE[$key]; // We try to unserialize the value. if(is_string($object)) { $unserializedObject = @unserialize($object); if(!$unserializedObject) { return $object; } return $unserializedObject; } return $object; } /* * function: exists * This function look if there is an object linked * to the key in parameters. * * parameters: * - $key : the key of the object to get in cookie. * return: * - true if found, else false. */ public function exists($key) { // We get the cookie key $key = $this->getCookieKey($key); return @$_COOKIE[$key] != NULL; } /* * function: remove * This function remove the object in the cookie. * * parameters: * - $key : the key of the object to remove in cookie. * return: * - none. */ public function remove($key) { // We get the cookie key $key = $this->getCookieKey($key); setcookie($key,"",time() - 3600); } } ?>
23) Print all possible combinations of r elements in a given array of size n #include<bits/stdc++.h> using namespace std; void printCombination(int arr[], int n, int r) { // A temporary array to store // all combination one by one int data[r]; combinationUtil(arr, data, 0, n-1, 0, r); } void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << " "; cout << endl; return; } // replace index with all possible // elements. The condition "end-i+1 >= r-index" // makes sure that including one element // at index will make a combination with // remaining elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } int main() { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); }
# Typo app This is an application for demo purposes. Fully and even more inspired by [keybr.com](https://keybr.com/) ## Features 1. This app is all about typing, so you won't need a mouse. Well, actually you cannot use mouse, only your keyboard. 2. App offers you a set Levels each having a number of assignments. 3. Each Level has minimum threshold which you have to achieve to get to the next level. The goal is to help you advance in typing and reach 50 words per minute (WPM) with 99% accuracy, which is 10 wpm above the average. Yet, you will start from basics. 4. Each level suggests a subset of letters, starting from 6 and appending more and more each level also increasing the word size. Letters are sorted by their occurrence rates. 5. Two key metrics (I name three, including score) - WPM and Accuracy - allow the app to score you. Both metrics contribute the score equally; a WPM index used in scoring is 45 (which is 5 above the avg). 6. Each level in its turn offers you an Assignment which consists of 13 words. 7. The app starts tracking the time when the Assignment is issued; abandons it when the interruption condition met, such as mouse move is detected. 8. The app stores progress in the Browser Local Storage each time user advance to a new Assignment by saving current level and achieved scores. 9. Fullscreen aka Zen mode. Hit `Shift+Enter` to open the app in the fullscreen. ## How to use the app 1. First time you visit the app page you should see a popup which will introduce you to the app. Since now on you won't be using a mouse to interact with the app. Hit `Enter` to close the popup. Hit `Shift+?` to call it back. 2. To start practicing you would need to type in `start`, this will bring a new assignment on the screen. 3. Assignments consist of a number of words divided by whitespaces (which look like • bullets). Whitespaces are parts of assignment. 4. When you hit the wrong character it, first of all, limits you to advance to the next character, and also contributes your error rate (accuracy). 5. If you start an assignment and don't want to finish it you may use one of the interruptions to exit it. Don't worry, the score will not be spoiled. You can move a mouse, click, hit `Esc` or fire the popup. 6. You can see your level and metrics below the keyboard on the screen. Refer to the popup (`Shift+?`) to relate icons and actual metrics' names. Here is the list of all interactions you can use within the app | Interaction | Effect | |---------------------|--------------------------------------------| | `Shift+?` | Open a Popup, interrupt current Assignment | | `Enter` | Close a Popup | | `Shift+Enter` | Zen-mode | | `Esc` | Interrupt current Assignment | | Mouse-move (>100px) | Interrupt current Assignment | | Mouse-click | Interrupt current Assignment | # Technical information ## Stack This app is written using NextJS (react) (`create-next-app`), TailwindCSS, Redux and TypeScript. This is a Single-Page App with no backend. ## Architecture The app takes an advantage of SSR of a page containing the main view to read, build and serve a file contents (the Workbook). Further components, starting from the view itself (wrapped into a Store Provider) are client-side rendered. The initial state of the application is restored in 2 stages: 1. Read the Workbook on the server 2. Read the Local Storage on the client Further on, the state is managed with Redux, actions and thunks (just 1, tbh). ### Component -> State flow This is not purely data-flow diagram, it shows the most essential parts of the app and how they are connected. Here the blue arrows show actions dispatching (most if not all) ![Actions Flow](doc/assets/action_flow.png) ### State -> Component At this diagram you may see which components depend on which state. Both diagrams give an overview of how the application is organized. ![Consumption of States](doc/assets/state_consumption.png) ## Dev Notes ### State Management In the app we have 2 kinds of states: shared and local (frequently updated). Definitely local states should be organized using React hooks at the place they are needed. In my case Redux is used where the state change rate is relatively low and/or the state to be shared. For example, I had an idea to keep all shortcuts at one place. One of the shortcuts open the popup. I could have done it using React's state and keep everything related to a popup there by providing initial state from parent (which actually restores it). ### Future development I tried to move most of the configs away from components that use them. That's said I simply import required configs at place they needed. I suppose that is OK for a small app, but for the future, depending on level of customization, we may provide configs using React Context for example (or Redux either), so that app can be dynamically updated. ### Tools choice I picked up NextJS as it is a mature React Framework with frequent updates and improvements. To me, it simplifies the initial steps of developing an app. NextJS out of the box (using a `create-next-app` I mean) may be configured for TailwindCSS which also helps to stay in JSX (TSX) without a distraction. Though, I don't really like their way of styling elements, I thought that would be a good idea to concentrate more on the app itself, rather than styling it from scratch. At some components I tried to move class names into separate files and keep them there for the sake of isolation and scoping the focus on elements. ## Run the app To run this app you will need an NPM installed. Then run 2 commands ```bash # navigate to the root folder # where package.json is placed npm install ``` ```bash npm run dev ```
# -*- coding: utf-8 -*- """ Created on Wed Jan 10 23:33:45 2024 @author: Akash """ import torch import torch.nn as nn def double_conv(input_channels,output_channels): conv = nn.Sequential( nn.Conv2d(input_channels,output_channels,kernel_size=3, padding='same',bias=0), nn.BatchNorm2d(output_channels), nn.ReLU(inplace=True), nn.Conv2d(output_channels,output_channels,kernel_size=3, padding='same',bias=0), nn.BatchNorm2d(output_channels), nn.ReLU(inplace=True) ) return conv class UNet(nn.Module): def __init__(self,input_channels=1,output_channels=1,filters=[64,128,256,512]): super(UNet,self).__init__() self.max_pool_layer = nn.MaxPool2d(kernel_size=2, stride=2) self.down_conv_1 = double_conv(1, 64) self.down_conv_2 = double_conv(64, 128) self.down_conv_3 = double_conv(128, 256) self.down_conv_4 = double_conv(256, 512) self.down_conv_5 = double_conv(512,1024) # in orginal paper it's not exactly double layer for this line. self.dropout = nn.Dropout2d(p=0.2) self.upconv_transpose_1 = nn.ConvTranspose2d(in_channels=1024, out_channels=512, kernel_size=2, stride=2 ) self.up_conv_1 = double_conv(1024, 512) self.upconv_transpose_2 = nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=2, stride=2 ) self.up_conv_2 = double_conv(512, 256) self.upconv_transpose_3 = nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=2, stride=2 ) self.up_conv_3 = double_conv(256, 128) self.upconv_transpose_4 = nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=2, stride=2 ) self.up_conv_4 = double_conv(128, 64) self.final_conv = nn.Conv2d(64, 1, kernel_size=1) #overriding inbuilt forward function def forward(self, image): layer1 = self.down_conv_1(image) #print(layer1.size()) pool1 = self.max_pool_layer(layer1) layer2 = self.down_conv_2(pool1) pool2 = self.max_pool_layer(layer2) layer3 = self.down_conv_3(pool2) pool3 = self.max_pool_layer(layer3) layer4 = self.down_conv_4(pool3) pool4 = self.max_pool_layer(layer4) ulayer = self.down_conv_5(pool4) print(layer4.size()) print(ulayer.size()) #upsampling / decoder upconv = self.upconv_transpose_1(ulayer) concat_skip_layer = torch.cat([layer4, upconv],1) concat_up_1 = self.up_conv_1(concat_skip_layer) dropout = self.dropout(concat_up_1) upconv = self.upconv_transpose_2(dropout) concat_skip_layer = torch.cat([layer3, upconv],1) concat_up_1 = self.up_conv_2(concat_skip_layer) dropout = self.dropout(concat_up_1) upconv = self.upconv_transpose_3(dropout) concat_skip_layer = torch.cat([layer2, upconv],1) concat_up_1 = self.up_conv_3(concat_skip_layer) dropout = self.dropout(concat_up_1) upconv = self.upconv_transpose_4(dropout) concat_skip_layer = torch.cat([layer1, upconv],1) concat_up_1 = self.up_conv_4(concat_skip_layer) dropout = nn.Dropout2d(p=0.5)(concat_up_1) print(concat_up_1.size()) output_layer = self.final_conv(dropout) print(output_layer.size()) return output_layer if __name__ == "__main__": image = torch.rand((1,1,512,512)) model = UNet() print(model(image).size())
#[aoc_generator(day3)] pub fn input_generator(input: &str) -> Vec<String> { input .lines() .filter(|s| !(*s).is_empty()) .map(|s| s.to_owned()) .collect::<Vec<String>>() } #[aoc(day3, part1)] pub fn solve_part1(input: &[String]) -> usize { let most_common = get_value_balance_per_bit(input); let mut gamma_rate: usize = 0; for value in most_common { gamma_rate <<= 1; gamma_rate += if value > 0 { 1 } else { 0 }; } let bitcount = input.iter().map(|x| x.len()).max().unwrap(); let epsilon_rate = usize::pow(2, bitcount as u32) - gamma_rate - 1; gamma_rate * epsilon_rate } #[aoc(day3, part2)] pub fn solve_part2(input: &[String]) -> usize { get_oxygen_generator_rating(input) * get_co2_scrubber_rating(input) } pub fn get_value_balance_per_bit(input: &[String]) -> Vec<i32> { let bitcount = input.iter().map(|x| x.len()).max().unwrap(); let mut balance_per_bit = vec![0; bitcount]; for value in input { for (bit_pos, bit_value) in value.chars().enumerate() { if bit_value == '1' { balance_per_bit[bit_pos] += 1; } else { balance_per_bit[bit_pos] -= 1; } } } balance_per_bit } pub fn filter_by_bit_value(input: &[String], bit_pos: usize, bit_value: usize) -> Vec<String> { let mut result = Vec::new(); for value in input { if value.as_bytes()[bit_pos] as char == char::from_digit(bit_value as u32, 10).unwrap() { result.push(value.to_owned()); } } result } pub fn get_oxygen_generator_rating(input: &[String]) -> usize { let bitcount = input.iter().map(|x| x.len()).max().unwrap(); let mut remaining = input.to_owned(); for bit_pos in 0..bitcount { let balance_per_bit = get_value_balance_per_bit(&remaining); let most_common = if balance_per_bit[bit_pos] >= 0 { 1 } else { 0 }; remaining = filter_by_bit_value(&remaining, bit_pos, most_common); if remaining.len() == 1 { return usize::from_str_radix(&remaining[0], 2).unwrap(); } } panic!("No oxygen generator rating found (remaining input: {:?})", remaining); } pub fn get_co2_scrubber_rating(input: &[String]) -> usize { let bitcount = input.iter().map(|x| x.len()).max().unwrap(); let mut remaining = input.to_owned(); for bit_pos in 0..bitcount { let balance_per_bit = get_value_balance_per_bit(&remaining); let least_common = if balance_per_bit[bit_pos] < 0 { 1 } else { 0 }; remaining = filter_by_bit_value(&remaining, bit_pos, least_common); if remaining.len() == 1 { return usize::from_str_radix(&remaining[0], 2).unwrap(); } } panic!("No oxygen generator rating found (remaining input: {:?})", remaining); } #[cfg(test)] mod test { use super::*; pub fn sample_str() -> String { String::from("00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 ") } #[test] pub fn test_solve_part1() { let input = input_generator(sample_str().as_str()); let expected_output = 198; let output = solve_part1(&input); assert_eq!(output, expected_output); } #[test] pub fn test_get_oxygen_generator_rating() { let input = input_generator(sample_str().as_str()); let expected_output = 23; let output = get_oxygen_generator_rating(&input); assert_eq!(output, expected_output); } #[test] pub fn test_get_co2_scrubber_rating() { let input = input_generator(sample_str().as_str()); let expected_output = 10; let output = get_co2_scrubber_rating(&input); assert_eq!(output, expected_output); } #[test] pub fn test_solve_part2() { let input = input_generator(sample_str().as_str()); let expected_output = 230; let output = solve_part2(&input); assert_eq!(output, expected_output); } }
#ifndef STRING2_H_ #define STRING2_H_ #include <iostream> class String { private: char * str; int len; static int num_strings; public: static const int CINLIM = 80; public: String(const char * s); String(); String(const String &); ~String(); int length() const {return len;} String & operator=(const String &); String & operator=(const char *); String & operator+(const String &); char & operator[](int i); const char & operator[](int i) const; void stringup(); void stringlow(); int has(char c) const; friend bool operator<(const String &st, const String &st2); friend bool operator>(const String &st1, const String &st2); friend bool operator==(const String &st, const String &st2); friend String operator+(const char * s, const String &st2); friend std::ostream & operator<<(std::ostream & os, const String & st); friend std::istream & operator>>(std::istream & is, String & st); static int HowMany(); }; #endif
package com.codewave.demo.hktvmall.model.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Builder public class User { Long id; String name; String username; String email; String phone; String website; Address address; Company company; @Data @AllArgsConstructor @NoArgsConstructor public class Address { String stree; String suite; String city; String zipcode; Geo geo; @Data @AllArgsConstructor @NoArgsConstructor public class Geo { @JsonProperty(value = "lat") String latitude; @JsonProperty(value = "lng") String longitude; } } @Data @AllArgsConstructor @NoArgsConstructor public class Company{ String name; String catchPhrase; String bs; } } /* * import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Builder public class User { } { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } }, */
const express = require("express"); const router = express.Router(); const Users = require("../models/Users.js"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcryptjs"); router.post("/authentication", async (req, res) => { try { const allUsers = await Users.find({ username: req.body.username }); if (allUsers.length != 0) { const comparePassword = await bcrypt.compare( req.body.password, allUsers[0].password ); if (comparePassword) { const user = { name: req.body.username, access: allUsers[0]["priviledge"], }; const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET); res.json({ status: "1", message: "You are successfully loggedin", appbearer: accessToken, }); } else { res.json({ status: "0", message: "Incorrect password" }); } } else { res.json({ status: "0", message: "User not found" }); } } catch (err) { res.json({ status: "0", message: err.message }); } }); router.post("/saveCredentials", async (req, res) => { //finding exiting user const emailExists = await Users.findOne({ username: req.body.username }); if (emailExists) return res.json({ message: "Email already exists" }); //hashing password const salt = await bcrypt.genSalt(10); const hashPassword = await bcrypt.hash(req.body.password, salt); const authData = new Users({ username: req.body.username, password: hashPassword, }); //creating new users try { await authData.save(); res.json({ status: "1", message: "Credentials saved successfully" }); } catch (err) { res.json({ status: "0", message: err.message }); } }); router.post("/refreshToken", () => {}); router.post("/logout", () => {}); module.exports = router;
import { Observable} from 'rxjs'; import { Component, OnDestroy, OnInit } from '@angular/core'; import { select, Store } from '@ngrx/store'; import { AppState } from '../../../../../libs/core-data/src/lib/state'; import { getErrorMessageSelector, getProjectArraySelector, getSelectedProjectSelector } from '../../../../../libs/core-data/src/lib/state/projects/projects.selector'; import { CreateProjectAction, DeleteProjectAction, LoadProjectsAction, ResetSelectedProjectAction, SelectProjectAction, UpdateProjectAction } from '../../../../../libs/core-data/src/lib/state/projects/projects.actions'; import { guid } from '../../../../../libs/core-data/src/lib/utils/helpers'; import { Project } from '../../../../../libs/core-data/src/lib/projects/project.model'; import { Customer } from '../../../../../libs/core-data/src/lib/customers/customer.model'; import { CustomersService } from '../../../../../libs/core-data/src/lib/customers/customers.service'; import { NotificationsService } from '../../../../../libs/core-data/src/lib/notifications/notifications.service'; import { takeWhile } from 'rxjs/operators'; @Component({ selector: 'app-projects', templateUrl: './projects.component.html', styleUrls: ['./projects.component.scss'] }) export class ProjectsComponent implements OnInit, OnDestroy { private _componentIsActive!: boolean projects$!: Observable<ReadonlyArray<Project>>; customers$: Observable<Customer[]> | undefined; currentProject$: Observable<Project | undefined> | undefined; errorMessage$!: Observable<string | undefined>; constructor(private readonly _customerService: CustomersService, private readonly _notificationsService: NotificationsService, private readonly _store: Store<AppState>) { } ngOnInit() { this._componentIsActive = true; this.projects$ = this._store.pipe(select(getProjectArraySelector)); this.currentProject$ = this._store.pipe(select(getSelectedProjectSelector)); this.errorMessage$ = this._store.pipe(select(getErrorMessageSelector)); this.getCustomers(); this.getProjects(); this.errorMessage$.pipe(takeWhile(() => this._componentIsActive)).subscribe(message => { if (message) { this._notificationsService.emit(message); } }); } resetCurrentProject() { this._store.dispatch(new ResetSelectedProjectAction()); } selectProject(projectId: string) { this._store.dispatch(new SelectProjectAction(projectId)); } getCustomers() { this.customers$ = this._customerService.all(); } saveProject(project: Project): void { if (!project.id) { this.createProject(project); } else { this.updateProject(project); } } createProject(project: Project): void { project.id = guid(); this._store.dispatch(new CreateProjectAction(project)); // TODO: REFACTOR! this._notificationsService.emit('Project created!'); this.resetCurrentProject(); } updateProject(project: Project): void { this._store.dispatch(new UpdateProjectAction(project)); // TODO: REFACTOR! this._notificationsService.emit('Project saved!'); this.resetCurrentProject(); } deleteProject(projectId: string): void { this._store.dispatch(new DeleteProjectAction(projectId)); // TODO: REFACTOR! this._notificationsService.emit('Project deleted!'); this.resetCurrentProject(); } private getProjects() { this._store.dispatch(new LoadProjectsAction()); } ngOnDestroy(): void { this._componentIsActive = false; } }
#include "main.h" /** * _memset - Fills the first n bytes of the memory area * pointed by @s with the constant byte @b * @s: A pointer to the memory area to be filled * @b: The character to fill the memory area with * @n: The number of bytes to be filled * * Return: A pointer to the filled memory area @s */ void *_memset(void *s, int b, size_t n) { unsigned int index; unsigned char *memory = s, value = b; for (index = 0; index < n; index++) memory[index] = value; return (memory); }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import { AngularFireModule } from '@angular/fire'; import { AngularFireDatabaseModule } from '@angular/fire/database'; import { environment } from '../environments/environment'; import { CreateEtudiantComponent } from './etudiants/create-etudiant/create-etudiant.component'; import { ListEtudiantComponent } from './etudiants/list-etudiant/list-etudiant.component'; import { DetailEtudiantComponent } from './etudiants/detail-etudiant/detail-etudiant.component'; import {AngularFirestore, FirestoreSettingsToken} from '@angular/fire/firestore'; import { SignupComponent } from './auth/signup/signup.component'; import { SigninComponent } from './auth/signin/signin.component'; import {AuthGuardService} from './services/auth-guard.service'; import {AuthService} from './services/auth.service'; import {EtudiantService} from './etudiants/etudiant.service'; import {HttpClientModule} from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, CreateEtudiantComponent, ListEtudiantComponent, DetailEtudiantComponent, SignupComponent, SigninComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule, AngularFireModule.initializeApp(environment.firebase), AngularFireDatabaseModule // for database ], providers: [[AngularFirestore], AuthService, EtudiantService, AuthGuardService], bootstrap: [AppComponent] }) export class AppModule { }
import { filter } from "lodash"; import { sentenceCase } from "change-case"; import { useEffect, useState } from "react"; import { allUsers } from "../../utils/Constants"; import { useDispatch, useSelector } from "react-redux"; import axios from "../../utils/axios"; import { useNavigate } from "react-router-dom"; import VisibilityIcon from '@mui/icons-material/Visibility'; // @mui import { Card, Table, Stack, Paper, Avatar, Button, Popover, Checkbox, TableRow, MenuItem, TableBody, TableCell, Container, Typography, IconButton, TableContainer, TablePagination, } from "@mui/material"; import Iconify from "../../Components/Iconify/Iconify"; import Scrollbar from "../../Components/DashboardLayout/Scrollbar"; // sections import UserListHead from "../../Components/Admin/Users/UserListHead"; import UserListToolbar from "../../Components/Admin/Users/UserListToolbar"; // ---------------------------------------------------------------------- const TABLE_HEAD = [ { id: "name", label: "Name", alignRight: false }, { id: "domain", label: "domain", alignRight: false }, { id: "email", label: "Email", alignRight: false }, // { id: "isVerified", label: "Verified", alignRight: false }, // { id: "status", label: "Status", alignRight: false }, { id: "" }, ]; // ---------------------------------------------------------------------- function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === "desc" ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function applySortFilter(array, comparator, query) { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); if (query) { return filter( array, (_user) => _user.name.toLowerCase().indexOf(query.toLowerCase()) !== -1 ); } return stabilizedThis.map((el) => el[0]); } function UserButton({ userId }) { const navigate = useNavigate(); const handleViewUser = () => { navigate(`/admin/user_details/${userId}`); }; return ( <Button variant="outline" onClick={handleViewUser}> <VisibilityIcon /> </Button> ); } export default function UserList() { const token = useSelector((state) => state.token); const [userList, setUserList] = useState([]); const getUserList = async () => { try { const response = await axios.get(allUsers, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }); if (response && response.data && Array.isArray(response.data)) { console.log(response.data); setUserList(response.data); } else { console.log("Invalid response:", response); } } catch (error) { console.log("Error:", error); } }; useEffect(() => { getUserList(); }, []); const [open, setOpen] = useState(null); const [page, setPage] = useState(0); const [order, setOrder] = useState("asc"); const [selected, setSelected] = useState([]); const [orderBy, setOrderBy] = useState("name"); const [filterName, setFilterName] = useState(""); const [rowsPerPage, setRowsPerPage] = useState(5); const handleOpenMenu = (event) => { setOpen(event.currentTarget); }; const handleCloseMenu = () => { setOpen(null); }; const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === "asc"; setOrder(isAsc ? "desc" : "asc"); setOrderBy(property); }; const handleSelectAllClick = (event) => { if (event.target.checked) { const newSelecteds = userList.map((n) => n.name); setSelected(newSelecteds); return; } setSelected([]); }; const handleClick = (event, name) => { const selectedIndex = selected.indexOf(name); let newSelected = []; if (selectedIndex === -1) { newSelected = newSelected.concat(selected, name); } else if (selectedIndex === 0) { newSelected = newSelected.concat(selected.slice(1)); } else if (selectedIndex === selected.length - 1) { newSelected = newSelected.concat(selected.slice(0, -1)); } else if (selectedIndex > 0) { newSelected = newSelected.concat( selected.slice(0, selectedIndex), selected.slice(selectedIndex + 1) ); } setSelected(newSelected); }; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setPage(0); setRowsPerPage(parseInt(event.target.value, 10)); }; const handleFilterByName = (event) => { setPage(0); setFilterName(event.target.value); }; const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - userList.length) : 0; const filteredUsers = applySortFilter( userList, getComparator(order, orderBy), filterName ); const isNotFound = !filteredUsers.length && !!filterName; return ( <> <Container> <Stack direction="row" alignItems="center" justifyContent="space-between" mb={5} > <Typography variant="h6" gutterBottom> All Members </Typography> {/* <Button variant="contained" startIcon={<Iconify icon="eva:plus-fill" />} > New Member </Button> */} </Stack> <Card> <UserListToolbar numSelected={selected.length} filterName={filterName} onFilterName={handleFilterByName} /> <Scrollbar> <TableContainer sx={{ minWidth: 800 }}> <Table> <UserListHead order={order} orderBy={orderBy} headLabel={TABLE_HEAD} rowCount={userList.length} numSelected={selected.length} onRequestSort={handleRequestSort} onSelectAllClick={handleSelectAllClick} /> <TableBody> {filteredUsers .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row) => { const { id, name, domain, email, avatarUrl } = row; const selectedUser = selected.indexOf(name) !== -1; return ( <TableRow hover key={id} tabIndex={-1} role="checkbox" selected={selectedUser} > <TableCell padding="checkbox"> <Checkbox checked={selectedUser} onChange={(event) => handleClick(event, name)} /> </TableCell> <TableCell component="th" scope="row" padding="none"> <Stack direction="row" alignItems="center" spacing={2} > <Avatar alt={name} src={avatarUrl} /> <Typography variant="subtitle2" noWrap> {name} </Typography> </Stack> </TableCell> <TableCell align="left">{domain}</TableCell> <TableCell align="left">{email}</TableCell> <TableCell align="left"> <UserButton userId={id} /> </TableCell> <TableCell align="right"> <IconButton size="large" color="inherit" onClick={handleOpenMenu} > <Iconify icon={"eva:more-vertical-fill"} /> </IconButton> </TableCell> </TableRow> ); })} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> {isNotFound && ( <TableBody> <TableRow> <TableCell align="center" colSpan={6} sx={{ py: 3 }}> <Paper sx={{ textAlign: "center", }} > <Typography variant="h6" paragraph> Not found </Typography> <Typography variant="body2"> No results found for &nbsp; <strong>&quot;{filterName}&quot;</strong>. <br /> Try checking for typos or using complete words. </Typography> </Paper> </TableCell> </TableRow> </TableBody> )} </Table> </TableContainer> </Scrollbar> <TablePagination rowsPerPageOptions={[5, 10, 25]} component="div" count={userList.length} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </Card> </Container> <Popover open={Boolean(open)} anchorEl={open} onClose={handleCloseMenu} anchorOrigin={{ vertical: "top", horizontal: "left" }} transformOrigin={{ vertical: "top", horizontal: "right" }} PaperProps={{ sx: { p: 1, width: 140, "& .MuiMenuItem-root": { px: 1, typography: "body2", borderRadius: 0.75, }, }, }} > {/* <MenuItem> <Iconify icon={"eva:edit-fill"} sx={{ mr: 2 }} /> Edit </MenuItem> */} <MenuItem sx={{ color: "error.main" }}> <Iconify icon={"eva:trash-2-outline"} sx={{ mr: 2 }} /> Block </MenuItem> </Popover> </> ); }
import React, { useState, useContext } from 'react'; import { Link, useHistory } from 'react-router-dom'; import {FirebaseContext} from '../../store/Context' import Logo from '../../olx-logo.png'; import './Login.css'; function Login() { const history = useHistory() const [email, setEmail] = useState('') const [password, setPassword] = useState('') const {firebase} = useContext(FirebaseContext) const handleLogin = (e)=>{ e.preventDefault() firebase.auth().signInWithEmailAndPassword(email,password).then(()=>{ alert('Logged In') }).catch((error)=>{ alert(error.message) }).then(()=>{ history.push("/") }) } return ( <div> <div className="loginParentDiv"> <img width="200px" height="200px" src={Logo}></img> <form onSubmit={handleLogin} > <label htmlFor="fname">Email</label> <br /> <input className="input" type="email" onChange={(e)=>setEmail(e.target.value)} id="fname" name="email" /> <br /> <label htmlFor="lname">Password</label> <br /> <input className="input" type="password" onChange={(e)=>setPassword(e.target.value)} id="lname" name="password" /> <br /> <br /> <button>Login</button> </form> <Link to="/signup">Signup</Link> </div> </div> ); } export default Login;
package com.app.controllers; import com.app.models.Producto; import com.app.models.Usuario; import com.app.services.IProductoService; import com.app.services.IUsuarioService; import com.app.services.UploadFileService; import jakarta.servlet.http.HttpSession; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.experimental.FieldDefaults; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Controller @RequestMapping("/productos") @Slf4j @AllArgsConstructor @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) public class ProductoController { IProductoService productoService; UploadFileService uploadFileService; IUsuarioService usuarioService; @GetMapping("") public String show(Model model) { model.addAttribute("productos", productoService.findAll()); return "product/show"; } @GetMapping("/create") public String create() { return "product/create"; } @GetMapping("/delete/{id}") public String delete(@PathVariable(name = "id") Integer id) { Producto producto = productoService.findById(id).get(); uploadFileService.deleteImage(producto.getImagen()); productoService.delete(id); return "redirect:/productos"; } @GetMapping("/edit/{id}") public String edit(@PathVariable(name = "id") Integer id, Model model) { model.addAttribute("producto", productoService.findById(id)); return "product/edit"; } @PostMapping("/save") public String save(Producto producto, @RequestParam("img") MultipartFile file, HttpSession session) throws IOException { int id = (int) session.getAttribute("usuarioId"); producto.setUsuario(usuarioService.findById(id).get()); producto.setImagen(uploadFileService.saveImage(file)); productoService.save(producto); return "redirect:/productos"; } @PostMapping("/update") public String update(Producto producto, @RequestParam("img") MultipartFile file, HttpSession session) throws IOException { int id = (int) session.getAttribute("usuarioId"); producto.setUsuario(usuarioService.findById(id).get()); if (file.isEmpty()) { Producto producto1 = productoService.findById(producto.getId()).get(); producto.setImagen(producto1.getImagen()); } else { producto.setImagen(uploadFileService.saveImage(file)); uploadFileService.deleteImage(producto.getImagen()); } productoService.update(producto); return "redirect:/productos"; } }
/* * Copyright (C) 2018-2024 Velocity Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.velocitypowered.proxy.command.builtin; import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.velocitypowered.api.command.BrigadierCommand; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.permission.Tristate; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import java.util.Optional; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; /** * Implements Velocity's {@code /ping} command. */ public class PingCommand { private final ProxyServer server; public PingCommand(ProxyServer server) { this.server = server; } /** * Registers this command. */ public void register() { LiteralArgumentBuilder<CommandSource> node = BrigadierCommand.literalArgumentBuilder("ping") .requires(source -> source.getPermissionValue("velocity.command.ping") == Tristate.TRUE) .then( BrigadierCommand.requiredArgumentBuilder("player", StringArgumentType.word()) .requires(source -> source.getPermissionValue("velocity.command.ping.others") == Tristate.TRUE) .suggests((context, builder) -> { CommandSource source = context.getSource(); if (source.getPermissionValue("velocity.command.ping.others") != Tristate.TRUE) { return builder.buildFuture(); } final String argument = context.getArguments().containsKey("player") ? context.getArgument("player", String.class) : ""; for (final Player player : server.getAllPlayers()) { final String playerName = player.getUsername(); if (playerName.regionMatches(true, 0, argument, 0, argument.length())) { builder.suggest(playerName); } } return builder.buildFuture(); }) .executes(context -> { String player = context.getArgument("player", String.class); Optional<Player> maybePlayer = server.getPlayer(player); if (maybePlayer.isEmpty()) { context.getSource().sendMessage( CommandMessages.PLAYER_NOT_FOUND.arguments(Component.text(player)) ); return 0; } return this.getPing(context, maybePlayer.get()); }) ) .executes(context -> { if (context.getSource() instanceof Player player) { return this.getPing(context, player); } else { context.getSource().sendMessage(CommandMessages.PLAYERS_ONLY); return 0; } }); server.getCommandManager().register(new BrigadierCommand(node.build())); } private int getPing(CommandContext<CommandSource> context, Player player) { long ping = player.getPing(); if (ping == -1L) { context.getSource().sendMessage( Component.translatable("velocity.command.ping.unknown", NamedTextColor.RED) .arguments(Component.text(player.getUsername())) ); return 0; } // Check if sending player matches for the response message. boolean matchesSender = false; if (context.getSource() instanceof Player sendingPlayer) { if (player.getUniqueId().equals(sendingPlayer.getUniqueId())) { matchesSender = true; } } if (matchesSender) { context.getSource().sendMessage( Component.translatable("velocity.command.ping.self", NamedTextColor.GREEN) .arguments(Component.text(ping)) ); } else { context.getSource().sendMessage( Component.translatable("velocity.command.ping.other", NamedTextColor.GREEN) .arguments(Component.text(player.getUsername()), Component.text(ping)) ); } return Command.SINGLE_SUCCESS; } }
import { createSlice } from '@reduxjs/toolkit'; import { addInvoiceInitialValues } from '../../common-components/validator/invoice-validation'; const initialState = { addInvoice: { ...addInvoiceInitialValues?.addInvoice }, isSaved: false, isRequestToSave: false, isResponseFailed: false, isGetAll: false, isRequestToGetAll: false, isFailedToGetAll: false, invoiceList: [] }; export const InvoiceSlice = createSlice({ name: 'invoice', initialState, reducers: { // Invoice Details updateInvoiceAuto: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, invoiceAuto: action?.payload } } }; }, updateInvoiceNo: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, invoiceNo: action?.payload } } }; }, updateShiftingLuggage: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, shiftingLuggage: action?.payload } } }; }, updateTemplate: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, template: action?.payload } } }; }, updateDateOfInvoice: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, dateOfInvoice: action?.payload } } }; }, updateTruckNo: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, truckNo: action?.payload } } }; }, updateConsignmentNo: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, consignmentNo: action?.payload } } }; }, updateModeOfMoving: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, modeOfMoving: action?.payload } } }; }, updateDeliveryDate: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, deliveryDate: action?.payload } } }; }, updateInvoiceVehicleType: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, vehicleType: action?.payload } } }; }, updateInvoiceManufacturer: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, manufacturer: action?.payload } } }; }, updateInvoiceModel: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, invoiceDetails: { ...state.addInvoice.invoiceDetails, model: action?.payload } } }; }, // Billing Details updateBillingCompanyName: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, companyName: action?.payload } } }; }, updateApprovalAuthority: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, approvalAuthority: action?.payload } } }; }, updateAuthorityPersonName: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, authorityPersonName: action?.payload } } }; }, updateAuthorityMobileNumber: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, authorityMobileNumber: action?.payload } } }; }, updateCompanyAddress: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, companyAddress: action?.payload } } }; }, updateCompanyGST: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, companyGST: action?.payload } } }; }, updateEmployeeName: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, employeeName: action?.payload } } }; }, updateEmployeeDesignation: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, employeeDesignation: action?.payload } } }; }, updateEmployeeMobile: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, details: { ...state.addInvoice.billingDetails, employeeMobile: action?.payload } } }; }, // Billing Address updateBillingAddressCheck: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, billingAddressCheck: action?.payload } } }; }, updateCheckClientDetails: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, checkClientDetails: action?.payload } } }; }, updatePartyName: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, partyName: action?.payload } } }; }, updatePartyGST: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, partyGST: action?.payload } } }; }, updatePartyMobileNo: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, partyMobileNo: action?.payload } } }; }, updateAddress: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, address: action?.payload } } }; }, updateLandmark: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, landmark: action?.payload } } }; }, updatePincode: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, pincode: action?.payload } } }; }, updateState: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, state: action?.payload } } }; }, updateCity: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, city: action?.payload } } }; }, updateLocality: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, billingAddress: { ...state.addInvoice.billingAddress, locality: action?.payload } } }; }, updateInvoiceNumber: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, partyInvoiceDetails: { ...state.addInvoice.partyInvoiceDetails, invoiceNumber: action?.payload } } }; }, updateInvoiceDate: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, partyInvoiceDetails: { ...state.addInvoice.partyInvoiceDetails, invoiceDate: action?.payload } } }; }, updateSACCode: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, partyInvoiceDetails: { ...state.addInvoice.partyInvoiceDetails, SACCode: action?.payload } } }; }, updateCheck: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, surcharge: { ...state.addInvoice.charges.surcharge, check: action?.payload } } } }; }, updateValue: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, surcharge: { ...state.addInvoice.charges.surcharge, value: action?.payload } } } }; }, updateGstCheck: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, gst: { ...state.addInvoice.charges.gst, gstCheck: action?.payload } } } }; }, updateGstPercent: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, gst: { ...state.addInvoice.charges.gst, gstPercent: action?.payload } } } }; }, updateGstType: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, gst: { ...state.addInvoice.charges.gst, gstType: action?.payload } } } }; }, updateTransitInsuranceCheck: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, transitInsurance: { ...state.addInvoice.charges.transitInsurance, checkRequired: action?.payload } } } }; }, updateTransitInsuranceRequired: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, transitInsurance: { ...state.addInvoice.charges.transitInsurance, required: action?.payload } } } }; }, updateTransitInsuranceShiftingLuggage: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, transitInsurance: { ...state.addInvoice.charges.transitInsurance, shiftingLuggage: action?.payload } } } }; }, updateTransitInsuranceIns: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, transitInsurance: { ...state.addInvoice.charges.transitInsurance, insurance: action?.payload } } } }; }, updateTransitInsuranceGST: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, transitInsurance: { ...state.addInvoice.charges.transitInsurance, gst: action?.payload } } } }; }, updateTransitInsuranceValue: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, transitInsurance: { ...state.addInvoice.charges.transitInsurance, value: action?.payload } } } }; }, updateStorageCharge: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, storeCharges: { ...state.addInvoice.charges.storeCharges, required: action?.payload } } } }; }, updateStorageOptionsCharge: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, storeCharges: { ...state.addInvoice.charges.storeCharges, options: action?.payload } } } }; }, updateStorageFromCharge: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, storeCharges: { ...state.addInvoice.charges.storeCharges, from: action?.payload } } } }; }, updateStorageToCharge: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, storeCharges: { ...state.addInvoice.charges.storeCharges, to: action?.payload } } } }; }, updateStorageAmountCharge: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, storeCharges: { ...state.addInvoice.charges.storeCharges, amount: action?.payload } } } }; }, updateOtherCharge: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, otherCharges: { ...state.addInvoice.charges.otherCharges, required: action?.payload } } } }; }, updateJobType: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, otherCharges: { ...state.addInvoice.charges.otherCharges, jobType: action?.payload } } } }; }, updateJobTypeValue: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, otherCharges: { ...state.addInvoice.charges.otherCharges, value: action?.payload } } } }; }, updateDiscount: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, discount: { ...state.addInvoice.charges.discount, required: action?.payload } } } }; }, updateDiscountRequired: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, discount: { ...state.addInvoice.charges.discount, discountRequired: action?.payload } } } }; }, updateDiscountValue: (state, action) => { const { type, value } = action?.payload; return { ...state, addInvoice: { ...state.addInvoice, charges: { ...state.addInvoice.charges, discount: { ...state.addInvoice.charges.discount, type, value } } } }; }, updateRemark: (state, action) => { return { ...state, addInvoice: { ...state.addInvoice, remark: action?.payload } }; }, requestToSaveInvoice: (state, action) => { return { ...state, isRequestToSave: true, isResponseFailed: false, isSaved: false }; }, responseToSaveInvoice: (state, action) => { return { ...state, isSaved: true, isResponseFailed: false, isRequestToSave: true }; }, failedToSaveInvoice: (state, action) => { return { ...state, isResponseFailed: true, isRequestToSave: true, isSaved: false }; }, requestToGetAllInvoice: (state, action) => { return { ...state, isRequestToGetAll: true, isFailedToGetAll: false, isGetAll: false }; }, responseToGetAllInvoice: (state, action) => { return { ...state, isGetAll: true, isFailedToGetAll: false, isRequestToGetAll: true, invoiceList: action?.payload }; }, failedToGetAllInvoice: (state, action) => { return { ...state, isFailedToGetAll: true, isRequestToGetAll: true, isGetAll: false }; } } }); export default InvoiceSlice.reducer; export const { updateInvoiceAuto, updateInvoiceNo, updateShiftingLuggage, updateTemplate, updateDateOfInvoice, updateTruckNo, updateConsignmentNo, updateModeOfMoving, updateDeliveryDate, updateCheckClientDetails, updatePartyName, updatePartyGST, updatePartyMobileNo, updateAddress, updateLandmark, updatePincode, updateState, updateCity, updateLocality, updateInvoiceNumber, updateInvoiceDate, updateSACCode, updateRemark, updateBillingAddressCheck, updateBillingCompanyName, updateApprovalAuthority, updateAuthorityPersonName, updateAuthorityMobileNumber, updateCompanyAddress, updateCompanyGST, updateEmployeeName, updateEmployeeDesignation, updateEmployeeMobile, updateCheck, updateValue, updateGstCheck, updateGstPercent, updateGstType, updateTransitInsuranceCheck, updateTransitInsuranceRequired, updateTransitInsuranceShiftingLuggage, updateTransitInsuranceIns, updateTransitInsuranceGST, updateTransitInsuranceValue, updateStorageCharge, updateStorageFromCharge, updateStorageToCharge, updateStorageAmountCharge, updateStorageOptionsCharge, updateOtherCharge, updateJobType, updateJobTypeValue, updateDiscount, updateDiscountValue, updateInvoiceVehicleType, updateInvoiceManufacturer, updateInvoiceModel, updateDiscountRequired, requestToSaveInvoice, responseToSaveInvoice, failedToSaveInvoice, requestToGetAllInvoice, responseToGetAllInvoice, failedToGetAllInvoice } = InvoiceSlice.actions;
<?php namespace App\Http\Controllers; //use Illuminate\Http\Request; use Illuminate\Http\Request; use App\Domain\BookDomain; use App\Exceptions\BookException; use App\Http\Controllers\Controller; use App\Builder\BookBuilder; class BookController extends Controller { public function __construct(){ header('Access-Control-Allow-Origin: *'); } /** * Display a listing of the resource. */ public function index() { $objBuilder = new BookBuilder(); $dataToReturn = $objBuilder->index(); $httpResposeCode = $objBuilder->getHttpResponseCode(); if(!$httpResposeCode){ $httpResposeCode = 200; } return response()->json($dataToReturn, $httpResposeCode); } /** * Store a newly created resource in storage. */ public function store(Request $request) { $objBuilder = new BookBuilder(); $dataToReturn = $objBuilder->store($request); $httpResposeCode = $objBuilder->getHttpResponseCode(); if(!$httpResposeCode){ $httpResposeCode = 200; } return response()->json($dataToReturn, $httpResposeCode); } /** * Store a newly created resource in storage. */ public function storeBookSimple(Request $request, string $store_id) { $objBuilder = new BookBuilder(); $dataToReturn = $objBuilder->storeBookSimple($request, $store_id); $httpResposeCode = $objBuilder->getHttpResponseCode(); if(!$httpResposeCode){ $httpResposeCode = 200; } return response()->json($dataToReturn, $httpResposeCode); } /** * Display the specified resource. */ public function show(string $id) { $objBuilder = new BookBuilder(); $dataToReturn = $objBuilder->show($id); $httpResposeCode = $objBuilder->getHttpResponseCode(); if(!$httpResposeCode){ $httpResposeCode = 200; } return response()->json($dataToReturn, $httpResposeCode); } /** * Update the specified resource in storage. */ public function update(Request $request, string $id) { $objBuilder = new BookBuilder(); $dataToReturn = $objBuilder->update($request, $id); $httpResposeCode = $objBuilder->getHttpResponseCode(); if(!$httpResposeCode){ $httpResposeCode = 200; } return response()->json($dataToReturn, $httpResposeCode); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { $objBuilder = new BookBuilder(); $dataToReturn = $objBuilder->destroy($id); $httpResposeCode = $objBuilder->getHttpResponseCode(); if(!$httpResposeCode){ $httpResposeCode = 200; } return response()->json($dataToReturn, $httpResposeCode); } }