text
stringlengths
184
4.48M
/* GANG Software * GEOM/milieu/ui/ClipPlane.H * Copyright (C) 2002 Nicholas Schmitt <nick@gang.umass.edu> * Wed Sep 18 16:39:46 2002 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef milieu_ui_ClipPlane_INCLUDED #define milieu_ui_ClipPlane_INCLUDED #include "math/ReadUtil.H" #include "widget/ui/Dialog.H" #include "widget/ui/Choice.H" #include "widget/ui/Boolean.H" #include "milieu/opengl/ClipPlaneSet.H" namespace milieu { namespace opengl { class ClipPlaneSet; } namespace ui { class ClipPlane : public widget::ui::Dialog, public math::ReadUtil { public: typedef double Real; typedef math::Matrix<Real> Transform; // constructor ClipPlane(); // destructor virtual ~ClipPlane(); // interface virtual void clipplane_reset(); virtual void clipplane_reset( uint id ); virtual void clipplane_select( uint id ) { id_w()->set(id); } virtual void clipplane_enable( uint id, bool a ); virtual void clipplane_moving( uint id, bool a ); virtual void clipplane_show( uint id, bool a ); virtual void clipplane_attached( uint id, bool a ); virtual void clipplane_position( bool id, Transform const &a ); virtual void clipplane_synchronize() { set_ui_from_data( clipplaneset() ); } bool command( base::String const &command, base::String const &argument, base::String &response ); protected: // callbacks // callbacks virtual void id_cb() { clipplane_synchronize(); } virtual void enable_cb() { _enable( id_w()->get(), enable_w()->get() ); } virtual void moving_cb() { clipplaneset()->moving( id_w()->get(), moving_w()->get() ); } virtual void show_cb() { _show( id_w()->get(), show_w()->get() ); } virtual void attached_cb() { _attached( id_w()->get(), attached_w()->get() ); } virtual void reset_cb() { clipplane_reset( id_w()->get() ); } char const *label() { return "Clip Plane"; } private: // pure virtuals virtual ::milieu::opengl::ClipPlaneSet *clipplaneset() = 0; virtual ::milieu::opengl::ClipPlaneSet const *clipplaneset() const = 0; // virtual void geomobject_move_enable(bool state) = 0; // virtual void light_moving_off() = 0; // widgets virtual widget::ui::Choice *id_w() = 0; virtual widget::ui::Boolean *enable_w() = 0; virtual widget::ui::Boolean *moving_w() = 0; virtual widget::ui::Boolean *show_w() = 0; virtual widget::ui::Boolean *attached_w() = 0; // implementation void _select( uint id ); void _reset( uint id ); void _enable( uint id, bool a ) { clipplaneset()->enable( id, a ); } // void _moving( uint id, bool a ); void _show( uint id, bool a ) { clipplaneset()->show( id, a ); } void _attached( uint id, bool a ) { clipplaneset()->attached( id, a ); } // utility void set_ui_from_data( opengl::ClipPlaneSet *clipplaneset ); // disabled copy constructor ClipPlane( ClipPlane const & ); // disabled assignment operator ClipPlane &operator=( ClipPlane const & ); }; } // namespace ui } // namespace milieu #endif // milieu_ui_ClipPlane_INCLUDED
import React, { Component } from "react"; import axios from "axios"; import url from "./../../UrlConfig"; import "./Books.css"; import Book from "./Book/Book.js"; import { withRouter } from "react-router"; import Pagination from "react-js-pagination"; import Spinner from "../../common/Spinner/Spinner.js"; class Books extends Component { constructor(props) { super(props); this.state = { title: "", author: "", books: [], keyword: "", pageSize: 10, currentPage: 1, totalPages: 0, totalElements: 0, numberOfElements: 0, error: "", loading: true, }; } searchSpace = (event) => { if (event.key === "Enter") { let keyword = event.target.value; event.preventDefault(); this.getBookInfo(1, keyword); } }; handlePageChange = (page) => { this.getBookInfo(page, this.state.keyword); }; render() { if (this.state.loading === true) { return <Spinner />; } const books = this.state.books.map((book, index) => { return ( <Book id={"" + index} key={book.title + book.author} author={book.author} title={book.title} releasedYear={book.releasedYear} booksPages={book.booksPages} bookIsFinished={book.bookIsFinished} picture={book.picture} handleViewBook={(e) => this.handleViewBook(e, book.title, book.author) } /> ); }); return ( <div> <div className="col-lg-8 col-md-6 col-sm-12 p-0"> <input type="text" placeholder="Enter book title or author" className="plus" id="search" name="search" onKeyUp={(e) => this.searchSpace(e)} /> </div> <div className="self-card margin"> <div className="card-body"> <table className="table align-middle table-hover"> <thead> <tr> <th scope="col">&nbsp;</th> <th scope="col">Title</th> <th scope="col">Author</th> <th scope="col">&nbsp;</th> </tr> </thead> {books} </table> </div> </div> <nav aria-label="Page navigation example" className="pagination justify-content-center" > <Pagination className="page-item disabled page-link page-item" itemClass="page-item" linkClass="page-link" activePage={this.state.currentPage} itemsCountPerPage={this.state.pageSize} totalItemsCount={this.state.totalElements} pageRangeDisplayed={2} onChange={this.handlePageChange} /> </nav> </div> ); } getBookInfo(currentPage, keyword) { axios .get( `${url}/api/book?page=${ currentPage - 1 }&title=${keyword}&author=${keyword}` ) .then((answer) => { this.setState({ books: answer.data.content, totalPages: answer.data.totalPages, totalElements: answer.data.totalElements, numberOfElements: answer.data.numberOfElements, currentPage: answer.data.number + 1, }); }) .catch((error) => {}); } componentDidMount = () => { this.timerHandle = setTimeout( () => this.setState({ loading: false }), 3500 ); this.getBookInfo(this.state.currentPage, this.state.keyword); }; componentWillUnmount() { if (this.timerHandle) { clearTimeout(this.timerHandle); this.timerHandle = 0; } } handleViewBook = (e, title, author) => this.props.history.push(`/view_book/${title}/${author}`); } export default withRouter(Books);
import React, { useRef } from "react"; import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogBody, AlertDialogFooter, AlertDialogOverlay, Button, } from "@chakra-ui/react"; import "../style.css"; export default function AlertBox({ isOpen, onClose, handleDelete }) { const cancelRef = useRef(); return ( <AlertDialog isOpen={isOpen} leastDestructiveRef={cancelRef} onClose={onClose} > <AlertDialogOverlay /> <AlertDialogContent> <AlertDialogHeader>Delete Event</AlertDialogHeader> <AlertDialogBody> Are you sure you want to delete this event? </AlertDialogBody> <AlertDialogFooter> <Button ref={cancelRef} onClick={onClose} variant="outline"> Cancel </Button> <Button colorScheme="red" onClick={handleDelete} variant="outline" ml={3} > Delete </Button> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> ); }
<template> <div class="recommend_bg"> <div class="recommend_container"> <!-- 첫 화면의 요소 (showInitialContent 데이터 속성을 사용하여 초기 컨텐츠 표시하거나 숨기기)--> <div v-if="showInitialContent" class="recommend__front"> <div class="recommend_loader"> <span></span> </div> <div class="recommend_select"> <h1 @click="toggleContent">내 위치를 기반으로 추천받기</h1> <span>당신의 위치 기준으로 가장 가까운 3개의 촬영지와 그 영화들을 추천합니다.</span> <span></span> </div> </div> <!-- 진짜 보여줄 내용 --> <div v-if="!showInitialContent"> <h3> 나의 위치에서 가장 가까운 3개의 영화 촬영지입니다. </h3> <div class="recommend__back"> <div v-for="(recommend_item, index) in my_recommend_lst" :key="index"> <RecommendItem :item="recommend_item"/> </div> </div> </div> </div> </div> </template> <script> import RecommendItem from "@/components/RecommendItem.vue"; export default { name:'RecommendView', created(){ // this.$store.dispatch('getMovieLocations') // 타이밍 때문에 시간 걸어줌 setTimeout(() => { this.calculate() }, 100); }, components:{ RecommendItem, }, data(){ return{ my_recommend_lst : null, showInitialContent: true, } }, methods:{ calculate(){ var rad = function(x) { return x * Math.PI / 180; }; var getDistance = function(p1, p2) { var R = 6378137; // Earth’s mean radius in meter var dLat = rad(p2.latitude - p1.lat); var dLong = rad(p2.longitude - p1.lng); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1.lat)) * Math.cos(rad(p2.latitude)) * Math.sin(dLong / 2) * Math.sin(dLong / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; // returns the distance in meter }; const lst = this.$store.getters.currentLocations const position = this.$store.state.my_location const calculate_lst = [] // console.log(position.lng); // console.log(position.lat); for (const item of lst) { const newdata = { data:item, distance_from_me : getDistance(position, item) } calculate_lst.push(newdata) } const newlst = calculate_lst.sort(function(a, b){ return a.distance_from_me - b.distance_from_me }) // 동일한 객체 넣지 않는 함수 function pushUniqueObject(list, object) { const isDuplicate = list.some((cur) => { // Check for equality based on specific properties return cur.data.tmdb_id === object.data.tmdb_id }); if (!isDuplicate) { list.push(object); console.log(object.data.tmdb_id); } } pushUniqueObject const recommend_lst = [] for (const item of newlst) { if (recommend_lst.length < 3 ) { // recommend_lst.push(item) pushUniqueObject(recommend_lst, item) } } this.my_recommend_lst = recommend_lst }, // 클릭 이벤트 발생 시 'showInitialContent'를 false로 설정하여 초기 컨텐츠를 숨김. toggleContent() { this.showInitialContent = false; } // } } </script> <style> .recommend_bg { background-color: #1f1f1f; min-height: 100vh; display: flex; justify-content: center; align-items: center; overflow: hidden; } .recommend_container { display: flex; } .recommend_select, h3 { color: white; font-family: 'Black Han Sans', sans-serif; } .recommend_select h1 { cursor: pointer; } .recommend_select h1 { color: white; cursor: pointer; position: relative; border: none; background: none; text-transform: uppercase; transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); transition-duration: 400ms; transition-property: color; } .recommend_select h1:focus, .recommend_select h1:hover { color: #fff; } .recommend_select h1:focus:after, .recommend_select h1:hover:after { width: 100%; left: 0%; } .recommend_select h1:after { content: ""; pointer-events: none; bottom: -2px; left: 50%; position: absolute; width: 0%; height: 2px; background-color: #fff; transition-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1); transition-duration: 400ms; transition-property: width, left; } .recommend__back { display: flex; } /* RADAR */ .recommend_loader { position: relative; width: 200px; height: 200px; background: transparent; border-radius: 50%; box-shadow: 25px 25px 75px rgba(0,0,0,0.55); border: 1px solid #333; display: flex; align-items: center; justify-content: center; overflow: hidden; margin: 50px auto; } .recommend_loader::before { content: ''; position: absolute; inset: 20px; background: transparent; border: 1px dashed#444; border-radius: 50%; box-shadow: inset -5px -5px 25px rgba(0,0,0,0.25), inset 5px 5px 35px rgba(0,0,0,0.25); } .recommend_loader::after { content: ''; position: absolute; width: 50px; height: 50px; border-radius: 50%; border: 1px dashed#444; box-shadow: inset -5px -5px 25px rgba(0,0,0,0.25), inset 5px 5px 35px rgba(0,0,0,0.25); } .recommend_loader span { position: absolute; top: 50%; left: 50%; width: 50%; height: 100%; background: transparent; transform-origin: top left; animation: radar81 2s linear infinite; border-top: 1px dashed #fff; } .recommend_loader span::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: seagreen; transform-origin: top left; transform: rotate(-55deg); filter: blur(30px) drop-shadow(20px 20px 20px seagreen); } @keyframes radar81 { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style>
import {Application, ValueOrPromise} from '@loopback/core'; import {Class, RepositoryMixin, juggler} from '@loopback/repository'; import {RestApplication} from '@loopback/rest'; import {RatelimitStoreSourceProvider} from '../../providers'; import {RateLimitStoreClientType, RateLimitStoreSource} from '../../types'; import { KvMemoryDataSource, KvRedisDataSource, MemoryDataSource, MongoDataSource, MySQLDataSource, PostgresDataSource, RedisDataSource, } from '../fixtures/datasources'; import {mockAllStoreClients} from '../fixtures/mocks'; class TestApplication extends RepositoryMixin(RestApplication) {} const DATA_SOURCES = [ KvMemoryDataSource, KvRedisDataSource, MemoryDataSource, MongoDataSource, MySQLDataSource, PostgresDataSource, RedisDataSource, ]; describe('Rate Limit StoreSource Service', () => { const app = new TestApplication(); let spies: jest.SpyInstance[]; beforeAll(() => { spies = mockAllStoreClients(); DATA_SOURCES.map(ds => app.dataSource(ds)); }); afterAll(async () => { spies.map(spy => spy.mockRestore()); await app.stop(); }); describe('Ratelimit storesource with config', () => { it('kv-memory', async () => testWithDataSource(app, KvMemoryDataSource, RateLimitStoreClientType.Memory)); it('kv-redis', async () => testWithDataSource(app, KvRedisDataSource, RateLimitStoreClientType.Redis)); it('memory', async () => testWithDataSource(app, MemoryDataSource, RateLimitStoreClientType.Memory)); it('redis', async () => testWithDataSource(app, RedisDataSource, RateLimitStoreClientType.Redis)); it('mongodb', async () => testWithDataSource(app, MongoDataSource, RateLimitStoreClientType.MongoDB)); it('mysql', async () => testWithDataSource(app, MySQLDataSource, RateLimitStoreClientType.MySQL)); it('postgres', async () => testWithDataSource(app, PostgresDataSource, RateLimitStoreClientType.Postgres)); }); }); async function testWithDataSource( app: Application, ds: Class<juggler.DataSource>, expectedClientType: RateLimitStoreClientType, assertFn?: (storeSource: RateLimitStoreSource) => ValueOrPromise<void>, ) { const storeSource = await new RatelimitStoreSourceProvider(() => Promise.resolve({enabled: true}), app, { ds, }).value(); expect(storeSource.type).toEqual(expectedClientType); await assertFn?.(storeSource); }
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from the Oracle Third Party software advisories. # include("compat.inc"); if (description) { script_id(80609); script_version("$Revision: 1.2 $"); script_cvs_date("$Date: 2015/01/21 15:53:44 $"); script_cve_id("CVE-2012-1960", "CVE-2012-1970", "CVE-2012-1971", "CVE-2012-1972", "CVE-2012-1973", "CVE-2012-1974", "CVE-2012-1975", "CVE-2012-1976", "CVE-2012-3956", "CVE-2012-3957", "CVE-2012-3958", "CVE-2012-3959", "CVE-2012-3960", "CVE-2012-3961", "CVE-2012-3962", "CVE-2012-3963", "CVE-2012-3964", "CVE-2012-3966", "CVE-2012-3967", "CVE-2012-3968", "CVE-2012-3969", "CVE-2012-3970", "CVE-2012-3972", "CVE-2012-3974", "CVE-2012-3976", "CVE-2012-3978", "CVE-2012-3980"); script_name(english:"Oracle Solaris Third-Party Patch Update : firefox (multiple_vulnerabilities_in_firefox)"); script_summary(english:"Check for the 'entire' version."); script_set_attribute( attribute:"synopsis", value: "The remote Solaris system is missing a security patch for third-party software." ); script_set_attribute( attribute:"description", value: "The remote Solaris system is missing necessary patches to address security updates : - The qcms_transform_data_rgb_out_lut_sse2 function in the QCMS implementation in Mozilla Firefox 4.x through 13.0, Thunderbird 5.0 through 13.0, and SeaMonkey before 2.11 might allow remote attackers to obtain sensitive information from process memory via a crafted color profile that triggers an out-of-bounds read operation. (CVE-2012-1960) - Multiple unspecified vulnerabilities in the browser engine in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allow remote attackers to cause a denial of service (memory corruption and application crash) or possibly execute arbitrary code via unknown vectors. (CVE-2012-1970) - Multiple unspecified vulnerabilities in the browser engine in Mozilla Firefox before 15.0, Thunderbird before 15.0, and SeaMonkey before 2.12 allow remote attackers to cause a denial of service (memory corruption and application crash) or possibly execute arbitrary code via vectors related to garbage collection after certain MethodJIT execution, and unknown other vectors. (CVE-2012-1971) - Use-after-free vulnerability in the nsHTMLEditor::CollapseAdjacentTextNodes function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-1972) - Use-after-free vulnerability in the nsObjectLoadingContent::LoadObject function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-1973) - Use-after-free vulnerability in the gfxTextRun::CanBreakLineBefore function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-1974) - Use-after-free vulnerability in the PresShell::CompleteMove function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-1975) - Use-after-free vulnerability in the nsHTMLSelectElement::SubmitNamesValues function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-1976) - Use-after-free vulnerability in the MediaStreamGraphThreadRunnable::Run function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-3956) - Heap-based buffer overflow in the nsBlockFrame::MarkLineDirty function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code via unspecified vectors. (CVE-2012-3957) - Use-after-free vulnerability in the nsHTMLEditRules::DeleteNonTableElements function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-3958) - Use-after-free vulnerability in the nsRangeUpdater::SelAdjDeleteNode function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-3959) - Use-after-free vulnerability in the mozSpellChecker::SetCurrentDictionary function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-3960) - Use-after-free vulnerability in the RangeData implementation in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-3961) - Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 do not properly iterate through the characters in a text run, which allows remote attackers to execute arbitrary code via a crafted document. (CVE-2012-3962) - Use-after-free vulnerability in the js::gc::MapAllocToTraceKind function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code via unspecified vectors. (CVE-2012-3963) - Use-after-free vulnerability in the gfxTextRun::GetUserData function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via unspecified vectors. (CVE-2012-3964) - Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allow remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a negative height value in a BMP image within a .ICO file, related to (1) improper handling of the transparency bitmask by the nsICODecoder component and (2) improper processing of the alpha channel by the nsBMPDecoder component. (CVE-2012-3966) - The WebGL implementation in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 on Linux, when a large number of sampler uniforms are used, does not properly interact with Mesa drivers, which allows remote attackers to execute arbitrary code or cause a denial of service (stack memory corruption) via a crafted web site. (CVE-2012-3967) - Use-after-free vulnerability in the WebGL implementation in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code via vectors related to deletion of a fragment shader by its accessor. (CVE-2012-3968) - Integer overflow in the nsSVGFEMorphologyElement::Filter function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code via a crafted SVG filter that triggers an incorrect sum calculation, leading to a heap-based buffer overflow. (CVE-2012-3969) - Use-after-free vulnerability in the nsTArray_base::Length function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to execute arbitrary code or cause a denial of service (heap memory corruption) via vectors involving movement of a requiredFeatures attribute from one SVG document to another. (CVE-2012-3970) - The format-number functionality in the XSLT implementation in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 allows remote attackers to obtain sensitive information via unspecified vectors that trigger a heap-based buffer over-read. (CVE-2012-3972) - Untrusted search path vulnerability in the installer in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, and Thunderbird ESR 10.x before 10.0.7 on Windows allows local users to gain privileges via a Trojan horse executable file in a root directory. (CVE-2012-3974) - Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, and SeaMonkey before 2.12 do not properly handle onLocationChange events during navigation between different https sites, which allows remote attackers to spoof the X.509 certificate information in the address bar via a crafted web page. (CVE-2012-3976) - The nsLocation::CheckURL function in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, Thunderbird ESR 10.x before 10.0.7, and SeaMonkey before 2.12 does not properly follow the security model of the location object, which allows remote attackers to bypass intended content-loading restrictions or possibly have unspecified other impact via vectors involving chrome code. (CVE-2012-3978) - The web console in Mozilla Firefox before 15.0, Firefox ESR 10.x before 10.0.7, Thunderbird before 15.0, and Thunderbird ESR 10.x before 10.0.7 allows user-assisted remote attackers to execute arbitrary JavaScript code with chrome privileges via a crafted web site that injects this code and triggers an eval operation. (CVE-2012-3980)" ); # http://www.oracle.com/technetwork/topics/security/thirdparty-patch-map-1482893.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?b5f8def1" ); # https://blogs.oracle.com/sunsecurity/entry/multiple_vulnerabilities_in_firefox script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?09b23ad2" ); script_set_attribute(attribute:"solution", value:"Upgrade to Solaris 11.1.2.5."); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:C/I:C/A:C"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"cpe:/o:oracle:solaris:11.1"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:oracle:solaris:firefox"); script_set_attribute(attribute:"patch_publication_date", value:"2013/01/29"); script_set_attribute(attribute:"plugin_publication_date", value:"2015/01/19"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2015 Tenable Network Security, Inc."); script_family(english:"Solaris Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/Solaris11/release", "Host/Solaris11/pkg-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("misc_func.inc"); include("solaris.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); release = get_kb_item("Host/Solaris11/release"); if (isnull(release)) audit(AUDIT_OS_NOT, "Solaris11"); pkg_list = solaris_pkg_list_leaves(); if (isnull (pkg_list)) audit(AUDIT_PACKAGE_LIST_MISSING, "Solaris pkg-list packages"); if (empty_or_null(egrep(string:pkg_list, pattern:"^firefox$"))) audit(AUDIT_PACKAGE_NOT_INSTALLED, "firefox"); flag = 0; if (solaris_check_release(release:"0.5.11-0.175.1.2.0.5.0", sru:"SRU 2.5") > 0) flag++; if (flag) { error_extra = 'Affected package : firefox\n' + solaris_get_report2(); error_extra = ereg_replace(pattern:"version", replace:"OS version", string:error_extra); if (report_verbosity > 0) security_hole(port:0, extra:error_extra); else security_hole(0); exit(0); } else audit(AUDIT_PACKAGE_NOT_AFFECTED, "firefox");
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; export type State = { tasks: { [key: string]: { status: 'active' | 'completed'; title: string; }; }; filteredTasks: { [key: string]: { status: 'active' | 'completed'; title: string; }; }; lastTaskId: number; activeFilter: 'all' | 'active' | 'completed'; }; type Reducers = { addTask: (state: State, action: PayloadAction<string>) => void; toCompleteTask: (state: State, action: PayloadAction<number>) => void; removeCompletedTasks: (state: State) => void; setFilteredTasks: ( state: State, action: PayloadAction<'all' | 'active' | 'completed' | undefined> ) => void; }; const taskSlice = createSlice<State, Reducers>({ name: 'todo/task', initialState: { tasks: {}, filteredTasks: {}, lastTaskId: 0, activeFilter: 'all', } as State, reducers: { addTask(state, action) { const allTasks = { ...state.tasks }; allTasks[state.lastTaskId] = { title: action.payload, status: 'active', }; state.tasks = allTasks; const curId = state.lastTaskId; state.lastTaskId = curId + 1; }, toCompleteTask(state, action) { const allTasks = { ...state.tasks }; allTasks[action.payload].status = 'completed'; state.tasks = allTasks; }, removeCompletedTasks(state) { const allTasks = { ...state.tasks }; Object.keys(allTasks).forEach((el) => { if (allTasks[el].status === 'completed') { delete allTasks[el]; } }); state.tasks = allTasks; }, setFilteredTasks(state, action) { const allTasks = { ...state.tasks }; const filter = action.payload === undefined ? state.activeFilter : action.payload; if (filter !== 'all') { Object.keys(allTasks).forEach((key) => { if (allTasks[key].status !== filter) { delete allTasks[key]; } }); } state.filteredTasks = { ...allTasks }; state.activeFilter = filter; }, }, }); const taskReducer = taskSlice.reducer; export const { addTask, toCompleteTask, removeCompletedTasks, setFilteredTasks, } = taskSlice.actions; export default taskReducer;
// // Date: 2019-06-26 // Author: Spicer Matthews (spicer@skyclerk.com) // Last Modified by: Spicer Matthews // Copyright: 2019 Cloudmanic Labs, LLC. All rights reserved. // import 'rxjs/add/operator/takeUntil'; import * as Highcharts from 'highcharts'; import * as moment from 'moment-timezone'; import { AngularCsv } from 'angular7-csv/dist/Angular-csv' import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; import { ReportService, PnlNameAmount } from 'src/app/services/report.service'; import { Subject } from 'rxjs'; import { Title } from '@angular/platform-browser'; import { AccountService } from 'src/app/services/account.service'; declare var Pikaday: any; @Component({ selector: 'app-dashboard-graphs', templateUrl: './graphs.component.html', }) export class GraphsComponent implements OnInit { pageTitle: string = "Skyclerk | Dashboard Graphs"; showFilter: boolean = false; nameTitle: string = "Category"; type: string = "Profit & Loss by Category"; nameAmount: PnlNameAmount[] = []; destory: Subject<boolean> = new Subject<boolean>(); // Setup date pickers endDate: Date = new Date(); startDate: Date = moment(moment().format('YYYY-01-01')).toDate(); @ViewChild('endDateField') endDateField: ElementRef; @ViewChild('endDateTrigger') endDateTrigger: ElementRef; @ViewChild('startDateField') startDateField: ElementRef; @ViewChild('startDateTrigger') startDateTrigger: ElementRef; // Setup chart options chartOptions: any = { chart: { type: 'column' }, title: { text: '' }, credits: { enabled: false }, rangeSelector: { enabled: false }, scrollbar: { enabled: false }, navigator: { enabled: false }, legend: { enabled: false }, tooltip: { formatter: function() { // TODO(spicer): Manage different currencies return this.x + ': $' + Highcharts.numberFormat(this.y, 0, '.', ','); } }, yAxis: { title: { text: '' }, labels: { formatter: function() { // TODO(spicer): Manage different currencies return '$' + Highcharts.numberFormat(this.value, 0, '.', ','); } } }, xAxis: { categories: [] }, series: [ { name: "", color: "#757575", data: [] } ] } // // Constructor // constructor(public reportService: ReportService, public accountService: AccountService, public titleService: Title) { } // // ngOnInit // ngOnInit() { // Set page title. this.titleService.setTitle(this.pageTitle); // Setup date pickers. this.setupDatePickers(); // Build the page this.refreshPageData(); // Listen for account changes. this.accountService.accountChange.takeUntil(this.destory).subscribe(() => { this.refreshPageData(); }); } // // OnDestroy // ngOnDestroy() { this.destory.next(); this.destory.complete(); } // // Load the page data. // refreshPageData() { this.nameAmount = []; // Which report type is this? switch (this.type) { case "Income by Contact": this.loadIncomeByContact(); break; case "Expense by Contact": this.loadExpenseByContact(); break; case "Profit & Loss by Label": this.loadProfitLossByLabel(); break; case "Profit & Loss by Category": this.loadProfitLossByCategory(); break; } } // // loadIncomeByContact // loadIncomeByContact() { // Set titles this.nameTitle = "Contact"; // AJAX call to get data. this.reportService.getIncomeByContact(this.startDate, this.endDate, "asc").subscribe(res => { this.nameAmount = res; // Build Graph let cats = []; let data = []; for (let i = 0; i < res.length; i++) { // Set X-Axis cats.push(res[i].Name); // Set color let color = "#537b37"; // Set Y-Axis data.push({ color: color, y: res[i].Amount }); } // Rebuilt the chart this.chartOptions.series[0].name = this.nameTitle; this.chartOptions.series[0].data = data; this.chartOptions.xAxis.categories = cats; Highcharts.chart('chart', this.chartOptions); }); } // // loadExpenseByContact // loadExpenseByContact() { // Set titles this.nameTitle = "Contact"; // AJAX call to get data. this.reportService.getExpenseByContact(this.startDate, this.endDate, "asc").subscribe(res => { this.nameAmount = res; // Build Graph let cats = []; let data = []; for (let i = 0; i < res.length; i++) { // Set X-Axis cats.push(res[i].Name); // Set color let color = "#bb4626"; // Set Y-Axis data.push({ color: color, y: (res[i].Amount * -1) }); } // Rebuilt the chart this.chartOptions.series[0].name = this.nameTitle; this.chartOptions.series[0].data = data; this.chartOptions.xAxis.categories = cats; Highcharts.chart('chart', this.chartOptions); }) } // // loadProfitLossByCategory // loadProfitLossByCategory() { // Set titles this.nameTitle = "Category"; // AJAX call to get data. this.reportService.getProfitLossByCategory(this.startDate, this.endDate, "asc").subscribe(res => { this.nameAmount = res; // Build Graph let cats = []; let data = []; for (let i = 0; i < res.length; i++) { // Set X-Axis cats.push(res[i].Name); // Set color let color = "#537b37"; if (res[i].Amount < 0) { color = "#bb4626"; } // Set Y-Axis data.push({ color: color, y: res[i].Amount }); } // Rebuilt the chart this.chartOptions.series[0].name = this.nameTitle; this.chartOptions.series[0].data = data; this.chartOptions.xAxis.categories = cats; Highcharts.chart('chart', this.chartOptions); }); } // // loadProfitLossByLabel // loadProfitLossByLabel() { // Set titles this.nameTitle = "Label"; // AJAX call to get data. this.reportService.getProfitLossByLabel(this.startDate, this.endDate, "asc").subscribe(res => { this.nameAmount = res; // Build Graph let cats = []; let data = []; for (let i = 0; i < res.length; i++) { // Set X-Axis cats.push(res[i].Name); // Set color let color = "#537b37"; if (res[i].Amount < 0) { color = "#bb4626"; } // Set Y-Axis data.push({ color: color, y: res[i].Amount }); } // Rebuilt the chart this.chartOptions.series[0].name = this.nameTitle; this.chartOptions.series[0].data = data; this.chartOptions.xAxis.categories = cats; Highcharts.chart('chart', this.chartOptions); }) } // // Setup date pickers // setupDatePickers() { // Setup start date picker. new Pikaday({ defaultDate: this.startDate, field: this.startDateField.nativeElement, trigger: this.startDateTrigger.nativeElement, onSelect: (date: Date) => { this.startDate = date; this.refreshPageData(); } }); // Setup end date picker. new Pikaday({ defaultDate: this.endDate, field: this.endDateField.nativeElement, trigger: this.endDateTrigger.nativeElement, onSelect: (date: Date) => { this.endDate = date; this.refreshPageData(); } }); } // // Toggle filter // toggleFilter() { if (this.showFilter) { this.showFilter = false; } else { this.showFilter = true; } } // // Export CSV // doExportCSV() { let options = { fieldSeparator: ',', quoteStrings: '"', decimalseparator: '.', headers: [this.nameTitle, 'Amount'], showTitle: false, useBom: true, removeNewLines: false, keys: [] }; // Download CSV to browser. new AngularCsv(this.nameAmount, 'skyclerk-' + this.type, options); } } /* End File */
import React, { useEffect, useState } from "react"; import { Route, Routes, useNavigate } from "react-router-dom"; // import "./App.css"; import Header from "./Component/Header"; import styled from "styled-components"; import SideBar from "./Component/SideBar"; import Chat from "./Component/Chat"; import Login from "./Component/Login"; import { auth } from "./firebase"; import { onAuthStateChanged } from "firebase/auth"; function App() { // const navigation = useNavigate(); // const storage = localStorage.getItem("login"); const [login, setLogin] = useState(null); useEffect(() => { // setLogin(storage); onAuthStateChanged(auth, (user) => { if (user) { setLogin(true); // ... } else { setLogin(false); } }); }, []); // const loginHandler = (enter) => { // setLogin(enter); // }; // const logOutHandler = (enter) => { // setLogin(enter); // }; // console.log(login); return ( <div className="app"> {!login ? ( <Login /> ) : ( <> <Header /> <AppBody> <SideBar /> <Routes> <Route path="/" exact element={<Chat />} /> </Routes> </AppBody> </> )} </div> ); } // onAuthStateChanged(auth, (user) => { // if (user) { // // User is signed in, see docs for a list of available properties // // https://firebase.google.com/docs/reference/js/firebase.User // const uid = user.uid; // // ... // } else { // // User is signed out // // ... // } // }); export default App; const AppBody = styled.div` display: flex; height: 100vh; `;
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of Cilium package main import ( "context" "flag" "fmt" "log" "os" "runtime" "runtime/pprof" "github.com/sirupsen/logrus" "github.com/cilium/cilium/pkg/hive" "github.com/cilium/cilium/pkg/hive/cell" "github.com/cilium/cilium/pkg/hive/job" "github.com/cilium/cilium/pkg/logging" "github.com/cilium/cilium/pkg/statedb" "github.com/cilium/cilium/pkg/statedb/index" "github.com/cilium/cilium/pkg/statedb/reconciler" "github.com/cilium/cilium/pkg/time" ) var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`") var memprofile = flag.String("memprofile", "", "write memory profile to `file`") var numObjects = flag.Int("objects", 100000, "number of objects to create") var batchSize = flag.Int("batchsize", 1000, "batch size for writes") var incrBatchSize = flag.Int("incrbatchsize", 1000, "maximum batch size for incremental reconciliation") type testObject struct { id uint64 status reconciler.Status } func (t *testObject) GetStatus() reconciler.Status { return t.status } func (t *testObject) WithStatus(status reconciler.Status) *testObject { return &testObject{id: t.id, status: status} } type mockOps struct { } // Delete implements reconciler.Operations. func (mt *mockOps) Delete(ctx context.Context, txn statedb.ReadTxn, obj *testObject) error { return nil } // Prune implements reconciler.Operations. func (mt *mockOps) Prune(ctx context.Context, txn statedb.ReadTxn, iter statedb.Iterator[*testObject]) error { return nil } // Update implements reconciler.Operations. func (mt *mockOps) Update(ctx context.Context, txn statedb.ReadTxn, obj *testObject, changed *bool) error { if changed != nil { *changed = true } return nil } var _ reconciler.Operations[*testObject] = &mockOps{} var idIndex = statedb.Index[*testObject, uint64]{ Name: "id", FromObject: func(t *testObject) index.KeySet { return index.NewKeySet(index.Uint64(t.id)) }, FromKey: index.Uint64, Unique: true, } func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal("could not create CPU profile: ", err) } defer f.Close() // error handling omitted for example if err := pprof.StartCPUProfile(f); err != nil { log.Fatal("could not start CPU profile: ", err) } defer pprof.StopCPUProfile() } var ( mt = &mockOps{} db *statedb.DB ) testObjects, err := statedb.NewTable[*testObject]("test-objects", idIndex) if err != nil { panic(err) } logging.SetLogLevel(logrus.WarnLevel) hive := hive.New( statedb.Cell, job.Cell, reconciler.Cell, cell.Module( "test", "Test", cell.Provide(func(db_ *statedb.DB) (statedb.RWTable[*testObject], error) { db = db_ return testObjects, db.RegisterTable(testObjects) }), cell.Provide( func() (*mockOps, reconciler.Operations[*testObject]) { return mt, mt }, ), cell.Provide(func() reconciler.Config[*testObject] { return reconciler.Config[*testObject]{ // Don't run the full reconciliation via timer, but rather explicitly so that the full // reconciliation operations don't mix with incremental when not expected. FullReconcilationInterval: time.Hour, RetryBackoffMinDuration: time.Millisecond, RetryBackoffMaxDuration: 10 * time.Millisecond, IncrementalRoundSize: *incrBatchSize, GetObjectStatus: (*testObject).GetStatus, WithObjectStatus: (*testObject).WithStatus, Operations: mt, } }), cell.Invoke(reconciler.Register[*testObject]), ), ) err = hive.Start(context.TODO()) if err != nil { panic(err) } start := time.Now() // Create objects in batches to allow the reconciler to start working // on them while they're added. id := uint64(0) batches := int(*numObjects / *batchSize) for b := 0; b < batches; b++ { fmt.Printf("\rInserting batch %d/%d ...", b+1, batches) wtxn := db.WriteTxn(testObjects) for j := 0; j < *batchSize; j++ { testObjects.Insert(wtxn, &testObject{ id: id, status: reconciler.StatusPending(), }) id++ } wtxn.Commit() } fmt.Printf("\nWaiting for reconciliation to finish ...\n") // Wait for all to be reconciled by waiting for the last added objects to be marked // reconciled. This only works here since none of the operations fail. for { obj, _, watch, ok := testObjects.FirstWatch(db.ReadTxn(), idIndex.Query(id-1)) if ok && obj.status.Kind == reconciler.StatusKindDone { break } <-watch } end := time.Now() duration := end.Sub(start) timePerObject := float64(duration) / float64(*numObjects) objsPerSecond := float64(time.Second) / timePerObject if *memprofile != "" { f, err := os.Create(*memprofile) if err != nil { log.Fatal("could not create memory profile: ", err) } defer f.Close() // error handling omitted for example runtime.GC() // get up-to-date statistics if err := pprof.WriteHeapProfile(f); err != nil { log.Fatal("could not write memory profile: ", err) } } err = hive.Stop(context.TODO()) if err != nil { panic(err) } fmt.Printf("\n%d objects reconciled in %.2f seconds (batch size %d)\n", *numObjects, float64(duration)/float64(time.Second), *batchSize) fmt.Printf("Throughput %.2f objects per second\n", objsPerSecond) }
import { Children, cloneElement, HTMLAttributes, PropsWithChildren, ReactElement, ReactNode, useRef, } from 'react'; import cn from 'classnames'; import { useEventListener, useOnClickOutside } from 'usehooks-ts'; export interface PopoverProps extends PropsWithChildren, Omit<HTMLAttributes<HTMLDivElement>, 'content'> { content?: ReactNode; trigger?: 'click' | 'hover' | 'all'; opened?: boolean; disabled?: boolean; onOpen?: () => void; onClose?: () => void; } export const Popover = ({ children, content, opened = false, disabled = false, onOpen, onClose, trigger = 'hover', className, }: PopoverProps) => { const ref = useRef<HTMLDivElement>(null); const onShow = () => { if (trigger === 'hover' || !ref.current || disabled) return; ref.current.dataset.visible = JSON.stringify( !JSON.parse(ref.current.dataset.visible ?? JSON.stringify(opened)) ); onOpen?.(); }; const onHide = () => { if (!ref.current) return; ref.current.dataset.visible = 'false'; onClose?.(); }; useOnClickOutside(ref, onHide); useEventListener('scroll', onHide); return ( <div className='relative inline-block'> {Children.map(children as ReactElement, (child: ReactElement) => { return cloneElement(child as ReactElement, { onClick: onShow, className: cn(child.props?.className, { peer: !disabled && ['all', 'hover'].includes(trigger), }), role: 'button', }); })} <div data-visible={JSON.stringify(opened)} ref={ref} className={cn( '-top-2 data-[visible=true]:scale-100 data-[visible=true]:opacity-100 scale-0 delay-300 peer-hover:scale-100 min-w-full origin-bottom-right opacity-0 peer-hover:opacity-100 hover:opacity-100 hover:scale-100 transition-all duration-300 ease-in rounded-md backdrop-blur bg-opacity-50 bg-bg border-border border py-3 px-5 z-full -translate-y-full right-0 absolute', className )} > {content} </div> </div> ); };
import React, { Component } from "react"; import { Container, Input, Button ,ListGroup, ListGroupItem,Modal,ModalBody,ModalHeader} from "reactstrap"; import axios from "axios"; import cors from 'cors'; import moment from 'moment'; class App extends Component { state = { title: '', body:'', post:[], btn:false, }; handleChange = (event) => { this.setState({ [event.target.name]: event.target.value }); }; submit = (event) => { event.preventDefault(); const datas = { title: this.state.title, body: this.state.body, }; axios({ url: "api/save", //url: "/api/save", method: 'POST', data: datas, }) .then(() => { console.log("Data has been sent to the server!!"); this.resetBoxes(); this.getFromDb(); }) .catch((e) => { console.log("Internal Server Error occurred!! ", e); }); }; resetBoxes = ()=> { this.setState( { title:'', body:'' } ) } componentDidMount=()=> { this.getFromDb(); } getFromDb = ()=> { axios.get('/api/name') .then((res)=> { const datae = res.data; this.setState({post:datae}); console.log("Data retrieved!! "); console.log(this.state.post) // this.display(this.state.post) }) .catch((e) => { console.log("Error retrieving data!! ", e); }); } display = ({post}) => { // if(!(Object.keys(post).length)) return null; let x = (post).map((data,index)=> ( <ListGroupItem key={index} className="mx-3 bg-light my-1"> <h4 className="d-flex">{data.title}</h4> <p className="my-3 d-flex">{data.body}</p> </ListGroupItem> )); return x } handleBtn = () => { this.setState({btn:!this.state.btn}) this.display(this.state) } render() { return ( <Container className="text-center"> <h2 className="display-4 text-info my-4"><u>Basic MERN App</u></h2> <form className="form-input" onSubmit={this.submit}> <Input type="text" name="title" value={this.state.title} placeholder="Enter title here" onChange={this.handleChange} required="" /> <Input className="my-2" type="textarea" cols="30" rows="10" name="body" placeholder="Enter body here" onChange={this.handleChange} value={this.state.body} required="" /> <Button color="success" className="form-control mb-1"> Create </Button> </form> {/* <Button color="warning" className="form-control my-2" onClick={this.handleBtn} > Show Data </Button> */} { this.display(this.state)} </Container> ); } } export default App;
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:master_list/common/colors.dart'; import 'package:master_list/controllers/category_controller.dart'; import 'package:master_list/controllers/drawer_controller.dart'; import 'package:master_list/controllers/item_controller.dart'; import 'package:master_list/controllers/quantity_controller.dart'; import 'package:master_list/widgets/text_form_field.dart'; import '../widgets/drawer_widget.dart'; class AddItemScreen extends StatelessWidget { AddItemScreen({super.key}); final _formState = GlobalKey<FormState>(); @override Widget build(BuildContext context) { var itemController = Get.put(ItemController()); var categoryController = Get.put(CategoryController()); var quantityController = Get.put(QuantityController()); var drawerController = Get.put(DrawerIndexController()); if (categoryController.selectedValue.value == "") { categoryController.selectedValue.value = categoryController.categories[0].categoryName.toString(); } if (quantityController.selectedValue.value == "") { quantityController.selectedValue.value = quantityController.quantities[0].quantityName.toString(); } print( "categoryController.selectedValue.value : ${categoryController.selectedValue.value}"); print( "categoryController.categories[0].categoryName.toString() : ${categoryController.categories[0].categoryName.toString()}"); return Scaffold( appBar: AppBar( title: Text("Add Item"), centerTitle: true, ), drawer: DrawerWidget(), body: Padding( padding: const EdgeInsets.all(16.0), child: SingleChildScrollView( child: Form( key: _formState, child: Column( children: [ CustomTextFormField( controller: itemController.itemNameController, hintText: "Item Name", textInputType: TextInputType.text, labelText: "Item Name", color: Colors.blueAccent, ), Obx(() { print(categoryController.categories); return DropdownButtonFormField( padding: EdgeInsets.all(8), isExpanded: true, iconEnabledColor: PRIMARY_COLOR, decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide(color: PRIMARY_COLOR, width: 1), borderRadius: BorderRadius.circular(5)), ), icon: Icon(Icons.category), borderRadius: BorderRadius.circular(10), value: categoryController.selectedValue.value, items: categoryController.categories .map((element) => DropdownMenuItem( value: element.categoryName, child: Text(element.categoryName.toString()), )) .toSet() .toList(), hint: const Text("Category"), validator: (value) { if (itemController.itemCategoryNameController.text == "") { return "Select Category"; } }, onChanged: (value) { categoryController.selectedValue.value = value.toString(); itemController.itemCategoryNameController.text = value.toString(); }, ); }), Row( children: [ Expanded( child: CustomTextFormField( controller: itemController.itemQuantityAmountController, hintText: "Quantity", textInputType: TextInputType.numberWithOptions(decimal: true), labelText: "Quantity", color: Colors.blueAccent, ), ), Obx(() { print(quantityController.quantities); return DropdownButton( value: quantityController.selectedValue.value, disabledHint: Text("Select Quantity"), enableFeedback: true, items: quantityController.quantities .map((element) => DropdownMenuItem( value: element.quantityName, child: Text(element.quantityName.toString()), )) .toSet() .toList(), hint: const Text("Quantity"), onChanged: (value) { quantityController.selectedValue.value = value.toString(); itemController.itemQuantityController.text = value.toString(); }, ); }), ], ), CustomTextFormField( controller: itemController.itemPurchasePlaceController, hintText: "Place", textInputType: TextInputType.text, labelText: "Place", color: Colors.blueAccent, ), Obx( () => ElevatedButton( style: ElevatedButton.styleFrom( shape: BeveledRectangleBorder()), onPressed: () { if (_formState.currentState!.validate() && itemController.itemCategoryNameController.text != "" && itemController.itemQuantityController.text != "") { if (itemController.isEditMode.value) { itemController.itemCategoryNameController.text = categoryController.selectedValue.value; itemController.itemQuantityController.text = quantityController.selectedValue.value; itemController.editItem(); } else { itemController.addItem(); } itemController.itemPurchasePlaceController.text = ""; itemController.itemNameController.text = ""; itemController.itemQuantityAmountController.text = ""; itemController.itemQuantityController.text = ""; itemController.itemCategoryNameController.text = ""; drawerController.setCurrentDrawerItemIndex = 0; } else { Get.snackbar("Empty Fields", "Please select category or quantity"); } }, child: Text(categoryController.isEditMode.value ? "Update" : "Save")), ), ], ), ), ), )); } }
import logging from airflow import DAG from airflow.utils.dates import days_ago from airflow.operators.dummy_operator import DummyOperator from airflow.operators.bash import BashOperator from airflow.operators.python_operator import PythonOperator from airflow.hooks.postgres_hook import PostgresHook from datetime import datetime DEFAULT_ARGS = { 'owner': 'p-malyshev-9', 'poke_interval': 600, 'start_date': datetime(2022, 3, 1), 'end_date': datetime(2022, 3, 14) } with DAG("p_malyshev_9_lesson4_dag", schedule_interval='0 0 * * 1-6', default_args=DEFAULT_ARGS, max_active_runs=1, tags=['p-malyshev-9'] ) as dag: dummy = DummyOperator(task_id="p_malyshev_9_dummy") def heading_from_articles_func(current_date, **kwargs): execution_date = datetime.strptime(current_date, "%Y-%m-%d").date().isoweekday() pg_hook = PostgresHook(postgres_conn_id='conn_greenplum') conn = pg_hook.get_conn() cursor = conn.cursor() logging.info(f'execution weekday: {execution_date}') cursor.execute(f'SELECT heading FROM articles WHERE id = {execution_date}') query_res = cursor.fetchall() kwargs['ti'].xcom_push(value=query_res, key='heading') logging.info(query_res) heading_from_articles = PythonOperator( task_id='heading_from_articles', op_kwargs={'current_date': "{{ ds }}"}, python_callable=heading_from_articles_func, provide_context=True, dag=dag ) dummy >> heading_from_articles
import React, { PropTypes } from 'react' import { connect } from 'react-redux' import { createSelector } from 'reselect' import { PlayQueueItem } from './PlayQueueItem' export const PlayQueueListView = React.createClass({ propTypes: { queuedEpisodeUrls: PropTypes.array.isRequired }, render: function () { const rows = [] this.props.queuedEpisodeUrls.forEach((episodeUrl, idx) => { rows.push( <PlayQueueItem queueIndex={idx} key={idx} /> ) }) if (rows.length === 0) { rows.push(<div key='nothing-queued'>Nothing queued</div>) } return <div> {rows} </div> } }) const playQueueSelector = (state) => state.playQueue const mapStateToProps = createSelector( playQueueSelector, function (playQueue) { return { queuedEpisodeUrls: playQueue } } ) export const PlayQueueList = connect( mapStateToProps, null, null, {pure: true} )(PlayQueueListView)
import axios from "axios"; import {FC, useEffect, useState} from "react"; import {useDispatch, useSelector} from "react-redux"; import { updateUserExp, addUserExp, deleteUserExp, } from "../../redux/actions/private/applicantActions"; import Storage from "../../services/storage"; import { Experience, Header, Titles, Edit, ExperienceCard, SubTitles, EachContainer, NoExperience, EditInput, EditTextArea, DateInput, ParagraphStyle, } from "./Styles"; type Props = { userRole: string; }; export const ExperienceInfoComp: FC<Props> = ({userRole}) => { const applicantDetail = useSelector((state: any) => state.companyReducer.applicantDetail); let userId = useSelector((state: any) => state.userReducer.applicant.id); const dispatch = useDispatch(); const [flag, setFlag] = useState(0); const [displayFlag, setDisplayFlag] = useState("none"); const [overlayFlag, setOverlayFlag] = useState("none"); const [expArray, setExpArray] = useState([]); const token = Storage.get("token"); useEffect(() => { if (userRole === "company") { setExpArray(applicantDetail.experience) } else { axios.get(`${process.env.REACT_APP_API}/applicant/${userId}`, { headers: { token: token || "", }, } ) .then((res) => { setExpArray(res.data.experience) }) } }, [applicantDetail.id]) const [userExperience, setUserExperience] = useState({ id: "", company: "", position: "", startDate: "", endDate: "", description: "", applicantId: userId }); function editFunction(exp: any) { flag === 0 ? setFlag(100) : setFlag(0); overlayFlag === "none" ? setOverlayFlag("block") : setOverlayFlag("none"); displayFlag === "none" ? setDisplayFlag("flex") : setDisplayFlag("none"); setUserExperience({ id: exp.id, company: exp.company, position: exp.position, startDate: exp.startDate, endDate: exp.endDate, description: exp.description, applicantId: userId }); } function updateFunction() { flag === 0 ? setFlag(100) : setFlag(0); overlayFlag === "none" ? setOverlayFlag("block") : setOverlayFlag("none"); displayFlag === "none" ? setDisplayFlag("flex") : setDisplayFlag("none"); dispatch(updateUserExp(userExperience)); setTimeout(() => { axios.get(`${process.env.REACT_APP_API}/applicant/${userId}`, { headers: { token: token || "", }, } ) .then((res) => { setExpArray(res.data.experience) }) }, 500) } function closeModal() { flag === 0 ? setFlag(100) : setFlag(0); overlayFlag === "none" ? setOverlayFlag("block") : setOverlayFlag("none"); addDisplayFlag === "none" ? setAddDisplayFlag("flex") : setAddDisplayFlag("none"); } function handleChange(e: any) { setUserExperience({ ...userExperience, [e.target.name]: e.target.value, }); } const [addDisplayFlag, setAddDisplayFlag] = useState("none"); function addExperience() { flag === 0 ? setFlag(100) : setFlag(0); overlayFlag === "none" ? setOverlayFlag("block") : setOverlayFlag("none"); addDisplayFlag === "none" ? setAddDisplayFlag("flex") : setAddDisplayFlag("none"); } const [id, setId] = useState(2); function addHandleChange(e: any) { setAddUserExperience({ ...addUserExperience, [e.target.name]: e.target.value, }); } const [addUserExperience, setAddUserExperience] = useState({ id: id, company: "", position: "", startDate: "", endDate: "", description: "", }); function saveExperience() { setId(Math.floor(Math.random() * 98127319)); flag === 0 ? setFlag(100) : setFlag(0); overlayFlag === "none" ? setOverlayFlag("block") : setOverlayFlag("none"); addDisplayFlag === "none" ? setAddDisplayFlag("flex") : setAddDisplayFlag("none"); dispatch(addUserExp(addUserExperience, userId)); setAddUserExperience({ id: id, company: "", position: "", startDate: "", endDate: "", description: "", }); setTimeout(() => { axios.get(`${process.env.REACT_APP_API}/applicant/${userId}`, { headers: { token: token || "", }, } ) .then((res) => { setExpArray(res.data.experience) }) }, 500) } function deleteFunction(id: any) { dispatch(deleteUserExp(id)); setTimeout(() => { axios.get(`${process.env.REACT_APP_API}/applicant/${userId}`, { headers: { token: token || "", }, } ) .then((res) => { setExpArray(res.data.experience) }) }, 500) flag === 0 ? setFlag(100) : setFlag(0); overlayFlag === "none" ? setOverlayFlag("block") : setOverlayFlag("none"); displayFlag === "none" ? setDisplayFlag("flex") : setDisplayFlag("none"); } return ( <Experience> <Header> <Titles>Experiencia</Titles> </Header> {expArray.map((exp: any) => ( <ExperienceCard className="experience-card" key={exp.id}> <Header> <div></div> {userRole === "applicant" && <Edit onClick={() => editFunction(exp)}>Editar</Edit> } </Header> <EachContainer> <SubTitles>Empresa:</SubTitles> <ParagraphStyle>{exp.company}</ParagraphStyle> </EachContainer> <EachContainer> <SubTitles>Posición:</SubTitles> <ParagraphStyle>{exp.position}</ParagraphStyle> </EachContainer> <EachContainer> <SubTitles>Desde:</SubTitles> <ParagraphStyle>{exp.startDate}</ParagraphStyle> </EachContainer> <EachContainer> <SubTitles>Hasta:</SubTitles> <ParagraphStyle>{exp.endDate}</ParagraphStyle> </EachContainer> <EachContainer> <SubTitles>Descripción:</SubTitles> <ParagraphStyle>{exp.description}</ParagraphStyle> </EachContainer> </ExperienceCard> ))} <div className="edit-modal" style={{ position: "fixed", display: displayFlag, opacity: flag, flexDirection: "column", alignItems: "flex-start", padding: "40px", minWidth: '40%', width: "auto", height: "auto", background: "#FFFFFF", zIndex: "1001", top: "50%", left: "50%", transform: "translate(-50%, -50%)", borderRadius: "15px", boxShadow: "0px 0px 20px rgba(0, 0, 0, 0.7)", overflow: "hidden", transition: "all 1s", }} > <EachContainer> <SubTitles>Empresa:</SubTitles> <EditInput value={userExperience.company} name="company" onChange={(e) => handleChange(e)} ></EditInput> </EachContainer> <EachContainer> <SubTitles>Posición:</SubTitles> <EditInput value={userExperience.position} name="position" onChange={(e) => handleChange(e)} ></EditInput> </EachContainer> <EachContainer> <SubTitles>Desde:</SubTitles> <EditInput type="date" value={userExperience.startDate} name="startDate" onChange={(e) => handleChange(e)} ></EditInput> </EachContainer> <EachContainer> <SubTitles>Hasta:</SubTitles> <EditInput type="date" value={userExperience.endDate} name="endDate" onChange={(e) => handleChange(e)} ></EditInput> </EachContainer> <EachContainer> <SubTitles>Descripción:</SubTitles> <EditTextArea value={userExperience.description} name="description" onChange={(e) => handleChange(e)} ></EditTextArea> </EachContainer> <Header> <Edit onClick={() => deleteFunction(userExperience.id)}> Borrar </Edit> <Edit onClick={() => updateFunction()}>Guardar</Edit> </Header> </div> <div className="overlay" onClick={addExperience} style={{ position: "fixed", opacity: flag, display: overlayFlag, top: "0", left: "0", bottom: "0", right: "0", backgroundColor: "rgba(0, 0, 0, 0.4)", transition: "all 1s", zIndex: "1000", }} ></div> {userRole === "applicant" && ( expArray.length >= 0 && expArray.length < 4 ? ( <NoExperience className="experience-card"> <Edit onClick={() => addExperience()}> Añadir experiencia </Edit> </NoExperience> ) : ( <></> ) ) } <div className="add-experience" style={{ position: "fixed", display: addDisplayFlag, opacity: flag, flexDirection: "column", alignItems: "flex-start", padding: "40px", minWidth: '40%', width: "auto", height: "auto", background: "#FFFFFF", zIndex: "1001", top: "50%", left: "50%", transform: "translate(-50%, -50%)", borderRadius: "15px", boxShadow: "0px 0px 20px rgba(0, 0, 0, 0.7)", overflow: "hidden", transition: "all 1s", }} > <EachContainer> <SubTitles>Empresa:</SubTitles> <EditInput value={addUserExperience.company} name="company" onChange={(e) => addHandleChange(e)} ></EditInput> </EachContainer> <EachContainer> <SubTitles>Posición:</SubTitles> <EditInput value={addUserExperience.position} name="position" onChange={(e) => addHandleChange(e)} ></EditInput> </EachContainer> <EachContainer> <SubTitles>Desde:</SubTitles> <DateInput type="date" value={addUserExperience.startDate} name="startDate" onChange={(e) => addHandleChange(e)} ></DateInput> </EachContainer> <EachContainer> <SubTitles>Hasta:</SubTitles> <DateInput type="date" value={addUserExperience.endDate} name="endDate" onChange={(e) => addHandleChange(e)} ></DateInput> </EachContainer> <EachContainer> <SubTitles>Descripción:</SubTitles> <EditTextArea value={addUserExperience.description} name="description" onChange={(e) => addHandleChange(e)} ></EditTextArea> </EachContainer> <Header> <Edit onClick={() => closeModal()}>Descartar</Edit> <Edit onClick={() => saveExperience()}>Guardar</Edit> </Header> </div> </Experience> ); };
# HVAC Group [![GitHub Release][releases-shield]][releases] [![GitHub Activity][commits-shield]][commits] [![License][license-shield]](LICENSE) [![hacs][hacsbadge]][hacs] ![Project Maintenance][maintenance-shield] [![BuyMeCoffee][buymecoffeebadge]][buymecoffee] <!-- [![Discord][discord-shield]][discord] --> [![Community Forum][forum-shield]][forum] _Create a custom thermostat to control multiple other climate components._ **This integration will set up the following platforms.** | Platform | Description | | --------- | ---------------------------------------------------------------------- | | `climate` | The replacement thermostat which can control other nested thermostats. | ## Installation 1. Using the tool of choice open the directory (folder) for your HA configuration (where you find `configuration.yaml`). 1. If you do not have a `custom_components` directory (folder) there, you need to create it. 1. In the `custom_components` directory (folder) create a new folder called `hvac_group`. 1. Download _all_ the files from the `custom_components/hvac_group/` directory (folder) in this repository. 1. Place the files you downloaded in the new directory (folder) you created. 1. Restart Home Assistant 1. In the HA UI go to "Settings" -> "Devices & services" -> "Helpers" click "+" and search for "HVAC group" ## Configuration is done in the UI 1. Go to "Settings" -> "Devices & services" -> "Helpers" click "+ Create helper" and search for "HVAC group" 1. Name your new HVAC group. Something like `Bedroom climate` 1. Select one or more heating entities (e.g. the radiators and the electric heater in the bedroom) 1. Select one or more cooling entities (e.g. the air conditioning in the bedroom) 1. For both heaters and coolers, if you check `Toggle heaters/coolers on or off [...]`, they will physically be turned off if the desired temperature is reached 1. Select a climate entity which holds the current temperature (`Temperature sensor`) 1. If you check `Hide members`, creating the group will mark heater and cooler entities as hidden 1. Click `Submit` ## Contributions are welcome! If you want to contribute to this please read the [Contribution guidelines](CONTRIBUTING.md) --- [hvac_group]: https://github.com/tetele/hvac_group [buymecoffee]: https://www.buymeacoffee.com/t3t3l3 [buymecoffeebadge]: https://img.shields.io/badge/buy%20me%20a%20coffee-donate-yellow.svg?style=for-the-badge [commits-shield]: https://img.shields.io/github/commit-activity/y/tetele/hvac_group.svg?style=for-the-badge [commits]: https://github.com/tetele/hvac_group/commits/main [hacs]: https://github.com/hacs/integration [hacsbadge]: https://img.shields.io/badge/HACS-Custom-orange.svg?style=for-the-badge <!-- [discord]: https://discord.gg/Qa5fW2R --> <!-- [discord-shield]: https://img.shields.io/discord/330944238910963714.svg?style=for-the-badge --> <!-- [exampleimg]: example.png --> [forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=for-the-badge [forum]: https://community.home-assistant.io/ [license-shield]: https://img.shields.io/github/license/tetele/hvac_group.svg?style=for-the-badge [maintenance-shield]: https://img.shields.io/badge/maintainer-Tudor%20Sandu%20%40tetele-blue.svg?style=for-the-badge [releases-shield]: https://img.shields.io/github/release/tetele/hvac_group.svg?style=for-the-badge [releases]: https://github.com/tetele/hvac_group/releases
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework # All trademark and other rights reserved by their respective owners # Copyright 2008-2022 Neongecko.com Inc. # Contributors: Daniel McKnight, Guy Daniels, Elon Gasper, Richard Leeds, # Regina Bloomstine, Casimiro Ferreira, Andrii Pernatii, Kirill Hrymailo # BSD-3 License # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import sys import unittest from unittest.mock import patch, Mock from click.testing import CliRunner sys.path.append(os.path.dirname(os.path.dirname(__file__))) from neon_gui.service import NeonGUIService class TestGUIService(unittest.TestCase): @classmethod def setUpClass(cls) -> None: from neon_messagebus.service import NeonBusService cls.messagebus = NeonBusService(debug=True, daemonic=True) cls.messagebus.start() @classmethod def tearDownClass(cls) -> None: cls.messagebus.shutdown() def test_gui_service(self): alive = Mock() started = Mock() ready = Mock() stopping = Mock() service = NeonGUIService(alive_hook=alive, started_hook=started, ready_hook=ready, stopping_hook=stopping, daemonic=True) # alive.assert_called_once() started.assert_not_called() ready.assert_not_called() stopping.assert_not_called() service.start() service.started.wait() alive.assert_called_once() started.assert_called_once() ready.assert_called_once() stopping.assert_not_called() service.shutdown() stopping.assert_called_once() service.join(10) self.assertFalse(service.is_alive()) class TestCLI(unittest.TestCase): runner = CliRunner() @patch("neon_gui.cli.init_config_dir") @patch("neon_gui.__main__.main") def test_run(self, main, init_config): from neon_gui.cli import run self.runner.invoke(run) init_config.assert_called_once() main.assert_called_once() if __name__ == '__main__': unittest.main()
// // CronParserTests.swift // CronParserTests // // Created by Ruben Exposito Marin on 1/9/22. // import XCTest class CronParserTests: XCTestCase { var sut: CronParser! let cronField1 = CronField(hours: "1", minutes: "30", command: "/bin/run_me_daily") let cronField2 = CronField(hours: "*", minutes: "45", command: "/bin/run_me_hourly") let cronField3 = CronField(hours: "*", minutes: "*", command: "/bin/run_me_every_minute") let cronField4 = CronField(hours: "19", minutes: "*", command: "/bin/run_me_sixty_times") override func setUpWithError() throws { sut = CronParser() } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } // MARK: calculateNextExecutionTimes func testCronParser_CalculateNextExecutionTimes_ReturnsEmptyIfNoTimeArgument() { let executionTimes = sut.calculateNextExecutionTimes() XCTAssertEqual(executionTimes, []) } func testCronParser_CalculateNextExecutionTimes_ReturnsTimesIfTimeArgument() { let timeArgument = TimeArgument(time: "16:10") sut.timeArgument = timeArgument sut.cronFields = [cronField1] let executionTimes = sut.calculateNextExecutionTimes() XCTAssertNotEqual(executionTimes, []) } func testCronParser_CalculateNextExecutionTimes_ReturnsSameTimeTodayForBothAsterisks() { let timeArgument = TimeArgument(time: "16:10") sut.timeArgument = timeArgument sut.cronFields = [cronField3] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "16:10") XCTAssertEqual(components[1], "today") } func testCronParser_CalculateNextExecutionTimes_ReturnsOneHourMoreAndTodayForHourAsteriskAndLessMinutesForCronField() { let timeArgument = TimeArgument(time: "16:50") sut.timeArgument = timeArgument sut.cronFields = [cronField2] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "17:50") XCTAssertEqual(components[1], "today") } func testCronParser_CalculateNextExecutionTimes_ReturnsCurrentHoursCronMinutesAndTodayForHourAsteriskAndEqualOrMoreMinutesForCronField() { let timeArgument = TimeArgument(time: "16:40") sut.timeArgument = timeArgument sut.cronFields = [cronField2] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "16:45") XCTAssertEqual(components[1], "today") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHours00MinutesAndTomorrowForMinutesAsteriskAndLessHoursForCronField() { let timeArgument = TimeArgument(time: "20:40") sut.timeArgument = timeArgument sut.cronFields = [cronField4] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "19:00") XCTAssertEqual(components[1], "tomorrow") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHours00MinutesAndTodayForMinutesAsteriskAndMoreHoursForCronField() { let timeArgument = TimeArgument(time: "18:40") sut.timeArgument = timeArgument sut.cronFields = [cronField4] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "19:00") XCTAssertEqual(components[1], "today") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHoursCurrentMinutesAndTodayForMinutesAsteriskAndEqualHoursForCronField() { let timeArgument = TimeArgument(time: "19:40") sut.timeArgument = timeArgument sut.cronFields = [cronField4] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "19:40") XCTAssertEqual(components[1], "today") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHoursCronMinutesAndTomorrowForLessHoursForCronField() { let timeArgument = TimeArgument(time: "2:40") sut.timeArgument = timeArgument sut.cronFields = [cronField1] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "1:30") XCTAssertEqual(components[1], "tomorrow") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHoursCronMinutesAndTodayForMoreHoursForCronField() { let timeArgument = TimeArgument(time: "0:40") sut.timeArgument = timeArgument sut.cronFields = [cronField1] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "1:30") XCTAssertEqual(components[1], "today") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHoursCronMinutesAndTomorrowForSameHoursAndLessMinutesForCronField() { let timeArgument = TimeArgument(time: "1:40") sut.timeArgument = timeArgument sut.cronFields = [cronField1] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "1:30") XCTAssertEqual(components[1], "tomorrow") } func testCronParser_CalculateNextExecutionTimes_ReturnsCronHoursCronMinutesAndTomorrowForSameHoursAndSameOrMoreMinutesForCronField() { let timeArgument = TimeArgument(time: "1:30") sut.timeArgument = timeArgument sut.cronFields = [cronField1] let executionTimes: [String] = sut.calculateNextExecutionTimes() let components = executionTimes[0].components(separatedBy: " ") XCTAssertEqual(components[0], "1:30") XCTAssertEqual(components[1], "today") } }
<?php // J'appelle la classe dont je vais avoir besoin: require_once('../../Model/AgentRepository.php'); // Pour des raisons de sécurité je souhaite vérifier si l'utilisateur qui souhaite afficher cette page est bien connecté. Pour cela je vais avoir besoin d'utiliser le systeme de session donc je commence par le démarrer: session_start(); // Je vais maintenant vérifier que l'utilisateur souhaitant afficher cette page est bien autorisé à le faire. Si ce n'est pas le cas, je redirige ce dernier vers la page de connexion, sinon le script continue: if (!isset($_SESSION['userEmail']) || $_SESSION['userRole'] != 'ROLE_ADMIN') { header('Location: loginView.php'); } else { // Afin de gérer les erreurs de éventuelles de mon script, je décide de mettre ce dernier dans un bloc try...catch: try { // Je vérifie que l'administrateur est bien cliqué sur l'un des boutons: if (isset($_GET['confirm'])) { // Si l'administrateur clique sur le bouton "oui": if ($_GET['confirm'] == 'yes') { // Avant de supprimer mon agent, il est stipulé dans l'énoncé du devoir qu'une mission doit avoir 1ou plusieurs agents. Mon agent n'ayant pas de référence dans la table mission, il faut que j'empêche "manuellement" la suppression de mon agent si celui ci est le dernier affecté à la mission. Je vais pour cela dans un premier temps avoir besoin de me connecter à la base de données. Ettant donné que je souhaite faire tourner mon applucation en local ou en production j'utilise cette condition: if (getenv('JAWSDB_URL') !== false) { $dbparts = parse_url(getenv('JAWSDB_URL')); $hostname = $dbparts['host']; $username = $dbparts['user']; $password = $dbparts['pass']; $database = ltrim($dbparts['path'], '/'); } else { $username = 'root'; $password = 'root'; $database = 'GDWFSCAWEXAIII1A'; $hostname = 'localhost'; } // Je peux créer mintenant mon objet PDO: $db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password); // J'instancie un nouvel objet de ma classe AgentRepository: $agentRepository = new AgentRepository($db); // J'utilise la fonction getMissionIdOfThisAgent de ma classe afin de récupérer l'id de la mission sur lequel mon agent est affecté: $missionId = $agentRepository->getMissionIdOfThisAgent($_GET['id']); // Maintenant je compte les agents affectés sur cette mission à l'aide de la fonction countAgentIOfThisMission de ma classe AgentRepository. Si je n'ai qu'un seul agent affecté sur cette mission alors je lance une exception sinon je supprime l'agent: if ($agentRepository->countAgentIOfThisMission($missionId) == false) { throw new Exception('Suppression impossible. Cet agent est le dernier agent affecté à la mission concernée.'); } else { // J'utilise la fonction deleteThisAgentWithThisId() afin de supprimer mon agent: $agentRepository->deleteThisAgentWithThisId($_GET['id']); // Si une erreur se déroule dans la suppression de l'agent une erreur est levée. Si au contraire cette suppression se passe bien je dirige l'administrateur vers la page qui liste les agents et où il verra que la suppression s'est bien faite: header('Location: agentListView.php'); } } else { // Si l'administrateur clique sur "non" alors je le redirige vers la page qui liste les agents: header('Location: agentListView.php'); } } } catch (Exception $exception) { $agentDeleteViewMessage = $exception->getMessage(); } }
import { calculatorUISelectors } from "./PageData/CalculatorUI"; /** * Takes a string and returns it wrapped in a data-test-id attribute selector string. * * @param testId - The test ID to format. * @returns The formatted test ID as a string. * @example * formatTestId('login-button'); * // Returns '[data-test-id="login-button"]' */ export function formatTestId(testId: string): string { return `[data-test-id="${testId}"]`; } /** * Parses a math expression and performs clicks on the calculator UI based on the digits and characters in the expression. * * @param expression - The math expression to parse. * @example * parseMathExpressionToClicks("1 + 2"); * // This will click the 1, +, and then 2 buttons in that order on the calculator UI. */ export function parseMathExpressionToClicks(expression: string): void { const components = expression.split(" "); components.forEach((component: string) => { component.split("").forEach((digit: string) => { const selector = calculatorUISelectors.get(digit); cy .get(selector) .click(); }); }); } /** * Replaces math symbols in the input string with their corresponding keystrokes. * * @param input - The input string containing math symbols. * @returns The modified string with math symbols replaced by keystrokes. * * @example * mathSymbolToKeystroke("2 × 3 ÷ 4"); * // Returns "2 * 3 / 4" */ export function mathSymbolToKeystroke(input: string): string { input = input.replace("÷", "/"); input = input.replace("×", "*"); return input; }
import { ref } from 'vue'; import { storeToRefs } from 'pinia'; import { deleteAddressApi } from '@/api/Address'; import { useSnackbarStore } from '@/stores/snackbar'; import { useAddressStore } from '@/stores/address'; export function useDeleteAddress() { const { address } = storeToRefs(useAddressStore()); const { setSnackbarDataAndShow } = useSnackbarStore(); const isLoading = ref<boolean>(false); const errorData = ref<string>(''); const isSuccess = ref<boolean>(false); const deleteAddress = async () => { isLoading.value = true; try { await deleteAddressApi(+address.value.id); errorData.value = ''; isSuccess.value = true; } catch (error) { let errorMessage = 'Unknown Error'; if (error instanceof Error) { errorMessage = error.message; } errorData.value = errorMessage; isSuccess.value = false; setSnackbarDataAndShow(errorData.value, 'error'); } finally { isLoading.value = false; } }; return { deleteAddress, isLoading, isSuccess }; }
<template> <div> <h1>人员列表</h1> <input type="text" v-model.trim="name"> <button @click="addPerson">添加</button> <ul> <li v-for="(item ) in personList" :key="item.id">{{item.name}}</li> </ul> </div> </template> <script> import {mapState} from 'vuex' export default { name:'Person', data() { return { name:'' }; }, //生命周期 - 创建完成(访问当前this实例) created() { }, //生命周期 - 挂载完成(访问DOM元素) mounted() { }, computed:{ ...mapState('personAbout',['personList']), }, methods:{ addPerson(){ this.$store.commit('personAbout/ADD_PERSON',{ id:new Date().getTime(), name : this.name }) } } }; </script> <style scoped> </style>
import 'package:flutter/material.dart'; import 'package:listat/EditList.dart'; // Ensure this path is correct import 'package:listat/sqldb.dart'; // Ensure this path is correct import 'package:shared_preferences/shared_preferences.dart'; class BrowseList extends StatefulWidget { @override _BrowseListState createState() => _BrowseListState(); } Future<Map<String, String?>> retrieveSharedPreferencesData() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String? email = prefs.getString('email'); String? password = prefs.getString('password'); // Print the retrieved values // print('Email: $email'); // print('Password: $password'); return { 'email': email, 'password': password, }; // this line is for you moayed if you want to store these in a variable you do so like this // retrieveSharedPreferencesData().then((values) { // String? email = values['email']; // String? password = values['password']; // // Print or use the retrieved email and password strings // print('Email: $email'); // print('Password: $password'); // }); } class _BrowseListState extends State<BrowseList> { final SqlDb sqlDb = SqlDb(); bool isLoading = true; List lists = []; Future<void> readData() async { retrieveSharedPreferencesData().then((values) async { String? email = values['email']; String? password = values['password']; print('Email: $email'); print('Password: $password'); List<Map> response = await sqlDb.readData("SELECT * FROM listat WHERE email <> '$email';"); lists.clear(); lists.addAll(response); }); isLoading = false; if (mounted) { setState(() {}); } } @override void initState() { super.initState(); readData(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, // Set the background color to white appBar: appBar(), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ dynamicCards(), cardPadding(context), ], ), ); } AppBar appBar() { return AppBar( backgroundColor: Colors.white, elevation: 0, title: const Text( 'My Lists', style: TextStyle( color: Color(0xFF3E4462), fontSize: 21, fontWeight: FontWeight.bold, ), ), centerTitle: true, iconTheme: const IconThemeData(color: Color(0xFF3E4462)), ); } Expanded dynamicCards() { return Expanded( child: isLoading ? const Center(child: CircularProgressIndicator()) : lists.isNotEmpty ? ListView.builder( itemCount: lists.length, itemBuilder: (context, i) { return Container( margin: const EdgeInsets.only( top: 14.0, left: 17.0, right: 17.0), decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.25), blurRadius: 15.0, offset: const Offset(0, 4), ), ], borderRadius: BorderRadius.circular(24.0), ), child: Stack( children: [ ListTile( leading: Container( width: 82.0, height: 82.0, child: Image.network( 'image_url_or_asset', fit: BoxFit.cover, ), ), title: Text( "${lists[i]['name']}", style: const TextStyle( fontWeight: FontWeight.bold, color: Color.fromRGBO(0, 0, 0, 0.75), fontSize: 18, ), ), subtitle: Text( "${lists[i]['description']}", style: const TextStyle( color: Color.fromRGBO(0, 0, 0, 0.75), fontSize: 13, ), ), contentPadding: const EdgeInsets.only(left: 16.0, right: 48.0), ), Positioned( top: 0, right: 0, child: PopupMenuButton<String>( onSelected: (String value) { if (value == 'Edit') { Navigator.of(context).push( MaterialPageRoute( builder: (context) => EditList( List_name: lists[i]['name'], List_dec: lists[i]['description'], id: lists[i]['id'], ), ), ); } else if (value == 'Delete') { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Confirm Delete'), content: const Text( 'Are you sure you want to delete this item?'), actions: <Widget>[ TextButton( child: const Text('Cancel'), onPressed: () { Navigator.of(context).pop(); }, ), TextButton( child: const Text('Delete'), onPressed: () async { Navigator.of(context).pop(); int response = await sqlDb.deleteData( "DELETE FROM listat WHERE id = ${lists[i]['id']}"); if (response > 0) { readData(); } }, ), ], ); }, ); } }, itemBuilder: (BuildContext context) { return {'Edit', 'Delete'}.map((String choice) { return PopupMenuItem<String>( value: choice, child: Text(choice), ); }).toList(); }, icon: const Icon(Icons.more_vert), ), ), ], ), ); }, ) : const Center(child: Text("No data found")), ); } Padding cardPadding(BuildContext context) { return const Padding( padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 8.0), ); } }
import torch import torch.nn as nn import torch.optim as optim import numpy as np import gymnasium as gym from collections import namedtuple # Define the Q-network class QNetwork(nn.Module): def __init__(self, input_size, output_size, hidden_size): super(QNetwork, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, output_size) def forward(self, x): x = torch.relu(self.fc1(x)) x = self.fc2(x) return x # Define the experience namedtuple Experience = namedtuple('Experience', ('state', 'action', 'next_state', 'reward', 'done')) # Q-learning agent class DQNAgent: def __init__(self, input_size, output_size, hidden_size, lr, gamma): self.q_network = QNetwork(input_size, output_size, hidden_size) self.target_network = QNetwork(input_size, output_size, hidden_size) self.target_network.load_state_dict(self.q_network.state_dict()) self.optimizer = optim.Adam(self.q_network.parameters(), lr=lr) self.gamma = gamma def select_action(self, state, epsilon): if np.random.rand() < epsilon: return np.random.choice(range(self.q_network.fc2.out_features)) else: with torch.no_grad(): q_values = self.q_network(torch.FloatTensor(state)) return torch.argmax(q_values).item() def update_q_network(self, experiences): batch = Experience(*zip(*experiences)) state_batch = torch.stack(batch.state) action_batch = torch.tensor(batch.action) next_state_batch = torch.stack(batch.next_state) reward_batch = torch.tensor(batch.reward, dtype=torch.float32) done_batch = torch.tensor(batch.done, dtype=torch.float32) current_q_values = self.q_network(state_batch).gather(1, action_batch.unsqueeze(1)) next_q_values = self.target_network(next_state_batch).max(1)[0].detach() target_q_values = reward_batch + (1 - done_batch) * self.gamma * next_q_values #target_q_values = reward_batch + self.gamma * next_q_values loss = nn.functional.mse_loss(current_q_values, target_q_values.unsqueeze(1)) self.optimizer.zero_grad() loss.backward() self.optimizer.step() def update_target_network(self): self.target_network.load_state_dict(self.q_network.state_dict()) # Main training loop def train_dqn(env_name, num_episodes, epsilon_decay, hidden_size=128, lr=0.001, gamma=0.99): env = gym.make(env_name) input_size = env.observation_space.shape[0] output_size = env.action_space.n agent = DQNAgent(input_size, output_size, hidden_size, lr, gamma) epsilon = 1.0 for episode in range(num_episodes): state, info = env.reset() episode_reward = 0 while True: action = agent.select_action(state, epsilon) next_state, reward, done, _, _ = env.step(action) experience = Experience( state=torch.FloatTensor(state), action=action, next_state=torch.FloatTensor(next_state), reward=reward, done=done ) agent.update_q_network([experience]) episode_reward += reward if done: break state = next_state epsilon = max(epsilon * epsilon_decay, 0.01) # Decay epsilon over time agent.update_target_network() if episode % 10 == 0: print(f"Episode: {episode}, Epsilon: {epsilon}, Episode Reward: {episode_reward}") torch.save(agent.target_network.state_dict(), "frogger.policy") env.close() return agent def test_dqn(env_name, agent, epsilon=0.0): env = gym.make(env_name, render_mode="human") state, info = env.reset() episode_reward = 0 agent.target_network.load_state_dict(torch.load("frogger.policy")) while True: action = agent.select_action(state, epsilon) next_state, reward, done, _, _ = env.step(action) episode_reward += reward if done: break state = next_state env.close() return episode_reward # Example usage if __name__ == "__main__": #env_name ="ALE/Frogger-ram-v5" env_name = 'Freeway-ramDeterministic-v4' # Change to the desired Atari RAM game num_episodes = 200 epsilon_decay = 0.995 hidden_size = 128 learning_rate = 0.0001 discount_factor = 0.99 agent = train_dqn(env_name, num_episodes, epsilon_decay, hidden_size, learning_rate, discount_factor) #env = gym.make(env_name) #input_size = env.observation_space.shape[0] #output_size = env.action_space.n #hidden_size = 128 #agent = DQNAgent(input_size, output_size, hidden_size, 0, 0) input("Press Enter to continue...") test_dqn(env_name, agent)
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>User | Các thiết bị</title> <!-- Custom fonts for this template--> <link href="../../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" rel="stylesheet" /> <link href="../../vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" rel="stylesheet" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" /> <!-- Custom styles for this template--> <link href="../../css/sb-admin-2.min.css" rel="stylesheet" /> <link href="../../css/dashboard.css" rel="stylesheet" /> <link href="../../css/item-product.css" rel="stylesheet" /> </head> <body id="page-top"> <div id="wrapper" class="row"> <!-- Sidebar --> <div th:replace="~{fragments/user_sidebar :: sidebar(active=3)}"></div> <!-- Content Wrapper --> <div id="content-wrapper " class="col-12 col-md-10 d-flex flex-column flex-grow-1"> <!-- Main Content --> <div id="content"> <!-- Topbar --> <div th:replace="~{fragments/user_topbar :: topbar( userName = ${session.user.hoTen}, userAvatar = '/media/images/user_default.png' )}"> </div> <!-- Begin Page Content --> <div class="container-fluid"> <!-- Member Statistic --> <div class="ui-borrow-equipment" th:if="${#lists.isEmpty(xlList)}"> <div class="ui-top d-flex justify-content-between"> <div class="div-button-form-control d-flex flex-grow-1 search"> <div class="col"> <input type="text" class="form-control button-form-control" id="txt-search" placeholder="Nhập vào đây để tìm kiếm" aria-label="" > </div> <div class="col"> <button class="btn btn-secondary" onclick="searchByMaThietBi()">Tìm kiếm</button> </div> </div> <div class="d-flex justify-content-between flex-shrink-0"> <input type="datetime-local" name="date" id="date" class="form-control" onchange="searchThietBi()" th:value="${date}"> </div> </div> <div class="ui-center"> <div th:each="tb : ${tbList}"> <div class="product-container"> <div class="product-top"> <img th:attr="src=@{|/media/images/thietbi${tb.maTB.toString().charAt(0)}.jpg|}" alt="" class="image-product"/> </div> <div class="product-bottom mt-5"> <div class="ui-data"> <div class="name-laptop text-primary font-weight-bold d-flex flex-column justify-content-center align-items-center"> <span th:text="${tb.maTB}"></span> <br/> <span th:text="${tb.tenTB}"></span> </div> </div> <p class="describe" th:text="${tb.moTaTB}"></p> <div class="button-cart"> <p class="button-reservation button bg-primary p-3 text-white border border-primary" th:onclick="'reservationThietBi(\'' + ${session.user.maTV} + '\', \'' + ${tb.maTB} + '\')'"> Đặt chỗ </p> </div> </div> </div> </div> </div> <div class="ui-bottom"> <div th:replace="~{fragments/pagination :: pagination( urlPrefix = ${params.isEmpty() ? '/user/thiet-bi?' : '/user/thiet-bi?' + params + '&'}, totalPages = ${tbList.totalPages}, currentPage = ${tbList.number + 1}, pageSize = ${tbList.size}, totalItems = ${tbList.totalElements})}"> </div> </div> </div> <div class="row" th:if="${!#lists.isEmpty(xlList)}"> <div class="col-md-3" th:each="xl : ${xlList}"> <div class="card text-white bg-danger mb-3"> <div class="card-header" th:text="${xl.maXL}"></div> <div class="card-body"> <h5 class="card-title" th:text="${xl.hinhThucXL}"></h5> <p class="card-text" th:text="${xl.ngayXL}"></p> </div> </div> </div> </div> </div> <!-- /.container-fluid --> </div> </div> <!-- End of Content Wrapper --> </div> <!-- End of Page Wrapper --> <script src="../../vendor/jquery/jquery.min.js"></script> <script src="../../vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="../../vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Datatables --> <script src="../../vendor/datatables/jquery.dataTables.min.js"></script> <script src="../../vendor/datatables/dataTables.bootstrap4.min.js"></script> <!-- Page level custom scripts --> <script src="../../js/demo/datatables-demo.js"></script> <!--Date Range Picker --> <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script> <!-- SELECT --> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script> <script src="../../js/utils.js" type="module"></script> <script> function searchThietBi() { const searchText = document.getElementById("txt-search").value; const currentDate = new Date(); // Lấy thời gian hiện tại const dateInput = document.getElementById("date"); const selectedDate = new Date(dateInput.value); // Lấy thời gian đã chọn từ input // Nếu thời gian đã chọn là trong quá khứ, cập nhật lại giá trị là thời gian hiện tại if (selectedDate < currentDate) { dateInput.value = formatDate(currentDate); } // Cập nhật URL với các tham số tìm kiếm const newUrl = window.location.href.split('?')[0] + `?tenTB=${searchText}&date=${dateInput.value}`; window.location.href = newUrl; } function formatDate(date) { const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); return `${year}-${month}-${day}T${hours}:${minutes}`; } document.getElementById("txt-search").addEventListener("keydown", function (event) { if (event.key === 'Enter') { searchThietBi(); } }) function reservationThietBi(maTV, maTB) { var date = $("#date").val(); // Lấy giá trị của input#date if (confirm('Bạn có chắc chắn muốn đặt chỗ thiết bị này?')) { $.ajax({ type: "GET", url: "/thong-tin/dat-cho", data: { maTV: maTV, maTB: maTB, date: date }, success: function(response) { alert(response); window.location.reload(); }, error: function(xhr) { alert(xhr.responseText); } }); } } function borrowThietBi(maTV, maTB) { var date = $("#date").val(); // Lấy giá trị của input#date if (confirm('Bạn có chắc chắn muốn mượn thiết bị này?')) { $.ajax({ type: "GET", url: "/thong-tin/muon", data: { maTV: maTV, maTB: maTB, date: date}, success: function(response) { alert(response); window.location.reload(); }, error: function(xhr) { alert(xhr.responseText); } }); } } </script> </script> </body> </html>
// // StepBarChart.swift // Walken Track // // Created by Ben Morgiewicz on 5/11/24. // import SwiftUI import Charts struct StepBarChart: View { @State private var rawSelectedDate: Date? var selectedStat: HealthMetricContext var chartData: [HealthMetric] var selectedHealthMetric: HealthMetric? { guard let rawSelectedDate else { return nil } return chartData.first { Calendar.current.isDate(rawSelectedDate, inSameDayAs: $0.date) } } var avgStepCount: Double { guard !chartData.isEmpty else { return 0 } let totalSteps = chartData.reduce(0) { $0 + $1.value } return totalSteps/Double(chartData.count) } var body: some View { VStack { NavigationLink(value: selectedStat) { HStack { VStack(alignment: .leading) { Label("Steps", systemImage: "figure.walk") .font(.title3.bold()) // .foregroundStyle(.pink) .foregroundStyle(.linearGradient( colors: [.black.opacity(0.7), .pink, .pink], startPoint: .bottom, endPoint: .top )) Text("Avg: \(Int(avgStepCount)) Steps") .font(.caption) } Spacer() Image(systemName: "chevron.right") } } .foregroundStyle(.secondary) .padding(.bottom, 12) Chart { if let selectedHealthMetric { RuleMark(x: .value("Selected Metric", selectedHealthMetric.date, unit: .day)) .foregroundStyle(Color.secondary.opacity(0.4)) .offset(y: -10) .annotation( position: .top, spacing: 0, overflowResolution: .init( x: .fit(to: .chart), y: .disabled) ) { annotationView } } RuleMark(y: .value("Average", avgStepCount)) .foregroundStyle(Color.secondary) .lineStyle(.init(lineWidth: 1, dash: [5])) // ForEach(HealthMetric.mockData) { steps in ForEach(chartData) { steps in BarMark( x: .value("Date", steps.date, unit: .day), y: .value("Steps", steps.value) ) // .foregroundStyle(Color.pink.gradient) .foregroundStyle(.linearGradient( colors: [.black.opacity(0.7), .pink, .pink, .pink], startPoint: .bottom, endPoint: .top )) .opacity(rawSelectedDate == nil || steps.date == selectedHealthMetric?.date ? 1.0 : 0.4 ) .cornerRadius(8) } } .frame(height: 150) .chartXSelection(value: $rawSelectedDate.animation(.easeInOut)) .chartXAxis { AxisMarks { AxisValueLabel(format: .dateTime.month(.defaultDigits).day()) .foregroundStyle(.pink) } } .chartYAxis { AxisMarks { value in AxisGridLine() .foregroundStyle(Color.secondary.opacity(0.3)) AxisValueLabel(( value.as(Double.self) ?? 0).formatted(.number.notation(.compactName))) .foregroundStyle(.pink) } } } .padding() .background(RoundedRectangle(cornerRadius: 12).fill(Color(.secondarySystemBackground))) } var annotationView: some View { VStack(alignment: .leading) { Text( selectedHealthMetric?.date ?? .now, format: .dateTime.weekday(.abbreviated).month(.abbreviated).day() ) .font(.footnote.bold()) .foregroundStyle(.secondary) Text( selectedHealthMetric?.value ?? 0, format: .number.precision(.fractionLength(0)) ) .fontWeight(.heavy) .foregroundStyle(.pink) } .padding(12) .background( RoundedRectangle(cornerRadius: 8) .fill(Color(.secondarySystemBackground)) .shadow(color: .secondary.opacity(0.4), radius: 4, x: 4, y: 4) ) } } #Preview { StepBarChart(selectedStat: .steps, chartData: HealthMetric.mockData) }
<x-app-layout> <x-slot name="header"> <div class="flex justify-between items-center"> <x-header-heading :sup="__('Edit question')"> {{ $question->question_text }} </x-header-heading> <div class="flex gap-2"> @can('delete', $question) <x-danger-button x-data="" x-on:click.prevent="$dispatch('open-modal', 'confirm-course-deletion')" >{{ __('Delete Course') }}</x-danger-button> @endcan <a href="{{ route('courses.questions.index', $question->course) }}"> <x-secondary-button type="button"> {{ __('Cancel') }} </x-secondary-button> </a> </div> </div> </x-slot> <x-app-container> <x-container-section> <form action="{{ route('questions.update', $question) }}" method="POST" x-data="{isOpenQuestion: false}"> @csrf @method('PATCH') <!-- Question itself --> <div> <x-input-label for="question_text" :value="__('Question')"/> <x-text-input id="question_text" class="block mt-1 w-full" name="question_text" :value="old('name', $question->question_text)" required /> <x-input-error :messages="$errors->get('question_text')" class="mt-2"/> </div> <!-- Is the question open? --> <div class="mt-4" > <x-input-label for="is_open_question" :value="__('Is open question')"/> <div class="flex items-center mt-2"> <x-text-input id="is_open_question" type="checkbox" class="inline-block" name="is_open_question" value="{{ old('is_open_question', $question->is_open_question) }}" required x-model="isOpenQuestion" x-init="isOpenQuestion = $el.value" /> {{ $question->is_open_question ? 'open' : 'not_open' }} <span class="ml-2 leading-none" x-text="isOpenQuestion ? 'Question is open' : 'Question has answers'"></span> </div> <x-input-error :messages="$errors->get('is_open_question')" class="mt-2"/> </div> <!-- Open answer --> <div class="mt-4" x-show="isOpenQuestion" style="display: none"> <x-input-label for="open_answer" :value="__('Open answer')"/> <x-text-input id="open_answer" class="block mt-1 w-full" name="question_text" :value="old('open_answer', $question->open_answer)" required /> <x-input-error :messages="$errors->get('open_answer')" class="mt-2"/> </div> <!-- or answers separated by enter --> <div class="mt-4" x-show="!isOpenQuestion" style="display: none"> <x-input-label for="answers" :value="__('Answers')"/> <x-text-input id="answers" class="block mt-1 w-full" name="answers" :value="old('answers', $question->answers->collect()->join('ahoj'))" required /> {{ $question->answers->pluck('answer_text') }} <x-input-error :messages="$errors->get('open_answer')" class="mt-2"/> </div> <div class="mt-4"> <x-primary-button> {{ __('Save') }} </x-primary-button> </div> </form> </x-container-section> </x-app-container> </x-app-layout> <!-- Modal to confirm deleting a course --> <?php // TODO: MAKE IT DELETE THE QUESTION, NOT ACCOUNT // create a new route course.delete and copy the general body of the controller method from ProfileController ?> <x-modal name="confirm-course-deletion" :show="$errors->userDeletion->isNotEmpty()" focusable> <form method="post" action="{{ route('questions.destroy', $question) }}" class="p-6"> @csrf @method('delete') <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100"> {{ __('Are you sure you want to delete this course?') }} </h2> <p class="mt-1 text-sm text-gray-600 dark:text-gray-400"> {{ __('Once your account is deleted, all of its resources and data will be permanently deleted. Please enter your password to confirm you would like to permanently delete your account.') }} </p> <div class="mt-6"> <x-input-label for="password" value="{{ __('Password') }}" class="sr-only"/> <x-text-input id="password" name="password" type="password" class="mt-1 block w-3/4" placeholder="{{ __('Password') }}" /> <x-input-error :messages="$errors->userDeletion->get('password')" class="mt-2"/> </div> <div class="mt-6 flex justify-end"> <x-secondary-button x-on:click="$dispatch('close')"> {{ __('Cancel') }} </x-secondary-button> <x-danger-button class="ms-3"> {{ __('Delete Account') }} </x-danger-button> </div> </form> </x-modal>
# AWSTrial, A mechanism and service for offering a cloud image trial # # Copyright (C) 2010 Scott Moser <smoser@ubuntu.com> # Copyright (C) 2010 Dave Walker (Daviey) <DaveWalker@ubuntu.com> # Copyright (C) 2010 Michael Hall <mhall119@gmail.com> # Copyright (C) 2010 Dustin Kirkland <kirkland@ubuntu.com> # Copyright (C) 2010 Andreas Hasenack <andreas@canonical.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from optparse import make_option from django.core.management.base import BaseCommand, CommandError from trial.models import Campaign import sys class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--long', '-l', dest='long', help='Help for the long options'), ) help = 'add a campaign. <name> <verbose_name> <number> <active>' def handle(self, *args, **options): active = True if len(args) == 3: (name,vname,number) = args elif len(args) == 4: (name,vname,number,active) = args if active in ("0", "False", "FALSE", "false"): active = False else: active = True else: print "%s\n bad usage" % self.help sys.exit(1) ncampaign = Campaign(active=active, name=name, verbose_name=vname, max_instances=number) ncampaign.save() print "created %s with %s. active=%s" % (name, number, active) # vi: ts=4 expandtab
import { Button, Checkbox, FormControl, FormControlLabel, FormGroup, InputLabel, MenuItem, TextField, } from "@mui/material"; import { useForm } from "react-hook-form"; import { NavLink, useNavigate } from "react-router-dom"; import CredentialsModel from "../../../Models/CredentialsModel"; import { authStore } from "../../../Redux/AuthState"; import notify from "../../../Utils/Notify"; import authService from "../../../Services/AuthService"; import "./Login.css"; import { useEffect } from "react"; import AsideNavIcon from "../../../assets/Images/VacationImages/aside-icon.png"; function Login(): JSX.Element { const { register, handleSubmit, formState: { errors }, setValue, } = useForm<CredentialsModel>(); const navigate = useNavigate(); useEffect(() => { navigate("/login"); let list = document.querySelectorAll(".list"); list.forEach((item) => { item.classList.remove("active"); }); list[2].classList.add("active"); }, []); async function send(credentials: CredentialsModel): Promise<void> { try { // console.log("Arrived!"); await authService.login(credentials); const token = authStore.getState(); const user = token.user; // notify.success(`Welcome back! ${user.firstName} ${user.lastName}`); let list = document.querySelectorAll(".list"); list.forEach((item) => { item.classList.remove("active"); }); list[0].classList.add("active"); authStore.getState().justLoggedIn = true; navigate("/vacations"); } catch (err) { notify.error("Invalid email or password please try again"); } } return ( <div id="page" className="site login-show"> <div className="container"> <div className="wrapper"> <div className="login"> <div className="content-heading"> <div className="y-style"> <div className="logo"> <img src={AsideNavIcon} alt="" /> </div> <div className="welcome"> <h2> Welcome <br /> Back! </h2> <p>Get start to be creative</p> </div> </div> </div> <div className="content-form"> <div className="y-style"> <form onSubmit={handleSubmit(send)}> <p> <label>Email</label> <input className="weird-border" required autoFocus type="text" placeholder="Enter your email" {...register("email")} pattern="^(?!.*\.{2})(?!\.)[A-Za-z0-9_.'-]*[A-Za-z0-9_'-]@(?!_)(?:[a-z0-9_'-]+\.)+[a-z0-9_'-]{2,}$" /> </p> <p> <label>Password</label> <input className="weird-border" required type="password" placeholder="Enter your password" {...register("password")} max="256" min="4" /> </p> <p> <Button sx={{ marginTop: "10px", }} color="success" type="submit" variant="outlined" > Submit </Button> </p> </form> <div className="afterform"> <NavLink className="link" to="/register"> <Button className="t-login" sx={{ color: "green", }} > Register </Button> </NavLink> </div> </div> </div> </div> </div> </div> </div> ); } export default Login;
<script setup> import { reactive, ref, computed } from 'vue' import {defineEmits} from 'vue' // defineProps({ // msg: { // type: String, // required: true // } // }) // const state = ref({ count: 0 }) // function increment(){ // state.value.count++ // } // const author = reactive({ // name: 'John Doe', // books:[ // 'vue 1', // 'vue 2', // 'vue 3' // ] // }) // const publishedBoooksMessage = computed(() => { // return author.books.length > 0 ? 'Yes' : 'No' // }) // const isActive = ref(true) // const hasError = ref(true) // const items = ref([{id:1,message:'Foaaaao'},{id:2,message:'Bassssssar'}]) const emit = defineEmits(['addItem']) const inputs = reactive({name:"", url:""}) function submit(){ if (!inputs.url.includes('http')){ inputs.url = `http://${inputs.url}` } const data = JSON.parse(JSON.stringify(inputs)) emit("addItem", data); inputs.name = ""; inputs.url = ""; } </script> <template> <form class="form" @submit.prevent="submit"> <div class="mb-3"> <label class="form-label"> Name </label> <input v-model="inputs.name" type="text" class="form-control" /> </div> <div class="mb-3"> <label class="form-label"> URL </label> <input v-model="inputs.url" type="text" class="form-control" /> </div> <button type="submit" class="btn btn-success"> Add </button> </form> </template>
/* FreeRTOS V7.0.1 - Copyright (C) 2011 Real Time Engineers Ltd. *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! http://www.FreeRTOS.org - Documentation, latest information, license and contact details. http://www.SafeRTOS.com - A version that is certified for use in safety critical systems. http://www.OpenRTOS.com - Commercial support, development, porting, licensing and training services. */ /*----------------------------------------------------------- * Simple GPIO (parallel port) IO routines. *-----------------------------------------------------------*/ /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" /* Standard demo include. */ #include "partest.h" /* Freescale includes. */ #include "common.h" /* Only the LEDs on one of the two seven segment displays are used. */ #define partstMAX_LEDS 4 /* The bits used to control the LEDs on the TWR-K60N512. */ const unsigned long ulLEDs[ partstMAX_LEDS ] = { ( 1UL << 10UL ), ( 1UL << 29UL ), ( 1UL << 28UL ), ( 1UL << 11UL ) }; /*-----------------------------------------------------------*/ void vParTestInitialise( void ) { /* Set PTA10, PTA11, PTA28, and PTA29 (connected to LED's) for GPIO functionality. */ PORTA_PCR10 = ( 0 | PORT_PCR_MUX( 1 ) ); PORTA_PCR11 = ( 0 | PORT_PCR_MUX( 1 ) ); PORTA_PCR28 = ( 0 | PORT_PCR_MUX( 1 ) ); PORTA_PCR29 = ( 0 | PORT_PCR_MUX( 1 ) ); /* Change PTA10, PTA11, PTA28, PTA29 to outputs. */ GPIOA_PDDR=GPIO_PDDR_PDD( ulLEDs[ 0 ] | ulLEDs[ 1 ] | ulLEDs[ 2 ] | ulLEDs[ 3 ] ); /* Start with LEDs off. */ GPIOA_PTOR = ~0U; } /*-----------------------------------------------------------*/ void vParTestSetLED( unsigned long ulLED, signed portBASE_TYPE xValue ) { if( ulLED < partstMAX_LEDS ) { if( xValue == pdTRUE ) { GPIOA_PCOR = ulLEDs[ ulLED ]; } else { GPIOA_PSOR = ulLEDs[ ulLED ]; } } } /*-----------------------------------------------------------*/ void vParTestToggleLED( unsigned long ulLED ) { if( ulLED < partstMAX_LEDS ) { GPIOA_PTOR = ulLEDs[ ulLED ]; } } /*-----------------------------------------------------------*/ long lParTestGetLEDState( unsigned long ulLED ) { long lReturn = pdFALSE; if( ulLED < partstMAX_LEDS ) { lReturn = GPIOA_PDOR & ulLEDs[ ulLED ]; if( lReturn == 0 ) { lReturn = pdTRUE; } else { lReturn = pdFALSE; } } return lReturn; }
package commands; import console.ConsoleOutput; import console.OutputColors; import exceptions.IllegalArgumentsException; import managers.CommandManager; /** * Команда 'help' * Вывести справку по доступным командам */ public class Help extends Command { private final CommandManager commandManager; private final ConsoleOutput consoleOutput; public Help(ConsoleOutput consoleOutput, CommandManager commandManager) { super("help", ": вывести справку по доступным командам"); this.commandManager = commandManager; this.consoleOutput = consoleOutput; } /** * Исполнить команду * * @param args аргументы команды * @throws IllegalArgumentsException неверные аргументы команды */ @Override public void execute(String args) throws IllegalArgumentsException { if (!args.isBlank()) throw new IllegalArgumentsException(); commandManager.getCommands() .forEach(command -> consoleOutput.println(OutputColors.toColor(command.getName(), OutputColors.CYAN) + command.getDescription())); } }
# Radboud FUS measurement kit <a name="readme-top"></a> <div align="center"> <img src="/images/Radboud-logo.jpg" alt="ru_logo" width="auto" height="70" /> <img src="/images/fuslogo.png" alt="fus_logo" width="auto" height="70"> <img src="/images/igtlogo.jpeg" alt="igt_logo" width="auto" height="70"> </div> <div align="center"> <img src="/images/sonorover-one.png" alt="sonorover-one" width="1000" height="auto" /> </div> <!-- TABLE OF CONTENTS --> # 📗 Table of Contents - [📖 About the Project](#about-project) - [Key Features](#key-features) - [👥 Authors](#authors) - [✒️ How to cite](#how-to-cite) - [💻 Getting Started](#getting-started) - [Setup](#setup) - [Usage](#usage) - [🔭 Future Features](#future-features) - [🤝 Contributing](#contributing) - [📝 License](#license) <!-- PROJECT DESCRIPTION --> # 📖 Radboud FUS measurement kit <a name="about-project"></a> (Project id: **0003429** ) **Radboud FUS measurement kit** is a comprehensive kit allowing precise hydrophone measurements of your TUS transducers for verification, characterization and monitoring overall system performance. This project is facilitated by the Radboud Focused Ultrasound Initiative. For more information, please visit the [website](https://www.ru.nl/en/donders-institute/research/research-facilities/focused-ultrasound-initiative-fus). <!-- Features --> ## Key Features <a name="key-features"></a> - **Affordable** - **High quality** <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- AUTHORS --> ## 👥 Authors <a name="authors"></a> 👤 **[Stein Fekkes](https://www.ru.nl/en/people/fekkes-s), [FUS Initiative](https://www.ru.nl/en/donders-institute/research/research-facilities/focused-ultrasound-initiative-fus), Radboud University** - GitHub: [@StefFek-GIT](https://github.com/StefFek-GIT) - [LinkedIn](https://linkedin.com/in/sfekkes) 👤 **[Margely Cornelissen](https://www.ru.nl/en/people/cornelissen-m), [FUS Initiative](https://www.ru.nl/en/donders-institute/research/research-facilities/focused-ultrasound-initiative-fus), Radboud University** - GitHub: [@MaCuinea](https://github.com/MaCuinea) - [LinkedIn](https://linkedin.com/in/margely-cornelissen) 👤 **Erik Dumont, [Image Guided Therapy (IGT)](http://www.imageguidedtherapy.com/)** - [LinkedIn](https://linkedin.com/in/erik-dumont-986a814) <p align="right">(<a href="#readme-top">back to top</a>)</p> ## ✒️ How to cite <a name="how-to-cite"></a> If you use this kit in your research or project, please cite it as follows: Margely Cornelissen, Stein Fekkes (Radboud University, Nijmegen, The Netherlands) & Erik Dumont (Image Guided Therapy, Pessac, France) (2024), Radboud FUS measurement kit (version 0.8), https://github.com/Donders-Institute/Radboud-FUS-measurement-kit <!-- GETTING STARTED --> ## 💻 Getting Started <a name="getting-started"></a> ### Setup #### Hardware The hardware files are stored as native solidworks files and as step format. The main assembly file: W0003510-00-01-SonoRover One.SLDASM will contain all references to part files and subassemblies. #### Software Clone this repository to your desired folder: - Git terminal ``` sh cd my-folder git clone git@github.com:Donders-Institute/Radboud-FUS-measurement-kit.git ``` - GitHub Desktop 1. Click on 'Current repository'. 2. Click on 'Add' and select 'Clone repository...'. 3. Choose 'URL' and paste the following repository URL: [https://github.com/Donders-Institute/Radboud-FUS-measurement-kit.git](https://github.com/Donders-Institute/Radboud-FUS-measurement-kit.git) 4. Choose your desired folder and clone the repository. ### Usage #### Software The software is provided as-is. As it is currently version 0.8, it is mainly intended for inspiration and preliminary use. We are actively working on cleaning, restructuring, and rewriting the code for a 1.0 release in the future. The primary script is [characterizationPipeline.py](characterizationPipeline.py). Running this script launches a GUI to set the following parameters: 1. **Path and filename of protocol excel file**: Select the required protocol Excel file. Refer to the example template [here](SonoRover%20One/software/example%20input/protocol%20template/template_protocol_input.xlsx). This file contains sequences with various foci, power outputs, timing parameters, and/or coordinate grids. It is specific to a driving system-transducer combination. **Note**: If you change the headers in the Excel file, you must also update the corresponding headers in the code. - **Sequence**: The sequence number, ranging from 1 to the total number of sequences in the Excel file. - **Modulation**: Choose from Square, Linear, or Tukey ramp shapes from the dropdown. - **Ramp duration [us]** - **Ramp duration step size [us]**: Temporal resolution of ramping, applicable only for the IGT system. - **Pulse duration [us]** - **Pulse Repetition Frequency [Hz]** - **Pulse Repetition Interval [ms]** - **Pulse Train Duration [ms]** - **Isppa [W/cm²], Global power [mW], or Amplitude [%]**: Select the applicable power parameter for the chosen driving system from the dropdown. Amplitude is used for the IGT system; Isppa or global power is used for the Sonic Concepts system. It is recommended to use global power for the Sonic Concepts system. **Note**: If Isppa is chosen, a conversion table in an Excel file (e.g., [here](SonoRover%20One/software/example%20input/protocol%20template/isppa_to_global_power_template.xlsx)) is required with global power in mW and intensity in W/cm2. If you change the headers in the Excel file, you must also update the corresponding headers in the code. - **Corresponding value**: The value for the selected power parameter. - **Path and filename of Isppa to Global power conversion Excel**: Provide the path to the Isppa-global power conversion table. This parameter is skipped if Isppa is not selected. - **Focus [mm]** - **Coordinates based on Excel file or parameters on the right?**: Choose to define a grid using a coordinate Excel file or by defining grid sizes in this file from the dropdown. Coordinate file examples are [here](SonoRover%20One/software/example%20input/coordinate%20templates). **Note**: Coordinate files allow more flexibility in grid point arrangement. All grids are based on a chosen zero point (for example: focus or exit plane). Headers in the Excel file must match those used in the code. - **Path and filename of coordinate Excel**: Provide the path to the coordinate Excel file. This parameter is skipped if 'Coordinates based on Excel file' is not selected. **Note**: if 'Parameters on the right' is not chosen as input parameter, below parameters are skipped. - **max. ± x [mm] w.r.t. relative zero**: The maximum movement in the ±x direction in mm relative to the chosen zero point. - **max. ± y [mm] w.r.t. relative zero**: The maximum movement in the ±y direction in mm relative to the chosen zero point. - **max. ± z [mm] w.r.t. relative zero**: The maximum movement in the ±z direction in mm relative to the chosen zero point. - **direction_slices**: Choose the direction of the slices from the dropdown. Refer to the example image in the [protocol template](SonoRover%20One/software/example%20input/protocol%20template/template_protocol_input.xlsx). - **direction_rows**: Choose the direction of the rows from the dropdown. Refer to the example image in the [protocol template](SonoRover%20One/software/example%20input/protocol%20template/template_protocol_input.xlsx). - **direction_columns**: Choose the direction of the columns from the dropdown. Refer to the example image in the [protocol template](SonoRover%20One/software/example%20input/protocol%20template/template_protocol_input.xlsx). - **step_size_x [mm]**: The grid size in the x-direction. - **step_size_y [mm]**: The grid size in the y-direction. - **step_size_z [mm]**: The grid size in the z-direction. 2. **US Driving System** 3. **Transducer** 4. **Operating frequency [kHz]** 5. **COM port of US driving system**: Required for Sonic Concepts driving system. 6. **COM port of positioning system** 7. **Hydrophone acquisition time [us]** 8. **Picoscope sampling frequency multiplication factor**: Minimum multiplication factor is 2. 9. **Absolute G code x-coordinate of relative zero**: The x-coordinate of the chosen zero point. 10. **Absolute G code y-coordinate of relative zero**: The y-coordinate of the chosen zero point. 11. **Absolute G code z-coordinate of relative zero**: The z-coordinate of the chosen zero point. 12. **Perform all protocols in sequence without waiting for user input?**: If yes, the characterization will proceed through all sequences in the protocol Excel file without stopping for input between sequences. After all parameters are set, click 'ok' to start the characterization. Log files and an output folder will be created in the same directory as the protocol Excel file. ![image](https://github.com/Donders-Institute/Radboud-FUS-measurement-kit/assets/134381864/dcc80f2d-cc04-42ec-afbc-a19f55aed547) <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- FUTURE FEATURES --> ## 🔭 Future Features <a name="future-features"></a> #### Software - [ ] **Implemented driving system abstract class to easily integrate driving systems from other manufacturers** - [ ] **Cleaner, restructured and more robust code** - [ ] **Compatibility check of chosen equipment** <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- CONTRIBUTING --> ## 🤝 Contributing <a name="contributing"></a> Contributions, issues, and feature requests are welcome! Feel free to check the [issues page](../../issues/). If you have any questions, please feel free to reach out to us via email at fus@ru.nl. We'd love to hear from you. <p align="right">(<a href="#readme-top">back to top</a>)</p> ## 📝 License <a name="license"></a> This project is [MIT](./LICENSE) licensed. <p align="right">(<a href="#readme-top">back to top</a>)</p>
import {useState, useEffect} from 'react'; import constate from 'constate'; import {useMutation} from 'react-query'; import {pushData} from '../query/mutations'; const useDataContext = () => { const [name, setName] = useState<string>(''); const [age, setAge] = useState<string>(''); const mutation = useMutation(() => pushData(name, age)); const {isLoading, error, mutate} = mutation; useEffect(() => { error && console.warn(error); }, [error]); return {name, setName, age, setAge, isLoading, mutate}; }; export const [UserDataProvider, useUserData] = constate(useDataContext);
{% load static %} <!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"> <meta property="og:type" content="website"> <meta property="og:url" content="https://carwash.binokor-asaka.uz/"> <meta property="og:title" content="Car Wash"> <meta property="og:description" content="Simple CRM System for Car Wash"> <meta property="og:image" content="https://metatags.io/assets/meta-tags-16a33a6a8531e519cc0936fbba0ad904e52d35f34a46c97a2c9f6f7dd7d336f2.png"> <!-- links --> <link rel="stylesheet" href="{% static 'assets/css/style.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/responsive.css' %}"> <link rel="stylesheet" href="https://site-assets.fontawesome.com/releases/v6.3.0/css/all.css"> <title>Car Wash | {% block title %}{% endblock title %}</title> </head> <body> <header> <div class="section-wrapp"> <div class="container"> <div class="header-top_wrapper"> <h1 class="main-header_title"> {% block page %}{% endblock page %} </h1> <div class="header-info_wrapper"> <div class="header-info_item_wrapper"> <i class="fa-solid fa-clock"></i> <span class="header-time_info"></span> </div> <div class="header-info_item_wrapper"> <i class="fa-solid fa-calendar-days"></i> <span class="header-date_info"></span> </div> <div class="header-info_item_wrapper"> <i class="fa-solid fa-clouds"></i> <span class="booked-wzs-day-number">Topilmadi°</span> </div> <div class="header-info_item_wrapper"> <a href="{% url 'common:logout' %}" class="order-detail_buy_btn">Chiqish</a> </div> </div> </div> </div> </div> <div class="header-side_bar_wrapper"> <div class="header-side_bar"> <nav class="header_navigation"> <ul class="nav_items_wrapper"> <li class="nav_item selected"> <a class="nav-link" href="{% url 'common:home' %}"><i class="fa-solid fa-house"></i></a> </li> <li class="nav_item"> <a class="nav-link" href="{% url 'common:order' %}"><i class="fa-solid fa-square-plus"></i></a> </li> <li class="nav_item"> <a class="nav-link" href="{% url 'common:queue' %}"><i class="fa-solid fa-car-mirrors"></i></a> </li> <li class="nav_item"> <a class="nav-link" href="{% url 'common:washing' %}"><i class="fa-solid fa-car-wash"></i></a> </li> <li class="nav_item"> <a><i class="fa-solid fa-square-dollar"></i></a> </li> <li class="nav_item nav_item_last"> <a class="nav-link" href="{% url 'common:settings' %}"><i class="fa-duotone fa-gear"></i></a> </li> <li class="nav_item_helper"></li> </ul> </nav> <div class="nav_bg"></div> </div> </div> </header> <main> <div class="main-hero"> <div class="section-wrapp"> <div class="container"> {% block content %} {% endblock %} </div> </div> </div> </main> <footer> <div class="section-wrapp"> <div class="container"> <ul class="footer-list"> <li class="footer-item"> Copyright © 2023. CarWash. All rights reserved. </li> <li class="footer-item"> <ul class="footer-inner_list"> <li class="footer-inner_item"> <a href="#"> <i class="fa-brands fa-facebook-f"></i> </a> </li> <li class="footer-inner_item"> <a href="#"> <i class="fa-brands fa-instagram"></i> </a> </li> </ul> </li> </ul> </div> </div> </footer> <script src="{% static 'assets/js/vanilla-tilt_settings.js' %}"> </script> <script src="{% static 'assets/js/vanilla-tilt.min.js' %}"></script> <script src="{% static 'assets/js/main.js' %}"></script> <script> var navLinks = document.querySelectorAll('.nav-link'); navLinks.forEach((e) => { if (e.pathname === window.location.pathname) { e.parentElement.classList.add('selected'); } else { e.parentElement.classList.remove('selected') } }) </script> {% block script %} {% endblock %} </body> </html>
package in.fssa.fertagriboomi.servlets; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import in.fssa.fertagriboomi.exception.ServiceException; import in.fssa.fertagriboomi.exception.ValidationException; import in.fssa.fertagriboomi.model.DeliveryAddresses; import in.fssa.fertagriboomi.model.OrderItems; import in.fssa.fertagriboomi.model.Orders; import in.fssa.fertagriboomi.service.DeliveryAddressService; import in.fssa.fertagriboomi.service.OrdersService; /** * Servlet implementation class OrderDetailsServlet */ @WebServlet("/order/order_details") public class OrderDetailsServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int orderId = Integer.parseInt(request.getParameter("order_id")); try { int addressId = new OrdersService().getAddressIdByOrderId(orderId); Orders order = new OrdersService().findOrderIdByOrderId(orderId); DeliveryAddresses address = new DeliveryAddressService().findAddressById(addressId); List<OrderItems> orderItemsList = new OrdersService().findAllOrderItemsByOrderId(orderId); //System.out.println(orderItemsList); request.setAttribute("ORDERS", order); request.setAttribute("ORDER_ITEMS_LIST", orderItemsList); request.setAttribute("ADDRESS_DETAILS", address); RequestDispatcher dispatcher = request.getRequestDispatcher("/order_details.jsp"); dispatcher.forward(request, response); } catch (ServiceException | ValidationException e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } } }
####################### Modals ####################### ## Modal to explain what median is median_modal <- modalDialog( h3("What is the median?"), p("This a measure of the typical wait experienced by patients being treated in this Board/specialty who completed their wait in the period. One simple way of explaining this statistic is that approximately half of patients treated waited less than the figure shown and half experienced a wait greater than this."), size = "l", easyClose = TRUE, fade=TRUE, footer = modalButton("Close (Esc)") ) ## Modal to explain what 90th percentile is p90_modal <- modalDialog( h3("What is the 90th percentile?"), p("This reflects the maximum wait experienced by 9 out of 10 patients that were treated in this Board/specialty in this period."), size = "l", easyClose = TRUE, fade=TRUE, footer = modalButton("Close (Esc)") ) cp_1_modal <- modalDialog( h3("What is the final priority?"), p("The data captured and presented reflects the category most recently applied to the patient. If the patient's clinical need is deemed to have increased during a routine re-evaluation then their catgeory may be escalated, for example from category P4 to P3; conversely, if the patient's condition has stabilised, they may have been moved to a lower category. As a result, there may be occasions where patients are recorded as having waited beyond the recommended timescales outlined in the Framework but may have only been assigned to the more urgent category recently."), size = "l", easyClose = TRUE, fade=TRUE, footer = modalButton("Close (Esc)") ) ### Modal links observeEvent(input$btn_modal_median, { showModal(median_modal) }) observeEvent(input$btn_modal_90th, { showModal(p90_modal) }) observeEvent(input$btn_modal_cp1, { showModal(cp_1_modal) })
const router = require("express").Router(); const User = require("../models/User"); const CryptoJS = require("crypto-js"); const verify = require("./verifyToken"); //UPDATE router.put("/:id", verify, async (req, res) => { if (req.user.id === req.params.id || req.user.isAdmin) { if (req.body.password) { req.body.password = CryptoJS.AES.encrypt( req.body.password, process.env.SECRET_KEY ).toString(); } try { const updatedUser = await User.findByIdAndUpdate( req.params.id, { $set: req.body, }, { new: true } ); res.status(200).json(updatedUser); } catch (err) { res.status(500).json(err); } } else { res.status(403).json("You can update only your account!"); } }); //DELETE router.delete("/:id", verify, async (req, res) => { if (req.user.id === req.params.id || req.user.isAdmin) { try { await User.findByIdAndDelete(req.params.id); res.status(200).json("User has been deleted..."); } catch (err) { res.status(500).json(err); } } else { res.status(403).json("You can delete only your account!"); } }); //GET router.get("/find/:id", async (req, res) => { try { const user = await User.findById(req.params.id); const { password, ...info } = user._doc; res.status(200).json(info); } catch (err) { res.status(500).json(err); } }); //GET ALL router.get("/", verify, async (req, res) => { console.log("users get all route"); const query = req.query.new; if (req.user.isAdmin) { try { const users = query ? await User.find().sort({ _id: -1 }).limit(10) : await User.find(); res.status(200).json(users); } catch (err) { res.status(500).json(err); } } else { res.status(403).json("You are not allowed to see all users!"); } }); //GET USER STATS router.get("/stats", async (req, res) => { const today = new Date(); const latYear = today.setFullYear(today.setFullYear() - 1); const MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; try { const data = await User.aggregate([ { $project: { month: { $month: "$createdAt" }, }, }, { $group: { _id: "$month", total: { $sum: 1 }, }, }, ]); res.status(200).json(data); } catch (err) { res.status(500).json(err); } }); module.exports = router;
import 'package:app_movil_s2/main.dart'; // ignore: unused_import import 'package:app_movil_s2/screen/home_screen.dart'; import 'package:flutter/material.dart'; void main() => runApp(const Otro()); class Otro extends StatelessWidget { const Otro({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Material App', theme: ThemeData.dark().copyWith( primaryColor: Colors.orange, hintColor: Colors.black, scaffoldBackgroundColor: Colors.black, appBarTheme: const AppBarTheme( color: Colors.orange, ), ), home: Scaffold( appBar: AppBar( title: const Text('Otro Halloween',style: TextStyle(fontSize: 38.0),), actions: <Widget>[ IconButton( icon: const Icon(Icons.arrow_back), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const MainScreen()), ); }, ), ] ), body: const Center( child: Text('Otro Screen Halloween'), ), ), ); } }
# Importing necessary libraries import pandas as pd from sklearn.cluster import KMeans from sklearn.model_selection import train_test_split from imblearn.over_sampling import SMOTE from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from sklearn.model_selection import KFold from sklearn.metrics import balanced_accuracy_score # Importing the datasheet data = pd.read_excel("data2sep.xlsx", sheet_name="fin_full") # KMeans Clustering kmeans = KMeans(n_clusters=2, random_state=20, n_init='auto') labels = kmeans.fit_predict(data[['tot_deaths_pm']]) data['label'] = labels # Splitting in train and test dataset # Dropping columns with non-numerical values and tot_deaths_pm (used for labels) data.drop(['continent', 'location', 'tot_deaths_pm'], axis=1, inplace=True) X = data.drop('label', axis=1) y = data['label'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=20) # SMOTE technique smote = SMOTE(random_state=20) X_train_smote, y_train_smote = smote.fit_resample(X_train, y_train) # Scaling between [0,1] using MinMaxScaler scaler = MinMaxScaler() X_train_scaled = scaler.fit_transform(X_train_smote) X_test_scaled = scaler.transform(X_test) # Random Forest rf_param_grid = {'n_estimators': range(50, 501, 50)} kf = KFold(n_splits=5, shuffle=True, random_state=20) # 5-Fold rf_scores = [] # Initialise the random forest scores array # Looping over all the parameters (n_estimators) for n_estimators in rf_param_grid['n_estimators']: rf = RandomForestClassifier(n_estimators=n_estimators, random_state=20) scores = [] # Splitting the training dataset into train test data for 5-Fold validation for train_idx, test_idx in kf.split(X_train_scaled): X_train_cv, X_test_cv = X_train_scaled[train_idx], X_train_scaled[test_idx] y_train_cv, y_test_cv = y_train_smote[train_idx], y_train_smote[test_idx] rf.fit(X_train_cv, y_train_cv) y_pred_cv = rf.predict(X_test_cv) scores.append(balanced_accuracy_score(y_test_cv, y_pred_cv)) # scores based on balanced_accuracy rf_scores.append((n_estimators, sum(scores) / len(scores))) rf_best_params = max(rf_scores, key=lambda x: x[1]) # Extracting the best scores print(f'Random Forest Optimal Hyperparameters: n_estimators={rf_best_params[0]}') rf_data = pd.DataFrame(rf_scores, columns=['n_estimators', 'Scores']) # Converting array to dataframe to export to excel # Neural Network nn_param_grid = { 'hidden_layer_sizes': [(50, 50), (55, 55), (60, 60), (65, 65), (70, 70), (75, 75), (80, 80), (50, 50, 50), (55, 55, 55), (60, 60, 60), (65, 65, 65), (70, 70, 70), (75, 75, 75), (80, 80, 80)], 'activation': ['relu', 'logistic'] # Defining the params (logistic -> sigmoid) } kf = KFold(n_splits=5, shuffle=True, random_state=20) # 5-fold nn_scores = [] # Initialise the neural network scores array # Looping over all the parameters (activation, hidden_layer_sizes) for activation in nn_param_grid['activation']: for hidden_layer_sizes in nn_param_grid['hidden_layer_sizes']: nn = MLPClassifier(hidden_layer_sizes=hidden_layer_sizes, activation=activation, max_iter=500, random_state=20) scores = [] # Splitting the training dataset into train test data for 5-Fold validation for train_idx, test_idx in kf.split(X_train_scaled): X_train_cv, X_test_cv = X_train_scaled[train_idx], X_train_scaled[test_idx] y_train_cv, y_test_cv = y_train_smote[train_idx], y_train_smote[test_idx] nn.fit(X_train_cv, y_train_cv) y_pred_cv = nn.predict(X_test_cv) scores.append(balanced_accuracy_score(y_test_cv, y_pred_cv)) # scores based on balanced_accuracy nn_scores.append((hidden_layer_sizes, activation, sum(scores) / len(scores))) nn_best_params = max(nn_scores, key=lambda x: x[2]) # Extracting the best scores print(f'Neural Network Optimal Hyperparameters: hidden_layer_sizes={nn_best_params[0]}, activation="{nn_best_params[1]}"') # Converting array to dataframe to export to excel nn_data = pd.DataFrame(nn_scores, columns=['Layers', 'Activation', 'Scores']) nn_data['Activation'] = nn_data['Activation'].replace({'logistic' : 'sigmoid'}) # Exporting to excel file with pd.ExcelWriter('hptoutput.xlsx') as writer: rf_data.to_excel(writer, sheet_name='random_forest', index=False) nn_data.to_excel(writer, sheet_name='neural_net', index=False)
import { FC, useEffect, useRef } from 'react'; interface YouTubePlayerProps { videoId: string; } export const YouTubePlayer: FC<YouTubePlayerProps> = ({ videoId }) => { const playerRef = useRef<YT.Player | null>(null); useEffect(() => { const protocol = window.location.protocol; const host = window.location.host; const initializePlayer = () => { if (window.YT) { onYouTubeIframeAPIReady(); } else { const youtubeScript = document.createElement('script'); youtubeScript.src = 'https://www.youtube.com/iframe_api'; document.body.appendChild(youtubeScript); } }; const onPlayerReady = () => { playerRef.current?.playVideo(); }; const onYouTubeIframeAPIReady = () => { if (playerRef.current) { playerRef.current.destroy(); } playerRef.current = new YT.Player('youtube-player', { height: '390', width: '640', videoId, playerVars: { autoplay: 1, origin: `${protocol}//${host}`, }, events: { onReady: onPlayerReady, }, }); }; initializePlayer(); (window as any).onYouTubeIframeAPIReady = onYouTubeIframeAPIReady; return () => { if (playerRef.current) { playerRef.current.destroy(); } delete (window as any).onYouTubeIframeAPIReady; }; }, [videoId]); return ( <div className='video'> <div id='youtube-player' className='video__iframe' /> </div> ); };
import { Location } from '@angular/common'; import { Injectable } from '@angular/core'; import { NavigationStart, Router } from '@angular/router'; import { RestApiService } from '../rest-api/rest-api.service'; import { Api } from 'src/app/constant/api'; import { Employee } from 'src/app/entities/employee'; import { Token } from 'src/app/entities/token'; @Injectable({ providedIn: 'root', }) export class AuthService { accessToken!: string | null; public isAuthorized = false; public isAdmin!: boolean; url = 'http://localhost:3000/v1/api/auth/refreshToken'; constructor( private rest: RestApiService, private router: Router, private location: Location ) { this.getAccessToken(); this.router.events.subscribe((event) => { if (event instanceof NavigationStart) { if (this.accessToken && event.url === '/login') { console.log('logined'); this.location.back(); } } }); } async login(user: any) { try { const response = await this.rest.post(`${Api.AUTH}/login`, user); let value = response as { token: Token; employee: Employee }; console.log(value); localStorage.setItem('token', value.token.accessToken); // localStorage.setItem('refreshToken', value.token.refreshToken); localStorage.setItem('employeeId', value.employee._id.toString()); this.router.navigate(['/']); } catch (error: any) { console.log(error.error.message); } } async register(user: any) { try { await this.rest.post(`${Api.AUTH}/register`, user); this.router.navigate(['/login']); } catch (error: any) { console.log(error.error.message); } } getAccessToken() { const token = localStorage.getItem('token'); this.accessToken = token; return this.accessToken; } async refreshToken() { const refreshTokenDB: string | null = localStorage.getItem('refreshToken'); const refreshToken = await this.rest.post(this.url, { refreshToken: refreshTokenDB, }); return refreshToken; } logout() { this.isAuthorized = false; } }
const { CommandInteraction } = require("discord.js"); const { Colores } = require("../resources"); const DarkShop = require("./DarkShop"); const InteractivePages = require("./InteractivePages"); class Top { #res = []; /** * * @param {*} users Mongoose Documents * @param {CommandInteraction} interaction * @param {String} type */ constructor(users, interaction, type) { this.type = type; this.users = users; this.interaction = interaction; this.Emojis = this.interaction.client.Emojis; this.base = { author_icon: this.interaction.guild.iconURL({ dynamic: true }) ?? this.interaction.member.displayAvatarURL(), color: Colores.verdejeffrey, description: ``, addon: `{txt}`, footer: `Página {ACTUAL} de {TOTAL}`, icon_footer: this.interaction.guild.iconURL() } this.top = new Map(); } async init() { // generate top switch (this.type) { case "dinero": await this.#currencyTop(); break; case "exp": await this.#expTop(); break; case "rep": await this.#repTop(); break; case "warns": await this.#warnsTop(); break; } //interactive pages const interactive = new InteractivePages(this.base, this.top, 5); return interactive.init(this.interaction); } async #currencyTop() { const { Currency, DarkCurrency } = this.interaction.client.getCustomEmojis(this.interaction.guild.id); const darkshop = new DarkShop(this.interaction.guild); this.base.title = `Top de ${Currency.name}`; for await (const user of this.users) { const member = this.interaction.guild.members.cache.get(user.user_id) ?? null; // agregar la cantidad de darkcurrency if (member && !member.user.bot) { let darkcurrency = user.economy.dark?.currency ?? 0; let darkcurrencyValue = user.economy.dark?.currency ? await darkshop.equals(null, user.economy.dark.currency) : 0; let finalQuantity = darkcurrencyValue != 0 ? darkcurrencyValue + user.economy.global.currency : user.economy.global.currency; let toPush = { user_id: member.user.id, currency: darkcurrency, // numero de dj que tiene currencyValue: Math.round(darkcurrencyValue), // lo que valen esos dcurrency en dinero ahora mismo total: Math.round(finalQuantity), // la suma del valor de los dcurrency y el dinero alltime: user.data.counts.normal_currency } if(toPush.total > 0) this.#res.push(toPush); } } // ordenar de mayor a menor this.#sort(); const userRank = this.#getRank(this.#res, this.interaction.user.id); this.base.footer = `Eres el ${userRank.textRank} en el top • Página {ACTUAL} de {TOTAL}` // determinar el texto a agregar for await (const user of this.#res) { let darkshopMoney; if (user.currency != 0) darkshopMoney = ` (${DarkCurrency}${user.currency.toLocaleString('es-CO')}➟**${Currency}${user.currencyValue.toLocaleString('es-CO')}**)` else darkshopMoney = ""; const txt = this.#getTxt(user, [`${Currency}**${user.total.toLocaleString('es-CO')}**${darkshopMoney}`, `|| Obtenido desde siempre: **${Currency}${user.alltime.toLocaleString("es-CO")}** ||`]) this.top.set(user.user_id, { txt }) } } async #expTop() { this.base.title = "Top de EXP" this.users.forEach(user => { const member = this.interaction.guild.members.cache.get(user.user_id) ?? null; if (member && !member.user.bot) { let toPush = { user_id: member.user.id, level: user.economy.global.level, total: user.economy.global.exp } if(toPush.total > 0) this.#res.push(toPush) } }); // ordenar de mayor a menor this.#sort(); const userRank = this.#getRank(this.#res, this.interaction.user.id); this.base.footer = `Eres el ${userRank.textRank} en el top • Página {ACTUAL} de {TOTAL}` // determinar el texto a agregar for await (const user of this.#res) { const txt = this.#getTxt(user, [ `Nivel: \`${user.level.toLocaleString("es-CO")}\``, `EXP: \`${user.total.toLocaleString('es-CO')}\`` ]) this.top.set(user.user_id, { txt }) } } async #repTop() { this.base.title = "Top de Reputaciones" this.users.forEach(user => { const member = this.interaction.guild.members.cache.get(user.user_id) ?? null; if (member && !member.user.bot) { let toPush = { user_id: member.user.id, total: user.economy.global.reputation } if (toPush.total != 0) this.#res.push(toPush) } }); // ordenar de mayor a menor this.#sort(); const userRank = this.#getRank(this.#res, this.interaction.user.id); this.base.footer = `Eres el ${userRank.textRank} en el top • Página {ACTUAL} de {TOTAL}` // determinar el texto a agregar for await (const user of this.#res) { const txt = this.#getTxt(user, [ `Reputaciones: \`${user.total.toLocaleString("es-CO")}\`` ]) this.top.set(user.user_id, { txt }) } } async #warnsTop() { this.base.title = "Top de Warns" this.users.forEach(user => { const member = this.interaction.guild.members.cache.get(user.user_id) ?? null; if (member && !member.user.bot) { let toPush = { user_id: member.user.id, total: user.data.counts.warns } if (toPush.total != 0) this.#res.push(toPush) } }); // ordenar de mayor a menor this.#sort(); const userRank = this.#getRank(this.#res, this.interaction.user.id); this.base.footer = `Eres el ${userRank.textRank} en el top • Página {ACTUAL} de {TOTAL}` // determinar el texto a agregar for await (const user of this.#res) { const txt = this.#getTxt(user, [ `Warns totales: \`${user.total.toLocaleString("es-CO")}\`` ]) this.top.set(user.user_id, { txt }) } } #getRank(query, id) { let number = query.findIndex(x => x.user_id === id) + 1; let textRank; switch (number) { case 0: textRank = `último`; break; case 1: textRank = `🏆${number}ro`; break; case 2: textRank = `🥈${number}do`; break; case 3: textRank = `🥉${number}ro`; break; case 4: case 5: case 6: textRank = `${number}to`; break; case 7: case 10: textRank = `${number}mo`; break; case 9: textRank = `${number}no`; break; default: textRank = `${number}vo`; break; } return { textRank, number } } #getTxt(user, reps = []) { let txt, toadd = ""; const rank = this.#getRank(this.#res, user.user_id).number const member = this.interaction.guild.members.cache.find(x => x.id === user.user_id); reps.forEach(rep => { toadd += `\n**—** ${rep}` }); if (rank === 1) { txt = `**🏆 ${member.user.username}**${toadd}\n\n`; } else if (rank === 2) { txt = `**🥈 ${member.user.username}**${toadd}\n\n`; } else if (rank === 3) { txt = `**🥉 ${member.user.username}**${toadd}\n\n`; } else { txt = `**${rank}. ${member.user.username}**${toadd}\n\n`; } return txt; } #sort() { this.#res.sort(function (a, b) { if (a.total > b.total) { return -1; } if (a.total < b.total) { return 1; } return 0; }) } } module.exports = Top
/* * timer.h: Threaded timer class * * See the README file for copyright information and how to reach the author. * */ #ifndef __XINELIBOUTPUT_TIMER_H #define __XINELIBOUTPUT_TIMER_H // // cTimerCallback : timer callback handler interface // class cTimerCallback { protected: virtual bool TimerEvent() = 0; // return false to cancel timer virtual void *TargetId() { return (void*)this; } virtual int size() { return sizeof(*this); } virtual bool is(void *data, int len) { return len==sizeof(*this) && TargetId()==data; } friend class cTimerThread; public: static void Set(cTimerCallback *, unsigned int TimeoutMs); static void Cancel(cTimerCallback *); virtual ~cTimerCallback(); }; // // cTimerEvent : base class for timer events // class cTimerEvent : protected cTimerCallback { private: cTimerEvent(cTimerEvent&); protected: cTimerEvent() {}; virtual void AddEvent(unsigned int TimeoutMs); static void CancelAll(void *Target); template<class TCLASS> friend void CancelTimerEvents(TCLASS*); friend class cTimerThread; public: static void Cancel(cTimerEvent *&); }; // // make gcc 3.4.5 happy // template<class TCLASS, class TRESULT> cTimerEvent *CreateTimerEvent(TCLASS *c, TRESULT (TCLASS::*fp)(void), unsigned int TimeoutMs); template<class TCLASS, class TRESULT, class TARG1> cTimerEvent *CreateTimerEvent(TCLASS *c, TRESULT (TCLASS::*fp)(TARG1), TARG1 arg1, unsigned int TimeoutMs); template<class TCLASS> cTimerEvent *CreateTimerEvent(TCLASS *c, void (TCLASS::*fp)(void), unsigned int TimeoutMs, bool runOnce = true); template<class TCLASS, class TARG1> cTimerEvent *CreateTimerEvent(TCLASS *c, void (TCLASS::*fp)(TARG1), TARG1 arg1, unsigned int TimeoutMs, bool runOnce = true); // // Timer event templates // template <class TCLASS, class TRESULT> class cTimerFunctorR0 : public cTimerEvent { public: protected: typedef TRESULT (TCLASS::*TFUNC)(void); cTimerFunctorR0(TCLASS *obj, TFUNC f, unsigned int TimeoutMs) : m_obj(obj), m_f(f) { AddEvent(TimeoutMs); } virtual ~cTimerFunctorR0() {}; virtual bool TimerEvent(void) { return (*m_obj.*m_f)(); } virtual void *TargetId() { return (void*)m_obj; } virtual int size() { return sizeof(*this); } virtual bool is(void *data, int len) { return sizeof(*this)==len && !memcmp(this,data,len); } private: TCLASS *m_obj; TFUNC m_f; friend cTimerEvent *CreateTimerEvent<TCLASS,TRESULT>(TCLASS*,TFUNC,unsigned int); }; template <class TCLASS, class TRESULT, class TARG1> class cTimerFunctorR1 : public cTimerEvent { public: protected: typedef TRESULT (TCLASS::*TFUNC)(TARG1); cTimerFunctorR1(TCLASS *obj, TFUNC f, TARG1 arg1, unsigned int TimeoutMs) : m_obj(obj), m_f(f), m_arg1(arg1) { AddEvent(TimeoutMs); } virtual ~cTimerFunctorR1() {}; virtual bool TimerEvent(void) { return (*m_obj.*m_f)(m_arg1); } virtual void *TargetId() { return (void*)m_obj; } virtual int size() { return sizeof(*this); } virtual bool is(void *data, int len) { return sizeof(*this)==len && !memcmp(this,data,len); } private: TCLASS *m_obj; TFUNC m_f; TARG1 m_arg1; friend cTimerEvent *CreateTimerEvent<TCLASS,TRESULT,TARG1>(TCLASS*,TFUNC,TARG1,unsigned int); }; template <class TCLASS> class cTimerFunctor0 : public cTimerEvent { public: protected: typedef void (TCLASS::*TFUNC)(void); cTimerFunctor0(TCLASS *obj, TFUNC f, unsigned int TimeoutMs, bool runOnce) : m_obj(obj), m_f(f), m_runAgain(!runOnce) { AddEvent(TimeoutMs); } virtual ~cTimerFunctor0() {}; virtual bool TimerEvent(void) { (*m_obj.*m_f)(); return m_runAgain; } virtual void *TargetId() { return (void*)m_obj; } virtual int size() { return sizeof(*this); } virtual bool is(void *data, int len) { return sizeof(*this)==len && !memcmp(this,data,len); } private: TCLASS *m_obj; TFUNC m_f; bool m_runAgain; friend cTimerEvent *CreateTimerEvent<TCLASS>(TCLASS*,TFUNC,unsigned int,bool); }; template <class TCLASS, class TARG1> class cTimerFunctor1 : public cTimerEvent { public: protected: typedef void (TCLASS::*TFUNC)(TARG1); cTimerFunctor1(TCLASS *obj, TFUNC f, TARG1 arg1, unsigned int TimeoutMs, bool runOnce) : m_obj(obj), m_f(f), m_arg1(arg1), m_runAgain(!runOnce) { AddEvent(TimeoutMs); } virtual ~cTimerFunctor1() {}; virtual bool TimerEvent(void) { (*m_obj.*m_f)(m_arg1); return m_runAgain; } virtual void *TargetId() { return (void*)m_obj; } virtual int size() { return sizeof(*this); } virtual bool is(void *data, int len) { return sizeof(*this)==len && !memcmp(this,data,len); } private: TCLASS *m_obj; TFUNC m_f; TARG1 m_arg1; bool m_runAgain; friend cTimerEvent *CreateTimerEvent<TCLASS,TARG1>(TCLASS*,TFUNC,TARG1,unsigned int,bool); }; // // Function templates for timer event creation and cancellation // template<class TCLASS, class TRESULT> cTimerEvent *CreateTimerEvent(TCLASS *c, TRESULT (TCLASS::*fp)(void), unsigned int TimeoutMs) { return new cTimerFunctorR0<TCLASS,TRESULT>(c,fp,TimeoutMs); } template<class TCLASS, class TRESULT, class TARG1> cTimerEvent *CreateTimerEvent(TCLASS *c, TRESULT (TCLASS::*fp)(TARG1), TARG1 arg1, unsigned int TimeoutMs) { return new cTimerFunctorR1<TCLASS,TRESULT,TARG1>(c,fp,arg1,TimeoutMs); } template<class TCLASS> cTimerEvent *CreateTimerEvent(TCLASS *c, void (TCLASS::*fp)(void), unsigned int TimeoutMs, bool runOnce = true) { return new cTimerFunctor0<TCLASS>(c,fp,TimeoutMs,runOnce); } template<class TCLASS, class TARG1> cTimerEvent *CreateTimerEvent(TCLASS *c, void (TCLASS::*fp)(TARG1), TARG1 arg1, unsigned int TimeoutMs, bool runOnce = true) { return new cTimerFunctor1<TCLASS,TARG1>(c,fp,arg1,TimeoutMs,runOnce); } template<class TCLASS> void CancelTimerEvents(TCLASS *c) { cTimerEvent::CancelAll((void*)c); } // usage: // // 'this' derived from cTimerHandler: // Set timer: // cTimerCallback::Set(this, TimeoutMs); // Cancel timer: // - return false from handler or // - call cTimerCallback::Cancel(this); or // - delete 'this' object // // any function of any class: // Set timer: // - cTimerEvent *event = CreateTimerEvent(...); // example: // CreateTimerEvent(this, &cXinelibDevice::TimerEvent, 1, 1000); // -> calls this->cXinelibDevice::TimerEvent(1) every second until stopped. // Cancel timer: // - if handler returns bool: return false from handler // - handler is type of void: timer runs only once // - call cTimerEvent::Cancel(event) // Cancel all timers for object: // - Call CancelTimerEvents(object) // - Call CancelTimerEvents(this) #endif // __XINELIBOUTPUT_TIMER_H
import React, { useEffect, useState } from "react"; import { Grid } from "@material-ui/core"; import { DayTime } from "./DayTime"; import { PontoContext } from "../../Contexts/Ponto"; import MenuPeriod from "./MenuPeriod"; import axios from "axios"; import { APIBaseURL } from "../../Settings/Settings.json"; import Cookies from "js-cookie"; class InfoDay { constructor() { this.Date = null; this.Entrada = null; this.Almoço = null; this.Volta = null; this.Saída = null; } } export default function Ponto() { const [dataParsed, setDataParsed] = useState([]); const [period, setPeriod] = useState({}); useEffect(() => { if (period.start) fetchTimes(); }, [period]); const parseDay = (dateTime) => { if (dateTime === null) { return new Date(1900, 1, 1, 0, 0); } let date_str = dateTime.toString().split("T")[0].split("-"); let time_str = dateTime.toString().split("T")[1].split(":"); let date = new Date( parseInt(date_str[0]), parseInt(date_str[1]) - 1, parseInt(date_str[2]), parseInt(time_str[0]), parseInt(time_str[1]) ); return date; }; const parseDateWork = (workDay) => { let day = new InfoDay(); Object.keys(workDay).map((key) => { switch (key.toLowerCase()) { case "dateday": day.Date = parseDay(workDay[key]); break; case "startday": day.Entrada = parseDay(workDay[key]); break; case "stoplunch": day.Almoço = parseDay(workDay[key]); break; case "backlunch": day.Volta = parseDay(workDay[key]); case "endday": day.Saída = parseDay(workDay[key]); } }); return day; }; const parseData = (data) => { let aux = []; data.map((day) => { let workDay = parseDateWork(day); aux.push(workDay); }); setDataParsed(aux); }; const fetchTimes = () => { let url = APIBaseURL + "timework/getTimeWorkPeriod" + "?start=" + period.start.toISOString() + "&end=" + period.end.toISOString(); axios .get(url, { headers: { Authorization: `Bearer ${Cookies.get("FINLOGIN")}`, }, }) .then((res) => res.data) .then((data) => parseData(data)); }; return ( <PontoContext> <Grid container spacing={1} direction="column"> <Grid item xs={12}> <MenuPeriod setDate={setPeriod} /> </Grid> {dataParsed.map((day, index) => { return ( <Grid key={index} item xs={12}> <DayTime infoDay={day} /> </Grid> ); })} </Grid> </PontoContext> ); }
from flask import Flask, render_template app = Flask(__name__) # Additional page to say hello in the root route @app.route('/') def hello_page(): return render_template ("hello.html") # /play route render a template with 3 blue boxes @app.route('/play') def play(): return render_template ("index.html", number_of_boxes = 3, color = "#9FC5F8")# Put the default values for number of boxes and color # /play/<x> route render a template with x number of blue boxes @app.route('/play/<number>') def play_with_number(number): if (number.isnumeric()): # Check if the number is valid number = int(number) # convert the string to number return render_template ("index.html", number_of_boxes = number, color = "#9FC5F8")# Pass the number of boxes that entered by the user in URL return "Error: please enter a valid number of boxes, try again !" # /play/<x>/<color> route render a template with x number of boxes the color of the provided value @app.route('/play/<number>/<color>') def play_with_color(number, color): if (number.isnumeric()): # Check if the number is valid number = int(number) # convert the string to number return render_template ("index.html", number_of_boxes = number, color = color)# Pass the number of boxes and color entered by the user in URL return "Error: please enter a valid number of boxes, try again !" # Ensure this file is being run directly and not from a different module if (__name__ == "__main__"): app.run(debug = True) # Run the app in debug mode
Computing Computing Parallel Interface – durch Arduino gesteuert (3) Jens Lemkamp Im dritten Teil der Parallel-Interface- und Arduino-Reihe wollen wir unser erstes Modell zum Leben erwecken. Es handelt sich um einen Klassiker der MSR-Technik (Messen-SteuernRegeln). Ich habe aus dem Ur-Computing-Kasten (30554) des Jahres 1984 das Modell ‚Antennenrotor‘ gewählt, um die Analog-Eingänge des Arduinos für eine typische Regelungsaufgabe zu verwenden, die immer wieder für unterschiedliche Zwecke auftaucht [1]. Aufgabenstellung Eine drehbar gelagerte Antenne soll mittels eines Drehrades, welches als sogenanntes Stellglied fungiert, ferngesteuert werden. Die Antenne ist auf einem Zahn-Drehkranz montiert. In der Mitte ist ein Potentiometer verbaut, welches bei Rotation der Antenne verstellt wird und somit die Winkelposition misst. Der Drehkranz wird durch einen Minimot mit Getriebe und Schnecke angetrieben (Abb. 1). Damit gliedert sich der Gesamtaufbau in folgende Komponenten: 1. Drehrad mit Poti (Sollwert-Eingabe) 2. Poti im Drehkranz (Istwert-Messung) 3. Motor, Getriebe, Zahnkranz (Stellglied) Regelung Hier haben wir es schon mit den drei wesentlichen Teilen einer einfachen Regelung zu tun. Warum der Aufbau eine echte Regelung ist und keine Steuerung, erklärt sich aus dem geschlossenen Regelkreis (Abb. 2) [2]. Für unser Antennenmodell bedeutet das: · Geregelt wird die Regelgröße x (Drehwinkel der Antenne). x ist damit auch der sogenannte Istwert. · Die Führungsgröße w ist der Sollwert des Antennenwinkels, einstellbar durch das Handrad. · e ist die Regelabweichung. Diese ist Null, wenn Soll- und Istwert gleich sind, d. h. die Antenne hat die von uns eingestellte (Soll-) Position angefahren. · Der Regler (in unserem Modell der Arduino mit Programm) bildet aus dem Soll- und Istwert die Stellgröße y. Das ist der Wert, um den die Antenne verfahren werden muss, wenn sie nicht die Sollposition hat. · Die Regelstrecke besteht aus Motor, Schnecke und Zahnrad. · z ist die Störgröße. In der Realität könnte z. B. der Wind eine Kraft auf die Antenne bringen, welche zur Veränderung des Istwertes (also des Drehwinkels der Antenne) führt. Der Regler stellt dann automatisch nach. Somit haben wir einen geschlossen Regelkreis. vollständig Schaltung Ein Potentiometer (kurz: Poti) ist ein verstellbarer Widerstand mit drei Anschlüssen. Ein Schleifer wird durch die Verstellung des Drehwinkels einer Achse über eine Widerstandsbahn geführt. Die beiden äußeren Anschlüsse werden mit 0 V und +5 V verbunden (Abb. 3). Das Poti verhält sich wie ein Spannungsteiler (Abb. 4). Widerstände werden mit dem Formelzeichen R bezeichnet, Spannungen mit U. Die Einheiten sind W (sprich: Ohm) für den elektrischen Widerstand und V (sprich: Volt) für die Spannung. Dabei gelten die folgenden Gesetzmäßigkeiten: · Die beiden Einzelwiderstände addieren sich zu einem Gesamtwiderstand: R1 + R2 = Rges. · Die Spannungen am Spannungsteiler verhalten sich zueinander im Verhältnis wie die Widerstände zueinander: U1 + U2 = Uges. Dabei ist U1 die Spannung über R1 und U2 über R2. Uges. ist die Spannung über beide Widerstände, hier also 5 V. Der Schleifer ist mit dem Anschluss ‚X‘ verbunden. Wenn das Poti ganz nach rechts bzw. im Schaltbild nach oben gedreht wird, ist der Schleifer direkt mit + bzw. 5 V verbunden, auf Linksanschlag bzw. unten entsprechend mit 0 V. Bei Einstellungen zwischen 5 V und 0 V stellen sich analog zum Drehwinkel Zwischenwerte ein. Sollte z. B. der Schleifer exakt auf Mittelstellung stehen, erhalten wir 2,5 V am Anschluss ‚X‘. Wenn unser Poti einen Gesamtwiderstand von z. B. 100 kW hat (dieser Wert ist meist auf dem Gehäuse aufgedruckt; manchmal wird das W-Zeichen weggelassen und man findet nur ‚100 k‘) und das Poti auf Mittelstellung gedreht wird, teilen sich die Widerstandswerte genau auf. Mit einem Ohm-Meter (ist in den meisten Multimetern bzw. Vielfach-Messgeräten enthalten) kann man dann also zwischen dem Mittelabgriff und jedem der beiden anderen Anschlüssen jeweils 50 kW (also genau die Hälfte von 100 kW) messen. Achtung: Wenn man Widerstandswerte mit einem Messgerät messen möchte, muss jede Computing externe Spannung (also unsere 5 V aus dem Beispiel) abgeschaltet sein, sonst kann das Messgerät zerstört werden. Außerdem sollten alle Anschlüsse frei und nicht mit anderen Schaltungsteilen verbunden sein, weil man sonst fehlerhafte Messwerte erhalten kann. Die Spannungen verhalten sich wie die Widerstandswerte, demnach stellen sich bei Uges. = 5 V und Poti auf Mittelstellung folgende Werte ein: R1 = 50 kW, R2 = 50 kW R1 + R2 = Rges. = 50 kW + 50 kW = 100 kW U1 = 2,5 V, U2 = 2,5 V U1 + U2 = Uges. = 2,5 V + 2,5 V = 5 V Ein weiteres Beispiel: Der Schleifer des Potis steht nahe bei dem 5 V- und deutlich vom 0 V-Anschluss entfernt, sagen wir bei ca. 10 %. Dann haben wir folgende Verhältnisse: Daher erklären sich auch die 5 V aus den Rechenbeispielen, denn der Arduino wird mit 5 V versorgt und die Analog-DigitalWandler vertragen ohne zusätzliche Beschaltung maximal 5 V. Ein zweites Poti stellt als Handrad die Istwerteingabe dar. R1 = 10 kW, R2 = 90 kW R1 + R2 = Rges. = 10 kW + 90 kW = 100 kW Und für die Spannungen gilt: U1 = 0,5 V (10 %), U2 = 4,5V (90 %) U1 + U2 = Uges. = 0,5 V + 4,5 V = 5 V Man kann auch sagen, dass sich die Spannung am Mittelanschluss des Potis proportional zum Drehwinkel verhält. Das setzt ein ideales, lineares Potentiometer voraus. Damit können wir jetzt den Drehwinkel einer Poti-Achse mittels der Spannung messen, die sich mit dem Drehwinkel verändert. Modell Der Aufbau des Modells ist trivial: Ich habe es aus der Anleitung des 1984er Computing-Kastens weitestgehend original nachgebaut [1]. Wir treiben einen Drehkranz mittels Mini-Motor und Schnecke an. In der Mitte des Drehkranzes ist ein Poti montiert, welches den Istwert (Drehwinkel der Antenne) misst und an den Arduino weitergibt (Abb. 5). Der Analog0-Eingang des Arduinos wird mit dem Mittelabgriff des Handrades verbunden, der Mittelabgriff des Potis vom Drehkranz mit dem Analog1-Eingang (Abb. 6). Die beiden anderen Anschlüsse der Potis werden jeweils mit 0 V und 5 V verbunden, und zwar der Anschluss am Linkseinschlag mit 0 V, der Anschluss am Rechtseinschlag mit +5 V (dabei die Spannungsversorgung vom Arduino verwenden!). Programm Das Programm ist im Ablauf den alten Basic-Programmen aus dieser Baukastenreihe nachempfunden: · Das entsprechende Bit wird im Ausgabebyte gesetzt und der Motor durch die Funktion motout() gestartet. motout() ist eine Funktion, welche die die Bits des outbyte zum Interface überträgt (siehe Gesamtprogramm) und damit den Motor startet. · Wenn i < 1 ist die Sollposition erreicht (Istwert = Sollwert), und es werden eine Lampe ein- und der Motor ausgeschaltet. Die beiden Variablen ‚soll‘ und ‚ist‘ werden mit den Messwerten aus dem Analog/Digitalwandlern des Arduino versorgt. Aus diesen beiden Werten wird die Regelabweichung e gebildet und in der Variablen i hinterlegt. Das ist der Absolutwert der Differenz von Soll- und Istwert. Jetzt kommt es zu einer Besonderheit, ohne die das Programm bzw. der Regler nicht ordentlich arbeiten würde. Dieser Effekt ist auch in der Programmieranleitung des UrComputing-Kastens beschrieben, und die Lösung dieses typischen Regel-Problems habe ich – mit abgewandelten Parametern – übernommen. Diese Werte (Soll, Ist, Differenz) werden über die serielle Schnittstelle an einen evtl. angeschlossenen Computer gesendet und können dort mit einem Terminal-Programm angezeigt werden. Jetzt wird ausgewertet und der Motor ggf. gefahren: · Wenn der Sollwert kleiner als der Istwert ist, muss der Motor die Antenne links herum drehen. · Ist der Sollwert größer als der Istwert, muss die Antenne entsprechend nach rechts rotiert werden. Bei Erreichen der Soll-Position genügt es nicht, den Motor einfach nur zu stoppen: Computing durch die Masse des Antennenmastes, des Drehkranzes und des Getriebes läuft die Antenne etwas nach. Das führt dann dazu, dass beim nächsten Durchlauf des Loops der Regler feststellt, dass der Sollwert überschritten wurde und nachregelt, d. h. der Motor fährt zurück, wird beim Ziel (Sollwert = Istwert) wieder gestoppt, und läuft wieder etwas nach, diesmal aber in der anderen Richtung. Damit zittert die Antenne um ihre eigentlich Soll-Position bzw. fährt je nach Masse hin und her: Der Regler „schwingt“. Eigentlich ist aber gewünscht, das die Antenne bei Erreichen der Soll-Position stoppt und dort bleibt, bis ein neuer Sollwert kommt oder aber eine Störgröße die Antenne aus der Position bringt und der Regler deshalb eingreifen muss. Daher erfolgt im letzten Teil der Hauptschleife eine Abfrage, wie weit der Istwert vom Sollwert entfernt ist. Ist die Differenz kleiner 30, wird eine kleine Pause eingelegt und der Motor gestoppt. Die Länge dieser Pause bis zum Abschalten ist abhängig von der Differenz. Je kleiner die Differenz, desto eher wird der Motor abgeschaltet. Danach geht der Regelkreis weiter im Durchlauf, d. h. wir fragen erneut die Sollund Istwerte ab und durchlaufen den Regler wie gehabt; der Motor wird eingeschaltet, falls noch eine Differenz zwischen Soll und Istwert besteht. Durch die Pause (Differenz i∙3) in Millisekunden wird der Motor schon vor Erreichen des Sollwertes abgebremst, weil wir ihn nicht durchlaufen lassen, sondern abschalten. Damit wird der Motor langsamer, je näher wir dem Ziel kommen, und der Regler schwingt nicht über. Die Länge der Pause und der Beginn der Bremsphase sollte der Mechanik des Modells angepasst werden, da sie abhängig von der Masse der Konstruktion, dem Getriebe, dem Motor und der genauen Spannung ist, mit der unsere Anlage versorgt wird. Quellen [1] fischertechnik: Programmieranleitung. fischertechnik Computing, fischerwerke 1984. [2] Gerhard Bader: Grundlagen der digitalen Regelung. In: fischertechnik und Computer, CHIP Special 1987, S. 19-25.
import { useContext } from 'react'; import { UserContext } from '../../contexts/UserContext'; import { AiOutlineHome } from 'react-icons/ai'; import { CgSearch } from 'react-icons/cg'; import { BsChatDots } from 'react-icons/bs'; import { AiOutlineBell } from 'react-icons/ai'; import { AiOutlineUser } from 'react-icons/ai'; import Link from 'next/link'; import { Container } from './styles'; const FooterMenu = () => { const { notifications } = useContext(UserContext); const size = '26px'; const color = '#7d1d39'; return ( <Container> <Link href="/members"> <div> <CgSearch size={size} color={color} /> </div> </Link> <Link href="/notifications"> <div> <AiOutlineBell size={size} color={color} /> {notifications.length > 0 ? ( <div className="notification">{notifications.length}</div> ) : null} </div> </Link> <Link href="/feed"> <div> <AiOutlineHome size={size} color={color} /> </div> </Link> <Link href="/chat"> <div> <BsChatDots size={size} color={color} /> </div> </Link> <Link href="/profile"> <div> <AiOutlineUser size={size} color={color} /> </div> </Link> </Container> ); }; export default FooterMenu;
<!DOCTYPE html> <html lang="pt" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Pokemon Relatório</title> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link rel="stylesheet" type="text/css" th:href="@{/css/styles.css}"> </head> <body class="container"> <h2 style="text-align: center;">Relatório com dados de pokemon</h2> <form method="get"> <select id="tipo" name="tipo"> <option value="">Selecione o Tipo</option> <option th:each="tipo : ${tipos}" th:value="${tipo}" th:text="${tipo}">Todos tipos</option> </select> <div> <button type="submit" class="btn-pdf-view" th:formaction="@{/pokemons/pdf/view}">visualizar PDF</button> <button type="submit" class="btn-pdf-download" th:formaction="@{/pokemons/pdf/download}">download PDF</button> <button type="submit" class="btn-html-view" th:formaction="@{/pokemons/html}">visualizar HTML</button> </div> </form> <div> <a th:href="@{/}">voltar</a> </div> <div class="pikachu_background"> <div class="eye eye-left"> <div class="eye-inner"></div> </div> <div class="eye eye-right"> <div class="eye-inner"></div> </div> </div> <script> const container = document.querySelector('.container'); container.addEventListener('mousemove', (e) => { const eyes = document.querySelectorAll('.eye'); [].forEach.call(eyes, function (eye) { // Get the mouse position on the horizontal axis let mouseX = eye.getBoundingClientRect().right; // If it's the left eye we need the left offset instead the right if (eye.classList.contains('eye-left')) { mouseX = eye.getBoundingClientRect().left; } // Now we also need the vertical offset let mouseY = eye.getBoundingClientRect().top; // Now, we are going to calculate the radian value of the offset between the mouse and the eye let radianDegrees = Math.atan2(e.pageX - mouseX, e.pageY - mouseY); // Let's convert this into a degree-based value so we can use it in CSS let rotationDegrees = radianDegrees * (180 / Math.PI) * -1 + 180; // Now, all we have to do is add this degree to our eye! eye.style.transform = `rotate(${rotationDegrees}deg)`; }); }); </script> </body> </html>
from datetime import datetime from typing import NoReturn from django.contrib import messages from django.http import HttpRequest, JsonResponse, HttpResponse from django.shortcuts import render, redirect from django.views.decorators.http import require_http_methods, require_POST from backend.models import Invoice from backend.types.htmx import HtmxHttpRequest @require_http_methods(["POST"]) def edit_invoice(request: HtmxHttpRequest): try: invoice = Invoice.objects.get(id=request.POST.get("invoice_id", "")) except Invoice.DoesNotExist: return JsonResponse({"message": "Invoice not found"}, status=404) if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization: return JsonResponse( {"message": "You do not have permission to edit this invoice"}, status=403, ) elif request.user != invoice.user: return JsonResponse( {"message": "You do not have permission to edit this invoice"}, status=403, ) attributes_to_updates = { "date_due": datetime.strptime(request.POST.get("date_due", ""), "%Y-%m-%d").date(), "date_issued": request.POST.get("date_issued"), "client_name": request.POST.get("to_name"), "client_company": request.POST.get("to_company"), "client_address": request.POST.get("to_address"), "client_city": request.POST.get("to_city"), "client_county": request.POST.get("to_county"), "client_country": request.POST.get("to_country"), "self_name": request.POST.get("from_name"), "self_company": request.POST.get("from_company"), "self_address": request.POST.get("from_address"), "self_city": request.POST.get("from_city"), "self_county": request.POST.get("from_county"), "self_country": request.POST.get("from_country"), "notes": request.POST.get("notes"), "invoice_number": request.POST.get("invoice_number"), "vat_number": request.POST.get("vat_number"), "reference": request.POST.get("reference"), "sort_code": request.POST.get("sort_code"), "account_number": request.POST.get("account_number"), "account_holder_name": request.POST.get("account_holder_name"), } for column_name, new_value in attributes_to_updates.items(): setattr(invoice, column_name, new_value) invoice.save() if request.htmx: messages.success(request, "Invoice edited") return render(request, "base/toasts.html") return JsonResponse({"message": "Invoice successfully edited"}, status=200) @require_POST def change_status(request: HtmxHttpRequest, invoice_id: int, status: str) -> HttpResponse: status = status.lower() if status else "" if not request.htmx: return redirect("invoices:dashboard") try: invoice = Invoice.objects.get(id=invoice_id) except Invoice.DoesNotExist: return return_message(request, "Invoice not found") if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization or request.user != invoice.user: return return_message(request, "You don't have permission to make changes to this invoice.") if status not in ["paid", "overdue", "pending"]: return return_message(request, "Invalid status. Please choose from: pending, paid, overdue") if invoice.payment_status == status: return return_message(request, f"Invoice status is already {status}") invoice.payment_status = status invoice.save() dps = invoice.dynamic_payment_status if (status == "overdue" and dps == "pending") or (status == "pending" and dps == "overdue"): message = f""" The invoice status was automatically changed from <strong>{status}</strong> to <strong>{dps}</strong> as the invoice dates override the manual status. """ return return_message(request, message, success=False) send_message(request, f"Invoice status been changed to <strong>{status}</strong>", success=True) return render(request, "pages/invoices/dashboard/_modify_payment_status.html", {"status": status, "invoice_id": invoice_id}) @require_POST def edit_discount(request: HtmxHttpRequest, invoice_id: str): discount_type = "percentage" if request.POST.get("discount_type") == "on" else "amount" discount_amount_str: str = request.POST.get("discount_amount", "") percentage_amount_str: str = request.POST.get("percentage_amount", "") if not request.htmx: return redirect("invoices:dashboard") try: invoice: Invoice = Invoice.objects.get(id=invoice_id) except Invoice.DoesNotExist: return return_message(request, "Invoice not found", False) if not invoice.has_access(request.user): return return_message(request, "You don't have permission to make changes to this invoice.", False) if discount_type == "percentage": try: percentage_amount = int(percentage_amount_str) if percentage_amount < 0 or percentage_amount > 100: raise ValueError except ValueError: return return_message(request, "Please enter a valid percentage amount (between 0 and 100)", False) invoice.discount_percentage = percentage_amount else: try: discount_amount = int(discount_amount_str) if discount_amount < 0: raise ValueError except ValueError: return return_message(request, "Please enter a valid discount amount", False) invoice.discount_amount = discount_amount invoice.save() messages.success(request, "Discount was applied successfully") response = render(request, "base/toasts.html") response["HX-Trigger"] = "update_invoice" return response def return_message(request: HttpRequest, message: str, success: bool = True) -> HttpResponse: send_message(request, message, success) return render(request, "base/toasts.html") def send_message(request: HttpRequest, message: str, success: bool = False) -> None: if success: messages.success(request, message) else: messages.error(request, message)
public without sharing class GNE_SFA2_Scheduler implements Database.Batchable<sObject>, Database.Stateful { public Enum JobType {Queued, Processing, Scheduled, Executed, Failed} private static final String SCHEDULER_JOB_PREFIX = 'SFA Scheduler - '; private static final String SCHEDULER_JOB_SUFIX_DATE_FORMAT = 'yyyy-MM-dd'; private static final Integer BATCH_SIZE = 1; private static final String SCHEDULE_DISABLE_VALUE = 'disabled'; private static Set<String> alreadyScheduled; private String jobType; // START STATIC METHODS public static Id scheduleJob(GNE_SFA2_Scheduler.Schedulable handler, String jobType, String scheduledExpression) { return scheduleJob(handler, jobType, scheduledExpression, null); } public static Id scheduleJob(GNE_SFA2_Scheduler.Schedulable handler, String jobType, String scheduledExpression, Map<String,String> jobProperties) { Id newJobId = null; if(alreadyScheduled==null) { alreadyScheduled = new Set<String>(); } if(alreadyScheduled.add(jobType.toUpperCase())) { newJobId = intScheduleJob(handler, jobType, scheduledExpression, jobProperties); } return newJobId; } private static Id intScheduleJob(GNE_SFA2_Scheduler.Schedulable handler, String jobType, String scheduledExpression, Map<String,String> jobProperties) { SFA2_Scheduler_Job_gne__c job = getSchedulerJob(jobType, true); if(job!=null) { DateTime scheduleDT = getJobScheduleTime(scheduledExpression); CronTrigger cronJob = getCurrentScheduleCronJob(job.Cron_Job_Id_gne__c); DateTime nowTimeStamp = DateTime.now(); if(scheduleDT!=null && cronJob==null && job.Status_gne__c!=GNE_SFA2_Scheduler.JobType.Queued.name()) { job.Queued_Date_gne__c = nowTimeStamp; job.Scheduled_Date_gne__c = job.Executed_Date_gne__c = null; job.Status_gne__c = GNE_SFA2_Scheduler.JobType.Queued.name(); job.Status_Details_gne__c = null; job.Cron_Job_Id_gne__c = null; job.Job_Properties_json_gne__c = jobProperties!=null && !jobProperties.isEmpty() ? JSON.serialize(jobProperties) : null; job.Scheduled_Expression_gne__c = scheduledExpression; job.Handler_json_gne__c = JSON.serialize(handler); job.Handler_Class_gne__c = handler.getSelfClass().getName(); job.OwnerId = UserInfo.getUserId(); if(!System.isFuture() && !System.isBatch() && !System.isQueueable() && !System.isScheduled()) { scheduleJob(job, true); } Database.upsert(job, SFA2_Scheduler_Job_gne__c.Job_Type_gne__c, false); } } return job!=null ? job.Id : null; } public static void onUpdateSchedulerJob(List<SFA2_Scheduler_Job_gne__c> triggerNew, List<SFA2_Scheduler_Job_gne__c> triggerOld) { Integer idx=0; for(SFA2_Scheduler_Job_gne__c job : triggerNew) { SFA2_Scheduler_Job_gne__c oldJob = triggerOld[idx++]; if(job.Status_gne__c==GNE_SFA2_Scheduler.JobType.Processing.name() && oldJob.Status_gne__c==GNE_SFA2_Scheduler.JobType.Queued.name()) { scheduleJob(job); } } } public static void onDeleteSchedulerJob(List<SFA2_Scheduler_Job_gne__c> triggerOld) { Integer idx=0; for(SFA2_Scheduler_Job_gne__c job : triggerOld) { if(job.Status_gne__c==GNE_SFA2_Scheduler.JobType.Scheduled.name() && String.isNotBlank(job.Cron_Job_Id_gne__c) && job.Cron_Job_Id_gne__c instanceof Id) { try { System.abortJob(job.Cron_Job_Id_gne__c); } catch(Exception ex) {} } } } public static void scheduleJob(SFA2_Scheduler_Job_gne__c job) { scheduleJob(job, false); } public static void scheduleJob(SFA2_Scheduler_Job_gne__c job, Boolean tryAgainMode) { try { DateTime scheduleDT = getJobScheduleTime(job.Scheduled_Expression_gne__c); String jobType = job.Job_Type_gne__c; GNE_SFA2_Scheduler scheduler = new GNE_SFA2_Scheduler(jobType); job.Cron_Job_Id_gne__c = System.scheduleBatch(scheduler, SCHEDULER_JOB_PREFIX + jobType + ' ' + scheduleDT.format(SCHEDULER_JOB_SUFIX_DATE_FORMAT), Integer.valueOf((scheduleDT.getTime()-System.now().getTime())/(1000*60))+1, BATCH_SIZE); job.Status_gne__c = GNE_SFA2_Scheduler.JobType.Scheduled.name(); job.Scheduled_Date_gne__c = DateTime.now(); } catch(Exception ex) { if(tryAgainMode!=true) { job.Status_gne__c = GNE_SFA2_Scheduler.JobType.Failed.name(); job.Status_Details_gne__c = ex.getMessage() + '\n' + ex.getStackTraceString(); } logException(ex, job.Job_Type_gne__c); } } private static SFA2_Scheduler_Job_gne__c getSchedulerJob(String jobType, Boolean lockRecord) { SFA2_Scheduler_Job_gne__c result = null; if(lockRecord) { try { List<SFA2_Scheduler_Job_gne__c> jobs = [ SELECT Job_Type_gne__c, Status_gne__c, Cron_Job_Id_gne__c, Job_Properties_json_gne__c, Handler_json_gne__c, Handler_Class_gne__c, Scheduled_Expression_gne__c, Queued_Date_gne__c, Scheduled_Date_gne__c, Executed_Date_gne__c FROM SFA2_Scheduler_Job_gne__c WHERE Job_Type_gne__c = :jobType FOR UPDATE ]; result = !jobs.isEmpty() ? jobs[0] : new SFA2_Scheduler_Job_gne__c(Name = jobType, Job_Type_gne__c = jobType); } catch(Exception ex) {} } else { List<SFA2_Scheduler_Job_gne__c> jobs = [ SELECT Job_Type_gne__c, Status_gne__c, Cron_Job_Id_gne__c, Job_Properties_json_gne__c, Handler_json_gne__c, Handler_Class_gne__c, Scheduled_Expression_gne__c, Queued_Date_gne__c, Scheduled_Date_gne__c, Executed_Date_gne__c FROM SFA2_Scheduler_Job_gne__c WHERE Job_Type_gne__c = :jobType ]; result = !jobs.isEmpty() ? jobs[0] : new SFA2_Scheduler_Job_gne__c(Name = jobType, Job_Type_gne__c = jobType); } return result; } private static DateTime getJobScheduleTime(String scheduledExpression) { DateTime result = null; String scheduleTimeAsString = scheduledExpression; if(scheduleTimeAsString!=SCHEDULE_DISABLE_VALUE) { Pattern dayAndTimePattern = Pattern.compile('(\\d|[\\*\\?]);(\\d{1,2}|[\\*\\?]):(\\d{1,2}|[\\*\\?])'); scheduleTimeAsString = dayAndTimePattern.matcher(scheduleTimeAsString).matches() ? scheduleTimeAsString : '6;5:10'; DateTime now = DateTime.now(); Integer currentDay = Integer.valueOf(now.formatGmt('u')); Integer currentHour = Integer.valueOf(now.formatGmt('HH')); Integer currentMinute = Integer.valueOf(now.formatGmt('mm')); Matcher m = dayAndTimePattern.matcher(scheduleTimeAsString); m.find(); Boolean dailyOrWeeklyMode = !m.group(1).isNumeric(); Integer dayOfWeek = dailyOrWeeklyMode ? currentDay : Integer.valueOf(m.group(1)); Boolean hourlyMode = !m.group(2).isNumeric(); Integer hour = hourlyMode ? currentHour : Integer.valueOf(m.group(2)); Boolean minutelyMode = !m.group(3).isNumeric(); Integer minute = minutelyMode ? currentMinute : Integer.valueOf(m.group(3)); result = DateTime.newInstanceGmt(now.dateGmt(), Time.newInstance(hour,minute,0,0)); result = result.addDays(Math.mod(dayOfWeek+7-currentDay,7)); result = result<=now ? result.addMinutes(minutelyMode ? 1 : 0) : result; result = result<=now ? result.addHours(hourlyMode ? 1 : 0) : result; result = result<=now ? result.addDays(dailyOrWeeklyMode ? 1 : 7) : result; } return result; } private static CronTrigger getCurrentScheduleCronJob(String jobId) { CronTrigger job = null; if(String.isNotBlank(jobId)) { List<CronTrigger> jobs = [SELECT Id FROM CronTrigger WHERE Id = :jobId AND TimesTriggered = 0 LIMIT 1]; for(CronTrigger iJob : jobs) { job = iJob; } } return job; } private static void logException(Exception ex, String jobType) { Batch_Runner_Error_Log_gne__c log = new Batch_Runner_Error_Log_gne__c( Batch_Name_gne__c = SCHEDULER_JOB_PREFIX + jobType, Batch_Class_gne__c = GNE_SFA2_Scheduler.class.getName(), Batch_Job_Id_gne__c = null, Batch_Start_Date_gne__c = DateTime.now(), Error_Type_gne__c = GNE_Batch_Runner.LogErrorType.APEX_ERROR.name(), Error_Subtype_gne__c = ex.getTypeName(), Error_Short_Description_gne__c = ex.getMessage(), Error_Description_gne__c = ex.getMessage() + '\nStackTrace:\n['+ ex.getStackTraceString() +']' ); Database.insert(log, false); } // END Static methods public GNE_SFA2_Scheduler(String jobType) { this.jobType = jobType; } public String getJobType() { return this.jobType; } public List<SObject> start(Database.BatchableContext BC) { return new List<SObject>(); } public void execute(Database.BatchableContext BC, List<SObject> scope) {} public void finish(Database.BatchableContext BC) { SFA2_Scheduler_Job_gne__c job = getSchedulerJob(getJobType(), false); Boolean isExecuted = false; DateTime nowTimeStamp = DateTime.now(); if(job!=null && job.Id!=null && job.Status_gne__c==GNE_SFA2_Scheduler.JobType.Scheduled.name()) { try { Map<String,String> jobProperties = String.isNotBlank(job.Job_Properties_json_gne__c) ? (Map<String,String>)JSON.deserialize(job.Job_Properties_json_gne__c, Map<String,String>.class) : null; SchedulableContext sc = new SchedulableContext(getJobType(), jobProperties, job.Queued_Date_gne__c, job.Scheduled_Date_gne__c, nowTimeStamp); GNE_SFA2_Scheduler.Schedulable handler = (GNE_SFA2_Scheduler.Schedulable)JSON.deserialize(job.Handler_json_gne__c, System.Type.forName(job.Handler_Class_gne__c)); isExecuted = true; handler.execute(sc); } catch(Exception ex) { GNE_SFA2_Scheduler.logException(ex, getJobType()); job.Status_Details_gne__c = ex.getMessage() + '\n' + ex.getStackTraceString(); } finally { job.Status_gne__c = isExecuted ? GNE_SFA2_Scheduler.JobType.Executed.name() : GNE_SFA2_Scheduler.JobType.Failed.name(); job.Executed_Date_gne__c = isExecuted ? nowTimeStamp : null; Database.update(job, false); } } } public interface Schedulable { System.Type getSelfClass(); void execute(SchedulableContext sc); } public class SchedulableContext { private transient String jobType; private transient Map<String,String> jobProperties; private transient DateTime queuedDate; private transient DateTime scheduledDate; private transient DateTime executedDate; public SchedulableContext(String jobType, Map<String,String> jobProperties, DateTime queuedDate, DateTime scheduledDate, DateTime executedDate) { this.jobType = jobType; this.jobProperties = jobProperties; this.queuedDate = queuedDate; this.scheduledDate = scheduledDate; this.executedDate = executedDate; } public String getJobType() { return this.jobType; } public Map<String,String> getJobProperties() { if(this.jobProperties==null) { this.jobProperties = new Map<String,String>(); } return this.jobProperties; } public DateTime getQueuedDate() { return this.queuedDate; } public DateTime getScheduledDate() { return this.scheduledDate; } public DateTime getExecutedDate() { return this.executedDate; } } }
import * as tslib_1 from "tslib"; // tslint:disable:no-access-missing-member import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { PagerContextService } from "./pager-context.service"; import { PagerElementComponent } from './pager-element.component'; import { LocalizationService } from '@progress/kendo-angular-l10n'; /** * Displays buttons for navigating to the first and the previous page. */ var PagerPrevButtonsComponent = (function (_super) { tslib_1.__extends(PagerPrevButtonsComponent, _super); function PagerPrevButtonsComponent(localization, pagerContext, cd) { var _this = _super.call(this, localization, pagerContext) || this; _this.cd = cd; return _this; } Object.defineProperty(PagerPrevButtonsComponent.prototype, "disabled", { /** * @hidden * * @readonly * @type {boolean} * @memberOf PagerPrevButtonsComponent */ get: function () { return this.currentPage === 1 || !this.total; }, enumerable: true, configurable: true }); PagerPrevButtonsComponent.prototype.onChanges = function (_a) { var total = _a.total, skip = _a.skip, pageSize = _a.pageSize; this.total = total; this.skip = skip; this.pageSize = pageSize; this.cd.markForCheck(); }; return PagerPrevButtonsComponent; }(PagerElementComponent)); export { PagerPrevButtonsComponent }; PagerPrevButtonsComponent.decorators = [ { type: Component, args: [{ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'kendo-pager-prev-buttons', template: "\n <a href=\"#\"\n [title]=\"textFor('pagerFirstPage')\"\n (click)=\"currentPage !== 1 ? changePage(0) : false\"\n [ngClass]=\"{\n 'k-link': true,\n 'k-pager-nav': true,\n 'k-state-disabled': disabled,\n 'k-pager-first': true\n }\">\n <span [attr.aria-label]=\"textFor('pagerFirstPage')\"\n [ngClass]=\"{\n 'k-icon':true,\n 'k-i-seek-w': true\n }\">\n </span>\n </a>\n <a href=\"#\"\n [title]=\"textFor('pagerPreviousPage')\"\n (click)=\"currentPage !== 1 ? changePage(currentPage-2) : false\"\n [ngClass]=\"{\n 'k-link': true,\n 'k-pager-nav': true,\n 'k-state-disabled': disabled,\n '': true\n }\">\n <span [attr.aria-label]=\"textFor('pagerPreviousPage')\"\n [ngClass]=\"{\n 'k-icon':true,\n 'k-i-arrow-w': true\n }\">\n </span>\n </a>\n " },] }, ]; /** @nocollapse */ PagerPrevButtonsComponent.ctorParameters = function () { return [ { type: LocalizationService, }, { type: PagerContextService, }, { type: ChangeDetectorRef, }, ]; };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./lib/vue.js"></script> </head> <body> <div id="app"> <!-- v-text指令 --> <p v-text="username"></p> <!-- p标签的内容被覆盖了 --> <p v-text="gender">性别</p> <hr> <!-- 插值语法:不会覆盖标签内原有内容 --> <p>{{username}}</p> <p>性别{{gender}}</p> <hr> <!-- v-html指令:前面两个没法渲染标签 --> <div v-text="info"></div> <div>{{info}}</div> <div v-html="info"></div> </div> <script> const vm = new Vue({ el: "#app", data: { "username": "zhangsan", "gender": "女", "info": "<h1 style='color:red;font-weight:bold'>欢迎大家来学习vue.js</h1>" } }) </script> </body> </html>
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tracetransform // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform" import ( "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/sdk/instrumentation" tracesdk "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" tracepb "go.opentelemetry.io/proto/otlp/trace/v1" ) // Spans transforms a slice of OpenTelemetry spans into a slice of OTLP // ResourceSpans. func Spans(sdl []tracesdk.ReadOnlySpan) []*tracepb.ResourceSpans { if len(sdl) == 0 { return nil } rsm := make(map[attribute.Distinct]*tracepb.ResourceSpans) type key struct { r attribute.Distinct is instrumentation.Scope } ssm := make(map[key]*tracepb.ScopeSpans) var resources int for _, sd := range sdl { if sd == nil { continue } rKey := sd.Resource().Equivalent() k := key{ r: rKey, is: sd.InstrumentationScope(), } scopeSpan, iOk := ssm[k] if !iOk { // Either the resource or instrumentation scope were unknown. scopeSpan = &tracepb.ScopeSpans{ Scope: InstrumentationScope(sd.InstrumentationScope()), Spans: []*tracepb.Span{}, SchemaUrl: sd.InstrumentationScope().SchemaURL, } } scopeSpan.Spans = append(scopeSpan.Spans, span(sd)) ssm[k] = scopeSpan rs, rOk := rsm[rKey] if !rOk { resources++ // The resource was unknown. rs = &tracepb.ResourceSpans{ Resource: Resource(sd.Resource()), ScopeSpans: []*tracepb.ScopeSpans{scopeSpan}, SchemaUrl: sd.Resource().SchemaURL(), } rsm[rKey] = rs continue } // The resource has been seen before. Check if the instrumentation // library lookup was unknown because if so we need to add it to the // ResourceSpans. Otherwise, the instrumentation library has already // been seen and the append we did above will be included it in the // ScopeSpans reference. if !iOk { rs.ScopeSpans = append(rs.ScopeSpans, scopeSpan) } } // Transform the categorized map into a slice rss := make([]*tracepb.ResourceSpans, 0, resources) for _, rs := range rsm { rss = append(rss, rs) } return rss } // span transforms a Span into an OTLP span. func span(sd tracesdk.ReadOnlySpan) *tracepb.Span { if sd == nil { return nil } tid := sd.SpanContext().TraceID() sid := sd.SpanContext().SpanID() s := &tracepb.Span{ TraceId: tid[:], SpanId: sid[:], TraceState: sd.SpanContext().TraceState().String(), Status: status(sd.Status().Code, sd.Status().Description), StartTimeUnixNano: uint64(sd.StartTime().UnixNano()), EndTimeUnixNano: uint64(sd.EndTime().UnixNano()), Links: links(sd.Links()), Kind: spanKind(sd.SpanKind()), Name: sd.Name(), Attributes: KeyValues(sd.Attributes()), Events: spanEvents(sd.Events()), DroppedAttributesCount: uint32(sd.DroppedAttributes()), DroppedEventsCount: uint32(sd.DroppedEvents()), DroppedLinksCount: uint32(sd.DroppedLinks()), } if psid := sd.Parent().SpanID(); psid.IsValid() { s.ParentSpanId = psid[:] } return s } // status transform a span code and message into an OTLP span status. func status(status codes.Code, message string) *tracepb.Status { var c tracepb.Status_StatusCode switch status { case codes.Ok: c = tracepb.Status_STATUS_CODE_OK case codes.Error: c = tracepb.Status_STATUS_CODE_ERROR default: c = tracepb.Status_STATUS_CODE_UNSET } return &tracepb.Status{ Code: c, Message: message, } } // links transforms span Links to OTLP span links. func links(links []tracesdk.Link) []*tracepb.Span_Link { if len(links) == 0 { return nil } sl := make([]*tracepb.Span_Link, 0, len(links)) for _, otLink := range links { // This redefinition is necessary to prevent otLink.*ID[:] copies // being reused -- in short we need a new otLink per iteration. otLink := otLink tid := otLink.SpanContext.TraceID() sid := otLink.SpanContext.SpanID() sl = append(sl, &tracepb.Span_Link{ TraceId: tid[:], SpanId: sid[:], Attributes: KeyValues(otLink.Attributes), DroppedAttributesCount: uint32(otLink.DroppedAttributeCount), }) } return sl } // spanEvents transforms span Events to an OTLP span events. func spanEvents(es []tracesdk.Event) []*tracepb.Span_Event { if len(es) == 0 { return nil } events := make([]*tracepb.Span_Event, len(es)) // Transform message events for i := 0; i < len(es); i++ { events[i] = &tracepb.Span_Event{ Name: es[i].Name, TimeUnixNano: uint64(es[i].Time.UnixNano()), Attributes: KeyValues(es[i].Attributes), DroppedAttributesCount: uint32(es[i].DroppedAttributeCount), } } return events } // spanKind transforms a SpanKind to an OTLP span kind. func spanKind(kind trace.SpanKind) tracepb.Span_SpanKind { switch kind { case trace.SpanKindInternal: return tracepb.Span_SPAN_KIND_INTERNAL case trace.SpanKindClient: return tracepb.Span_SPAN_KIND_CLIENT case trace.SpanKindServer: return tracepb.Span_SPAN_KIND_SERVER case trace.SpanKindProducer: return tracepb.Span_SPAN_KIND_PRODUCER case trace.SpanKindConsumer: return tracepb.Span_SPAN_KIND_CONSUMER default: return tracepb.Span_SPAN_KIND_UNSPECIFIED } }
<?php namespace App\Http\Controllers\Frontend; use App\Http\Controllers\Controller; use App\Models\Prompt; use Illuminate\Http\Request; use Inertia\Inertia; class DiscountController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $prompts = Prompt::where('status', 1) ->has('discount') ->when(request()->filled('s_query'), function ($query) { $query->where('title', 'like', '%' . request()->s_query . '%'); }) ->with(['promptmodel:id,title,created_at', 'user:id,name,username,created_at,avatar', 'discount']) ->withCount(['likes as is_liked' => function ($query) { $query->where('user_id', auth()->id()); }]) ->orderBy(request()->sort ?? 'created_at', request()->order ?? 'desc') ->paginate(); $seo = get_option('seo_discount',true); $meta['title'] = $seo->site_name ?? ''; $meta['site_name'] = $seo->site_name ?? ''; $meta['description'] = $seo->matadescription ?? ''; $meta['tags'] = $seo->matatag ?? ''; $meta['preview'] = asset($seo->preview ?? ''); config()->set('seotools.metaDescription',$meta['description']); config()->set('seotools.keyWords',$meta['tags']); config()->set('seotools.site_name',$meta['title']); config()->set('seotools.current_url', url()->current()); config()->set('seotools.metaImage',$meta['preview']); return Inertia::render('Frontend/Discount/Index', [ 'prompts' => $prompts, 'seo' => $meta ]); } }
from datetime import datetime from pydantic import UUID4, BaseModel __all__ = ( "PostCreate", "PostEdit", "PostGet", ) class PostBase(BaseModel): title: str content: str is_private: bool = False class PostCreate(PostBase): repost_on: str | None = None class PostEdit(PostBase): title: str | None = None content: str | None = None class PostGet(PostBase): id: UUID4 author: UUID4 repost_on: UUID4 | None = None created_at: datetime updated_at: datetime | None = None
import React from 'react'; import { render, fireEvent, screen, } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; import '@testing-library/jest-dom/extend-expect'; import Login from '../components/auth/Login'; const mockStore = configureStore([]); describe('Login Component', () => { let store; let initialState; beforeEach(() => { initialState = { login: { status: '', error: '', }, }; store = mockStore(initialState); }); it('renders the login form', async () => { render( <Provider store={store}> <MemoryRouter initialEntries={['/login']}> <Routes> <Route path="/login" element={<Login />} /> </Routes> </MemoryRouter> </Provider>, ); const emailInput = screen.getByPlaceholderText('Email'); const passwordInput = screen.getByPlaceholderText('Password'); expect(emailInput).toBeInTheDocument(); expect(passwordInput).toBeInTheDocument(); }); it('submits the login form', async () => { render( <Provider store={store}> <MemoryRouter initialEntries={['/login']}> <Routes> <Route path="/login" element={<Login />} /> </Routes> </MemoryRouter> </Provider>, ); const emailInput = screen.getByPlaceholderText('Email'); const passwordInput = screen.getByPlaceholderText('Password'); const loginButton = screen.getByRole('button', { name: 'Login' }); const mockUser = { email: '__test__@example.com', password: 'password123' }; store.dispatch = jest.fn(); fireEvent.change(emailInput, { target: { value: mockUser.email } }); fireEvent.change(passwordInput, { target: { value: mockUser.password } }); fireEvent.click(loginButton); expect(store.dispatch).toHaveBeenCalledTimes(1); }); });
const App = () => { const name: string = "Edmund"; const surname = "Jackovskij"; const age: number = 31; const isAdult: boolean = true; const wife: null = null; const favoriteColor: undefined = undefined; const numbers: number[] = [1, 2, 3, 4, 5]; // naudosim sita const items: (number | string)[] = [1, 2, "3", "4"]; const item: number | string = "1"; // const dog: any = { // name: "brisius", // age: 1, // }; // geriau nenaudoti, bet yra galimybe, paleisti taip, type any, siek tiek neigia typescripto prasme // const numbers1: Array<number> = [1, 2, 3, 4, 5]; // const numbers1: Array<number | string> = [1, 2, 3, 4, 5]; const addNumber = (num1: number, num2: number) => { return num1 + num2; }; const addedNumber = addNumber(1, 5); // OBJEKTAI const car: { make: string; color: string; } = { make: "Audi", color: "", }; const response = true; if (response) { car.color = "Black"; } const car1: { make: string; model?: string; } = { make: "Audi", }; if (response) { car1.model = "A8"; } type PPerson = { name: string; age: number; email?: string; }; // type atlieka ta pacia funkcija kaip ir interface interface Person { name: string; // required laukas age: number; // required laukas email?: string; //optional laukas (?) } interface SuperHero { power: string; } interface SuperPerson extends SuperHero { name: string; } const person: Person = { name: "Edma", age: 31, }; const person1: PPerson = { name: "Edmund", age: 31, email: "edma@gmail.com", }; const hero: SuperPerson = { power: "flying", name: "Petras", }; console.log(person, person1, hero); //_____________________________________ console.log( name, surname, age, isAdult, wife, favoriteColor, numbers, items, item, addedNumber ); const title: string = "Vermontas"; const subTitle: string = "Kavinė - Baras"; const peopleCount: number = 5; const maxPeopleCount: number = 26; const isOpen: boolean = true; const openTime: string = "12:00"; const closeTime: string = "02:00"; const security: null = null; console.log( title, subTitle, peopleCount, maxPeopleCount, isOpen, openTime, closeTime, security ); // 1 uzduotis const returnString = (name?: string) => { if (name) { return `One for ${name}, one for me`; } else { return "One for you, one for me"; } }; // 2 uzduotis const ageInDifferentPlanets = (ageInSeconds: number) => { const earthYears: number = ageInSeconds / 31557600; const mercury: number = earthYears * 0.2408467; const venus: number = earthYears * 0.61519726; const earthDays: number = earthYears * 365.25; const mars: number = earthYears * 1.8808158; const jupiter: number = earthYears * 11.862615; const saturn: number = earthYears * 29.447498; const uranus: number = earthYears * 84.016846; const neptune: number = earthYears * 164.79132; return ( <div> <p>Your age in seconds: {ageInSeconds}</p> <p>Your age in Earth is: {earthYears}</p> <p>Your age in Mercury: {mercury}</p> <p>Your age in Venus: {venus}</p> <p>Your age in Earth's days: {earthDays}</p> <p>Your age in Mars: {mars}</p> <p>Your age in Jupiter: {jupiter}</p> <p>Your age in Saturn: {saturn}</p> <p>Your age in Uranus: {uranus}</p> <p>Your age in Neptune: {neptune}</p> </div> ); }; // 3 uzduotis const covertToAcronym = (longName: string) => { const toWords = longName.split(" "); const accronymLetters = toWords.map((word) => word.charAt(0).toUpperCase()); const accronym: string = accronymLetters.join(""); return ( <div> <p>Your long name: {longName}</p> <p>Your accronym: {accronym}</p> </div> ); }; // 4 uzduotis type User = { name: string; age: number; occupation: string; }; const users: User[] = [ { name: "Max Mustermann", age: 25, occupation: "Chimney sweep", }, { name: "Kate Müller", age: 23, occupation: "Astronaut", }, ]; const logPerson = (users: User[]) => { return ( <div> {users.map((user) => ( <p key={user.name}> - {user.name}, {user.age} </p> ))} </div> ); }; const logPersonConsoleLog = (user: User) => { console.log(` - ${user.name}, ${user.age}`); }; console.log("Users:"); users.forEach(logPersonConsoleLog); // 5 uzduotis return ( <div> <h1>Task 1</h1> <p>Empty: {returnString()}</p> <p>With Name: {returnString("Tomas")}</p> <h1>Task 2</h1> <div>{ageInDifferentPlanets(1000000000)}</div> <h1>Task 3</h1> <div>{covertToAcronym("Baisiai Mandras Volkswagenas")}</div> <h1>Task 4</h1> <div>{logPerson(users)}</div> </div> ); }; export default App;
import React, { useEffect, useState, useContext } from "react"; import { makeStyles } from "@material-ui/core/styles"; import PropTypes from "prop-types"; import RegularButton from "components/CustomButtons/Button"; import PopUpCustome from "components/PopUp/PopUp"; import GridItem from "components/Grid/GridItem.js"; import GridContainer from "components/Grid/GridContainer.js"; import Table from "components/Table/Table.js"; import Card from "components/Card/Card.js"; import CardHeader from "components/Card/CardHeader.js"; import CardBody from "components/Card/CardBody.js"; import { getCourseById } from "api/Core/Course"; import { removeStudentToCourse } from "api/Core/Course"; import { GeneralContext } from "providers/GeneralContext"; import { trackPromise } from "react-promise-tracker"; const styles = (theme) => ({ cardCategoryWhite: { "&,& a,& a:hover,& a:focus": { color: "rgba(255,255,255,.62)", margin: "0", fontSize: "14px", marginTop: "0", marginBottom: "0", }, "& a,& a:hover,& a:focus": { color: "#FFFFFF", }, }, cardTitleWhite: { color: "#FFFFFF", marginTop: "0px", minHeight: "auto", fontWeight: "300", fontFamily: "bakh", marginBottom: "3px", textDecoration: "none", "& small": { color: "#777", fontSize: "65%", fontWeight: "400", lineHeight: "1", }, }, large: { width: theme.spacing(18), height: theme.spacing(18), }, }); const useStyles = makeStyles(styles); export default function ListOfStudents(props) { const classes = useStyles(); const [currentPage_MainbarCurrentStudent, setCurrentPage_MainbarCurrentStudent] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [currentStudents, setCurrentStudents] = useState() const { setConfirmPopupOpen, onConfirmSetter, setOpenToast, onToast } = useContext(GeneralContext); const { openListStudentPopUp, RemoveSuccess, closePopUpList, userIdCourse } = props useEffect(() => { trackPromise(getCurrentStudents(userIdCourse)) }, [userIdCourse]) const getCurrentStudents = async (id) => { let response = await getCourseById(id); if (response.data.result) { setCurrentStudents(response.data.result.students) } } const removeStudentInCourse = async (id) => { const data = { userId: id, courseId: userIdCourse } let response = await removeStudentToCourse(data); if (response.data.result) { setOpenToast(true) onToast(response.data.message[0].message, "success") getCurrentStudents(userIdCourse) } } const handleChangePage = (event, newPage) => { setCurrentPage_MainbarCurrentStudent(newPage) } const handleChangeRowsPerPage = (event) => { setRowsPerPage(+event.target.value); setCurrentPage_MainbarCurrentStudent(0); }; return ( <PopUpCustome open={openListStudentPopUp} handleClose={() => { closePopUpList() }} className="popUpAllCurrentStudent"> <GridContainer> <GridItem xs={12} sm={12} md={12}> <Card> <CardHeader color="info"> <h4 className={classes.cardTitleWhite}>تمام دانشجویان</h4> </CardHeader> <CardBody> {currentStudents != undefined && currentStudents.length > 0 ? <Table tableHeaderColor="info" tableHead={["", "اسم", "ایمیل", ""]} tableData={currentStudents} currentPage={currentPage_MainbarCurrentStudent} handleChangePage={handleChangePage} handleChangeRowsPerPage={handleChangeRowsPerPage} rowsCount={rowsPerPage} removeStudent={(id) => { onConfirmSetter('آیا برای حذف دانشجو مطمئن هستید؟', () => { trackPromise(removeStudentInCourse(id)) }) setConfirmPopupOpen(true) }} currentStudent /> : <div style={{ textAlign: 'center', marginTop: 10, backgroundColor: "#ec7254", color: "white", borderRadius: 5, paddingTop: 10, paddingBottom: 10 }}>دانشجویی ثبت نام نکرده</div>} </CardBody> {currentStudents != undefined && currentStudents.length > 0 && <div style={{ display: "flex", justifyContent: "center" }}> <RegularButton color="success" size="sm" onClick={() => { RemoveSuccess() }}>ثبت تغییرات</RegularButton> </div>} </Card> </GridItem> </GridContainer> </PopUpCustome> ) } ListOfStudents.propTypes = { openListStudentPopUp: PropTypes.bool, RemoveSuccess: PropTypes.func, closePopUpList: PropTypes.func, userIdCourse: PropTypes.string };
// // StringExtensions.swift // TinkoffNews // // Created by Станислав Сарычев on 06.07.17. // Copyright © 2017 Станислав Сарычев. All rights reserved. // import UIKit extension String { init(htmlEncodedString: String) { self.init() guard let encodedData = htmlEncodedString.data(using: .utf8) else { self = htmlEncodedString return } let attributedOptions: [String : Any] = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue ] do { let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) self = attributedString.string } catch { print("Error: \(error)") self = htmlEncodedString } } }
<!DOCTYPE html> <html> <head> <title>数学加减法测试</title> <meta name="keywords" content="test" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> * html, * html body { background: #f3f3f3; background-attachment:fixed } table.mathtable { font-family:"微软雅黑",Microsoft YaHei,Arial, Helvetica, sans-serif, "宋体"; font-size:20px; color:#333333; border-width: 1px; border-color: #a9c6c9; border-collapse: collapse; } a:link, a:visited, a:hover, a:active{ font-family:"微软雅黑",Microsoft YaHei,Arial, Helvetica, sans-serif, "宋体";font-size:14px; text-decoration:none; outline:none; } table.mathtable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #a9c6c9; text-align:center; } table.mathtable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #a9c6c9; min-width:150px; text-align:right; } .oddrowcolor{ background-color:#d4e3e5; } .evenrowcolor{ background-color:#c3dde0; } .content { margin: 0 auto; width: 800px; } .tlf { text-align:left; } .tct { text-align:center; } input { font-size:18px; } .inright { float:right; } .inleft { float:left; } .subbtn { margin: 0 auto; padding-top: 15px; width: 50px; clear:both; } .retCl { width: 350px; margin-left: -100px; font-size:16px; color:blue; } .tit { margin: 40px 0 15px; text-align: center; font-size:28px; } .condition { width: 800px; margin: 0 auto; padding: 10px 0; text-align: left; font-size:18px; } .optionInput { background: #fff none repeat scroll 0 0; color: #000; height: 24px; line-height: 24px; padding: 0 5px; width: 160px; font-size:16px; } .changeSubj { margin-left: 20px; color: #000; line-height: 24px; padding: 2px 5px; width: 100px; font-size:16px; } .p10 { padding-left: 10px; } .m15 { margin-top: 15px; } </style> <!-- Javascript goes in the document HEAD --> <script type="text/javascript"> var k_array; //生成需要的随机数字 function generateRandom(min, max){ var c = max-min+1; return Math.floor(Math.random() * c + min); } //生成页面内容 function generateMathsContent(min, max) { var outhtml = generatePlusContentStr(min, max); outhtml += generateMinusContentStr(min, max); return outhtml; } //加法 function generatePlusContentStr(min, max){ min = min + 1; max = max - 1; var output = "<table class=\"mathtable inleft\" id=\"plustable\">"; output += "<tr><th>加法运算</th><th>结果</th></tr>"; for(var i=0; i<10; i++){ var v1 = generateRandom(min, max); var v2 = generateRandom(min, max-v1); var key = v1 + "+" + v2; if(k_array.hasOwnProperty(key)) { i--; } else { output += "<tr><td>" + v1 + " + " + v2 + " = <input class=\"p10\" id=\"" + key + "\" type=\"text\" value=\"\" size=\"3\"></td><td style=\"text-align:center;\"><span id=\"" + key + "_py\"></span></td></tr>"; k_array[key] = v1+v2; } } output += "</table>"; return output; } //减法 function generateMinusContentStr(min, max){ min = min + 1; var output = "<table class=\"mathtable inright\" id=\"minustable\">"; output += "<tr><th>减法运算</th><th>结果</th></tr>"; for(var i=0; i<10; i++){ var v1 = generateRandom(min, max); var v2 = generateRandom(min, v1); var key = v1 + "-" + v2; if(k_array.hasOwnProperty(key)) { i--; } else { output += "<tr><td>" + v1 + " - " + v2 + " = <input class=\"p10\" id=\"" + key + "\" type=\"text\" value=\"\" size=\"3\"></td><td style=\"text-align:center;\"><span id=\"" + key + "_py\"></span></td></tr>"; k_array[key] = v1-v2; } } output += "</table>"; return output; } //提交批阅 function submitContent() { var len = Object.keys(k_array).length; var correct_ct = 0; var wrong_ct = 0; for(var i=0; i<len; i++) { var key = Object.keys(k_array)[i]; var value = k_array[key]; var itemv = document.getElementById(key).value; if(itemv != "" && itemv == value){ document.getElementById(key+"_py").innerHTML="<font color=green>√</font>"; correct_ct++; } else { document.getElementById(key+"_py").innerHTML="<font color=red>×</font> <span style=\"font-size:18px;\">(正确答案:" + value + ")</span>"; wrong_ct++; } } var message = ""; if(correct_ct === len) { message = "恭喜你,全部正确,真棒!"; } else { message = "您答对了 " + correct_ct + " 题, 答错了 " + wrong_ct + " 题,还需继续努力!"; } document.getElementById("retItem").innerHTML=message; } function altRows(id){ if(document.getElementsByTagName){ var table = document.getElementById(id); var rows = table.getElementsByTagName("tr"); for(i = 0; i < rows.length; i++){ if(i % 2 == 0){ rows[i].className = "evenrowcolor"; }else{ rows[i].className = "oddrowcolor"; } } } } function generateBtnContent() { var outhtml = "<input type=\"button\" class=\"m15\" value=\"提交批阅\" onclick=\"javascript:submitContent();\">"; outhtml += "<div class=\"retCl m15\" id=\"retItem\"></div>"; return outhtml; } function changeCondition() { var sValue = document.getElementById("selectValue").value; if(sValue === '') { alert("请先选择一个运算范围"); return; } var v_array = new Array(); v_array['1'] = [0, 100]; v_array['2'] = [0, 10]; v_array['3'] = [10, 50]; v_array['4'] = [50, 100]; v_array['5'] = [10, 20]; var selected = v_array[sValue]; generatePage(selected[0], selected[1]); } function generatePage(min, max) { k_array = new Array(); document.getElementById("content").innerHTML=generateMathsContent(min, max); document.getElementById("btnDiv").innerHTML=generateBtnContent(); altRows('plustable'); altRows('minustable'); document.getElementById("retItem").innerHTML=""; } function changeSubject() { changeCondition(); } window.onload=function(){ generatePage(10, 20); } </script> </head> <body> <div class="tit">加减法测试</div> <div class="condition"> 选择运算范围: <select class="optionInput" id="selectValue" onchange="javascript:changeCondition();"> <option value="">请选择</option> <option value="1">0~100</option> <option value="2">0~10</option> <option value="3">10~50</option> <option value="4">50~100</option> <option value="5">100~1000</option> </select> <input type="button" class="changeSubj" value="换题" onclick="javascript:changeSubject();"> </div> <div class="content" id='content'></div> <div class="subbtn" id='btnDiv'></div> </body> </html>
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; const main = document.querySelector("main"); function getCountries() { return __awaiter(this, void 0, void 0, function* () { const response = yield fetch('https://restcountries.com/v3.1/all'); const countries = response.json(); return countries; }); } function createDiv() { const div = document.createElement("div"); return div; } function createA(nameCountrie) { const a = document.createElement("a"); a.href = `https://en.wikipedia.org/wiki/${nameCountrie}`; a.target = "_blank"; return a; } function createImg(url, alt) { const img = document.createElement("img"); img.src = url; img.alt = alt; return img; } function createH2(nameCountrie) { const h2 = document.createElement("h2"); h2.textContent = nameCountrie; return h2; } function rendercountries(countries) { const div = createDiv(); const a = createA(countries.name.common); const img = createImg(countries.flags.png, countries.flags.alt); const h2 = createH2(countries.name.common); a.append(img); div.append(a, h2); main.append(div); } function setup() { return __awaiter(this, void 0, void 0, function* () { try { const countries = yield getCountries(); console.log(countries[0].name.common); countries.forEach(countrie => rendercountries(countrie)); console.log(countries); } catch (error) { } }); } document.addEventListener("DOMContentLoaded", setup);
// // GradebookCell.swift // SakaiClientiOS // // Created by Pranay Neelagiri on 5/13/18. // import UIKit import ReusableSource /// The table view cell to display a GradeItem in a gradebook class GradebookCell: UITableViewCell, ConfigurableCell { typealias T = GradeItem let titleLabel: UILabel = { let titleLabel: UILabel = UIView.defaultAutoLayoutView() titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping titleLabel.textColor = Palette.main.primaryTextColor return titleLabel }() let gradeLabel: UILabel = { let gradeLabel: UILabel = UIView.defaultAutoLayoutView() gradeLabel.textAlignment = NSTextAlignment.right gradeLabel.textColor = Palette.main.primaryTextColor return gradeLabel }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupView() setConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupView() { backgroundColor = Palette.main.secondaryBackgroundColor.color(withTransparency: 0.3) selectedBackgroundView = selectedView() contentView.addSubview(titleLabel) contentView.addSubview(gradeLabel) } private func setConstraints() { let margins = contentView.layoutMarginsGuide titleLabel.constrainToMargins(of: contentView, onSides: [.bottom, .top, .left]) titleLabel.trailingAnchor.constraint(equalTo: gradeLabel.leadingAnchor) .isActive = true titleLabel.widthAnchor.constraint(equalTo: margins.widthAnchor, multiplier: 0.5).isActive = true gradeLabel.constrainToMargins(of: contentView, onSides: [.bottom, .top, .right]) } /// Configure the GradebookCell with a GradeItem object /// /// - Parameters: /// - item: The GradeItem to be used as the model for the cell /// - indexPath: The indexPath at which the GradebookCell will be displayed in the UITableView func configure(_ item: GradeItem, at indexPath: IndexPath) { var grade: String if let itemGrade = item.grade { grade = itemGrade } else { grade = "" } titleLabel.text = item.title gradeLabel.text = "\(grade) / \(item.points)" } }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:maktabat_alharam/screens/all_services/pages/reserve_article_research/new_order/models/all_university.dart'; import 'package:maktabat_alharam/screens/widgets/constants.dart'; import '../../../../../../config/dio_helper/dio.dart'; class DropDownListUniversityName extends StatefulWidget { final AllUni? initial; final ValueChanged<AllUni> onChanged; const DropDownListUniversityName({Key? key, this.initial, required this.onChanged}) : super(key: key); @override State<DropDownListUniversityName> createState() => _DropDownListUniversityNameState(); } class _DropDownListUniversityNameState extends State<DropDownListUniversityName> { AllUni? selected; final grads = <AllUni>[]; int? valueSelected; @override void initState() { if (widget.initial != null) { selected = widget.initial; } getUni(); super.initState(); } @override Widget build(BuildContext context) { // double height = MediaQuery.of(context).size.height; double width = MediaQuery.of(context).size.width; return Container( padding: const EdgeInsets.symmetric(horizontal: 20), margin: const EdgeInsets.symmetric(horizontal: 35, vertical: 8), width: width, // height: height*0.09, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: Colors.white, border: Border.all(color: kPrimaryColor)), child: DropdownButtonHideUnderline( child: DropdownButton<AllUni>( value: selected, // autofocus: true, // isDense: true, //isExpanded: true, hint: Text( "university".tr + ' :', style: const TextStyle( color: kPrimaryColor, fontSize: 16, fontFamily: "DinReguler", ), ), borderRadius: BorderRadius.circular(10), icon: Image.asset("assets/image/smallarrow.png"), // elevation: 16, style: const TextStyle( color: kTextColor, fontSize: 16, fontFamily: "DinReguler", ), underline: null, onChanged: (AllUni? newValue) { if (newValue == null) return; selected = newValue; widget.onChanged(selected!); setState(() {}); }, items: grads.map<DropdownMenuItem<AllUni>>((AllUni value) { return DropdownMenuItem<AllUni>( value: value, child: Text( value.nameAr!, style: const TextStyle( color: kTextColor, fontSize: 16, fontFamily: "DinReguler", ), ), ); }).toList(), ), ), ); } Future<void> getUni() async { grads.clear(); final res = await NetWork.get('ThesisDepositionRequest/GetAllUniversities'); (res.data['data'] as List) .map((e) => grads.add(AllUni.fromJson(e))) .toList(); setState(() {}); } }
import { Modal } from "antd"; import { ReactNode, SetStateAction, useState } from "react"; type ConfirmModalPropsType = { title: string; okButtonText?: string; open: boolean; setOpen: React.Dispatch<SetStateAction<boolean>>; children: ReactNode; footer?: boolean; className?: string; confirmHandler?: VoidFunction; }; const PopModal = ({ open, setOpen, children, title, okButtonText, footer, className, confirmHandler, }: ConfirmModalPropsType) => { const [loading, setLoading] = useState(false); const handleOk = () => { setLoading(true); if (confirmHandler) setTimeout(() => { confirmHandler(); setLoading(false); setOpen(false); }, 1000); }; return ( <Modal className={className} open={open} title={title} centered okText={okButtonText || "Sure"} onOk={handleOk} onCancel={() => setOpen(false)} confirmLoading={loading} footer={ footer ? (_, { OkBtn, CancelBtn }) => ( <> <CancelBtn /> <OkBtn /> </> ) : null } > {children} </Modal> ); }; export default PopModal;
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:plants_care_uganda_ltd/auth/forgot_password.dart'; import 'package:plants_care_uganda_ltd/auth1/sign_up.dart'; import 'package:plants_care_uganda_ltd/pages/admin/admin.dart'; import 'package:plants_care_uganda_ltd/pages/admin/adminHome.dart'; import 'package:plants_care_uganda_ltd/screens/homeScreen.dart'; class SignIn extends StatefulWidget { const SignIn({super.key}); @override _SignInState createState() => _SignInState(); } class _SignInState extends State<SignIn> { bool _isObscure3 = true; bool visible = false; final _formkey = GlobalKey<FormState>(); final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Column( children: <Widget>[ SingleChildScrollView( child: Container( decoration: BoxDecoration( color: Colors.white, ), width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Center( child: SingleChildScrollView( child: Container( margin: const EdgeInsets.all(12), child: Form( key: _formkey, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox( height: 20, ), Image.asset( 'assets/logo.png', height: 130, ), const Text( 'Welcome Back', style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, color: Colors.green, ), ), const Text('Plants Care Uganda Ltd'), const Text( 'Making Farming Profitable', style: TextStyle( color: Colors.green, fontStyle: FontStyle.italic, ), ), const SizedBox( height: 30, ), TextFormField( controller: emailController, //new decoration1 from mytextfield decoration: InputDecoration( floatingLabelBehavior: FloatingLabelBehavior.always, contentPadding: const EdgeInsets.symmetric( horizontal: 42, vertical: 20), enabledBorder: OutlineInputBorder( gapPadding: 10, borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Colors.black), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide(color: Colors.black), ), labelText: 'Email', hintText: 'Enter Email', suffixIcon: const Icon(Icons.mail_lock_outlined), ), validator: (value) { if (value!.isEmpty) { return "Email cannot be empty"; } if (!RegExp( "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]") .hasMatch(value)) { return ("Please enter a valid email"); } else { return null; } }, onSaved: (value) { emailController.text = value!; }, keyboardType: TextInputType.emailAddress, ), const SizedBox( height: 20, ), TextFormField( controller: passwordController, obscureText: _isObscure3, decoration: InputDecoration( floatingLabelBehavior: FloatingLabelBehavior.always, contentPadding: const EdgeInsets.symmetric( horizontal: 42, vertical: 20), enabledBorder: OutlineInputBorder( gapPadding: 10, borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Colors.black), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide(color: Colors.black), ), labelText: 'Password', hintText: 'Enter Password', suffixIcon: IconButton( icon: Icon(_isObscure3 ? Icons.visibility : Icons.visibility_off), onPressed: () { setState(() { _isObscure3 = !_isObscure3; }); }), ), validator: (value) { RegExp regex = RegExp(r'^.{6,}$'); if (value!.isEmpty) { return "Password cannot be empty"; } if (!regex.hasMatch(value)) { return ("please enter valid password min. 6 character"); } else { return null; } }, onSaved: (value) { passwordController.text = value!; }, keyboardType: TextInputType.emailAddress, ), const SizedBox( height: 5, ), //forgot password Padding( padding: const EdgeInsets.symmetric(horizontal: 25), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute( builder: (context) { return const ForgotPassword(); })); }, child: const Text('Forgot Password?', style: TextStyle(color: Colors.grey))), ], ), ), const SizedBox( height: 15, ), SizedBox( height: 60, width: double.infinity, child: MaterialButton( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(12.0))), elevation: 5.0, height: 40, onPressed: () { setState(() { visible = true; }); signIn(emailController.text, passwordController.text); }, color: Colors.white, child: const Text( "Login", style: TextStyle( fontSize: 20, ), ), ), ), const SizedBox( height: 10, ), Visibility( maintainSize: true, maintainAnimation: true, maintainState: true, visible: visible, child: Container( child: const CircularProgressIndicator( color: Colors.grey, ))), const SizedBox( height: 30, ), Column( children: [ const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ const Text("Don't have an account?,"), // GestureDetector( // onTap: () { // Navigator.push(context, // MaterialPageRoute( // builder: (context) { // return const SignUp1(); // })); // }, // child: const Text( // "Sign Up", // style: TextStyle( // color: Colors.deepOrange, // ), // ), // ), ], ), ], ), ], ), ), ), ), ), ), ), ], ), ), ); } //teacher==donor //student==recipient void route() { User? user = FirebaseAuth.instance.currentUser; var kk = FirebaseFirestore.instance .collection('users') .doc(user!.uid) .get() .then((DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists) { if (documentSnapshot.get('role') == "Sales Man") { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const HomeScreen(), ), ); } //new // else if (documentSnapshot.get('role') == "Engineer") { // Navigator.pushReplacement( // context, // MaterialPageRoute( // builder: (context) => const HomeScreen(), // ), // ); // } else { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => AdminHome(), ), ); } } else { print('Document does not exist on the database'); } }); } //not signing in void signIn(String email, String password) async { if (_formkey.currentState!.validate()) { try { UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword( email: email, password: password, ); route(); } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { print('No user found for that email.'); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('No user found for that email.')), ); } else if (e.code == 'wrong-password') { print('Wrong password provided for that user.'); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Wrong password provided for that user.')), ); } // } finally { // setState(() { // visible = false; // }); } } } }
import React, { useState } from 'react'; import Swal from 'sweetalert2'; import withReactContent from 'sweetalert2-react-content'; import "./sign.css" import { useNavigate } from 'react-router-dom'; const MySwal = withReactContent(Swal); function SignupForm() { const [isOpen, setIsOpen] = useState(true); const navigate = useNavigate() // const toggleForm = () => { // setIsOpen(!isOpen); // if (onClose) { // onClose(); // } // }; const handleSignInClick = () => { navigate('/guide'); }; const handleSubmit = (e) => { e.preventDefault(); const username = document.getElementById('username').value; const email = document.getElementById('email').value; const password = document.getElementById('password').value; const confirmPassword = document.getElementById('confirmPassword').value; if (password !== confirmPassword) { MySwal.fire({ icon: 'error', title: 'Passwords do not match', }); return; } const userData = { username: username, email: email, password: password, }; console.log('Submitting user data:', userData); fetch('api/sign', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData), }) .then((response) => { console.log('Response status:', response.status); console.log('Response OK:', response.ok); if (response.status === 201) { MySwal.fire({ icon: 'success', title: 'Registration successful', }); } else { MySwal.fire({ icon: 'error', title: 'Registration failed', }); } }) .catch((error) => { console.error('Error during registration:', error); MySwal.fire({ icon: 'error', title: 'An error occurred during registration', }); }); }; return ( <div className={`form ${isOpen ? 'open' : 'closed'}`}> <div className="form-container"> <form onSubmit={handleSubmit}> <div className="inputs"> <h3>Tour Guide</h3> <input type="text" id="username" placeholder="Username" required /> <input type="email" id="email" placeholder="Email" required /> <input type="password" id="password" required placeholder="Enter password" /> <input type="password" id="confirmPassword" required placeholder="Confirm password" /> <button type="submit" onClick={handleSignInClick}>Sign Up</button> </div> </form> </div> <style> {` input[type="text"], input[type="email"], input[type="password"] { text-transform: none; /* Remove default capitalization */ } `} </style> </div> ); } export default SignupForm;
import type { PropType, ExtractPropTypes, CSSProperties } from 'vue' import { makeArrayProp, makeBooleanProp, makeStringProp } from '../common/props' type SkeletonTheme = 'text' | 'avatar' | 'paragraph' | 'image' type SkeletonAnimation = 'gradient' | 'flashed' export type SkeletonRowColObj = { [key: string]: any type?: 'rect' | 'circle' | 'text' size?: string | number width?: string | number height?: string | number margin?: string | number background?: string marginLeft?: string | number marginRight?: string | number borderRadius?: string | number backgroundColor?: string } export type SkeletonRowCol = number | SkeletonRowColObj | Array<SkeletonRowColObj> export type SkeletonThemeVars = { notifyPadding?: string notifyFontSize?: string notifyTextColor?: string notifyLineHeight?: number | string notifyDangerBackground?: string notifyPrimaryBackground?: string notifySuccessBackground?: string notifyWarningBackground?: string } export const skeletonProps = { /** * 骨架图风格,有基础、头像组合等两大类 */ theme: makeStringProp<SkeletonTheme>('text'), /** * 用于设置行列数量、宽度高度、间距等。 * @example * 【示例一】,`[1, 1, 2]` 表示输出三行骨架图,第一行一列,第二行一列,第三行两列。 * 【示例二】,`[1, 1, { width: '100px' }]` 表示自定义第三行的宽度为 `100px`。 * 【示例三】,`[1, 2, [{ width, height }, { width, height, marginLeft }]]` 表示第三行有两列,且自定义宽度、高度和间距 */ rowCol: makeArrayProp<SkeletonRowCol>(), /** * 是否为加载状态,如果是则显示骨架图,如果不是则显示加载完成的内容 * @default true */ loading: makeBooleanProp(true), /** * 动画效果,有「渐变加载动画」和「闪烁加载动画」两种。值为空则表示没有动画 */ animation: { type: String as PropType<SkeletonAnimation>, default: '' }, // 自定义类名 customClass: { type: [String, Array, Object], default: '' }, // 自定义样式 customStyle: { type: Object as PropType<CSSProperties>, default() { return {} } } } export type SkeletonProps = ExtractPropTypes<typeof skeletonProps>
const fs = require('fs'); const mariadb = require('mariadb'); const { execSync, exec } = require('child_process'); async function main() { console.log('Script started') let conn; try { const pool = mariadb.createPool({ host: 'localhost', port: 3306, user: 'pmifsm', password: 'pmifsm', connectionLimit: 5, database: 'pmifsm' }); conn = await pool.getConnection(); const snowArchival = new SnowArchival(conn, '/mt/ebs/result', 1000); await snowArchival.start(); console.log('Script finished'); } catch (err) { console.log(err); } finally { if (conn) await conn.end(); } } class SnowArchival { conn; resultDir; batchSize; excludedRitms = [ '2437ffc5478b295047f2c071e36d43df', '43cd2bd5478f695047f2c071e36d43e0', 'b89ae391478f695047f2c071e36d436d', 'd630e4d51b0ba550b3f5a6c3b24bcbe0', 'ff4f94951b0ba550b3f5a6c3b24bcb76', ] constructor(conn, resultDir, batchSize) { this.conn = conn; this.resultDir = resultDir; this.batchSize = batchSize; } async start() { let startIdx = 0; while (true) { let tasks = await this.getTasks(startIdx, this.batchSize); if (tasks.length === 0) break; if (startIdx === 0) { tasks = tasks.filter(t => !this.excludedRitms.includes(t.sys_id)) } startIdx += this.batchSize; const groupPath = this.getGroupPath(tasks); console.log(groupPath, startIdx) for (const task of tasks) { try { const taskPath = this.getTaskPath(groupPath, task) execSync(`mkdir -p ${taskPath}`); await this.extractCsv(task, taskPath); await this.extractAttachments(task, taskPath); } catch (err) { console.error(`sys_id: ${task.sys_id}, task_number: ${task.number}, err:`, err); } } } } async extractCsv(task, taskPath) { const journals = await this.conn.query(`select * from sys_journal_field where element in ('work_notes', 'comments') and element_id = '${task.number}' order by sys_created_on;`); const commentsAndWorkNotes = journals.map(this.constructJournal).join('\n'); const assignedTo = await this.getAssignedTo(task); const catItemName = await this.getCatItemName(task); const reference = await this.getReference(task); const context = await this.conn.query(`select name, stage from wf_context where sys_id = '${task.sys_id}'`); const stage = await this.conn.query(`select name from wf_stage where sys_id = '${context.stage}'`) const data = { 'Number': task.number, 'Cat Item': catItemName, 'Watch List': task.a_str_24, 'Stage': stage.name, 'Approval Attachment': '', 'State': task.state, 'U Approval Request': task.a_str_11, 'Approval Set': task.approval_set, 'Assigned To': assignedTo, 'Assignment Group': task.assignment_group, 'Short Description': task.short_description, 'Resolved By': assignedTo, 'Closed Time': task.u_closed_time, 'Resolution Note': task.a_str_10, 'Closed At': task.closed_at, 'Comments And Work Notes': commentsAndWorkNotes, 'Contact Person': task.a_str_28, 'Request': task.a_str_2, 'Reopen Count': '', 'Reference 1': reference, 'Sys Created By': task.sys_created_by, 'Reassignment Count': task.reassignment_count, 'Generic Mailbox': task.a_str_23, 'Cc': task.a_str_24, 'To Address': task.a_str_25, 'Opened At': task.opened_at, 'External Users Email': task.a_str_7, 'Approval': task.approval, 'Contact Type': task.contact_type, 'Ritm Region': task.a_str_27, 'Ritm Source': task.a_str_22, 'Priority': task.priority, 'State': task.state } const header = Object.keys(data).join(','); const values = Object.values(data).join(','); // Write CSV string to file // const filepath = `\"${taskPath}/${task.number}.csv\"` // fs.writeFileSync('data.csv', `${header}\n${values}`); // execSync(`mv data.csv ${filepath}`); } async getAssignedTo(task) { const user = await this.conn.query(`select name from sys_user where sys_id = '${task.a_ref_10}'`); return user.name; } async getCatItemName(task) { const cat = await this.conn.query(`select name from sc_cat_item where sys_id = '${task.a_ref_1}'`); return cat.name; } async getReference(task) { const refTask = await this.conn.query(`select number from task where sys_id = '${task.a_ref_9}'`); return refTask.number; } constructJournal(j) { return '${j.sys_created_by}\n${j.sys_created_on}\n${j.value}'; } async getTasks(offset, limit, taskNumber) { if (taskNumber) { return this.conn.query(` select * from task where number = ${taskNumber}; `); } return this.conn.query(` select * from task where sys_class_name = 'sc_req_item' order by number limit ${limit} offset ${offset}; `); } async extractAttachments(task, taskPath) { const chunks = await this.getChunks(task.sys_id); this.groupChunksIntoAttachments(chunks).forEach(a => this.extractAttachment(a, taskPath) ); } getChunks(sysId) { return this.conn.query(`select sad.sys_attachment as sys_attachment_id, sa.file_name as file_name, sa.compressed as compressed, sad.data as data from sys_attachment sa join sys_attachment_doc sad on sa.sys_id = sad.sys_attachment and sa.table_sys_id = '${sysId}' order by sad.position; `); } groupChunksIntoAttachments(chunks) { const grouped = chunks.reduce((acc, chunk) => { if (!acc[chunk.sys_attachment_id]) { acc[chunk.sys_attachment_id] = {chunks: []}; } acc[chunk.sys_attachment_id].chunks.push(chunk); return acc; }, {}); const res = Object.values(grouped); return res; } extractAttachment(attachment, taskPath) { const base64Chunks = attachment.chunks.map(chunk => chunk.data); const concatenatedBuffer = this.decodeMultipartBase64(base64Chunks); const meta = attachment.chunks[0]; const attachmentFilePath = `\"${taskPath}/${meta.file_name}\"`; if (meta.compressed > 0) { this.writeCompressedFile(attachmentFilePath, concatenatedBuffer); } else { this.writeFile(attachmentFilePath, concatenatedBuffer); } } decodeMultipartBase64(base64Chunks) { const binaryChunks = base64Chunks.map(chunk => Buffer.from(chunk, 'base64')); return Buffer.concat(binaryChunks); } writeCompressedFile(filepath, buf) { try { execSync('rm tmp', { stdio: [] })} catch (e) {}; fs.writeFileSync('tmp.gz', buf); execSync(`gzip -d tmp.gz && mv tmp ${filepath}`); } writeFile(filepath, buf) { fs.writeFileSync(filepath, buf); } getTaskPath(groupPath, task) { return `${groupPath}/${task.number}/${this.formatDateWithTime(task.sys_created_on)}` } getGroupPath(tasks) { const startTask = tasks[0]; const endTask = tasks[tasks.length - 1] return `${this.resultDir}/${startTask.number}-${endTask.number}_${this.formatDate(startTask.sys_created_on)}_${this.formatDate(endTask.sys_created_on)}` } formatDate(date) { const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; const day = String(date.getDate()).padStart(2, '0'); const month = months[date.getMonth()]; const year = date.getFullYear(); return `${day}${month}${year}`; } formatDateWithTime(date) { const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; const day = String(date.getDate()).padStart(2, '0'); const month = months[date.getMonth()]; const year = date.getFullYear(); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${day}${month}${year}_${hours}${minutes}`; } } main();
import EventEmitter from 'events'; import { Library } from '.'; const lengths = { byte: 1, int: 4, int32: 4, uint32: 4, int64: 8, uint64: 8, dword: 4, short: 2, long: 8, float: 4, double: 8, bool: 1, boolean: 1, ptr: 4, pointer: 4, // str: 0, // string: 0, // vec3: 0, // vector3: 0, // vec4: 0, // vector4: 0, }; // Tracks used and unused registers class Registers { registers: Readonly<{ DR0: number; DR1: number; DR2: number; DR3: number }>; used: number[]; constructor() { this.registers = Object.freeze({ DR0: 0x0, DR1: 0x1, DR2: 0x2, DR3: 0x3, }); this.used = []; } getRegister() { const unused = Object.values(this.registers).filter((r) => !this.used.includes(r)); return unused[0]; } busy(register: number) { this.used.push(register); } unbusy(register: number) { this.used.splice(this.used.indexOf(register), 1); } } export default class Debugger extends EventEmitter { memoryjs: Library; registers: Registers; attached: boolean; intervals: { register: number; id: NodeJS.Timer }[]; constructor(memoryjs: Library) { super(); this.memoryjs = memoryjs; this.registers = new Registers(); this.attached = false; this.intervals = []; } attach(processId: number, killOnDetatch = false) { const success = this.memoryjs.attachDebugger(processId, killOnDetatch); if (success) this.attached = true; return success; } detatch(processId: number) { this.intervals.map(({ id }) => clearInterval(id)); return this.memoryjs.detatchDebugger(processId); } removeHardwareBreakpoint(processId: number, register: number) { const success = this.memoryjs.removeHardwareBreakpoint(processId, register); if (success) { this.registers.unbusy(register); } // Find the register's corresponding interval and delete it this.intervals.forEach(({ register: r, id }) => { if (r === register) { clearInterval(id); } }); return success; } setHardwareBreakpoint(processId: number, address: number, trigger: number, dataType: keyof typeof lengths | 'string') { let size: number; // If we are breakpointing a string, we need to determine the length of it if (dataType === 'string') { const { handle } = this.memoryjs.openProcess(processId); const value = this.memoryjs.readMemory(handle, address, 'string'); size = value.length; this.memoryjs.closeProcess(handle); } else size = lengths[dataType]; // Obtain an available register const register = this.registers.getRegister(); const success = this.memoryjs.setHardwareBreakpoint(processId, address, register, trigger, size); // If the breakpoint was set, mark this register as busy if (success) { this.registers.busy(register); this.monitor(register); } return register; } monitor(register: number, timeout = 100) { const id = setInterval(() => { const debugEvent = this.memoryjs.awaitDebugEvent(register, timeout); if (debugEvent) { this.memoryjs.handleDebugEvent(debugEvent.processId, debugEvent.threadId); // Global event for all registers this.emit('debugEvent', { register, event: debugEvent, }); // Event per register this.emit(`${register}`, debugEvent); } }, 100); this.intervals.push({ register, id }); } }
4/22/2018 Pro-Tip: Watch https://www.youtube.com/watch?v=77W2JSL7-r8 for using Github Desktop. :D ## Installing Github Desktop, creating repository, saving files in repository 1. Go to www.desktop.github.com 2. Download and install for Windows/Mac as appropriate 3. Sign in with your Github credentials/create one if you don't have one 4. I followed the tutorial from here but what was not apparent was adding files. a. Create a new repository (i.e. folder), or add an existing one if you already have it. b. Create/copy files you want to share into this new folder that you created. My Github is under Documents and hence the repository filepath looks something like this- C:/Users/Asengupta/Document/Github_intro/Githubdesktop_intro.txt ## Committing to Git To add the files to github, you have to commit them. To commit a file, do the following: 1. Give a name to the action (i.e. if you are adding a file, write which date you added it, later you might need to edit the file, so have that info in that tab. Description is optional but always a good idea to provide some infromation about the action you are performing. 2. If you keep typing after commit, the changes will keep happening real time in the document after you save the changes you make. 3. But remember to add a description and hit commit after every change if you want your file (which is now in the repository to show those changes) ##Branching:"When you create a branch in your project, you're creating an environment where you can try out new ideas. Changes you make on a branch don't affect the master branch, so you're free to experiment and commit changes, safe in the knowledge that your branch won't be merged until it's ready to be reviewed by someone you're collaborating with" ** I don't think we need this right now but might be a good idea to familiarize ourselves with it. This is another useful link outlining the various steps in Git: https://guides.github.com/introduction/flow/ ##Publishing a repository 1. Use the third icon below the menu bar in your github desktop window to publish a respository. Until I did this, I wasn't able to see this repository in my github online. 2. When you try to, it will ask you to sign in to your git account (hence, have one handy) 3. The code/document can be kept private if it is a paid git account. I don't have one, so I uncheck the box and click publish respository. This essentially is the "push" command where you are pushing your files to the online git magic world. 4. Any changes you make to the document after it has been committed, you add a description and hit commit but now also click on "Push Origin" icon. ##Cloning a repository 1. If you want to clone this current repository, go to the Repository option under File menu. Click on "Clone Repository". 2. Copy-paste the url if you have it (For example, I cloned your ISME 2013 BNTI R code) 3. You won't see anything in the github desktop panels, but if you go back to the folder (in my case the Git folder under Documents), you can see the file. 4. So in our case, when we are working with a text document and you want to add extra text to the document, you would open it up, make changes, which you should be able to see in guthub desktop. Commit that to the master branch, but this happens locally. 5. "Push" this up to Github (At this point, I don't know if the push command I make at my end is going to change your code...I think this is where the branching part comes into play). Not sure, I would need a partner to figure this out.
<style> #material-gradient-chart stop { stop-color: #00bdae; } #fabric-gradient-chart stop { stop-color: #4472c4; } #bootstrap-gradient-chart stop { stop-color: #a16ee5; } #bootstrap4-gradient-chart stop { stop-color: #a16ee5; } #highcontrast-gradient-chart stop { stop-color: #79ECE4; } #tailwind-gradient-chart stop { stop-color: #4f46e5; } #bootstrap5-gradient-chart stop { stop-color: #6355C7; } #material-dark-gradient-chart stop { stop-color: #9ECB08; } #fabric-dark-gradient-chart stop { stop-color: #4472c4; } #bootstrap-dark-gradient-chart stop { stop-color: #a16ee5; } #tailwind-dark-gradient-chart stop { stop-color: #8B5CF6; } #bootstrap5-dark-gradient-chart stop { stop-color: #8F80F4; } #fluent-gradient-chart stop { stop-color: #1AC9E6; } #fluent-dark-gradient-chart stop { stop-color: #1AC9E6; } #material3-gradient-chart stop { stop-color: #6355C7; } #material3-dark-gradient-chart stop { stop-color: #4EAAFF; } .chart-gradient stop[offset="0"] { stop-opacity: 0.75; } .chart-gradient stop[offset="1"] { stop-opacity: 0; } #control-container { padding: 0px !important; } </style> <div class="control-section"> <div id="zoom-container" align='center'></div> </div> <div id="action-description"> <p> This sample demonstrates the zooming and panning features of the charts. </p> </div> <div id="description"> <p>This sample shows the following zooming and panning behaviors.</p> <ul> <li>Click and drag the mouse on a chart area to enable selection zooming.</li> <li>Hover the mouse on the toolbar at the top right corner of chart area to switch between zooming and panning.</li> <li>Pinch in and pinch out the chart area to zoom in or zoom out the chart in touch enabled devices.</li> <li>Touch and drag to pan the chart.</li> <li>Double tap to reset the zoomed chart.</li> </ul> <p>The chart component supports four types of zooming which can be set using <a target="_blank" href="https://ej2.syncfusion.com/javascript/documentation/api/chart/zoomSettingsModel/#enableselectionzooming">enableSelectionZooming</a>, <a target="_blank" href="https://ej2.syncfusion.com/javascript/documentation/api/chart/zoomSettingsModel/#enablepinchzooming">enablePinchZooming</a>, <a target="_blank" href="https://ej2.syncfusion.com/javascript/documentation/api/chart/zoomSettingsModel/#enablemousewheelzooming">enableMouseWheelZooming</a>, and <a target="_blank" href="https://ej2.syncfusion.com/javascript/documentation/api/chart/zoomSettingsModel/#enabledeferredzooming">enableDeferredZooming</a> properties.</p> <p>The chart supports different mode of zooming which can be set using <a target="_blank" href="http://ej2.syncfusion.com/javascript/documentation/chart/api-zoomSettings.html#mode-zoommode">mode</a> property.</code> </p> <ul> <li><code>XY</code> - Zoom the chart with respect to both the axis.</li> <li><code>X</code> - Zoom the chart with respect to horizontal axis.</li> <li><code>Y</code> - Zoom the chart with respect to vertical axis.</li> </ul> <br> <p> More information on the Zooming can be found in this <a target="_blank" href="https://ej2.syncfusion.com/javascript/documentation/chart/zooming/">documentation section</a>. </p> </div> <svg style="height: 0"> <defs> <linearGradient id="material-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="fabric-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="bootstrap-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="bootstrap4-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="highcontrast-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="tailwind-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="bootstrap5-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="material-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="fabric-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="bootstrap-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="tailwind-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="bootstrap5-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="fluent-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="fluent-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="material3-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> <linearGradient id="material3-dark-gradient-chart" style="opacity: 0.75" class="chart-gradient" x1="0" x2="0" y1="0" y2="1"> <stop offset="0"></stop> <stop offset="1"></stop> </linearGradient> </defs> </svg>
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entity; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; /** * * @author pupil */ @Entity public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @Lob private byte[] cover; public Book() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public byte[] getCover() { return cover; } public void setCover(byte[] cover) { this.cover = cover; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + Objects.hashCode(this.id); hash = 53 * hash + Objects.hashCode(this.title); hash = 53 * hash + Arrays.hashCode(this.cover); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Book other = (Book) obj; if (!Objects.equals(this.title, other.title)) { return false; } if (!Objects.equals(this.id, other.id)) { return false; } if (!Arrays.equals(this.cover, other.cover)) { return false; } return true; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", cover=" + cover + '}'; } }
package gui.button; import gui.frame.DescriptionPanel; import gui.frame.ImagePanel; import gui.frame.MainFrame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JToggleButton; import code.Difficulty; /** * This button sets create the options panel and update it considering the button pressed in the options panel.<br> * It can set the difficulty and display information on the chosen difficulty. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class OptionsButton extends JButton implements ActionListener{ private static final long serialVersionUID = 1L; private MainFrame mf; private ImagePanel optionsPan; private JPanel jpan; private DescriptionPanel descDifficulty; private ButtonGroup difficultySelection; private Difficulty temp; private NoobButton noobB; private EasyButton easyB; private MediumButton mediumB; private HardButton hardB; private HardCoreButton hardCoreB; private CreditsButton creditsB; private ReturnButton returnMenuOB; public OptionsButton(String s, MainFrame mainf, JPanel pan) { super(s); mf = mainf; jpan = pan; } /** * Create the options panel which allows the user to chose between difficulties. */ public void createOptionsPan() { optionsPan = new ImagePanel("./images/bg/options_image_feu_desc_voit.png"); descDifficulty = new DescriptionPanel(); difficultySelection = new ButtonGroup(); noobB = new NoobButton("NOOB"); easyB = new EasyButton("EASY"); mediumB = new MediumButton("MEDIUM"); hardB = new HardButton("HARD"); hardCoreB = new HardCoreButton("HARDCORE "); creditsB = new CreditsButton("Crédits"); returnMenuOB = new ReturnButton("<html>Retourner au<br><center>menu</center></html>"); optionsPan.setLayout(null); descDifficulty.setLocation(mf.getWidth()/2-mf.getWidth()/6, mf.getHeight()*2/5); descDifficulty.setSize(mf.getWidth()/3, mf.getHeight()/3); descDifficulty.setBounds(mf.getWidth()/2-mf.getWidth()/6, mf.getHeight()*2/5,mf.getWidth()/3, mf.getHeight()/3); noobB.setBounds(mf.getWidth()/2-mf.getWidth()/16-mf.getWidth()/6-mf.getWidth()/6, mf.getHeight()/5, mf.getWidth()/8, mf.getHeight()/10); easyB.setBounds(mf.getWidth()/2-mf.getWidth()/16-mf.getWidth()/6, mf.getHeight()/5, mf.getWidth()/8, mf.getHeight()/10); mediumB.setBounds(mf.getWidth()/2-mf.getWidth()/16, mf.getHeight()/5, mf.getWidth()/8, mf.getHeight()/10); mediumB.setSelected(true); hardB.setBounds(mf.getWidth()/2+mf.getWidth()/16+mf.getWidth()/6-mf.getWidth()/8, mf.getHeight()/5, mf.getWidth()/8, mf.getHeight()/10); hardCoreB.setBounds(mf.getWidth()/2+mf.getWidth()/16+mf.getWidth()/6+mf.getWidth()/6-mf.getWidth()/8, mf.getHeight()/5, mf.getWidth()/8, mf.getHeight()/10); creditsB.setBounds(mf.getWidth()/2-mf.getWidth()/16, mf.getHeight()*4/5, mf.getWidth()/8, mf.getHeight()/10); returnMenuOB.setBounds(mf.getWidth()*4/5,mf.getHeight()*5/7,mf.getWidth()/6,mf.getHeight()/10); noobB.addActionListener(noobB); noobB.addMouseListener(noobB); easyB.addActionListener(easyB); easyB.addMouseListener(easyB); mediumB.addActionListener(mediumB); mediumB.addMouseListener(mediumB); hardB.addActionListener(hardB); hardB.addMouseListener(hardB); hardCoreB.addActionListener(hardCoreB); hardCoreB.addMouseListener(hardCoreB); creditsB.addActionListener(creditsB); returnMenuOB.addActionListener(returnMenuOB); difficultySelection.add(noobB); difficultySelection.add(easyB); difficultySelection.add(mediumB); difficultySelection.add(hardB); difficultySelection.add(hardCoreB); optionsPan.add(descDifficulty); optionsPan.add(noobB); optionsPan.add(easyB); optionsPan.add(mediumB); optionsPan.add(hardB); optionsPan.add(hardCoreB); optionsPan.add(creditsB); optionsPan.add(returnMenuOB); } @Override public void actionPerformed(ActionEvent e) { createOptionsPan(); mf.getContentPane().setVisible(false); mf.setContentPane(optionsPan); } /** * Set the difficulty to NOOB and update the information displayed. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class NoobButton extends JToggleButton implements MouseListener, ActionListener{ private static final long serialVersionUID = 1L; public NoobButton(String s) { super(s); } @Override public void actionPerformed(ActionEvent e) { mf.setDifficulty(Difficulty.NOOB); descDifficulty.changeText(Difficulty.NOOB); temp = null; } @Override public void mouseClicked(MouseEvent e){} @Override public void mouseEntered(MouseEvent e) { temp = mf.getDifficulty(); descDifficulty.changeText(Difficulty.NOOB); } @Override public void mouseExited(MouseEvent e) { if(temp != null) { descDifficulty.changeText(temp); temp = null; } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} } /** * Set the difficulty to EASY and update the information displayed. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class EasyButton extends JToggleButton implements MouseListener, ActionListener{ private static final long serialVersionUID = 1L; public EasyButton(String s) { super(s); } @Override public void actionPerformed(ActionEvent e) { mf.setDifficulty(Difficulty.EASY); descDifficulty.changeText(Difficulty.EASY); temp = null; } @Override public void mouseClicked(MouseEvent e){} @Override public void mouseEntered(MouseEvent e) { temp = mf.getDifficulty(); descDifficulty.changeText(Difficulty.EASY); } @Override public void mouseExited(MouseEvent e) { if(temp != null) { descDifficulty.changeText(temp); temp = null; } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} } /** * Set the difficulty to MEDIUM and update the information displayed. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class MediumButton extends JToggleButton implements MouseListener, ActionListener{ /** * */ private static final long serialVersionUID = 1L; public MediumButton(String s) { super(s); } @Override public void actionPerformed(ActionEvent e) { mf.setDifficulty(Difficulty.MEDIUM); descDifficulty.changeText(Difficulty.MEDIUM); temp = null; } @Override public void mouseClicked(MouseEvent e){} @Override public void mouseEntered(MouseEvent e) { temp = mf.getDifficulty(); descDifficulty.changeText(Difficulty.MEDIUM); } @Override public void mouseExited(MouseEvent e) { if(temp != null) { descDifficulty.changeText(temp); temp = null; } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} } /** * Set the difficulty to HARD and update the information displayed. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class HardButton extends JToggleButton implements MouseListener, ActionListener{ private static final long serialVersionUID = 1L; public HardButton(String s) { super(s); } @Override public void actionPerformed(ActionEvent e) { mf.setDifficulty(Difficulty.HARD); descDifficulty.changeText(Difficulty.HARD); temp = null; } @Override public void mouseClicked(MouseEvent e){} @Override public void mouseEntered(MouseEvent e) { temp = mf.getDifficulty(); descDifficulty.changeText(Difficulty.HARD); } @Override public void mouseExited(MouseEvent e) { if(temp != null) { descDifficulty.changeText(temp); temp = null; } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} } /** * Set the difficulty to HARDCORE and update the information displayed. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class HardCoreButton extends JToggleButton implements MouseListener, ActionListener{ private static final long serialVersionUID = 1L; public HardCoreButton(String s) { super(s); } @Override public void actionPerformed(ActionEvent e) { mf.setDifficulty(Difficulty.HARDCORE); descDifficulty.changeText(Difficulty.HARDCORE); temp = null; } @Override public void mouseClicked(MouseEvent e){} @Override public void mouseEntered(MouseEvent e) { temp = mf.getDifficulty(); descDifficulty.changeText(Difficulty.HARDCORE); } @Override public void mouseExited(MouseEvent e) { if(temp != null) { descDifficulty.changeText(temp); temp = null; } } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} } /** * Return to the main menu button. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class ReturnButton extends JButton implements ActionListener{ private static final long serialVersionUID = 1L; public ReturnButton(String s) { super(s); } @Override public void actionPerformed(ActionEvent arg0) { mf.getContentPane().setVisible(false); jpan.setVisible(true); mf.setContentPane(jpan); } } /** * Display a dialog with credits. * @author NOVAK Johann * johann.novak@utbm.fr * @author SCHULZ Quentin * quentin.schulz@utbm.fr * * @version v0.1 */ public class CreditsButton extends JButton implements ActionListener { private static final long serialVersionUID = 1L; public CreditsButton(String title) { this.setText(title); } @Override public void actionPerformed(ActionEvent arg0) { JOptionPane.showMessageDialog(this, "\"Simulation de trafic de trains de véhicules\" est un jeu proposé par\n\nNOVAK Johann et SCHULZ Quentin GI01\n\nen tant que projet final en Automne 2013 de LO43 (Introduction à la POO)", "Crédits", JOptionPane.PLAIN_MESSAGE); } } }
#It contains both HTML and CSS style <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3-in-1 Game Website</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: hsl(243, 66%, 45%); } header { background-color: #333; color: #fff; padding: 10px; text-align: center; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } nav { background-color: #444; color: #fff; padding: 10px; text-align: center; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } nav ul { list-style-type: none; margin: 0; padding: 0; } nav ul li { display: inline; margin-right: 10px; } .game-link { display: inline-block; padding: 10px; border-radius: 5px; text-decoration: none; color: #fff; transition: background-color 0.3s; } #game1-link { background-color: #FF5733; } #game2-link { background-color: #5DADE2; } #game3-link { background-color: #58D68D; } .game-link:hover { background-color: #666; } main { padding: 20px; display: flex; flex-wrap: wrap; justify-content: space-around; } section { margin-bottom: 20px; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); transition: transform 0.3s, box-shadow 0.3s; background-color: #fff; width: calc(33.40% - 20px); margin-right: 20px; display: flex; flex-direction: column; } section:hover { transform: translateY(-5px); box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); } section h2 { background-color: #333; color: #fff; margin: 0; padding: 10px; text-align: center; } .game-box { flex-grow: 3; display: flex; flex-direction: column; justify-content: center; align-items: center; } img { max-width: 100%; height: auto; border-radius: 10px 10px 0 0; } .game-info { padding: 20px; text-align: center; } .game-info p { margin: 0; font-size: 18px; color: #333; } </style> </head> <body> <header> <h1>3-in-1 Game</h1> </header> <nav> <ul> <li><a href="#game1" id="game1-link" class="game-link">Game 1</a></li> <li><a href="#game2" id="game2-link" class="game-link">Game 2</a></li> <li><a href="#game3" id="game3-link" class="game-link">Game 3</a></li> </ul> </nav> <main> <section id="game1"> <h2>Game 1</h2> <div class="game-box"> <img src="egg-catcher.png" alt="Game 1 Image"> <div class="game-info" id="game1_output"></div> </div> </section> <section id="game2"> <h2>Game 2</h2> <div class="game-box"> <img src="image.png" alt="Game 2 Image"> <div class="game-info" id="game2_output"></div> </div> </section> <section id="game3"> <h2>Game 3</h2> <div class="game-box"> <img src="match-making.png" alt="Game 3 Image"> <div class="game-info" id="game3_output"></div> </div> </section> </main> </body> </html>
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( //La clase debe retornar algo! En este caso un Widget de tipo MaterialApp title: 'Widgets Mas utilizados', //Un atributo de MaterialApp es el titulo de tu app theme: ThemeData( //Otro atributo es theme, nos ayuda a darle color y personalización de estilo a tu app que puedes utilizar en cualquier lugar colorScheme: ColorScheme.fromSeed(seedColor: const Color.fromARGB(255, 109, 197, 219)), //Color principal de mi app useMaterial3: true, // Utilizamos Material Design ), home: const Birthday(), //Otro atributo de Material App, es la pantalla home , en este caso le paso otra clase, la clase "BirthdayCard" ); } } class Birthday extends StatelessWidget { const Birthday ({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Happy Birthday'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('Happy Birthday :)', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), Image.asset( 'https://hips.hearstapps.com/hmg-prod/images/birthday-cake-with-happy-birthday-banner-royalty-free-image-1656616811.jpg?crop=0.668xw:1.00xh;0.0255xw,0&resize=980:*' // Ruta de la imagen en tu proyecto ), ], ), ), ); } }
package me.saniukvyacheslav.message; import lombok.Setter; import me.saniukvyacheslav.util.string.RegexUtils; import me.saniukvyacheslav.util.string.StringUtils; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.regex.Matcher; /** * This class used for adding current time to logging messages. * if logging message pattern has "%TIME%" chars sequence, this instance replace it with current time. * Developers can set different time formats via * {@link me.saniukvyacheslav.logging.conf.LoggersConfiguration.LoggerConfigurationBuilder#setTimeFormat(String)} method * for different loggers configurations. By default, time format is "HH:mm:ss". */ public class PatternModifierTime implements PatternModifier { public static final String TIME_ARGUMENT_REGEX = "%TIME%"; public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; // Default time format; @Setter private DateTimeFormatter timeFormatter; // Time to string formatter; /** * Construct new instance of this class. */ public PatternModifierTime() { this.timeFormatter = DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT); } /** * Modify logging message pattern. * Replace "%TIME%" char sequence with current time. * @param aPattern - logging message pattern. * @param anArguments - modifier arguments. * @return - modified pattern. */ @Override public String modify(String aPattern, Object... anArguments) { StringUtils.checkForNull(aPattern, "aPattern"); Matcher matcher = RegexUtils.match(aPattern, TIME_ARGUMENT_REGEX); if (matcher != null) return matcher.replaceFirst(LocalTime.now().format(timeFormatter)); else return aPattern; } }
unit Unit1; {$mode objfpc}{$H+} { Name : Sutcliffe Pentagon Desc : example rendering a Sutcliffe Pentagon using the TFPCustomCanvas class helper changed to TPaintbox by : TRon 2023 (Pay It Forward) changed to TPaintbox by Boleeman origin : code based on https://github.com/tex2e/p5js-pentagon thread : https://forum.lazarus.freepascal.org/index.php/topic,64632.0.html } interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Spin, StdCtrls, SutcliffePentagonHelper; type { TForm1 } TForm1 = class(TForm) ColorButtonpencolor: TColorButton; ColorButtonbrushcolor: TColorButton; lblbrushcolor: TLabel; lblpencolor: TLabel; lblNest: TLabel; lblRadius: TLabel; lblStrutFactor: TLabel; lblStrutTarget: TLabel; lblSubStrutTarget: TLabel; lblNumSides: TLabel; SpinEditStrutFactor: TFloatSpinEdit; PaintBox1: TPaintBox; Panel1: TPanel; SpinEditNest: TSpinEdit; SpinEditRadius: TSpinEdit; SpinEditStrutTarget: TSpinEdit; SpinEditSubStrutTarget: TSpinEdit; SpinEditNumSides: TSpinEdit; procedure ColorButtonbrushcolorColorChanged(Sender: TObject); procedure ColorButtonpencolorColorChanged(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure SpinEditNestChange(Sender: TObject); procedure SpinEditNumSidesChange(Sender: TObject); procedure SpinEditRadiusChange(Sender: TObject); procedure SpinEditStrutFactorChange(Sender: TObject); procedure SpinEditStrutTargetChange(Sender: TObject); procedure SpinEditSubStrutTargetChange(Sender: TObject); private { private declarations } myBitmap: TBitmap; procedure UpdateParamsAndRedraw(Sender: TObject); public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin myBitmap := TBitmap.Create; myBitmap.SetSize(PaintBox1.Width, PaintBox1.Height); // Set initial values for the spin edits SpinEditNest.Value := 5; SpinEditRadius.Value := 350; SpinEditStrutFactor.Value := 0.30; SpinEditStrutTarget.Value := 4; SpinEditSubStrutTarget.Value := 3; SpinEditNumSides.Value := 7; end; procedure TForm1.ColorButtonpencolorColorChanged(Sender: TObject); begin PaintBox1.Invalidate; // Trigger a repaint when the pen color changes //ColorButtonpencolor.OnColorChanged := @ColorButtonpencolorColorChanged; end; procedure TForm1.ColorButtonbrushcolorColorChanged(Sender: TObject); begin PaintBox1.Invalidate; // Trigger a repaint when the brush color changes //ColorButtonbrushcolor.OnColorChanged := @ColorButtonbrushcolorColorChanged; end; procedure TForm1.PaintBox1Paint(Sender: TObject); var PaintBoxCanvas: TCanvas; begin PaintBoxCanvas := PaintBox1.Canvas; //PaintBoxCanvas.Brush.Color := RGBToColor(255, 255, 255); PaintBoxCanvas.Brush.Color := ColorButtonbrushcolor.ButtonColor; PaintBoxCanvas.FillRect(0, 0, PaintBox1.Width, PaintBox1.Height); //PaintBoxCanvas.Pen.Color := RGBToColor($bd, $4f, $1d); PaintBoxCanvas.Pen.Color := ColorButtonpencolor.ButtonColor; // render Sutcliffe pentagon to canvas PaintBoxCanvas.RenderSutcliffePentagon( SpinEditNest.Value, SpinEditRadius.Value, SpinEditStrutFactor.Value, SpinEditStrutTarget.Value, SpinEditSubStrutTarget.Value, SpinEditNumSides.Value ); // render Sutcliffe pentagon to canvas //PaintBoxCanvas.RenderSutcliffePentagon( // 5, // aNest // 350, // aRadius // 0.30, // aStrutFactor // 4, // aStrutTarget // 3, // aSubStrutTarget // 7 // aNumSides end; procedure TForm1.SpinEditNestChange(Sender: TObject); begin SpinEditNest.OnChange := @UpdateParamsAndRedraw; end; procedure TForm1.SpinEditNumSidesChange(Sender: TObject); begin SpinEditNumSides.OnChange := @UpdateParamsAndRedraw; end; procedure TForm1.SpinEditRadiusChange(Sender: TObject); begin SpinEditRadius.OnChange := @UpdateParamsAndRedraw; end; procedure TForm1.SpinEditStrutFactorChange(Sender: TObject); begin SpinEditStrutFactor.OnChange := @UpdateParamsAndRedraw; end; procedure TForm1.SpinEditStrutTargetChange(Sender: TObject); begin SpinEditStrutTarget.OnChange := @UpdateParamsAndRedraw; end; procedure TForm1.SpinEditSubStrutTargetChange(Sender: TObject); begin SpinEditSubStrutTarget.OnChange := @UpdateParamsAndRedraw; end; procedure TForm1.UpdateParamsAndRedraw(Sender: TObject); begin // Redraw the PaintBoxCanvas whenever any spin edit value changes PaintBox1.Invalidate; end; end.
import random import json import os import torch from src.chat.model.NLPTokenizer import NLPTokenizer from src.chat.model.model import NeuralNet from src.chat.train import ChatBotModel class ChatBot: def __init__( self, intents_path="./src/chat/intents.json", model_save_path="data.pth", bot_name="Sam", ): self.intents_path = intents_path self.model_save_path = model_save_path self.bot_name = bot_name self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.tokenizer = NLPTokenizer() self.intents = self.load_intents() self.data = self.load_model_data() self.model = self.load_model() def load_intents(self): with open(self.intents_path, "r") as json_data: intents = json.load(json_data) return intents def load_model_data(self): if not os.path.exists(self.model_save_path): chatbot = ChatBotModel(self.intents_path, self.model_save_path) chatbot.run() return torch.load(self.model_save_path) def load_model(self): model = NeuralNet( self.data["input_size"], self.data["hidden_size"], self.data["output_size"] ).to(self.device) model.load_state_dict(self.data["model_state"]) model.eval() return model def get_response(self, sentence): sentence = self.tokenizer.tokenize(sentence) X = self.tokenizer.bag_of_words(sentence, self.data["all_words"]) X = X.reshape(1, X.shape[0]) X = torch.from_numpy(X).to(self.device) output = self.model(X) _, predicted = torch.max(output, dim=1) tag = self.data["tags"][predicted.item()] probs = torch.softmax(output, dim=1) prob = probs[0][predicted.item()] if prob.item() > 0.75: for intent in self.intents["intents"]: if tag == intent["tag"]: return random.choice(intent["responses"]), [] else: return False, [] """if __name__ == "__main__": """
import 'dart:js'; import 'dart:html' as html; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:key_admin_panel/views/category/bloc/category_page_bloc.dart'; import 'package:key_admin_panel/views/category/category_page_ui.dart'; import 'package:key_admin_panel/views/keys/bloc/key_bloc.dart'; import 'package:key_admin_panel/views/keys/key_page_ui.dart'; import 'package:key_admin_panel/views/login/login_page_ui.dart'; import 'package:key_admin_panel/views/plan/bloc/plan_bloc.dart'; import 'package:key_admin_panel/views/plan/plan_page_ui.dart'; import '../views/login/bloc/login_bloc.dart'; import '../views/sidebar_drawer/side_drawer.dart'; import '../views/users/bloc/user_bloc.dart'; import '../views/users/user_page_ui.dart'; class RouteGenerate { static const String splashScreen = "/splash"; static const String homeScreen = "/home_page_ui"; static const String uerPage = "/UserPage"; static const String keyPageUI = "/key_page_ui"; static const String selectionScreen = "/SelectionScreen"; static const String passwordRecover = "/passwordRecover"; static const String signIn = "/signIn"; static const String login = "/login"; static const String analyseResultScreen = "/analyseResultScreen"; static const String cameraPreviewScreen = "/cameraPreviewScreen"; static const String categoryPageUI = "/categoryPageUI"; static const String planPageUI = "/planPageUI"; static Route<dynamic>? onCreateRoute(RouteSettings routeSettings) { var arg = routeSettings.arguments; switch (routeSettings.name) { /* case splashScreen: return MaterialPageRoute(builder: (context) { return BlocProvider( create: (context) { return SplashScreenBloc(); }, child: SplashScreen()); }); */ case login: return MaterialPageRoute(builder: (context){ return BlocProvider( create: (context) { return LoginBloc(); }, child: const LoginPageUI()); }); case homeScreen: return MaterialPageRoute(builder: (context) { return SideDrawer(); }); case keyPageUI: return MaterialPageRoute(builder: (context){ return BlocProvider( create: (context) { return KeyBloc(); }, child: KeyPageUI()); }); case uerPage: return MaterialPageRoute(builder: (context){ return BlocProvider( create: (context) { return UsersDataBloc(); }, child: UserPage()); }); case categoryPageUI: return MaterialPageRoute(builder: (context){ return BlocProvider( create: (context) { return CategoryPageBloc(); }, child: CategoryPageUI()); }); case planPageUI: return MaterialPageRoute(builder: (context){ return BlocProvider( create: (context){ return PlanBloc(); }, child: PlanPageUI()); }); /* case '/': html.window.location.reload();*/ } } }
import { View, StyleSheet, TextInput } from "react-native"; import { useFormik } from "formik"; import * as Yup from "yup"; import React, { useState } from "react"; import useAuth from "../../../hooks/useAuth"; import { user, userDetails } from "../../../utils/userDB"; import { AppText } from "../../AppText"; import { AppButton } from "../../AppButton"; import { AppTextInput } from "../../AppTextInput"; function LoginForm() { const [error, setError] = useState(""); const { login } = useAuth(); const formik = useFormik({ initialValues: initialValues(), validationSchema: Yup.object(validationSchema()), validateOnChange: false, onSubmit: (values) => { setError(""); const { username, password } = values; if (username !== user.username || password !== user.password) { setError( "¡Cuidado, el nombre de usuario o el password son incorrectos!" ); } else { login(userDetails); } }, }); return ( <View style={styles.container}> <AppText style={styles.title} bold={true}> Iniciar sesión </AppText> <AppTextInput placeholder="Nombre de usuario" style={styles.input} autoCapitalize="none" value={formik.values.username} onChangeText={(text: string) => formik.setFieldValue("username", text)} /> <AppTextInput placeholder="Password" style={styles.input} autoCapitalize="none" secureTextEntry={true} value={formik.values.password} onChangeText={(text: string) => formik.setFieldValue("password", text)} /> <AppButton onPress={() => formik.handleSubmit()} style={styles.buttonContainer} > <AppText style={styles.buttonText}>Iniciar sesión</AppText> </AppButton> <AppText style={styles.errorMessages}>{formik.errors.username}</AppText> <AppText style={styles.errorMessages}>{formik.errors.password}</AppText> <AppText style={styles.errorMessages}>{error}</AppText> </View> ); } function initialValues() { return { username: "", password: "", }; } function validationSchema() { return { username: Yup.string().required( "¡Cuidado, el nombre de usuario es requerido!" ), password: Yup.string().required("¡Cuidado, el password es requerido!"), }; } const styles = StyleSheet.create({ container: { marginTop: 150, paddingHorizontal: 20, }, title: { textAlign: "center", fontSize: 28, marginTop: 100, marginBottom: 15, }, input: { height: 35, margin: 12, borderWidth: 1, padding: 10, borderRadius: 3, }, buttonContainer: { backgroundColor: "#007AFF", marginHorizontal: 100, borderRadius: 3, padding: 7, alignItems: "center", justifyContent: "center", }, buttonText: { fontWeight: undefined, color: "#fff", }, errorMessages: { textAlign: "center", color: "red", marginTop: 10, }, }); export { LoginForm };
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:recipe_app_bloc/constants/Constants.dart'; import '../../../models/FoodType.dart'; import '../../recipe_info_screen/RecipeInfoScreen.dart'; import '../../recipe_info_screen/bloc/recipe_info_bloc.dart'; class FoodTypeWidget extends StatelessWidget { final List<FoodType> items; const FoodTypeWidget({Key? key, required this.items}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( height: 300, child: ListView( scrollDirection: Axis.horizontal, physics: const BouncingScrollPhysics(), children: [ const SizedBox(width: 20), ...items.map((item) { return RecipeCardType(items: item); }).toList() ], )); } } class RecipeCardType extends StatefulWidget { const RecipeCardType({ Key? key, required this.items, }) : super(key: key); final FoodType items; @override _RecipeCardTypeState createState() => _RecipeCardTypeState(); } class _RecipeCardTypeState extends State<RecipeCardType> { @override Widget build(BuildContext context) { return Stack( children: [ InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => BlocProvider( create: (context) => RecipeInfoBloc(), child: RecipeInfo( id: widget.items.id, ), ), ), ); }, child: ClipRRect( borderRadius: BorderRadius.circular(35), child: Container( height: 300, decoration: BoxDecoration( color: (int.tryParse(widget.items.id) ?? 0) % 2 == 0 ? kPrimaryColor : kSecondaryColor, boxShadow: const [ BoxShadow( offset: Offset(-2, -2), blurRadius: 12, color: Color.fromRGBO(0, 0, 0, 0.05), ), BoxShadow( offset: Offset(2, 2), blurRadius: 5, color: Color.fromRGBO(0, 0, 0, 0.10), ) ], borderRadius: BorderRadius.circular(10), ), margin: const EdgeInsets.all(8), width: 200, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10)), child: Container( width: 200, foregroundDecoration: const BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10)), ), child: CachedNetworkImage( imageUrl: widget.items.image, fit: BoxFit.cover, height: 150, ), ), ), const SizedBox( height: 10, ), Container( padding: const EdgeInsets.all(9), child: Text( widget.items.name, maxLines: 2, overflow: TextOverflow.ellipsis, style: headingTheme.copyWith(fontSize: 18), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), child: Text( "Ready in ${widget.items.readyInMinutes} Min", style: paraTheme.copyWith( fontSize: 14, color: Colors.pink, ), ), ), ], ), ), ), ), ], ); } }
# Sentence 012 > The staff is friendly and helpful, providing you with a map of the city when you arrive and offering advice if you require some. > 工作人员态度友善且乐于助人,会在您到达时为您提供城市地图,并在您需要时提供建议。 ## 语法笔记 > 本句的主干是The staff is friendly and helpful。providing you with…and offering advice…做伴随状语,其中包含when引导的时间状语从句和if引导的条件状语从句,and表并列,连接providing you with…和offering advice…两个部分。 ## 核心词表 - [ ] staff n. 全体职员 - 搭配: - the staff of a school 学校的教职员工 - [ ] friendly adj. 有好的 - [ ] helpful adj. 有帮助的,有益的 - [ ] provide vt. 提供 - 搭配: - provide sb. with sth. (=provide sth. for sb.) 为某人提供某物 - 派生: - provision n. 提供,攻击 - offer v./n. 提供;提出;出价 - 搭配: - offer sb. sth. (=offer sth. to sb.) 主动提出做某事 - [ ] advice n. 忠告,劝告,建议 - 搭配: - ask for advice 征求意见 - give/offer some advice 提建议 - take/allow one's advice 采纳、接纳某人的建议 - two pieces of advice 两条建议 ## 主题归纳 ### 与“出国旅游”有关的词: - [ ] aboard prep./adv. 在(船、飞机、火车)上 - [ ] abroad adv. 到国外,在国外 - 搭配:be/go abroad 在/去国外 - [ ] accommodation n. [pl.] 膳宿;调解 - [ ] baggage n. 行李 - [ ] book n. 书;本 v. 预订(房间、车票等) - [ ]
"use strict"; const nodeUuid = require("node-uuid"), _ = require("lodash"), BeginningState = require("dc-game-states").BeginningState, GameData = require("dc-engine").GameData, PresetHelper = require("./preset-helper"); function Game($players, $deckConfig, $choiceProvider) { let uuid = nodeUuid.v1(); let choiceProvider, gameData, state; function initialize() { choiceProvider = $choiceProvider; gameData = new GameData($players, $deckConfig); state = new BeginningState(gameData, choiceProvider); $players = $deckConfig = $choiceProvider = null; } // Returns promise for boolean: // true if game should continue // false if game is over function doNext() { return state.go() .then(function(newState) { state = newState; return !!state; }); } this.doNext = doNext; function getPlayerIndexById(playerId) { return _.findIndex(gameData.players, { id: playerId }); } this.getPlayerIndexById = getPlayerIndexById; function applyPreset(preset) { let helper = new PresetHelper(preset, gameData, choiceProvider); state = helper.createStateFromPreset(); for(let i = 0; i < gameData.players.length; ++i) { if(preset.players[i]) helper.adjustPlayer(gameData.players[i], preset.players[i], gameData); } } this.applyPreset = applyPreset; Object.defineProperties(this, { id: { enumerable: true, get: function() { return uuid; } }, players: { enumerable: true, get: function() { return gameData.players; } }, gameData: { enumerable: false, get: function() { return gameData; } } }); initialize(); } module.exports = Game;
class Solution { public long maxScore(int[] nums1, int[] nums2, int k) { var n = nums1.length; // merge nums1 & nums2 based on index var combined = new Pair[n]; for(var i=0; i<n; i++) combined[i] = new Pair(nums1[i], nums2[i]); // sort this combined array by nums2 value, descending // When we iterate over this sorted array, we know that smallest n2 is curr index Arrays.sort(combined, (c1, c2) -> c2.n2 - c1.n2); // priority queue to track smallest in nums1, so that it can be removed if needed var pq = new PriorityQueue<Integer>(); long ans = 0, num1Sum = 0; for(var cmb : combined){ num1Sum += cmb.n1; pq.offer(cmb.n1); if(pq.size() > k) num1Sum -= pq.poll(); // remove smallest num1 if(pq.size() == k) ans = Math.max(ans, num1Sum * cmb.n2); } return ans; } } class Pair { int n1; int n2; Pair(int n1, int n2) { this.n1 = n1; this.n2 = n2; } }
package main import "testing" func TestFromFeet(t *testing.T) { t.Run("empty input returns empty error", func(t *testing.T) { inp := HeightFeet{} got, err := FromFeet(inp) want := HeightMetric{} CheckGotWant(t, got, want) CheckError(t, err, "please input an imperial height") }) t.Run("empty input returns empty error", func(t *testing.T) { inp := HeightFeet{ Feet: 0, Inches: 0, } got, err := FromFeet(inp) want := HeightMetric{} CheckGotWant(t, got, want) CheckError(t, err, "please input an imperial height") }) t.Run("invalid feet returns invalid error", func(t *testing.T) { inp := HeightFeet{ Feet: -23, Inches: 2, } got, err := FromFeet(inp) want := HeightMetric{} CheckGotWant(t, got, want) CheckError(t, err, "invalid input") }) t.Run("invalid inches returns invalid error", func(t *testing.T) { inp := HeightFeet{ Feet: 5, Inches: -2, } got, err := FromFeet(inp) want := HeightMetric{} CheckGotWant(t, got, want) CheckError(t, err, "invalid input") }) t.Run("invalid inches returns invalid error", func(t *testing.T) { inp := HeightFeet{ Feet: 4, Inches: 23, } got, err := FromFeet(inp) want := HeightMetric{} CheckGotWant(t, got, want) CheckError(t, err, "invalid input") }) t.Run("valid input returns correct output", func(t *testing.T) { inp := HeightFeet{ Feet: 5, Inches: 2, } want := HeightMetric{ Centimetres: 157, Metres: 1.57, } got, _ := FromFeet(inp) CheckGotWant(t, got, want) }) } func TestFromMetric(t *testing.T) { t.Run("empty input returns empty error", func(t *testing.T) { inp := HeightMetric{ Centimetres: 0, Metres: 0, } got, err := FromMetric(inp) want := HeightFeet{} CheckGotWant(t, got, want) CheckError(t, err, "please input a metric height") }) t.Run("empty input returns empty error", func(t *testing.T) { inp := HeightMetric{} got, err := FromMetric(inp) want := HeightFeet{} CheckGotWant(t, got, want) CheckError(t, err, "please input a metric height") }) t.Run("conflicting input returns invalid error", func(t *testing.T) { inp := HeightMetric{ Metres: 1.86, Centimetres: 160, } got, err := FromMetric(inp) want := HeightFeet{} CheckGotWant(t, got, want) CheckError(t, err, "please only input one unit") }) t.Run("invalid metres input returns invalid error", func(t *testing.T) { inp := HeightMetric{ Metres: -2, Centimetres: 0, } got, err := FromMetric(inp) want := HeightFeet{} CheckGotWant(t, got, want) CheckError(t, err, "invalid input") }) t.Run("invalid centimetres input returns invalid error", func(t *testing.T) { inp := HeightMetric{ Metres: 0, Centimetres: -186, } got, err := FromMetric(inp) want := HeightFeet{} CheckGotWant(t, got, want) CheckError(t, err, "invalid input") }) t.Run("valid centimetres input returns correct output", func(t *testing.T) { inp := HeightMetric{ Metres: 0, Centimetres: 186, } want := HeightFeet{ Feet: 6, Inches: 1.2, } got, _ := FromMetric(inp) CheckGotWant(t, got, want) }) t.Run("valid metres input returns correct output", func(t *testing.T) { inp := HeightMetric{ Metres: 1.86, Centimetres: 0, } want := HeightFeet{ Feet: 6, Inches: 1.2, } got, _ := FromMetric(inp) CheckGotWant(t, got, want) }) }
import Container from "@material-ui/core/Container"; import React, { useContext } from "react"; import Typography from '@material-ui/core/Typography'; import Footer from "../../components/Footer/Footer"; import Header from '../../components/Header/Header' import { BoxEndereco, Font, ContainerTela, Flex, ModalCustom} from "./styled"; import CardOrder from '../../components/CardOrder/CardOrder' import Radio from '@material-ui/core/Radio' import FormControl from '@material-ui/core/FormControl' import FormControlLabel from '@material-ui/core/FormControlLabel' import RadioGroup from '@material-ui/core/RadioGroup' import Button from '@material-ui/core/Button'; import { styled } from '@material-ui/core/styles'; import { useNavigate } from "react-router-dom"; import { goToHomePage } from "../../routes/coordinator"; import AccessTimeIcon from '@material-ui/icons/AccessTime'; import { Modal } from "@material-ui/core"; import { GlobalStateContext } from "../../global/GlobalStateContext"; import useProtectedPage from "../../hooks/useProtectedPage"; const style = { position: 'absolute' , top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 400, bgcolor: '#e86e5a', boxShadow: 24, p: 4, color:"white", }; const ClickButtonn = styled(Button)({ textTransform: 'none', boxShadow: 'none', fontSize: 16, padding: '6px 12px', lineHeight: 2.0, marginBottom:'50px', }); const OrderPage = (props) => { useProtectedPage() const navigate = useNavigate() const [open, setOpen] = React.useState(false); const handleOpen = () => setOpen(true); const {cart,setCart}=useContext(GlobalStateContext) //Collapse const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; const handleClick=(e)=>{ goToHomePage(navigate) handleChange(); //handleSubmit(e); } return ( <Font> <ContainerTela> <Header title="Carrinho"/> <Modal open={open} onClose={handleClick} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <ModalCustom sx={style}> <AccessTimeIcon fontSize="large"/> <div> <Typography id="modal-modal-title" variant="h6" component="h2"> Pedido em andamento </Typography> <Typography id="modal-modal-description" sx={{ mt: 2 }}> <p> Bullguer Vila Madalena</p> </Typography> <Typography id="modal-modal-description" sx={{ mt: 2 }}> <h3>SUBTOTAL R$67,00</h3> </Typography> </div> </ModalCustom> </Modal> <BoxEndereco className="endereco"> <Typography gutterBottom variant="p" component="div" color="text.primary"> <strong>Endereço de entrega</strong> </Typography> <Typography gutterBottom variant="p" component="div" color="text.primary"> Rua Alessandra Viera </Typography> </BoxEndereco> </ContainerTela> <ContainerTela> <Container> <div style={{marginBottom:"16px" }}> <Typography gutterBottom variant="p" component="div" color="primary"> Bullguer Vila Madalena </Typography> <Typography gutterBottom variant="p" component="div" color="text.secondary"> R. Fradique Coutinho, 1136 - Vila Madalena </Typography> <Typography gutterBottom variant="p" component="div" color="text.secondary"> 30 - 45 min </Typography> </div> <CardOrder /> <CardOrder /> <Typography gutterBottom variant="p" component="div" color="text.primary" style={{textAlign:"right",marginBottom:"16px",marginTop:"16px"}}> <strong>Frete R$6,00</strong> </Typography> <Flex> <Typography gutterBottom variant="h6" component="div" color="text.primary"> <strong>SUBTOTAL</strong> </Typography> <Typography gutterBottom variant="h6" component="div" color="primary"> <strong> R$67,00</strong> </Typography> </Flex> <p style={{borderBottom:"1px solid black",paddingBottom:"10px",fontWeight:"bolder"}}>Forma de pagamento</p> <FormControl> <RadioGroup aria-labelledby="demo-controlled-radio-buttons-group" name="controlled-radio-buttons-group" > <FormControlLabel value="Dinheiro" control={<Radio color="black"/>} label="Dinheiro" /> <FormControlLabel value="Cartão de crédito" control={<Radio color="black"/>} label="Cartão de crédito" /> </RadioGroup> </FormControl> <div style={{margin: "16px auto"}}> <ClickButtonn variant="contained" color="primary" fullWidth onClick={handleOpen} ><b>Confirmar </b></ClickButtonn> </div> </Container> <Footer/> </ContainerTela> </Font> ) } export default OrderPage;
package org.sofka.tour.api.teams; import lombok.RequiredArgsConstructor; import org.sofka.tour.model.cyclists.Cyclists; import org.sofka.tour.model.teams.Teams; import org.sofka.tour.usecase.teams.*; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; @Component @RequiredArgsConstructor public class TeamsHandler { private final PostTeamsUseCase postTeamsUseCase; private final GetTeamsUseCase getTeamsUseCase; private final GetByIdTeamUseCase getByIdTeamUseCase; private final AddCyclistsToTeamUseCase addCyclistsToTeamUseCase; private final GetConsultCyclistsWithCodeTeamUseCase getConsultCyclistsWithCodeTeamUseCase; private final GetConsultTeamAssociatedCountryUseCase getConsultTeamAssociatedCountryUseCase; /*METODOS DE INSERCION*/ public Mono<ServerResponse> postSaveTeam(ServerRequest serverRequest){ return serverRequest.bodyToMono(Teams.class) .flatMap(result -> ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(postTeamsUseCase.saveTeam(result), Teams.class)); } public Mono<ServerResponse> postAddCyclistWithTeam(ServerRequest serverRequest){ var id = serverRequest.pathVariable("id"); return serverRequest.bodyToMono(Cyclists.class) .flatMap(result -> ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(addCyclistsToTeamUseCase.addCyclistToTeam(result, id), Teams.class)); } /*METODOS DE CONSULTAS*/ public Mono<ServerResponse> getListTeams(ServerRequest serverRequest){ return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(getTeamsUseCase.listTeams(),Teams.class); } public Mono<ServerResponse> getFindTeam(ServerRequest serverRequest){ var id = serverRequest.pathVariable("id"); return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(getByIdTeamUseCase.findTeamWithId(id), Teams.class); } public Mono<ServerResponse> getConsultCyclistsWithCodeTeam(ServerRequest serverRequest){ var code = serverRequest.pathVariable("code"); return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(getConsultCyclistsWithCodeTeamUseCase.consultCyclistsWithCodeTeam(code), Cyclists.class); } public Mono<ServerResponse> getConsultTeamAssociatedCountry(ServerRequest serverRequest){ var id = serverRequest.pathVariable("id"); return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(getConsultTeamAssociatedCountryUseCase.consultTeamAssociatedCountry(id), Teams.class); } }
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_hackathon_2023/foundation/supabase/supabase_client.dart'; import 'package:flutter_hackathon_2023/model/user.dart'; import 'package:flutter_hackathon_2023/repository/user/user_repository.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart' as riverpod; final userRepositoryProvider = riverpod.Provider<UserRepository>( (ref) => UserRepositoryImpl(ref.watch(supabaseClientProvider)), ); class UserRepositoryImpl implements UserRepository { const UserRepositoryImpl(this._client); static const _tableName = 'users'; final SupabaseClient _client; @override Future<UserModel> findById(int id) async { final results = await _client.from(_tableName).select().eq('id', id).then( (value) => value as List<dynamic>, ); return UserModel.fromJson( results[0] as Map<String, dynamic>, ); } @override Future<int> create(String name) async { final bearerToken = dotenv.get('SUPABASE_BEARER_TOKEN'); final result = await _client.functions.invoke( 'create_user', body: {'name': name}, headers: {'Authorization': 'Bearer $bearerToken'}, ); return UserModel.fromJson( result.data as Map<String, dynamic>, ).id; } }
import { Component, inject } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, catchError, EMPTY, Subscription } from 'rxjs'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-http-req-base', standalone: true, imports: [CommonModule], templateUrl: './http-req-base.component.html' }) export class HttpReqBaseComponent { private http = inject(HttpClient); requests: Subscription[] = []; message$ = new BehaviorSubject<string | null>(null); cancelAllRequests() { if (!this.requests) { this.message$.next('No request found!'); return; } this.requests.forEach(s => s.unsubscribe()); this.requests = []; this.message$.next('All requests were canceled'); } getData(path: string) { const url = `http://localhost:3000/${path}`; console.log('http.get', url); const request = this.http.get<{ message: string }>(url) .pipe( catchError((errorResponse: HttpErrorResponse) => { console.error('ERR', errorResponse); this.message$.next(errorResponse.message); return EMPTY; }) ).subscribe((response) => { console.log(response.message); this.message$.next(response.message); }); this.requests.push(request); } }
// Aug 15 // 238. Product of Array Except Self /* Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.) */ /** * @param {number[]} nums * @return {number[]} */ // Extension of left and right product list // O(n) || O(1) var productExceptSelf = function(nums) { const n = nums.length; const ans = Array(n); ans[0] = 1; for (let i = 1; i < n; i++) { ans[i] = ans[i - 1] * nums[i - 1]; } let rightProduct = 1; for (let i = n - 1; i >= 0; i--) { ans[i] = ans[i] * rightProduct; rightProduct *= nums[i]; } return ans; }; // use left and right product list // O(n) || O(n) var productExceptSelf = function(nums) { const n = nums.length; const leftProductList = Array(n); const rightProductList = Array(n); leftProductList[0] = 1; rightProductList[n - 1] = 1; for (let i = 1; i < n; i++) { leftProductList[i] = leftProductList[i - 1] * nums[i - 1]; } for (let i = n - 2; i >= 0; i--) { rightProductList[i] = rightProductList[i + 1] * nums[i + 1]; } const ans = Array(n); for (let i = 0; i < n; i++) { ans[i] = leftProductList[i] * rightProductList[i]; } return ans; }; // Brute Force // calculate the product except this index // O(n^2) || O(1) var productExceptSelf = function(nums) { const ans = []; for (let i = 0; i < nums.length; i++) { let product = 1; for (let j = 0; j < nums.length; j++) { if (j === i) continue; product *= nums[j]; } ans.push(product); } return ans; };
import { Utils } from '@nativescript/core'; import { isNullOrUndefined } from '@nativescript/core/utils/types'; import { AppDynamicsBreadcrumbVisibility, AppDynamicsErrorSeverityLevel, IAppDynamicsConfig, IAppDynamicsCrashCallback, IAppDynamicsCrashReportSummary } from './common'; export class AppDynamics { private static init(config: IAppDynamicsConfig) { const agentConfiguration = ADEumAgentConfiguration.alloc().initWithAppKey(config.appKey); if (config.collectorURL) { agentConfiguration.collectorURL = config.collectorURL; } if (config.screenshotURL) { agentConfiguration.screenshotURL = config.screenshotURL; } if (config.loggingLevel) { agentConfiguration.loggingLevel = <any>config.loggingLevel; } if (!isNullOrUndefined(config.enableLogging)) { agentConfiguration.enableLogging = config.enableLogging; } if (config.applicationName) { agentConfiguration.applicationName = config.applicationName; } if (config.reachabilityHostName) { agentConfiguration.reachabilityHostName = config.reachabilityHostName; } if (config.flushInterval) { agentConfiguration.flushInterval = config.flushInterval; } if (!isNullOrUndefined(config.anrDetectionEnabled)) { agentConfiguration.anrDetectionEnabled = config.anrDetectionEnabled; } if (!isNullOrUndefined(config.anrStackTraceEnabled)) { agentConfiguration.anrStackTraceEnabled = config.anrStackTraceEnabled; } if (!isNullOrUndefined(config.enableAutoInstrument)) { agentConfiguration.enableAutoInstrument = config.enableAutoInstrument; } if (config.interactionCaptureMode) { // agentConfiguration.withInteractionCaptureMode(config.loggingLevel) } // if (config.collectorChannelFactory) { // agentConfiguration.withCollectorChannelFactory(config.collectorChannelFactory) // } if (config.crashCallback) { ADEumCrashReportImpl.setCallback(config.crashCallback); agentConfiguration.crashReportCallback = <any>ADEumCrashReportImpl; } // if (config.networkRequestCallback) { // agentConfiguration.withNetworkRequestCallback() // } if (!isNullOrUndefined(config.screenshotsEnabled)) { agentConfiguration.screenshotsEnabled = config.screenshotsEnabled; } if (!isNullOrUndefined(config.jsAgentFetchEnabled)) { agentConfiguration.jsAgentEnabled = config.jsAgentEnabled; } if (!isNullOrUndefined(config.jsAgentAjaxEnabled)) { agentConfiguration.jsAgentAjaxEnabled = config.jsAgentAjaxEnabled; } if (!isNullOrUndefined(config.jsAgentFetchEnabled)) { agentConfiguration.jsAgentFetchEnabled = config.jsAgentFetchEnabled; } if (!isNullOrUndefined(config.jsAgentZonePromiseEnabled)) { agentConfiguration.jsAgentZonePromiseEnabled = config.jsAgentZonePromiseEnabled; } if (!isNullOrUndefined(config.crashReportingEnabled)) { agentConfiguration.crashReportingEnabled = config.crashReportingEnabled; } ADEumInstrumentation.initWithConfiguration(agentConfiguration); } public static start(config: IAppDynamicsConfig) { NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(UIApplicationDidFinishLaunchingNotification, null, NSOperationQueue.mainQueue, (appNotification) => { this.init(config); }); } public static shutdownAgent(): void { ADEumInstrumentation.shutdownAgent(); } public static restartAgent() { ADEumInstrumentation.restartAgent(); } /** * Blocks screenshot capture if it is currently unblocked. Otherwise, this has no effect.. * * If screenshots are disabled through `IAppDynamicsConfig` or through the controller UI, this method has no effect. * * If screenshots are set to manual mode in the controller UI, this method unblocks for manual mode only. * * WARNING: This will unblock capture for the entire app. * * The user is expected to manage any possible nesting issues that may occur if blocking and unblocking occur in different code paths. */ public static blockScreenshots() { ADEumInstrumentation.blockScreenshots(); } /** * Unblocks screenshot capture if it is currently blocked. Otherwise, this has no effect. * * If screenshots are disabled through `IAppDynamicsConfig` or through the controller UI, this method has no effect. * * If screenshots are set to manual mode in the controller UI, this method unblocks for manual mode only. * * WARNING: This will unblock capture for the entire app. * * The user is expected to manage any possible nesting issues that may occur if blocking and unblocking occur in different code paths. */ public static unblockScreenshots() { ADEumInstrumentation.unblockScreenshots(); } /** * Check if the ability to take screenshots is blocked. * * @returns `boolean` - boolean whether screenshot capture is blocked */ public static screenshotsBlocked(): boolean { return ADEumInstrumentation.screenshotsBlocked(); } /** * Asynchronously takes a screenshot of the current Activity’s window. * * If screenshots are disabled through `IAppDynamicsConfig` or through the controller UI, this method does nothing. * * This will capture everything, including personal information, so you must be cautious of when to take the screenshot. * * These screenshots will show up in the Sessions screen for this user. * * The screenshots are taken on a background thread, compressed, and only non-redundant parts are uploaded, so it is safe to take many of these without impacting performance of your application. */ public static takeScreenshot() { ADEumInstrumentation.takeScreenshot(); } /** * Starts a global timer with the given name. * * The name should contain only alphanumeric characters and spaces. * * Illegal characters shall be replaced by their ASCII hex value. * * WARNING: pre-4.3 agents threw an exception on illegal characters. * * @param name `string` The name of the timer. */ public static startTimer(name: string) { ADEumInstrumentation.startTimerWithName(name); } /** * Stops a global timer with the given name and reports it to the cloud. * * The name should contain only alphanumeric characters and spaces. * * Illegal characters shall be replaced by their ASCII hex value. * * WARNING: pre-4.3 agents threw an exception on illegal characters. * * @param name `string` The name of the timer. */ public static stopTimer(name: string) { ADEumInstrumentation.stopTimerWithName(name); } /** * Reports metric value for the given name. * * The name should contain only alphanumeric characters and spaces. * * Illegal characters shall be replaced by their ASCII hex value. * * WARNING: pre-4.3 agents threw an exception on illegal characters. * * @param option * * `name`: `string` - The name of the metric key. * * `value`: `number` - The value reported for the given key. */ public static reportMetric(option: { name: string; value: number }) { ADEumInstrumentation.reportMetricWithNameValue(option.name, option.value); } /** * Sets a key-value pair identifier that will be included in all snapshots. The identifier can be used to add any data you wish. * * The key must be unique across your application. The key namespace is distinct for each user data type. Re-using the same key overwrites the previous value. The key is limited to MAX_USER_DATA_STRING_LENGTH characters. * * A value of null will clear the data. * * This information is not persisted across application runs. Once the application is destroyed, the user data is cleared. * * @param option * * `key`: `string` - Your unique key. * * `value`: `boolean` - Your value, or null to clear this data. */ public static setUserData(option: { key: string; value: string }) { ADEumInstrumentation.setUserDataValue(option.key, option.value); } /** * Sets a key-value pair identifier that will be included in all snapshots. The identifier can be used to add any data you wish. * * The key must be unique across your application. The key namespace is distinct for each user data type. Re-using the same key overwrites the previous value. The key is limited to MAX_USER_DATA_STRING_LENGTH characters. * * A value of null will clear the data. * * This information is not persisted across application runs. Once the application is destroyed, the user data is cleared. * * @param option * * `key`: `string` - Your unique key. * * `value`: `boolean` - Your value, or null to clear this data. */ public static setUserDataLong(option: { key: string; value: number }) { ADEumInstrumentation.setUserDataLongValue(option.key, option.value); } /** * Sets a key-value pair identifier that will be included in all snapshots. The identifier can be used to add any data you wish. * * The key must be unique across your application. The key namespace is distinct for each user data type. Re-using the same key overwrites the previous value. The key is limited to MAX_USER_DATA_STRING_LENGTH characters. * * A value of null will clear the data. * * This information is not persisted across application runs. Once the application is destroyed, the user data is cleared. * * @param option * * `key`: `string` - Your unique key. * * `value`: `boolean` - Your value, or null to clear this data. */ public static setUserDataBoolean(option: { key: string; value: boolean }) { ADEumInstrumentation.setUserDataBooleanValue(option.key, option.value); } /** * Sets a key-value pair identifier that will be included in all snapshots. The identifier can be used to add any data you wish. * * The key must be unique across your application. The key namespace is distinct for each user data type. Re-using the same key overwrites the previous value. The key is limited to MAX_USER_DATA_STRING_LENGTH characters. * * A value of null will clear the data. * * The value has to be finite. Attempting to set infinite or NaN value, will clear the data. * * This information is not persisted across application runs. Once the application is destroyed, the user data is cleared. * * @param option * * `key`: `string` - Your unique key. * * `value`: `number` - Your value, or null to clear this data. */ public static setUserDataDouble(option: { key: string; value: number }) { ADEumInstrumentation.setUserDataDoubleValue(option.key, option.value); } /** * Sets a key-value pair identifier that will be included in all snapshots. The identifier can be used to add any data you wish. * * The key must be unique across your application. The key namespace is distinct for each user data type. Re-using the same key overwrites the previous value. The key is limited to MAX_USER_DATA_STRING_LENGTH characters. * * A value of `null` will clear the data. * * This information is not persisted across application runs. Once the application is destroyed, the user data is cleared. * * @param option * * `key`: `string` - Your unique key. * * `value`: `Date` - Your value, or null to clear this data. */ public static setUserDataDate(option: { key: string; value: Date }) { ADEumInstrumentation.setUserDataDateValue(option.key, option.value); } /** * Leaves a breadcrumb that will appear in a crash report and, optionally, session. * * Call this when something interesting happens in your application. * The breadcrumb will be included in different reports depending on the mode. * Each crash report displays the most recent 99 breadcrumbs. * * @param option * * `breadcrumb`: `string` - The string to include in the crash report and sessions. If it’s longer than 2048 characters, it will be truncated. If it’s empty, no breadcrumb will be recorded. * * `type?`: `string` `optional` - A mode from `AppDynamicsBreadcrumbVisibility`. If invalid, defaults to `AppDynamicsBreadcrumbVisibility.CRASHES_ONLY` */ public static leaveBreadcrumb(option: { description: string; mode?: AppDynamicsBreadcrumbVisibility }) { if (option.mode) { ADEumInstrumentation.leaveBreadcrumbMode(option.description, option.mode as number); } else { ADEumInstrumentation.leaveBreadcrumb(option.description); } } /** * Creates a crash report of the given crash dump. This crash report will be reported to collector when application restarts. * * @param option * * `crashDump`: `string` - Json string of the crash dump. * * `type`: `string` - crash report type. */ public static createCrashReport(option: { crashDump: string; type: string }) { ADEumInstrumentation.createCrashReportType(option.crashDump, option.type); } public static crashReportingEnabled(enabled: boolean, appKey: string) { const agentConfiguration = ADEumAgentConfiguration.alloc().initWithAppKey(appKey); agentConfiguration.crashReportingEnabled = enabled; ADEumInstrumentation.initWithConfiguration(agentConfiguration); } /** * Reports an error that was caught. * This can be called in catch blocks to report interesting errors that you want to track. * @param option * * `message`: `string` - error message or description. * * `severity`: `AppDynamicsErrorSeverityLevel` - Valid severity levels * * `stacktrace?`: `AppDynamicsErrorSeverityLevel` `optional` - allow stacktrace * `AppDynamicsErrorSeverityLevel.INFO`, * `AppDynamicsErrorSeverityLevel.WARNING`, * `AppDynamicsErrorSeverityLevel.CRITICAL` */ public static reportError(option: { message: string; severity: AppDynamicsErrorSeverityLevel; stacktrace?: boolean }) { const appID = NSBundle.mainBundle.infoDictionary.objectForKey('CFBundleIdentifier'); const domain = appID + '.ReportCrash.ErrorDomain'; const userInfo: NSDictionary<any, any> = NSMutableDictionary.alloc().init(); userInfo.setValueForKey(option.message, 'NSLocalizedDescriptionKey'); const error = NSError.errorWithDomainCodeUserInfo(domain, -101, userInfo); ADEumInstrumentation.reportErrorWithSeverityAndStackTrace(error, option.severity as number, option.stacktrace || false); } /** * Manually tracks a UI event. * * @param option * * * `activity` - The name of the parent page / fragment / screen. * * * `eventName` - The name of the event, of the action(e.g. “Button Pressed”, “Text View Unfocused”, “Table Cell Selected”) * * * `uiClass` - Class name(e.g.Xamarin.Forms.Button, MyNamespace.MyButton) * * * `startTimeEpochMills` - The time of the vent as unix time(milliseconds) * * * `label` - `Optional` The label’s value. * * * `accessibilityLabel` - `Optional` The accessibility value(e.g.button.accessibility) * * * `uiTag` - `Optional` UI Element tag’s value. (e.g.button.tag) * * * `index` - `Optional` Comma separated list of table view item indexes.Used for Table View Selection. * * * `uiResponder` - `Optional` Method name for the handler. */ public static trackUIEvent(option: { activity: string; eventName: string; uiClass: string; startTimeEpochMills: number | Date; label?: string; accessibilityLabel?: string; uiTag?: number; index?: string; uiResponder?: string }) { ADEumInstrumentation.TrackUIEventNameClassStartTimeLabelAccessibilityTagIndexUiResponder(option.activity, option.eventName, option.uiClass, option.startTimeEpochMills as Date, option.label, option.accessibilityLabel, option.uiTag, option.index, option.uiResponder); } } @NativeClass class ADEumCrashReportImpl extends NSObject implements ADEumCrashReportCallback { private static callback: IAppDynamicsCrashCallback; public static ObjCProtocols = [ADEumCrashReportCallback]; public static setCallback(callback: IAppDynamicsCrashCallback): ADEumCrashReportImpl { this.callback = callback; return <ADEumCrashReportImpl>super.new(); } public onCrashesReported(summaries: NSArray<ADEumCrashReportSummary> | ADEumCrashReportSummary[]) { ADEumCrashReportImpl.callback(summaries as IAppDynamicsCrashReportSummary[]); } }
document.addEventListener('DOMContentLoaded', function() { const screens = document.querySelectorAll('.screen'); const loginButton = document.getElementById('loginButton'); const registerButton = document.getElementById('registerButton'); const enterButton = document.getElementById('enterbutton'); const backToresultButton = document.querySelectorAll('#backToresultButton'); const backToLoginButton = document.getElementById('backToLoginButton'); const backToRegisterButton = document.getElementById('backToRegisterButton'); const captureButton = document.getElementById('captureButton'); const cropButton = document.getElementById('cropButton'); const restartButton = document.getElementById('restartButton'); const historyButton = document.getElementById('historybutton'); const uploadButton = document.getElementById('uploadButton'); const uploadInput = document.getElementById('uploadInput'); const backToWelcomeButtont = document.getElementById('backToWelcomeButton'); const logoutButton = document.getElementById('logoutButton'); const diseaseInfoButton = document.getElementById('diseaseInfoButton'); let cropper; const showScreen = (screenId) => { screens.forEach(screen => screen.classList.remove('active')); document.getElementById(screenId).classList.add('active'); }; loginButton.addEventListener('click', () => showScreen('loginScreen')); backToWelcomeButtont.addEventListener('click', () => showScreen('welcomeScreen')); registerButton.addEventListener('click', () => showScreen('registerScreen')); backToLoginButton.addEventListener('click', () => showScreen('loginScreen')); backToRegisterButton.addEventListener('click', () => showScreen('registerScreen')); diseaseInfoButton.addEventListener('click', () => showScreen('diseaseInfoScreen')); backToresultButton.forEach(button => button.addEventListener('click', () => showScreen('resultScreen'))); restartButton.addEventListener('click', () => { showScreen('captureScreen'); openCamera(); }); backToresultButton.forEach(button => button.addEventListener('click', () => showScreen('resultScreen'))); logoutButton.addEventListener('click', () => { sessionStorage.removeItem('username'); showScreen('welcomeScreen'); }); captureButton.addEventListener('click', captureImage); cropButton.addEventListener('click', cropAndUploadImage); uploadButton.addEventListener('click', () => uploadInput.click()); uploadInput.addEventListener('change', uploadImage); historyButton.addEventListener('click', fetchHistory); // Login form submission document.getElementById('loginForm').addEventListener('submit', (event) => { event.preventDefault(); const username = document.getElementById('loginUsername').value; const password = document.getElementById('loginPassword').value; loginUser(username, password); }); // Register form submission document.getElementById('registerForm').addEventListener('submit', (event) => { event.preventDefault(); const username = document.getElementById('registerUsername').value; const password = document.getElementById('registerPassword').value; registerUser(username, password); }); function openCamera() { navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } }) .then(function(stream) { const video = document.getElementById('video'); video.srcObject = stream; video.play(); video.style.display = 'block'; captureButton.style.display = 'block'; }) .catch(function(error) { console.error("獲取攝像頭失敗", error); }); } function captureImage() { const video = document.getElementById('video'); if (video && video.srcObject) { const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); video.srcObject.getTracks().forEach(track => track.stop()); video.style.display = 'none'; const imageDataUrl = canvas.toDataURL('image/png'); initializeCropper(imageDataUrl); } else { console.error("無法訪問攝像頭"); } } function uploadImage(event) { const file = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = function(e) { initializeCropper(e.target.result); } reader.readAsDataURL(file); } } function initializeCropper(imageDataUrl) { const preview = document.getElementById('preview'); preview.src = imageDataUrl; preview.style.display = 'block'; if (cropper) { cropper.destroy(); } cropper = new Cropper(preview, { aspectRatio: 1, viewMode: 1, }); showScreen('cropScreen'); document.getElementById('cropContainer').style.display = 'block'; cropButton.style.display = 'block'; } function cropAndUploadImage() { cropper.getCroppedCanvas().toBlob(function(blob) { const formData = new FormData(); formData.append('image', blob, 'croppedImage.png'); showProgress(); fetch('/upload', { method: 'POST', body: formData, }) .then(response => response.json()) .then(data => { showResult({ status: data.status, disease: data.disease, confidence: data.confidence + '%', imageSrc: URL.createObjectURL(blob) }); }) .catch(error => { console.error("Error uploading image:", error); }); }); } function showProgress() { const progressContainer = document.getElementById('progressContainer'); progressContainer.style.display = 'block'; let progress = 0; const interval = setInterval(() => { progress += 10; if (progress >= 100) { clearInterval(interval); progressContainer.style.display = 'none'; } }, 300); } function navigateToDiseaseInfo(disease) { window.location.href = `/disease/${disease}`; } function showResult(data) { showScreen('resultScreen'); const croppedImageElement = document.getElementById('croppedImage'); croppedImageElement.src = data.imageSrc; const analysisResultElement = document.getElementById('analysisResult'); analysisResultElement.innerHTML = ` <p>診斷結果</p> <div class="result-conclusion">${data.disease} 概率 ${data.confidence}</div> `; analysisResultElement.style.display = 'flex'; const diseaseInfoButton = document.getElementById('diseaseInfoButton'); diseaseInfoButton.style.display = 'block'; diseaseInfoButton.onclick = function() { navigateToDiseaseInfo(data.disease); }; restartButton.style.display = 'block'; } function fetchHistory() { const username = sessionStorage.getItem('username'); if (username) { document.getElementById('usernameDisplay').innerText = `${username}`; fetch(`/history?username=${username}`) .then(response => response.json()) .then(data => { const historyDiv = document.getElementById('history'); historyDiv.innerHTML = ''; data.history.forEach(entry => { const entryDiv = document.createElement('div'); entryDiv.classList.add('history-entry'); const photoImg = new Image(); photoImg.src = 'data:image/jpeg;base64,' + entry.photo; photoImg.classList.add('history-photo'); entryDiv.appendChild(photoImg); const infoDiv = document.createElement('div'); infoDiv.classList.add('history-info'); infoDiv.innerHTML = `Upload Time: ${entry.upload_time} <br> Diagnosis: ${entry.diagnosis}`; entryDiv.appendChild(infoDiv); historyDiv.appendChild(entryDiv); }); showScreen('historyScreen'); }) .catch(error => console.error('Error:', error)); } else { console.error('No username found in session storage.'); } } function loginUser(username, password) { fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) .then(response => response.json()) .then(data => { if (data.message === '登入成功') { sessionStorage.setItem('username', username); showScreen('captureScreen'); openCamera(); } else { alert('登入失敗'); } }); } function registerUser(username, password) { fetch('/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) .then(response => response.json()) .then(data => { if (data.message === '註冊成功') { showScreen('loginScreen'); } else { alert('註冊失敗'); } }); } });
#' **Figure 1B: genome coverage of ncba1.0 and gaps.** suppressPackageStartupMessages(library(tidyverse)) suppressPackageStartupMessages(library(magrittr)) #suppressPackageStartupMessages(library(GenomicRanges)) #suppressPackageStartupMessages(library(karyoploteR)) setwd('~/share/litt/proj/cow/results/') knitr::opts_knit$set(root.dir = '~/share/litt/proj/cow/results/') #' ## genome length: new.genomeLen <- read_csv('./metadata/NewAssembly//assembly_chrLength.csv') %>% filter(!grepl('Scaffold', seqname)) %>% suppressMessages() new.genomeLen$accum.len <- c(1, sapply(1:29, function(x){sum(new.genomeLen$length[1:x])})) new.genomeLen bos9.genomeLen <- read_delim('./metadata/ARS.UCD1.2/bosTau9.chrom.sizes.clean.txt', delim = '\t', col_names = c( 'seqname','length'))%>% suppressMessages() bos9.genomeLen$accum.len <- c(1, sapply(1:29, function(x){sum(bos9.genomeLen$length[1:x])})) bos9.genomeLen #' ## gap loci of the new assembly and bostau9 assembly.gaploci <- read_csv('./metadata/NewAssembly//cowNewAssembly_N_gap_locations.csv') %>% select(any_of(c('seqnames', 'start'))) %>% filter(!grepl('Scaffold', seqnames)) %>% suppressMessages() assembly.gaploci bos9.gaploci <- read_csv('./metadata/ARS.UCD1.2/ARS_UCD1.2_N_gap_locations.csv') %>% select(any_of(c('seqnames', 'start'))) %>% filter(!grepl('chrUn_', seqnames)) %>% suppressMessages() bos9.gaploci #' adjust the bostau9 loci according to the new assembly. bos9.gaploci$adj.start <- sapply(1:length(bos9.gaploci$start), function(x){ chrname = bos9.gaploci$seqnames[x] return(bos9.gaploci$start[x] * (new.genomeLen$length[new.genomeLen$seqname ==chrname] / bos9.genomeLen$length[bos9.genomeLen$seqname == chrname]) ) }) assembly.gaploci$accum.loci <- sapply(1:dim(assembly.gaploci)[1], function(x){ return(assembly.gaploci$start[x] + new.genomeLen$accum.len[new.genomeLen$seqname == assembly.gaploci$seqnames[x]]) }) bos9.gaploci$accum.loci <- sapply(1:dim(bos9.gaploci)[1], function(x){ return(bos9.gaploci$start[x] + bos9.genomeLen$accum.len[bos9.genomeLen$seqname == bos9.gaploci$seqnames[x]]) }) bos9.gaploci$accum.adj.loci <- sapply(1:dim(bos9.gaploci)[1], function(x){ return(bos9.gaploci$adj.start[x] + new.genomeLen$accum.len[new.genomeLen$seqname == bos9.gaploci$seqnames[x]]) }) #' ## genome coverage info assembly_cov_50k <- read_csv('./metadata/depthCovGCcontent/mosdepth/assembly/cow_assembly_coverage_50kb_q10.csv') %>% suppressMessages() assembly_cov_50k #' ## visualiztion. #layout(matrix(1)) #+ fig.width=18, fig.height=3, fig.align = 'center' layout(matrix(c(1,1,2,2,3,3,4,4,4), nrow =9, byrow = T)) par(mar =c(1,4,1,2), oma = c(1,2,1,1)) plot(x=0,xlim=c(0,dim(assembly_cov_50k)[1]),ylim=c(0,300), type = 'n', axes =F, xlab = "", ylab = '') rect(1:dim(assembly_cov_50k)[1], 0.1, (1:dim(assembly_cov_50k)[1]) +1, assembly_cov_50k$ont_50kb_cov, lwd=1, col = '#FFCCCC', border = '#FFCCCC') axis(2, at = c(0,300), line = -3) #plot.new() plot(x=0,xlim=c(0,dim(assembly_cov_50k)[1]),ylim=c(0,50), type = 'n', axes =F, xlab = "", ylab = '') rect(1:dim(assembly_cov_50k)[1], 0.1, (1:dim(assembly_cov_50k)[1]) +1, assembly_cov_50k$ccs_50kb_cov, lwd=1, col = '#00CCCC', border = '#00CCCC') axis(2, at = c(0,50), line = -3) plot(x=0,xlim=c(0,dim(assembly_cov_50k)[1]),ylim=c(0,200), type = 'n', axes =F, xlab = "", ylab = '') rect(1:dim(assembly_cov_50k)[1], 0.1, (1:dim(assembly_cov_50k)[1]) +1, assembly_cov_50k$ngs_50kb_csv, lwd=1, col = '#009966', border = '#009966') axis(2, at = c(0,200), line = -3) plot(x=0,xlim=c(0,sum(new.genomeLen$length)),ylim=c(0, 0.8), type = 'n', axes =F, xlab = "", ylab = '') axis(1, at = c(new.genomeLen$accum.len, sum(new.genomeLen$length)),labels = F, cex=2,2) rect(bos9.gaploci$accum.adj.loci, 0.1, bos9.gaploci$accum.adj.loci +1, 0.4, lwd=1) rect(assembly.gaploci$accum.loci, 0.5, assembly.gaploci$accum.loci +1, 0.8, lwd=1) layout(matrix(1))
import * as React from "react"; import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import AppBar from "@mui/material/AppBar"; import Typography from "@mui/material/Typography"; import MenuItem from "@mui/material/MenuItem"; import Menu from "@mui/material/Menu"; import YardIcon from "@mui/icons-material/Yard"; import { Button, Toolbar } from "@mui/material"; import { mainMenuHeight, pageName, settingsPath, viewPages, } from "../../utils/data"; import LanguageSelector from "./LanguageSelector"; const MainMenu = () => { const [subMenu, setSubMenu] = React.useState(null); const navigate = useNavigate(); const { t } = useTranslation(); //#region Methods const handleOpenSubMenu = (event) => { setSubMenu(event.currentTarget); }; const handleCloseSubMenu = () => { setSubMenu(null); }; const navigateViewAction = (path) => { handleCloseSubMenu(); navigate(path); }; const navigateAction = (path) => { navigate(path); }; //#endregion return ( <AppBar sx={{ height: `${mainMenuHeight}px` }} position="static" color="darkGreen" > <Toolbar variant="dense"> <YardIcon size="large" edge="start" sx={{ mr: 1 }} /> <Typography variant="pageTitle" component="div" sx={{ flexGrow: 1 }}> {pageName} </Typography> <div> <Button color="inherit" onClick={handleOpenSubMenu} sx={{ marginRight: 5 }} > <Typography variant="menuItem">{t("menu.views")}</Typography> </Button> <Menu id="menu-appbar" anchorEl={subMenu} anchorOrigin={{ vertical: "bottom", horizontal: "center", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "center", }} open={Boolean(subMenu)} onClose={handleCloseSubMenu} > {viewPages.map((page) => ( <MenuItem key={`menu-view-item-${page.pageKey}`} onClick={() => { navigateViewAction(page.pagePath); }} > <Typography key={`menu-view-item-name-${page.pageKey}`} variant="menuItem" > {t(page.pageName)} </Typography> </MenuItem> ))} </Menu> </div> <Button sx={{ marginRight: 1 }} color="inherit" onClick={() => navigateAction(settingsPath)} > <Typography variant="menuItem">{t("menu.settings")}</Typography> </Button> <LanguageSelector /> </Toolbar> </AppBar> ); }; export default MainMenu;
import { ChatInputCommandInteraction, EmbedBuilder } from 'discord.js'; import Command from '../../lib/structures/Command'; import LanguageFile from '../../lib/structures/interfaces/LanguageFile'; export default new Command({ name: 'help', description: 'The help command', category: 'information', async execute(client, interaction, guildConf) { let { util } = (await import(`../../lib/utils/lang/${guildConf.lang}`)) as LanguageFile; if ((interaction as ChatInputCommandInteraction).options.getString('command')) { let commandName = (interaction as ChatInputCommandInteraction).options.getString('command')!; let command = client.commands.get(commandName) || client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName)); if (!command) return interaction.reply({ embeds: [client.redEmbed(util.command.not_found)], ephemeral: true }); let embed = new EmbedBuilder() .setColor('Random') .setTitle(`${util.command.title} ${command.name}`) .setDescription(command.description) .addFields( { name: util.command.fields.required_perms, value: command.required_perms.join(', ') || 'No', inline: true }, { name: util.command.fields.required_roles, value: command.required_roles.join(', ') || 'No', inline: true }, { name: util.command.fields.alias, value: command.aliases.join(', ') || 'No', inline: true }, { name: util.command.fields.usage, value: `${command.name} ${command.required_args.map((a) => (a.optional ? `[${a.name}]` : `<${a.name}>`)).join(' ')}`, inline: false } ) .setFooter({ text: util.command.footer }); return interaction.reply({ embeds: [embed] }); } let prefix = guildConf.prefix; let commands = { info: client.commands.filter((cmd) => cmd.category == 'information'), util: client.commands.filter((cmd) => cmd.category == 'utility'), image_manipulation: client.commands.filter((cmd) => cmd.category == 'image_manipulation'), social: client.commands.filter((cmd) => cmd.category == 'social'), music: client.commands.filter((cmd) => cmd.category == 'music'), fun: client.commands.filter((cmd) => cmd.category == 'fun'), mod: client.commands.filter((cmd) => cmd.category == 'moderation'), config: client.commands.filter((cmd) => cmd.category == 'configuration') }; let help_embed = new EmbedBuilder(); help_embed.setTitle(util.help.title); help_embed.setDescription(util.help.description.replace('{prefix}', prefix)); help_embed.setColor(`Random`); help_embed.setThumbnail(`https://i.imgur.com/t3UesbC.png`); help_embed.setURL('https://trihammerdocs.gitbook.io/trihammer/'); Object.keys(commands).forEach((key) => { let k = key as 'info' | 'util' | 'image_manipulation' | 'social' | 'music' | 'fun' | 'mod' | 'config'; let cmds = commands[k]; help_embed.addFields({ name: `${util.help.fields[k]} - (${cmds.size})`, value: cmds.map((cmd) => `\`${cmd.name}\``).join(', ') || 'No', inline: true }); }); help_embed.setFooter({ text: client.commands.size + util.help.footer }); interaction.reply({ embeds: [help_embed] }); } });
export function reducer(state, { type, payload }) { switch (type) { case "GET_ITEMS": return{ ...state, items: payload || [], loading: false, } case "ADD_TO_BASKET":{ const itemIndex = state.order.findIndex( (orderItem) => orderItem.mainId === payload.mainId ); let newOrder = null; if (itemIndex < 0) { const newItem = { ...payload, quantity: 1, }; newOrder = [...state.order, newItem]; } else { newOrder = state.order.map((orderItem, index) => { if (index === itemIndex) { return { ...orderItem, quantity: orderItem.quantity + 1, }; } else { return orderItem; } }); } return { ...state, order: newOrder, alertName: payload.displayName, }; } case "REMOVE_FROM_BASKET": return { ...state, order: state.order.filter((el) => el.mainId !== payload.id), }; case "INCREMENT_QUANTITY": return { ...state, order: state.order.map((el) => { if (el.mainId === payload.id) { const newQuantity = el.quantity + 1; return { ...el, quantity: newQuantity, }; } else { return el; } }), }; case "DECREMENT_QUANTITY": return { ...state, order: state.order.map((el) => { if (el.mainId === payload.id) { const newQuantity = el.quantity - 1; return { ...el, quantity: newQuantity >= 1 ? newQuantity : 1, }; } else { return el; } }), }; case "BASKET_TOGGLE_SHOW": return { ...state, isBasketShow: !state.isBasketShow, }; case "CLOSE_ALLERT": return { ...state, alertName: "", }; default: return state; } }
<?php $host = 'localhost'; $dbname = 'comp-1006-lesson-examples'; $username = 'root'; $password = ''; // connect to the DB $dbh = new PDO( "mysql:host={$host};dbname={$dbname}", $username, $password ); $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); // build the SQL statment $sql = 'SELECT * FROM artists'; // prepare, execute, and fetchAll $artists = $dbh->query( $sql ); // count the rows $row_count = $artists->rowCount(); // close the DB connection $dbh = null; ?> <!DOCTYPE html> <html> <head> <link crossorigin='anonymous' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' integrity='sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7' rel='stylesheet'> <link crossorigin='anonymous' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css' integrity='sha384-aNUYGqSUL9wG/vP7+cWZ5QOM4gsQou3sBfWRr/8S3R1Lv0rysEmnwsRKMbhiQX/O' rel='stylesheet'> <title>All Artists</title> </head> <body> <div class='container'> <header> <h3 class='page-header'>All Artists</h3> </header> <section> <?php if ( $row_count > 0 ): ?> <table class='table'> <thead> <tr> <th>Artist</th> <th>Bio</th> <th>Actions</th> <th>Delete</th> </tr> </thead> <tbody> <?php foreach ( $artists as $artist ): ?> <tr> <td><a href="artist_songs.php?id=<?= $artist['id'] ?>"><?= strip_tags($artist['name']) ?></a></td> <td><a href="<?= htmlspecialchars( $artist['bio_link'] ) ?>"><?= strip_tags($artist['bio_link']) ?></a></td> <td><a href="#"><i class="fa fa-pencil"></i></a></td> <td> <form action="delete_artists.php" method="post"> <input type="hidden" name="id" value="<?= $artist['id'] ?>"> <button type="submit" style="border:0; background:none; padding:0; margin:0; color:#337ab7;" onclick="return confirm('Are you sure you want to delete this?')"><i class="fa fa-remove"></i></button> </form> </td> </tr> <?php endforeach ?> </tbody> </table> <?php else: ?> <div class="alert alert-warning"> No song information to display. </div> <?php endif ?> </section> </div> </body> </html>
<?php get_header(); /* Template Name: Popular Page */ ?> <div class="post-title col-xs-12"> <h2>Popular Posts</h2> <div class="separator"></div> </div><!-- post-title --> <ul class="feat-post clear"> <?php $pop_all = new WP_Query(array( 'post_type' => array( 'post', 'food', 'style', 'crafts' ), 'posts_per_page' => -1, )); while ($pop_all->have_posts()) : $pop_all->the_post(); ?> <li class="col-xs-12 col-sm-6 col-md-4 col-lg-4"> <div class="feat-image ease-in-out"> <a href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>"> <?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. the_post_thumbnail('large', array( 'class' => 'img-responsive' )); } ?> <div class="caption-overlay hidden-xs ease-in-out"> <p><span class="pink"><?php if( get_post_type() == 'food' ){ echo 'FOOD'; } elseif( get_post_type() == 'style' ){ echo 'STYLE'; } elseif( get_post_type() == 'crafts' ){ echo 'CRAFTS'; } ?></span></p> </div><!-- caption-overlay --> </a> </div><!-- feat-image --> <div class="caption"> <h3 class="pull-left"><a href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>"><?php the_title(); ?></a></h3> <p class="clear"><?php the_excerpt(); ?></p> </div><!-- caption --> </li> <?php endwhile; ?> </ul> <?php get_footer(); ?>