text
stringlengths
184
4.48M
import 'package:battery_service_app/admin_homescreen/admin_homescreen/admin_update/admin_taskdetails.dart'; import 'package:battery_service_app/employee_homescreen/employeee_taskdetailspage.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class AdminTaskUpdate extends StatefulWidget { const AdminTaskUpdate({super.key}); @override State<AdminTaskUpdate> createState() => _AdminTaskUpdateState(); } class _AdminTaskUpdateState extends State<AdminTaskUpdate> { final FirebaseAuth _auth = FirebaseAuth.instance; final CollectionReference tasksCollection = FirebaseFirestore.instance.collection('Task'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.red[300], title: Text( "Employee", style: TextStyle(fontSize: 26, color: Colors.white), ), centerTitle: true, ), body: StreamBuilder<QuerySnapshot>( stream: tasksCollection.snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { return Center(child: Text('Error: ${snapshot.error}')); } else if (!snapshot.hasData || snapshot.data!.docs.isEmpty) { return Center(child: Text('No tasks found.')); } else { return ListView( children: snapshot.data!.docs.map((document) { Map<String, dynamic> data = document.data() as Map<String, dynamic>; return TaskCard(data: data, documentId: document.id); }).toList(), ); } }, ), ); } } class TaskCard extends StatefulWidget { final Map<String, dynamic> data; final String documentId; TaskCard({required this.data, required this.documentId}); @override State<TaskCard> createState() => _TaskCardState(); } class _TaskCardState extends State<TaskCard> { @override Widget build(BuildContext context) { final status = widget.data['status']; // Determine the background color based on the status Color tileColor = status == 'Done' ? Colors.green : Colors.white; return Card( elevation: 3, margin: EdgeInsets.all(10), color: tileColor, // Set the background color here child: InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => AdminTaskDetailsPage( data: widget.data, documentId: widget.documentId, context: context, ), ), ); }, child: ListTile( title: Text(widget.data['buyer_name']), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Address: ${widget.data['address']}'), Text('Area: ${widget.data['area']}'), Text('Phone: ${widget.data['phone_no']}'), ], ), ), ), ); } }
import React from "react"; import { convertDate } from "../../../../Common/function"; import StarRating from "../../product/starRating/StarRating"; import "../../styles/homePage.scss"; const CommentDetail = ({ image, name, detail, rating, commentDate }) => { const editImageFrame = "https://i0.wp.com/digitalhealthskills.com/wp-content/uploads/2022/11/3da39-no-user-image-icon-27.png?fit=500%2C500&ssl=1"; return ( <div className="comment-detail"> <div className="comment-detail-image"> {image === "" || image === null ? ( <img src={editImageFrame} alt={name} /> ) : ( <img src={image} alt={name} /> )} </div> <div className="comment-detail-info"> <b>{name}</b> <div className="comment-detail-middle"> <b>Ngày bình luận:</b> {convertDate(commentDate)} <StarRating rating={rating} /> </div> <p>{detail}</p> </div> </div> ); }; export default CommentDetail;
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService } from 'src/app/servicios/auth.service'; import Swal from 'sweetalert2'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'], }) export class RegisterComponent implements OnInit { form!: FormGroup; errorCheck: boolean = false; Message: string = ''; constructor(private authService: AuthService, private router: Router) {} ngOnInit(): void { this.form = new FormGroup({ nick: new FormControl('', [ Validators.required, Validators.maxLength(30), ]), email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ Validators.required, Validators.minLength(6), ]), }); } onSubmit() { if (this.form.valid) { console.log(this.form); this.authService .register(this.form.value) .then(() => { Swal.fire({ icon: 'success', title: 'Registro exitoso', text: '¡Bienvenido!', showConfirmButton: false, timer: 1500, }).then(() => { this.router.navigate(['/home']); }); }) .catch((error) => { this.errorCheck = true; console.log(error.code); switch (error.code) { case 'auth/email-already-in-use': this.Message = 'Ya se encuentra un usuario registrado con ese email'; break; default: this.Message = 'Hubo un problema al registrar.'; break; } Swal.fire({ icon: 'error', title: 'Error al registrar', text: this.Message, timer: 4000, }); }); } else { Swal.fire({ icon: 'error', title: 'Complete los datos para registrar', text: 'Complete TODOS los datos requeridos.', timer: 4000, }); } } goToLogin(): void { this.router.navigate(['/login']); } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import backIcon from 'assets/images/back.svg'; import ToolTip from 'components/common/ToolTip'; import './index.scss'; import Breadcrumb from 'components/common/Breadcrumb'; import clockIcon from 'assets/images/time-icon.svg'; import iconTeamMember from 'assets/images/team-icon.svg'; const isEllipsisEnabled = () => window.screen.width <= 460; const PageHeading = ({ isBackButton, handleBackClick, isSecondary, isSticky, title, subTitle, children, iconReq, src, altText, imgOnClick, subtitleClassname, breadCrumbsData, teamIcon, getTeamInfo, isDateTime, }) => { return ( <> {breadCrumbsData && <Breadcrumb {...breadCrumbsData} />} <div className={`page-heading-section ${isSecondary ? 'secondary' : ''} ${isSticky ? 'sticky' : '' }`} > <div className="page-heading"> {isBackButton && ( <span className="back" onClick={handleBackClick}> <img src={backIcon} /> </span> )} {title && ( <h4 className="" data-testid="page-heading-test"> <span title={title}>{title}</span> </h4> )} {subTitle && isDateTime ? ( <> <img src={clockIcon} alt="subTitle" data-for={'clock'} data-tip={subTitle} /> <ToolTip id={'clock'} delayHide={200} className={'tooltip-text'} /> </> ) : ( <h6> <span className="ellipsis">{subTitle}</span> </h6> )} {/* {isEllipsisEnabled && ( <ToolTip id="mobile-title" className={'tooltip-text'} delayHide={200} /> )} */} {iconReq && <img src={src} alt={altText} onClick={imgOnClick} />} {teamIcon && <div className="team-icon"> <img src={iconTeamMember} onClick={() => getTeamInfo()} alt="Team Members" /> </div>} </div> <div className="page-heading-actions">{children}</div> </div> </> ); }; PageHeading.propTypes = { title: PropTypes.string.isRequired, }; export default PageHeading;
// sassの特徴 //・ネストできる(cssの定義の中にcssを書くことができる) //・変数が使える(例えばサイト内のテーマカラーを変数定義しておけば、後から変更になっても変数の内容を書き換えれば一括で変更できる) //・@import(ビルドする際、別のcssをひとまとめにしてくれる) // @extend(スタイルの拡張する機能、例えば.titleと.title-lgの2つのクラスがあり.title-lgはtitleのスタイルを継承して、フォントサイズだけ独自のサイズにしたい場合に使用) // @mixinはjsでいう関数のようなもの // @importでfooterとmenuのスタイルが書かれているcssを読み込む //@importする.scssのファイル名は_(アンダースコア)がついているがimportする際は省略可能 @import "./menu.scss"; @import "./footer.scss"; html, body, div, p, h1, h2, h3, h4, h5 { box-sizing: border-box; } body { margin: 0; padding: 0; font-size: 16px; font-family: sans-serif; } h1 { font-size: 2em; } .container { width: 980px; max-width: 100%; margin: 0 auto; padding: 0.5em; } .main-image { background-image: url("../images/thumbnail.jpg"); background-repeat: no-repeat; background-size: cover; background-position: center; position: relative; width: 100%; height: 600px; border-radius: 2em; margin: 1em 0; } $icon-size: 64px; .icon { width: $icon-size; height: $icon-size; border-radius: $icon-size / 2; padding: 4px; position: absolute; top: 1em; left: 1em; }
import '../../data/mapper/base/base_data_mapper.dart'; import '../../data/model/unit_response/unit_response.dart'; import '../entity/okr/unit/unit.dart'; class UnitDataMapper extends BaseDataMapper<UnitResponse, Unit> with DataMapperMixin { @override Unit mapToEntity(UnitResponse? data) { return Unit( id: data?.id, name: data?.name, parentId: data?.parentId, description: data?.description, coverImage: data?.coverImage, totalMemberCount: data?.totalMemberCount, subUnit: data?.subUnit, okRsId: data?.okRsId, tenantId: data?.tenantId, startDate: data?.startDate, endDate: data?.endDate, totalTask: data?.totalTask, taskDone: data?.taskDone, owner: data?.owner, // status: data?.status, createdBy: data?.createdBy, createdDate: data?.createdDate); } @override UnitResponse mapToData(Unit entity) { return UnitResponse( id: entity.id, name: entity.name, parentId: entity.parentId, description: entity.description, coverImage: entity.coverImage, totalMemberCount: entity.totalMemberCount, subUnit: entity.subUnit, okRsId: entity.okRsId, tenantId: entity.tenantId, startDate: entity.startDate, endDate: entity.endDate, totalTask: entity.totalTask, taskDone: entity.taskDone, owner: entity.owner, // status: entity.status, ); } }
import React from "react"; import { DialogContent, DialogOverlay } from "@reach/dialog"; import { handleDeleteCourse } from "../../../Redux/Actions/courses"; import { useDispatch } from "react-redux"; const DeleteCourseDialog = ({ showDialog, closeDialog, course }) => { const dispatch = useDispatch(); return ( <DialogOverlay isOpen={showDialog} onDismiss={closeDialog} style={{ background: "hsla(0,100%,100%,0.9)" }} > <DialogContent style={{ border: "solid 5px hsla(0,0%,0%,0.5)", borderRadius: "10px", boxShadow: "0px 10px 50px hsla(0,0%,0%,0.33)", }} > <div className="text-center"> <h4>حذف دوره {course.title}</h4> <hr /> <p>آیا از حذف دوره {course.title} اطمینان دارید؟</p> </div> <div> <button className="btn btn-danger pad2" style={{ margin: "1em" }} onClick={() => dispatch(handleDeleteCourse(course._id)) && closeDialog() } > مطمئن هستم </button> <button className="btn btn-warning pad2" style={{ margin: "1em" }} onClick={closeDialog} > انصراف </button> </div> </DialogContent> </DialogOverlay> ); }; export default DeleteCourseDialog;
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import Login from '../login/Login' import CreateQuiz from '../quiz/CreateQuiz' import Drawer from '../containers/Drawer' import { addQuizForm, submitQuiz, fetchQuiz} from './actions' class QuizContainer extends Component { constructor (props){ super(props); this.handleClick = this.handleClick.bind(this); this.handleSubmission = this.handleSubmission.bind(this); } handleClick (){ this.props.actions.addQuizForm(); } handleSubmission (){ console.log(this.refs.title.value,this.props.quiz.quizzes); this.props.actions.submitQuiz(this.refs.title.value,this.props.quiz.quizzes); } render() { var quizForms = []; for (var i = 0; i < this.props.quiz.questionForms; i++){ quizForms.push(<CreateQuiz handleSubmission={this.handleSubmission} key={i} id={i} />); } return ( <div> <span><h1>Create a new quiz.</h1></span> <span>Quiz title:</span> <input type="text" ref="title"></input> <button onClick={this.handleSubmission}> Create Quiz</button> {quizForms} <div onClick={this.handleClick}>[ + + + + +]</div> </div> ); }; } function mapStateToProps(state){ return { user: state.user, quiz: state.quiz, storedQuizzes: state.storedQuizzes } } function mapDispatchToProps(dispatch){ return { actions: bindActionCreators({ addQuizForm, submitQuiz, fetchQuiz },dispatch) } } export default connect(mapStateToProps,mapDispatchToProps)(QuizContainer);
<!-- - - This file is part of the OpenLink Software Virtuoso Open-Source (VOS) - project. - - Copyright (C) 1998-2013 OpenLink Software - - This project is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License as published by the - Free Software Foundation; only version 2 of the License, dated June 1991. - - This program is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - --> <?xml version="1.0" encoding="ISO-8859-1"?> <chapter label="III" id="chapter3"> <title>Virtual Database Concepts</title> <abstract> This document describes the SQL extensions, system tables and functions related to the Virtuoso Universe virtual database. </abstract> <sect1 id="TRANSMODEL"> <title>Transaction Model</title> <para> One transaction on the Virtuoso Universe server may contain operations on multiple remote data sources. As a general rule remote connections are in manual commit mode and Virtuoso wither commits or rolls back the transaction on each of the remote connections as the main transaction terminates. </para> <para> ODBC does not support two phase commit. Therefore a transaction that succeeds on one remote party may fail on another. </para> <para> A transaction involving local tables and tables on one remote data source will always complete correctly since the remote is committed before the local and the local is rolled back if the remote commit fails. </para> <para> Note that even though the client to Virtuoso connection may be in autocommit mode the continuing connections will typically not be autocommitting. </para> <para> A remote connection is in autocommit mode if the Virtuoso connection is and the statement is passed through unmodified. In all other cases remote connections are in manual commit mode. </para> </sect1> <sect1 id="STOREDPROCS"> <title>Stored Procedures</title> <sect2 id="vd_remote_data_source"> <title>DB.DBA.vd_remote_data_source</title> <programlisting>B.DBA.vd_remote_data_source ( in dsn varchar, in connstr varchar, in user varchar, in password varchar);</programlisting> <para> A remote data source is uniquely identified by its DSN, the dsn argument to this function. The connstr argument is presently ignored. The user and password are the login name and password to use when communicating with the remote data source. All Virtuoso users dealing with the remote data source will appear as this user to the remote data source. Virtuoso will make as many connections as there are concurrent users of the data source. Connections are cached by Virtuoso. </para><para> The default qualifier of the user of the remote data source is usually not relevant. </para><para> Remote table names should be fully qualified. </para> </sect2> <sect2 id="DB.DBA.vd_remote_table"> <title>DB.DBA.vd_remote_table</title> <programlisting>vd_remote_table ( in dsn varchar, in local_name varchar, in remote_name varchar);</programlisting> <para> Declares an existing table as resident on a data source previously declared with vd_remote_data_source. </para><para> This function declares the table local_name as table remote_name on the dsn. The tables names should be full, names with qualifier and owner. The names are case sensitive and must be in the exact case where they appear in the local and remote schemas. </para><para> If remote_name is NULL, the effect of a possible previous vd_remote_table is reversed. The table is thereafter treated as a local table, except in procedures and statements compiled when the remote declaration was in effect. </para> </sect2> </sect1> <sect1 id="TYPEMAPPING"> <title>Data Type Mappings</title> <para> If a statement is passed through to a remote data source, the types returned by SQLDescribeCol are taken directly from the remote prepare and converted to the closest Virtuoso supported type. </para><para> If a statement involves both local and remote objects all types are taken from the Virtuoso copy of the data dictionary. </para><para> In executing remote selects Virtuoso binds output columns according to the type and precision given by SQLDescribeCol after preparing the remote statement. </para> </sect1> <sect1 id="TIMESTAMP_AUTOINCREMENT"> <title>Timestamps &amp; Autoincrement</title> <para> A transaction timestamp is not the same across the transaction if the transaction has branches in different databases. </para><para> The data type and precision of a time stamp will also vary between different types of databases. </para><para> Hence timestamp columns coming from tables on different servers are not comparable for equality. </para><para> In inserts and updates of remote tables timestamps are assigned by the database where the table in question is physically located. </para><para> Indentity or autoincrement columns are likewise handled by the database holding the remote table. </para><para> Note that MS SQL Server and Virtuoso describe a timestamp column as a binary column in ODBC catalog and meta data calls. Thus remote SQL Server or Virtuoso timestamps will not appear as timestamps at all. </para><para> In the case of a Virtuoso remote database the binary timestamp can be cast into a DATETIME data type and it will appear as a meaningful datetime. </para> </sect1> <sect1 id="SYSTABS"> <title>System Tables</title> <!-- ******* Content not yet defined ******* --> </sect1> <sect1 id="VDBFUNCTIONS"> <title>VDB Functions</title> <sect2 id="ATTACH"> <title>ATTACH TABLE Statement</title> <programlisting>ATTACH TABLE table [AS local_name] FROM dsn [USER uid PASSWORD pwd]</programlisting> <variablelist> <varlistentry><term>dsn</term><listitem><para>scalar_exp </para></listitem></varlistentry> <varlistentry><term>user</term><listitem><para>scalar_exp </para></listitem></varlistentry> <varlistentry><term>password</term><listitem><para>scalar_exp </para></listitem></varlistentry> <varlistentry><term>table</term><listitem><para>identifier | identifier.identifier | identifier.identifier.identifier | identifier..identifier </para></listitem></varlistentry> <varlistentry><term>local_name</term><listitem><para>table </para></listitem></varlistentry> </variablelist> <para>This SQL statement defines a remote data source, copies the schema information of a giventable to the local database and defines the table as a remote table residing on the data source in question. </para><para> The table is a designation of the table&apos;s name on the remote data source dsn. It may consist of an optional qualifier, optional owner and table names, separated by dots. This must identify exactly one table on the remote dsn. The optional local_name is a on optionally qualified table name which will identify the table on the local database. If qualifier or owner are omitted, these default to the current qualifier &apos;dbname ()&apos; and the logged in user, as with CREATE TABLE. If the local_name is not given it defaults to the &lt;current qualifier&gt;.&lt;dsn&gt;.&lt;table name on dsn&gt;. The &lt;dsn&gt; will be the dsn with all alphabetic characters in upper case and all non-alphanumeric characters replaced by underscores. The &lt;table name on dsn&gt; will be the exact name as it is on the remote dsn, case unmodified. </para><para> If a dsn is not previously defined with vd_remote_data_source or ATTACH TABLE, the the USER and PASSWORD clauses have to be given. </para> </sect2> <sect2 id="REMOTECAT"> <title>Remote Catalog Access</title> <programlisting> Sql_data_sources () </programlisting> <programlisting> Sql_ravles( in dsn varchar, in qualifier varchar, in owner varchar, in table_name varchar, in tabletype varchar); </programlisting> <programlisting> Sql_columns ( in dsn varchar, in qualifier varchar, in owner varchar, in table_name varchar, in column varchar) </programlisting> <programlisting> Sql_statistics ( in dsn varchar, in qualifier varchar, in owner varchar, in table_name varchar, in is_unique integer, in detail integer) </programlisting> <programlisting> Sql_primary_keys ( in dsn varchar, in qualifier varchar, in owner varchar, in table_name varchar) </programlisting> <para> These SQL functions correspond to the ODBC catalog calls of similar name. These are used to access the data dictionary of remote data sources inside the ATTACH TABLE process. </para><para> The dsn argument must refer to a dsn previously defined by vd_remote_data_source or ATTACH TABLE. </para><para> For instance, the qualifier argument corresponds to the szTableQualifier and cbTableQualifier arguments of an ODBC catalog function. A SQL NULL value corresponds to the C NULL value. The arguments can contain % signs, which are interpreted as in LIKE. </para><para> These functions return an array, with one element for each row of the result set. Each row is represented as an array with one element for each column. </para> </sect2> <sect2 id="MANSETRDS"> <title>Manually Setting up a Remote Data Source</title> <para> Defining a remote table involves declaring the table as a local table and then defining the data source if not already defined and associating the new table with the remote data source. </para><para> The data source on which a table resides is declared at the table level. This has no connection to the table&apos;s qualifier. </para><para> Assume a remote ODBC data source named test containing a table xyz declared as follows: </para> <example id="VDOCS-TRANS-01"> <title>Example:</title> <programlisting> CREATE TABLE XYZ ( A INTEGER, B INTEGER, C INTEGER, PRIMARY KEY (A)); </programlisting> </example> <para> To defined this as a remote table on the data source Virtuoso, first define the table locally, using the above CREATE TABLE statement above. </para> <para> Then define the data source: </para> <programlisting> DB..vd_remote_data_source (&apos;test&apos;, &apos;&apos;, &apos;sa&apos;,&apos;&apos;); </programlisting> <para> And the table: </para> <programlisting> DB..vd_remote_table (&apos;test&apos;, &apos;DB.DBA.XYZ&apos;, &apos;master.dbo.XYZ&apos;); </programlisting> <para> This assumes that the remote data source has a login &apos;sa&apos; with an empty password and no special connection string options. The table names in vd_remote_table have to be fully qualified. We here assume that the Virtuoso table was created by DBA in under the default qualifier DB and the remote XYZ was created by dbo in master. </para> <para> The vd_remote_table declaration does not affect statements or procedures compiled prior to the declaration. </para> <para> Additional indices of remote tables may optionally be defined. They do not affect the operation of the SQL compiler. The remote data source makes the choice of index based on the order by clause in the statement passed through. </para> </sect2> </sect1> <sect1 id="BUGS"> <title>Bugs</title> <itemizedlist mark="bullet"> <listitem><para> Never define a local table as remote. The server will hang if it tries to make a remote commit on itself. </para></listitem> </itemizedlist> </sect1> </chapter>
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealthController : MonoBehaviour { public GameObject floatingTextPrefab, deathExplosion; public static PlayerHealthController instance; public Animator anim; public float maxHealth, currentHealth; public float invincibilityTime; private float invincibilityCounter; private void Awake() { instance = this; } void Start() { //Igualamos la vida a la vida maxima. ResetHealth(); } void Update() { if(invincibilityCounter > 0) { invincibilityCounter -= Time.deltaTime; } } public void TakeDamage() { //Comprobamos que el contador este en 0 para evitar que el jugador sea dañado multiples veces. if(invincibilityCounter <= 0) { //Restamos un punto de vida, actualizamos el UI, hacemos que aparezca el popup del daño y agregamos knockback. currentHealth --; UIManager.instance.UpdateHP(); AudioManager.instance.playSFX(8); ShowFloatingText(); PlayerController.instance.Knockback(); if(currentHealth <= 0) //Si muere el personaje corremos la funcion Death. { Death(); } else //Caso contrario le agregamos tiempo de invencibilidad. { invincibilityCounter = invincibilityTime; } } } public void Heal() { currentHealth ++; UIManager.instance.UpdateHP(); } void ShowFloatingText() { var ft = Instantiate(floatingTextPrefab, transform.position, transform.rotation, transform); ft.GetComponent<TextMesh>().text = "-1HP"; } public void Death() { Instantiate(deathExplosion, transform.position, transform.rotation); GameManager.instance.Respawn(); } public void ResetHealth() { currentHealth = maxHealth; UIManager.instance.UpdateHP(); } }
<template> <div class="layout-px-spacing"> <teleport to="#breadcrumb"> <ul class="navbar-nav flex-row"> <li> <div class="page-header"> <nav class="breadcrumb-one" aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="javascript:;">DataTables</a></li> <li class="breadcrumb-item active" aria-current="page"><span>HTML5 Export</span></li> </ol> </nav> </div> </li> </ul> </teleport> <div class="row layout-top-spacing"> <div class="col-12 layout-spacing"> <div class="panel br-6"> <div class="custom-table panel-body p-0"> <div class="d-flex flex-wrap justify-content-center justify-content-sm-start px-3 pt-3 pb-0"> <button variant="primary" class="btn m-1 btn-primary" @click="export_table('print')">Print</button> <button variant="primary" class="btn m-1 btn-primary" @click="export_table('pdf')">PDF</button> <span>{{ barangs }}</span> </div> <v-client-table :data="items" :columns="columns" :options="table_option"> <template #lastPrice="props"> {{ Number(props.row.lastPrice).toLocaleString() }} </template> <template #salePrice="props"> {{ Number(props.row.salePrice).toLocaleString() }} </template> <template #action="props"> <div class="custom-dropdown dropdown btn-group "> <div class="btn-group" href="#" role="button" id="pendingTask" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <!-- <button type="button" class="btn btn-blue">Open</button> --> <div role="group" class="btn-group"> <div class="dropdown b-dropdown custom-dropdown show btn-group"> <a class="btn dropdown-toggle btn-dark" ><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-down" > <polyline points="6 9 12 15 18 9"></polyline> </svg> </a> </div> </div> </div> <ul class="dropdown-menu dropdown-menu-end"> <li> <a href="javascript:void(0);" class="dropdown-item" @click="view_row(props.row)"> Edit </a> </li> <li> <a href="javascript:void(0);" class="dropdown-item" @click="view_row(props.row)"> Delete </a> </li> </ul> </div> </template> </v-client-table> </div> </div> </div> </div> <!-- --> </div> </template> <script setup> import { computed, onMounted, ref } from 'vue'; //pdf export import jsPDF from 'jspdf'; import 'jspdf-autotable'; import { useStore } from 'vuex'; import { useMeta } from '@/composables/use-meta'; useMeta({ title: 'Data Barang' }); const store = useStore(); const columns = ref(['kdPersediaan', 'nmPersediaan', 'stokPersediaan', 'satuanPersediaan', 'namaKtg', 'lastPrice', 'salePrice', 'action']); const items = ref([]); const table_option = ref({ perPage: 10, perPageValues: [5, 10, 20, 50], skin: 'table table-hover', columnsClasses: { action: 'actions text-center' }, pagination: { nav: 'scroll', chunk: 5 }, texts: { count: 'Showing {from} to {to} of {count}', filter: '', filterPlaceholder: 'Search...', limit: 'Results:', }, sortable: ['kdBarang', 'nmBarang', 'hrgPokok', 'hrgJual', 'namaKtg', 'stkBarang',], sortIcon: { base: 'sort-icon-none', up: 'sort-icon-asc', down: 'sort-icon-desc', }, resizableColumns: true, }); onMounted(() => { bind_data(); }); const bind_data = () => { store.dispatch('GetPersediaan'); items.value = store.getters.StatePersediaan; } const barangs = computed(() => { items.value = store.getters.StatePersediaan; // console.log(items) // return { items } }); const export_table = (type) => { let cols = columns.value.filter((d) => d != 'profile' && d != 'action'); let records = items.value; let filename = 'table'; if (type == 'csv') { let coldelimiter = ','; let linedelimiter = '\n'; let result = cols .map((d) => { return capitalize(d); }) .join(coldelimiter); result += linedelimiter; records.map((item) => { cols.map((d, index) => { if (index > 0) { result += coldelimiter; } let val = item[d] ? item[d] : ''; result += val; }); result += linedelimiter; }); if (result == null) return; if (!result.match(/^data:text\/csv/i) && !window.navigator.msSaveOrOpenBlob) { var data = 'data:application/csv;charset=utf-8,' + encodeURIComponent(result); var link = document.createElement('a'); link.setAttribute('href', data); link.setAttribute('download', filename + '.csv'); link.click(); } else { var blob = new Blob([result]); if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, filename + '.csv'); } } } else if (type == 'print') { var rowhtml = '<p>' + filename + '</p>'; rowhtml += '<table style="width: 100%; " cellpadding="0" cellcpacing="0"><thead><tr style="color: #515365; background: #eff5ff; -webkit-print-color-adjust: exact; print-color-adjust: exact; "> '; cols.map((d) => { rowhtml += '<th>' + capitalize(d) + '</th>'; }); rowhtml += '</tr></thead>'; rowhtml += '<tbody>'; records.map((item) => { rowhtml += '<tr>'; cols.map((d) => { let val = item[d] ? item[d] : ''; rowhtml += '<td>' + val + '</td>'; }); rowhtml += '</tr>'; }); rowhtml += '<style>body {font-family:Arial; color:#495057;}p{text-align:center;font-size:18px;font-weight:bold;margin:15px;}table{ border-collapse: collapse; border-spacing: 0; }th,td{font-size:12px;text-align:left;padding: 4px;}th{padding:8px 4px;}tr:nth-child(2n-1){background:#f7f7f7; }</style>'; rowhtml += '</tbody></table>'; var winPrint = window.open('', '', 'left=0,top=0,width=1000,height=600,toolbar=0,scrollbars=0,status=0'); winPrint.document.write('<title>Print</title>' + rowhtml); winPrint.document.close(); winPrint.focus(); winPrint.print(); // winPrint.close(); } else if (type == 'pdf') { cols = cols.map((d) => { return { header: capitalize(d), dataKey: d }; }); const doc = new jsPDF('l', 'pt', cols.length > 10 ? 'a3' : 'a4'); doc.autoTable({ headStyles: { fillColor: '#eff5ff', textColor: '#515365' }, columns: cols, body: records, styles: { overflow: 'linebreak' }, pageBreak: 'auto', margin: { top: 45 }, didDrawPage: () => { doc.text('Export Table', cols.length > 10 ? 535 : 365, 30); }, }); doc.save(filename + '.pdf'); } }; const excel_columns = () => { return { Name: 'name', Position: 'position', Office: 'office', Age: 'age', 'Start Date': 'start_date', Salary: 'salary', }; }; const excel_items = () => { return items.value; }; const capitalize = (text) => { return text .replace('_', ' ') .replace('-', ' ') .toLowerCase() .split(' ') .map((s) => s.charAt(0).toUpperCase() + s.substring(1)) .join(' '); }; const view_row = (item) => { alert('ID: ' + item.kdBarang + ', Name: ' + item.nmBarang); }; </script>
import 'dart:convert'; import 'package:foodie_bell/Api/request_manager.dart'; import 'package:http/http.dart' as http; class WSSignUpRequest extends APIRequest { String f_name; String l_name; String email; String password; String mobile; String address; WSSignUpRequest({ endPoint, this.f_name, this.l_name, this.email, this.password, this.mobile, this.address, }) : super(endPoint + "user_resgister") {} @override Map<String, Object> getParams() { Map<String, Object> params = Map<String, Object>(); params["f_name"] = this.f_name; params["email"] = this.email; params["password"] = this.password; params["l_name"] = this.l_name; params["mobile"] = this.mobile; params["address"] = this.address; params['latitude'] = "22.7488902"; params['longitude'] = "75.8947843"; return params; } @override String parseResponse(http.Response response, bool showLog) { super.parseResponse(response, showLog); String retVal = "Problem occured in parsing the response"; if (response.statusCode == 200) { try { Map<String, Object> responseData = jsonDecode(response.body); if (responseData.containsKey("success")) { this.response.addEntries(responseData.entries); retVal = ""; } } catch (e) { retVal = e.toString(); } } return retVal; } }
import express, { Application } from 'express'; import swaggerUi from 'swagger-ui-express'; import swaggerJsdoc, { Options } from 'swagger-jsdoc'; import homeRouter from './routes/home'; import taskRouter from './routes/tasks'; import { notFoundHandler } from './middlewares/notFoundHandler'; import { errorHandler } from './middlewares/errorHandler'; import userRouter from './routes/users'; // --- Polyfill for Prisma - Serializate big int declare global { interface BigInt { toJSON(): string; } } BigInt.prototype.toJSON = function (): string { return this.toString(); }; // --- const swaggerOptions: Options = { swaggerDefinition: { info: { title: 'Task Management API', version: '1.0.0', description: "Task services app's API" }, securityDefinitions: { bearerAuth: { type: 'apiKey', name: 'Authorization', scheme: 'bearer', in: 'header', }, }, }, security: [{ bearerAuth: [] }], apis: ['./src/routes/*.ts'], }; const app: Application = express(); const swaggerDocs = swaggerJsdoc(swaggerOptions); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs)); app.use('/', homeRouter); app.use('/tasks', taskRouter); app.use('/users', userRouter); app.use(notFoundHandler); app.use(errorHandler); export default app;
#include <cs50.h> #include <ctype.h> #include <stdio.h> #include <string.h> string decrypt_text(string key, string plaintext); bool is_contain_nonalphabet(string key); bool is_contain_duplicate(string key); int main(int argc, string argv[]) { // Verify input count if (argc != 2) { printf("Usage: ./substitution key\n"); return 1; } else if (strlen(argv[1]) != 26) { printf("Key must contain 26 characters.\n"); return 1; } else if (is_contain_nonalphabet(argv[1])) { printf("Key must only contain alphabetic characters.\n"); return 1; } else if (is_contain_duplicate(argv[1])) { printf("Key must not contain duplicate characters.\n"); return 1; } string plaintext = get_string("plaintext: "); const string ciphertext = decrypt_text(argv[1], plaintext); printf("ciphertext: %s\n", ciphertext); } string decrypt_text(string key, string plaintext) { string ciphertext = plaintext; for (int i = 0, len = strlen(plaintext); i < len; i++) { if (isupper(ciphertext[i])) { ciphertext[i] = toupper(key[ciphertext[i] - 'A']); } else if (islower(ciphertext[i])) { ciphertext[i] = tolower(key[ciphertext[i] - 'a']); } } return ciphertext; } bool is_contain_nonalphabet(string key) { for (int i = 0, len = strlen(key); i < len; i++) { if (!isalpha(key[i])) { return true; } } return false; } bool is_contain_duplicate(string key) { for (int current = 0, len = strlen(key); current < len; current++) { for (int next = current + 1; next < len - 1; next++) { if (tolower(key[current]) == tolower(key[next])) { return true; } } } return false; }
import { useEffect, useState, useContext } from 'react'; import { Link } from 'react-router-dom'; import "./Header.css"; import { PublicRoutes} from '../Routes/routes'; import setupHeaderMenu from '../utilities/navbarMobile'; import { FaOutdent} from 'react-icons/fa'; import { UserContext } from "../context/UsersContext"; import Cookies from 'universal-cookie'; import logo from "../assets/images/logo.png"; import Navbar from './Navbar'; // eslint-disable-next-line react/prop-types const Header = ({ section }) => { const [loginSelected, setLoginSelected] = useState(false); const { isAuthenticated, logOut } = useContext(UserContext); const [isSubMenuOpen, setIsSubMenuOpen] = useState(false); const cookies = new Cookies(); const userCookie = cookies.get('user'); const usernameC = userCookie ? userCookie.username : null; //TO DO // const leftNavbarItems = [ // { name: 'Explorar', path: `/explore` }, // { name: 'Noticias', path: `/news` }, // { name: 'Precios', path: `/pricing` }, // ]; useEffect(() => { setupHeaderMenu(); }, []) useEffect(() => { // Comprueba si la sección actual es "Iniciar Sesion" o "Registrarse" setLoginSelected(section === 'Iniciar Sesion' || section === 'Registrarse'); }, [section]); const toggleSubMenu = () => { setIsSubMenuOpen(!isSubMenuOpen); }; return ( <section id="header"> <div className='logo-and-sections'> <Link to={"/" + PublicRoutes.LANDING}> <img src={logo} className="logo" alt="" /> </Link> {/* <ul id='navbar'> {leftNavbarItems.map((item) => ( <li key={item.path}> <Link to={item.path}> {item.name} </Link> </li> )) } </ul> */} </div> <Navbar loginSelected={loginSelected} isAuthenticated={isAuthenticated} toggleSubMenu={toggleSubMenu} isSubMenuOpen={isSubMenuOpen} usernameC={usernameC} logOut={logOut} /> <div id="mobile"> <FaOutdent id="bar" size={22} /> </div> </section> ); }; export default Header;
import pdfrw def get_form_file_path(form): base = "backend/helpers/backend/" if form == "application": return base + "application/form.pdf" elif form == "site evaluation": return base + "site_eval/form.pdf" elif form == "construction": return base + "construction/form.pdf" else: raise Exception("Invalid form type!") def fill_pdf_form_fields(pdf_input_path, output_path, field_data): """ Fill the provided data into the PDF form fields using pdfrw. Args: - pdf_input_path (str): Path to the input PDF file. - output_path (str): Path to the output PDF file. - field_data (dict): Dictionary containing the field names as keys and data to be filled as values. Returns: - None """ output_path = f"backend/helpers/backend/application/{output_path}" template = pdfrw.PdfReader(pdf_input_path) if template.Root.AcroForm: template.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject("true"))) annotations = template.pages[0].Annots for annotation in annotations: if annotation.T: print(annotation.T) field_name = annotation.T[1:-1] if field_name not in field_data: print(f"Unexpected field: {field_name}") else: print(f"Processing field: {field_name}") annotation.update(pdfrw.PdfDict(V='{}'.format(field_data[field_name]))) pdfrw.PdfWriter().write(output_path, template)
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CashDiscipline.Module.BusinessObjects.Forex; using CashDiscipline.Module.BusinessObjects; using DevExpress.Persistent.Validation; using System.Diagnostics; using CashDiscipline.Module.BusinessObjects.Cash; using DevExpress.Data.Filtering; using CashDiscipline.Module.Controllers.Forex; using DevExpress.ExpressApp; using Xafology.ExpressApp.Xpo; using DevExpress.ExpressApp.Xpo; using DevExpress.Xpo; using CashDiscipline.Module.Controllers.Cash; using CashDiscipline.Module.DatabaseUpdate; using DevExpress.ExpressApp.Utils; using CashDiscipline.Module.ParamObjects.Cash; using Xafology.TestUtils; using CashDiscipline.UnitTests.TestObjects; using CashDiscipline.Module.Logic.Cash; using DevExpress.Xpo.DB; using System.Data.SqlClient; namespace CashDiscipline.UnitTests { [TestFixture] public class FixCashFlowTests : TestBase { #region Setup public FixCashFlowTests() { SetTesterDbType(TesterDbType.MsSql); var tester = Tester as MSSqlDbTestBase; if (tester != null) tester.DatabaseName = Constants.TestDbName; } public override void OnSetup() { CashDiscipline.Module.DatabaseUpdate.Updater.CreateDbObjects(ObjectSpace); CashDiscipline.Module.DatabaseUpdate.Updater.CreateCurrencies(ObjectSpace); SetOfBooks.GetInstance(ObjectSpace); CashDiscipline.Module.DatabaseUpdate.Updater.InitSetOfBooks(ObjectSpace); CashDiscipline.Module.DatabaseUpdate.Updater.CreateCashFlowDefaults(ObjectSpace); } public override void OnAddExportedTypes(ModuleBase module) { CashDisciplineTestHelper.AddExportedTypes(module); } #endregion [Test] public void FixSchedOutsTwiceAfterFixerChange() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 03); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixee2 = ObjectSpace.CreateObject<CashFlow>(); cfFixee2.TranDate = new DateTime(2016, 03, 03); cfFixee2.Account = account; cfFixee2.AccountCcyAmt = 500; cfFixee2.Activity = activity; cfFixee2.FixRank = 2; cfFixee2.Fix = schedOutFixTag; cfFixee2.DateUnFix = cfFixee2.TranDate; cfFixee2.FixActivity = cfFixee2.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 31); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 1400; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.FixFromDate = new DateTime(2016, 03, 1); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.Fix = schedOutFixTag; cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var algoObjSpace = (XPObjectSpace)Application.CreateObjectSpace(); var fixAlgo1 = new FixCashFlowsAlgorithm(algoObjSpace, paramObj); #endregion #region Assert Intermediate fixAlgo1.ProcessCashFlows(); ObjectSpace.Refresh(); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(5, cashFlows.Count()); Assert.AreEqual(300, cashFlows.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion #region Assert Final cfFixer1 = cashFlows.Where(cf => cf.Oid == cfFixer1.Oid).FirstOrDefault(); cfFixer1.TranDate = new DateTime(2016, 03, 28); cfFixer1.Save(); ObjectSpace.CommitChanges(); fixAlgo1.ProcessCashFlows(); ObjectSpace.Refresh(); var cashFlows2 = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(5, cashFlows2.Count()); // $500+$600 should move from 31st to 28th Assert.AreEqual(300, cashFlows2.Where(x => x.TranDate == new DateTime(2016, 03, 28)) .Sum(x => x.AccountCcyAmt)); Assert.AreEqual(0, cashFlows2.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion } [Test] public void FixSchedOutsTwiceAfterFixeeChange() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 03); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixee2 = ObjectSpace.CreateObject<CashFlow>(); cfFixee2.TranDate = new DateTime(2016, 03, 03); cfFixee2.Account = account; cfFixee2.AccountCcyAmt = 500; cfFixee2.Activity = activity; cfFixee2.FixRank = 2; cfFixee2.Fix = schedOutFixTag; cfFixee2.DateUnFix = cfFixee2.TranDate; cfFixee2.FixActivity = cfFixee2.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 31); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 1400; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.FixFromDate = new DateTime(2016, 03, 1); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.Fix = schedOutFixTag; cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo1 = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); #endregion #region Assert 1st run fixAlgo1.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(5, cashFlows.Count()); Assert.AreEqual(300, cashFlows.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion #region Assert 2nd run cfFixee1 = ObjectSpace.GetObjectByKey<CashFlow>(cfFixee1.Oid); // change Tran Date and simulate setting flag to false cfFixee1.TranDate = new DateTime(2016, 03, 05); cfFixee1.AccountCcyAmt = 700; ObjectSpace.CommitChanges(); fixAlgo1.ProcessCashFlows(); var cashFlows2 = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(5, cashFlows2.Count()); Assert.AreEqual(200, cashFlows2.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion } [Test] public void NotFixedIfDateNotMatched() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 12); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = schedOutFixTag; cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlowsPre = ObjectSpace.GetObjects<CashFlow>(); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert var cashFlowsPost = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(2, cashFlowsPost.Count); #endregion } [Test] public void FixSchedOutLockdownSaved() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 12); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = schedOutFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Saved Snapshot var logic = new SaveForecastSnapshot(ObjectSpace); logic.Process(); ObjectSpace.CommitChanges(); // select snapshot that's not the current snapshot var savedSnapshot = ObjectSpace.FindObject<CashFlowSnapshot>( CriteriaOperator.Parse("Name <> ?", "Current")); Assert.NotNull(savedSnapshot); // select current snapshot var currentSnapshot = ObjectSpace.FindObject<CashFlowSnapshot>( CriteriaOperator.Parse("Name = ?", "Current")); Assert.NotNull(currentSnapshot); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); paramObj.Snapshot = savedSnapshot; ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(500, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12) && cf.Snapshot == savedSnapshot) .Sum(cf => cf.AccountCcyAmt)); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-100, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate && cf.Snapshot.Oid == savedSnapshot.Oid) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(0, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12) && cf.Snapshot.Oid == savedSnapshot.Oid) .Sum(cf => cf.AccountCcyAmt)); #endregion } [Test] public void FixSchedOutLockdown() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 12); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = schedOutFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(500, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12)) .Sum(cf => cf.AccountCcyAmt)); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-100, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(0, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12)) .Sum(cf => cf.AccountCcyAmt)); #endregion } [Test] public void LockdownNonApForecast() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var audAccount = ObjectSpace.CreateObject<Account>(); audAccount.Name = "VHA ANZ AUD"; audAccount.Currency = ccyAUD; var usdAccount = ObjectSpace.CreateObject<Account>(); usdAccount.Name = "VHA ANZ USD"; usdAccount.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var bankFeeActivity = ObjectSpace.CreateObject<Activity>(); bankFeeActivity.Name = "Bank Fees"; bankFeeActivity.FixActivity = bankFeeActivity; bankFeeActivity.ForecastFixTag = CashDiscipline.Common.Constants.BankFeeFixTag; var apActivity = ObjectSpace.CreateObject<Activity>(); apActivity.Name = "AP Pymt"; apActivity.FixActivity = apActivity; var payrollActivity = ObjectSpace.CreateObject<Activity>(); payrollActivity.Name = "Payroll Pymt"; payrollActivity.FixActivity = payrollActivity; payrollActivity.ForecastFixTag = CashDiscipline.Common.Constants.PayrollFixTag; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B3"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = audAccount; cfFixee1.CounterCcy = ccyAUD; cfFixee1.AccountCcyAmt = -600; cfFixee1.CounterCcyAmt = -600; cfFixee1.Activity = apActivity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 25); cfFixer1.Account = audAccount; cfFixer1.CounterCcy = ccyAUD; cfFixer1.CounterCcyAmt = -12000; cfFixer1.AccountCcyAmt = -12000; cfFixer1.Activity = bankFeeActivity; cfFixer1.FixRank = 3; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; var cfFixer2 = ObjectSpace.CreateObject<CashFlow>(); cfFixer2.TranDate = new DateTime(2016, 03, 25); cfFixer2.Account = audAccount; cfFixer2.CounterCcy = ccyAUD; cfFixer2.CounterCcyAmt = -30000; cfFixer2.AccountCcyAmt = -30000; cfFixer2.Activity = payrollActivity; cfFixer2.FixRank = 3; cfFixer2.Fix = schedOutFixTag; cfFixer2.FixFromDate = new DateTime(2016, 03, 01); cfFixer2.FixToDate = new DateTime(2016, 03, 31); cfFixer2.DateUnFix = cfFixer2.TranDate; cfFixer2.FixActivity = cfFixer2.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = apActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); fixAlgo.ProcessCashFlows(); #endregion #region Assert var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-42000, cashFlows.Where(cf => cf.TranDate == new DateTime(2016, 03, 25)) .Sum(cf => cf.AccountCcyAmt)); #endregion } [Test] public void FixSchedOutsTwice() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 03); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixee2 = ObjectSpace.CreateObject<CashFlow>(); cfFixee2.TranDate = new DateTime(2016, 03, 03); cfFixee2.Account = account; cfFixee2.AccountCcyAmt = 500; cfFixee2.Activity = activity; cfFixee2.FixRank = 2; cfFixee2.Fix = schedOutFixTag; cfFixee2.DateUnFix = cfFixee2.TranDate; cfFixee2.FixActivity = cfFixee2.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 31); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 1400; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.FixFromDate = new DateTime(2016, 03, 1); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.Fix = schedOutFixTag; cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); ObjectSpace.CommitChanges(); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); #endregion #region Assert 1st run fixAlgo.ProcessCashFlows(); CashFlowSnapshot currentSnapshot = CashFlowHelper.GetCurrentSnapshot(ObjectSpace.Session); #endregion #region Assert 2nd run fixAlgo.ProcessCashFlows(); Assert.AreEqual(5, cashFlows.Count()); Assert.AreEqual(300, cashFlows.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion } //[Test] //public void TestFixParameters() //{ // var fixActivity = ObjectSpace.CreateObject<Activity>(); // fixActivity.Name = "AP Pymt"; // #region Arrange Fix Tags // var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); // schedOutFixTag.Name = "S2"; // schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; // var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); // allocFixTag.Name = "B3"; // allocFixTag.FixTagType = CashForecastFixTagType.Allocate; // CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); // ObjectSpace.CommitChanges(); // #endregion // #region Arrange Algorithm // var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); // paramObj.FromDate = new DateTime(2016, 01, 01); // paramObj.ToDate = new DateTime(2016, 12, 31); // paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); // paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); // paramObj.ApReclassActivity = fixActivity; // paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); // paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); // ObjectSpace.CommitChanges(); // var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); // var parameters = fixAlgo.CreateParameters(); // var sqlParameters = fixAlgo.CreateSqlParameters(); // // todo: is CashFlowFixParam created? // #endregion // #region Assert // var conn = ObjectSpace.Session.Connection; // var cmd = conn.CreateCommand(); // foreach (var parameter in parameters) // { // var sqlParameter = sqlParameters // .Where(p => p.ParameterName == parameter.ParameterName) // .FirstOrDefault(); // cmd.CommandText = "SELECT " + sqlParameter.CommandText; // var sqlValue = cmd.ExecuteScalar(); // Assert.AreEqual(string.Format("{0}:{1}", parameter.ParameterName, parameter.Value), // string.Format("{0}:{1}", parameter.ParameterName, sqlValue)); // } // #endregion //} [Test] [Category("Fix Cash Flow")] public void FixAllocLockdownFX() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Tech Cost"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B3"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = -600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 11); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = -500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-600 - 500, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 11)) .Sum(cf => cf.AccountCcyAmt)); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-500, cashFlows .Where(cf => cf.TranDate >= new DateTime(2016, 03, 01) && cf.TranDate <= new DateTime(2016, 4, 30)) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(-600, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 11)) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(-666.67, Math.Round(cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 11)) .Sum(cf => cf.FunctionalCcyAmt), 2)); Assert.AreEqual(100, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(111.11, Math.Round(cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate) .Sum(cf => cf.FunctionalCcyAmt), 2)); #endregion } [Test] [Category("Fix Cash Flow")] public void FixAllocLockdownAud() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ AUD"; account.Currency = ccyAUD; var techActivity = ObjectSpace.CreateObject<Activity>(); techActivity.Name = "Tech Cost"; techActivity.FixActivity = techActivity; var apActivity = ObjectSpace.CreateObject<Activity>(); apActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B3"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // Short-Term e.g. AP var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 10, 07); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = -500; cfFixee1.Activity = techActivity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; // Long-Term e.g. Planning var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 10, 07); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = -600; cfFixer1.Activity = techActivity; cfFixer1.FixRank = 3; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 10, 1); cfFixer1.FixToDate = new DateTime(2016, 10, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2020, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 10, 7); paramObj.ApayableNextLockdownDate = new DateTime(2016, 10, 14); paramObj.ApReclassActivity = apActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 10, 7); paramObj.PayrollNextLockdownDate = new DateTime(2016, 10, 12); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(cfFixee1.AccountCcyAmt - cfFixer1.AccountCcyAmt, cashFlows .Where(cf => cf.Fix.Name == CashDiscipline.Common.Constants.RevRecFixTag && cf.TranDate == cfFixee1.TranDate && cf.Activity.Name == apActivity.Name) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(-cfFixee1.AccountCcyAmt, cashFlows .Where(cf => cf.TranDate == cfFixee1.TranDate && cf.Fix.Name == CashDiscipline.Common.Constants.ReversalFixTag) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(cfFixer1.AccountCcyAmt - cfFixee1.AccountCcyAmt, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate && cf.Fix.Name == CashDiscipline.Common.Constants.ResRevRecFixTag) .Sum(cf => cf.AccountCcyAmt)); #endregion } // Test that fixes will still be applied even if the Fixer has a // FixFromDate and FixToDate outside the Fixee's date, i.e. there is no Fixer. // The Fixer simply falls in the lockdown period. [Test] [Category("Fix Cash Flow")] public void FixAllocLockdownCarriedForward() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ AUD"; account.Currency = ccyAUD; var techActivity = ObjectSpace.CreateObject<Activity>(); techActivity.Name = "Tech Cost"; techActivity.FixActivity = techActivity; var apActivity = ObjectSpace.CreateObject<Activity>(); apActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B3"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // Short-Term e.g. AP var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 10, 07); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = -500; cfFixee1.Activity = techActivity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; // Long-Term e.g. Planning var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 10, 07); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = -600; cfFixer1.Activity = techActivity; cfFixer1.FixRank = 3; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 9, 1); cfFixer1.FixToDate = new DateTime(2016, 9, 30); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2020, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 10, 7); paramObj.ApayableNextLockdownDate = new DateTime(2016, 10, 14); paramObj.ApReclassActivity = apActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 10, 7); paramObj.PayrollNextLockdownDate = new DateTime(2016, 10, 12); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(- cfFixer1.AccountCcyAmt, cashFlows .Where(cf => cf.Fix.Name == CashDiscipline.Common.Constants.RevRecFixTag && cf.TranDate == cfFixee1.TranDate && cf.Activity.Name == apActivity.Name) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(cfFixer1.AccountCcyAmt, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate && cf.Fix.Name == CashDiscipline.Common.Constants.ResRevRecFixTag) .Sum(cf => cf.AccountCcyAmt)); #endregion } [Test] [Category("Fix Cash Flow")] public void FixPayroll() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ AUD"; account.Currency = ccyAUD; var payrollActivity = ObjectSpace.CreateObject<Activity>(); payrollActivity.Name = "Payroll Pymt"; payrollActivity.FixActivity = payrollActivity; var apActivity = ObjectSpace.CreateObject<Activity>(); apActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); var payrollFixTag = ObjectSpace.FindObject<CashForecastFixTag>(CriteriaOperator.Parse( "Name = ?", CashDiscipline.Common.Constants.PayrollFixTag)); #endregion #region Arrange Transactions // Short-Term - not to be fixed since there's no fixer var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 9, 7); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = -500; cfFixee1.Activity = payrollActivity; cfFixee1.FixRank = 2; cfFixee1.Fix = payrollFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; // Short-Term - to be fixed var cfFixee2 = ObjectSpace.CreateObject<CashFlow>(); cfFixee2.TranDate = new DateTime(2016, 10, 7); cfFixee2.Account = account; cfFixee2.AccountCcyAmt = -500; cfFixee2.Activity = payrollActivity; cfFixee2.FixRank = 2; cfFixee2.Fix = payrollFixTag; cfFixee2.DateUnFix = cfFixee2.TranDate; cfFixee2.FixActivity = cfFixee2.Activity; // Long-Term e.g. Planning var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 10, 7); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = -600; cfFixer1.Activity = payrollActivity; cfFixer1.FixRank = 3; cfFixer1.Fix = payrollFixTag; cfFixer1.FixFromDate = new DateTime(2016, 9, 1); cfFixer1.FixToDate = new DateTime(2016, 9, 30); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2020, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 10, 7); paramObj.ApayableNextLockdownDate = new DateTime(2016, 10, 14); paramObj.ApReclassActivity = apActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 10, 7); paramObj.PayrollNextLockdownDate = new DateTime(2016, 10, 12); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(cfFixer1.AccountCcyAmt - cfFixee1.AccountCcyAmt, cashFlows .Where(cf => cf.TranDate == paramObj.PayrollNextLockdownDate) .Sum(cf => cf.AccountCcyAmt)); #endregion } [Test] public void FixFromDifferentCurrencyAndCounterparty() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var audAccount = ObjectSpace.CreateObject<Account>(); audAccount.Name = "VHA ANZ AUD"; audAccount.Currency = ccyAUD; audAccount.FixAccount = audAccount; var usdAccount = ObjectSpace.CreateObject<Account>(); usdAccount.Name = "VHA ANZ USD"; usdAccount.Currency = ccyUSD; usdAccount.FixAccount = audAccount; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Tech Cost"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; var defCparty = ObjectSpace.GetObjectByKey<Counterparty>( CashFlowDefaults.GetInstance(ObjectSpace).Counterparty.Oid); var cparty1 = ObjectSpace.CreateObject<Counterparty>(); cparty1.Name = "VPC"; cparty1.FixCounterparty = cparty1; var cparty2 = ObjectSpace.CreateObject<Counterparty>(); cparty2.Name = "Vodafone Procurement Company"; cparty2.FixCounterparty = cparty1; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B5"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 04, 08); cfFixee1.Status = CashFlowStatus.Actual; cfFixee1.Account = usdAccount; cfFixee1.CounterCcy = ccyUSD; cfFixee1.AccountCcyAmt = -600; cfFixee1.CounterCcyAmt = -600; cfFixee1.Activity = activity; cfFixee1.FixRank = 1; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; cfFixee1.Counterparty = cparty2; var fixerDate = new DateTime(2016, 05, 14); var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.Status = CashFlowStatus.Forecast; cfFixer1.TranDate = fixerDate; cfFixer1.Account = audAccount; cfFixer1.CounterCcy = ccyAUD; cfFixer1.CounterCcyAmt = -800; cfFixer1.AccountCcyAmt = -800; cfFixer1.Activity = activity; cfFixer1.FixRank = 5; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 04, 01); cfFixer1.FixToDate = new DateTime(2016, 04, 30); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 05, 06); paramObj.ApayableNextLockdownDate = new DateTime(2016, 05, 13); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 05, 06); paramObj.PayrollNextLockdownDate = new DateTime(2016, 05, 13); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-133.33, Math.Round(cashFlows .Where(cf => cf.TranDate == fixerDate) .Sum(cf => cf.CounterCcyAmt), 2)); Assert.AreEqual(-133.33, Math.Round(cashFlows .Where(cf => cf.TranDate == fixerDate) .Sum(cf => cf.FunctionalCcyAmt), 2)); #endregion } [Test] public void FixFromDifferentCurrency() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var audAccount = ObjectSpace.CreateObject<Account>(); audAccount.Name = "VHA ANZ AUD"; audAccount.Currency = ccyAUD; audAccount.FixAccount = audAccount; var usdAccount = ObjectSpace.CreateObject<Account>(); usdAccount.Name = "VHA ANZ USD"; usdAccount.Currency = ccyUSD; usdAccount.FixAccount = audAccount; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Tech Cost"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B3"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = usdAccount; cfFixee1.CounterCcy = ccyUSD; cfFixee1.AccountCcyAmt = -600; cfFixee1.CounterCcyAmt = -600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var fixerDate = new DateTime(2016, 03, 25); var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = fixerDate; cfFixer1.Account = audAccount; cfFixer1.CounterCcy = ccyAUD; cfFixer1.CounterCcyAmt = -500; cfFixer1.AccountCcyAmt = -500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(166.67, Math.Round(cashFlows .Where(cf => cf.TranDate == fixerDate) .Sum(cf => cf.CounterCcyAmt), 2)); Assert.AreEqual(166.67, Math.Round(cashFlows .Where(cf => cf.TranDate == fixerDate) .Sum(cf => cf.FunctionalCcyAmt), 2)); Assert.AreEqual(600.00, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 3, 25) && cf.Account.Name == "VHA ANZ AUD" && cf.Fix.Name == "R") .Sum(cf => cf.AccountCcyAmt)); #endregion } [Test] public void IfDeleteFixerCashFlow() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; var counterparty = ObjectSpace.CreateObject<Counterparty>(); counterparty.Name = "UNDEFINED"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; cfFixee1.Counterparty = counterparty; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 12); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = schedOutFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; cfFixer1.Counterparty = counterparty; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(500, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12)) .Sum(cf => cf.AccountCcyAmt)); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert Arrange cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-100, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(0, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12)) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(3, cashFlows.Count); #endregion #region Assert Delete Cash Flow cfFixer1 = ObjectSpace.FindObject<CashFlow>(CriteriaOperator.Parse("Oid = ?", cfFixer1.Oid)); cfFixer1.Delete(); ObjectSpace.CommitChanges(); fixAlgo.ProcessCashFlows(); cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(1, cashFlows.Count); #endregion } [Test] public void IfDeleteFixeeCashFlow() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; var counterparty = ObjectSpace.FindObject<Counterparty>(CriteriaOperator.Parse("Name = ?", "UNDEFINED")); ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; cfFixee1.Counterparty = counterparty; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 12); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = schedOutFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; cfFixer1.Counterparty = counterparty; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(500, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12)) .Sum(cf => cf.AccountCcyAmt)); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert Arrange cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(-100, cashFlows .Where(cf => cf.TranDate == paramObj.ApayableNextLockdownDate) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(0, cashFlows .Where(cf => cf.TranDate == new DateTime(2016, 03, 12)) .Sum(cf => cf.AccountCcyAmt)); Assert.AreEqual(3, cashFlows.Count); #endregion #region Assert Delete Cash Flow cfFixee1 = new XPQuery<CashFlow>(ObjectSpace.Session) .Where(cf => cf.Oid == cfFixee1.Oid).FirstOrDefault(); cfFixee1.Delete(); ObjectSpace.CommitChanges(); fixAlgo.ProcessCashFlows(); cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(1, cashFlows.Count); #endregion } [Test] public void FixPrioritizesMatchingCurrency() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var audAccount = ObjectSpace.CreateObject<Account>(); audAccount.Name = "VHA ANZ AUD"; audAccount.Currency = ccyAUD; var usdAccount = ObjectSpace.CreateObject<Account>(); usdAccount.Name = "VHA ANZ USD"; usdAccount.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Tech Cost"; activity.FixActivity = activity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S2"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B3"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 11); cfFixee1.Account = usdAccount; cfFixee1.CounterCcy = ccyUSD; cfFixee1.AccountCcyAmt = -600; cfFixee1.CounterCcyAmt = -600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = schedOutFixTag; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 26); cfFixer1.Account = audAccount; cfFixer1.CounterCcy = ccyAUD; cfFixer1.CounterCcyAmt = -500; cfFixer1.AccountCcyAmt = -500; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.Fix = allocFixTag; cfFixer1.FixFromDate = new DateTime(2016, 03, 01); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; var cfFixer2 = ObjectSpace.CreateObject<CashFlow>(); cfFixer2.TranDate = new DateTime(2016, 03, 26); cfFixer2.Account = usdAccount; cfFixer2.CounterCcy = ccyUSD; cfFixer2.CounterCcyAmt = -500; cfFixer2.AccountCcyAmt = -500; cfFixer2.Activity = activity; cfFixer2.FixRank = 3; cfFixer2.Fix = allocFixTag; cfFixer2.FixFromDate = new DateTime(2016, 03, 01); cfFixer2.FixToDate = new DateTime(2016, 03, 31); cfFixer2.DateUnFix = cfFixer2.TranDate; cfFixer2.FixActivity = cfFixer2.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); paramObj.Snapshot = SetOfBooks.GetInstance(ObjectSpace).CurrentCashFlowSnapshot; paramObj.Save(); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); fixAlgo.ProcessCashFlows(); #endregion #region Assert var cashFlows = ObjectSpace.GetObjects<CashFlow>(); Assert.AreEqual(100, cashFlows .Where(cf => cf.TranDate >= new DateTime(2016, 03, 25) && cf.TranDate <= new DateTime(2016, 03, 26) && cf.CounterCcy == ccyUSD).Sum(cf => cf.CounterCcyAmt)); Assert.AreEqual(-500, cashFlows .Where(cf => cf.TranDate >= new DateTime(2016, 03, 25) && cf.TranDate <= new DateTime(2016, 03, 26) && cf.CounterCcy == ccyAUD).Sum(cf => cf.CounterCcyAmt)); #endregion } [Test] public void MapCashFlows() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var audAccount = ObjectSpace.CreateObject<Account>(); audAccount.Name = "VHA ANZ AUD"; audAccount.Currency = ccyAUD; var usdAccount = ObjectSpace.CreateObject<Account>(); usdAccount.Name = "VHA ANZ USD"; usdAccount.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var techActivity = ObjectSpace.CreateObject<Activity>(); techActivity.Name = "Tech Cost"; techActivity.FixActivity = techActivity; var handsetActivity = ObjectSpace.CreateObject<Activity>(); handsetActivity.Name = "Handset Pchse"; handsetActivity.FixActivity = handsetActivity; var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Fix Tags var schedOutFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedOutFixTag.Name = "S"; schedOutFixTag.FixTagType = CashForecastFixTagType.ScheduleOut; var allocFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); allocFixTag.Name = "B"; allocFixTag.FixTagType = CashForecastFixTagType.Allocate; var schedInFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); schedInFixTag.Name = "C"; schedInFixTag.FixTagType = CashForecastFixTagType.ScheduleIn; var ignoreFixTag = ObjectSpace.CreateObject<CashForecastFixTag>(); ignoreFixTag.Name = "IG1"; ignoreFixTag.FixTagType = CashForecastFixTagType.Ignore; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); #endregion #region Arrange Transactions // act var cf1 = ObjectSpace.CreateObject<CashFlow>(); cf1.TranDate = new DateTime(2016, 03, 11); cf1.Account = usdAccount; cf1.CounterCcy = ccyUSD; cf1.AccountCcyAmt = -600; cf1.CounterCcyAmt = -600; cf1.Activity = handsetActivity; cf1.FixRank = 2; cf1.DateUnFix = cf1.TranDate; cf1.FixActivity = cf1.Activity; var cf2 = ObjectSpace.CreateObject<CashFlow>(); cf2.TranDate = new DateTime(2016, 03, 25); cf2.Account = audAccount; cf2.CounterCcy = ccyAUD; cf2.CounterCcyAmt = -500; cf2.AccountCcyAmt = -500; cf2.Activity = techActivity; cf2.FixRank = 3; cf2.FixFromDate = new DateTime(2016, 03, 01); cf2.FixToDate = new DateTime(2016, 03, 31); cf2.DateUnFix = cf2.TranDate; cf2.FixActivity = cf2.Activity; var cf3 = ObjectSpace.CreateObject<CashFlow>(); cf3.TranDate = new DateTime(2016, 03, 26); cf3.Account = usdAccount; cf3.CounterCcy = ccyUSD; cf3.CounterCcyAmt = -500; cf3.AccountCcyAmt = -500; cf3.Activity = techActivity; cf3.FixRank = 3; cf3.FixFromDate = new DateTime(2016, 03, 01); cf3.FixToDate = new DateTime(2016, 03, 31); cf3.DateUnFix = cf3.TranDate; cf3.FixActivity = cf3.Activity; ObjectSpace.CommitChanges(); #endregion #region Arrange Mapping int rowIndex = 0; int mapStep = 0; mapStep += 1; // increment to next step var map3 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map3.CriteriaExpression = "Source.Team LIKE 'AP' AND Activity.Name LIKE 'Handset Pchse'"; map3.CriteriaStatus = CashFlowStatus.Forecast; map3.FixActivity = handsetActivity; map3.Fix = schedOutFixTag; map3.FixRank = 2; map3.FixFromDateExpr = "TranDate"; map3.MapStep = mapStep; map3.RowIndex = rowIndex++; var map5 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map5.CriteriaExpression = "Source.Team LIKE 'AP' AND Activity.Name LIKE 'iPhone Pchse Pymt'"; map5.CriteriaStatus = CashFlowStatus.Forecast; map5.Fix = schedOutFixTag; map5.FixRank = 2; map5.FixFromDateExpr = "TranDate"; map5.FixActivity = handsetActivity; map5.MapStep = mapStep; map5.RowIndex = rowIndex++; var map6 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map6.CriteriaExpression = "Activity.Name IN ('V Subs Rcpt','3 DD','V Subs DD Rcpt')"; map6.CriteriaStatus = CashFlowStatus.Forecast; map6.Fix = schedInFixTag; map6.FixRank = 2; map6.FixFromDateExpr = "TranDate"; map6.MapStep = mapStep; map6.RowIndex = rowIndex++; var map7 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map7.CriteriaExpression = "Source.Team LIKE 'Trend' AND Activity.ActivityL1 NOT LIKE 'Receipts'"; map7.CriteriaStatus = CashFlowStatus.Forecast; map7.Fix = schedOutFixTag; map7.FixRank = 2; map7.FixFromDateExpr = "TranDate"; map7.MapStep = mapStep; map7.RowIndex = rowIndex++; var map8 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map8.CriteriaExpression = "Activity.ActivityL1 LIKE 'Receipts'"; map8.CriteriaStatus = CashFlowStatus.Forecast; map8.Fix = schedInFixTag; map8.FixRank = 2; map8.FixFromDateExpr = "dbo.BOMONTH(TranDate)"; map8.FixToDateExpr = "EOMONTH(TranDate)"; map8.MapStep = mapStep; map8.RowIndex = rowIndex++; var map9 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map9.CriteriaExpression = "Activity.ActivityL1 LIKE 'Financing Cash Flow'"; map9.CriteriaStatus = CashFlowStatus.Forecast; map9.Fix = ignoreFixTag; map9.FixFromDateExpr = "TranDate"; map9.MapStep = mapStep; map9.RowIndex = rowIndex++; var map1 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map1.CriteriaExpression = "Source.Team LIKE 'Treasury'"; map1.CriteriaStatus = CashFlowStatus.Forecast; map1.Fix = ignoreFixTag; map1.FixFromDateExpr = "TranDate"; map1.MapStep = mapStep; map1.RowIndex = rowIndex++; var map10 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map10.CriteriaExpression = "Source.Team LIKE 'Inventory'"; map10.CriteriaStatus = CashFlowStatus.Forecast; map10.Fix = schedOutFixTag; map10.FixRank = 3; map10.FixFromDateExpr = "dbo.BOMONTH(TranDate)"; map10.FixToDateExpr = "EOMONTH(TranDate)"; map10.MapStep = mapStep; map10.RowIndex = rowIndex++; var map4 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map4.CriteriaExpression = "Else"; map4.CriteriaStatus = CashFlowStatus.Forecast; map4.Fix = schedOutFixTag; map4.FixRank = 2; map4.FixFromDateExpr = "TranDate"; map4.RowIndex = rowIndex++; map4.MapStep = mapStep; mapStep += 1; // increment to next step var map2 = ObjectSpace.CreateObject<CashFlowFixMapping>(); map2.CriteriaExpression = "DATEDIFF(d, TranDate,EOMONTH(TranDate)) < 7"; map2.CriteriaStatus = CashFlowStatus.Forecast; map2.FixToDateExpr = "EOMONTH(TranDate)"; map3.RowIndex = rowIndex++; map2.MapStep = mapStep; #endregion #region Arrange Algorithm var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); paramObj.Snapshot = SetOfBooks.GetInstance(ObjectSpace).CurrentCashFlowSnapshot; paramObj.Save(); ObjectSpace.CommitChanges(); var mapper = new CashFlowFixMapper(ObjectSpace); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj, mapper); fixAlgo.ProcessCashFlows(); ObjectSpace.CommitChanges(); ObjectSpace.Refresh(); #endregion #region Assert // TODO #endregion #region Assert Step #endregion } [Test] public void FixSingleSchedOut() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fix1 = ObjectSpace.CreateObject<CashForecastFixTag>(); fix1.Name = "S2"; fix1.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Transactions // act var cf1 = ObjectSpace.CreateObject<CashFlow>(); cf1.TranDate = new DateTime(2016, 03, 03); cf1.Account = account; cf1.AccountCcyAmt = 1000; cf1.Activity = activity; cf1.FixRank = 2; cf1.Fix = fix1; cf1.DateUnFix = cf1.TranDate; cf1.FixActivity = cf1.Activity; var cf2 = ObjectSpace.CreateObject<CashFlow>(); cf2.TranDate = new DateTime(2016, 03, 31); cf2.Account = account; cf2.AccountCcyAmt = 1400; cf2.Activity = activity; cf2.FixRank = 3; cf2.FixFromDate = new DateTime(2016, 03, 1); cf2.FixToDate = new DateTime(2016, 03, 31); cf2.Fix = fix1; cf2.DateUnFix = cf2.TranDate; cf2.FixActivity = cf2.Activity; ObjectSpace.CommitChanges(); #endregion #region Act var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); fixAlgo.ProcessCashFlows(); #endregion #region Assert Assert.AreEqual(3, cashFlows.Count()); Assert.AreEqual(1400 - 1000, cashFlows.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion } [Test] public void FixSchedOuts() { #region Arrange Dimensions var ccyAUD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "AUD")); var ccyUSD = ObjectSpace.FindObject<Currency>(CriteriaOperator.Parse("Name = ?", "USD")); var account = ObjectSpace.CreateObject<Account>(); account.Name = "VHA ANZ USD"; account.Currency = ccyUSD; var rate = ObjectSpace.CreateObject<ForexRate>(); rate.FromCurrency = ccyAUD; rate.ToCurrency = ccyUSD; rate.ConversionDate = new DateTime(2013, 12, 31); rate.ConversionRate = 0.9M; var activity = ObjectSpace.CreateObject<Activity>(); activity.Name = "Device Purchase"; activity.FixActivity = activity; var fix1 = ObjectSpace.CreateObject<CashForecastFixTag>(); fix1.Name = "S2"; fix1.FixTagType = CashForecastFixTagType.ScheduleOut; CashDiscipline.Module.DatabaseUpdate.Updater.InitFixTags(ObjectSpace); var fixActivity = ObjectSpace.CreateObject<Activity>(); fixActivity.Name = "AP Pymt"; ObjectSpace.CommitChanges(); #endregion #region Arrange Transactions // act var cfFixee1 = ObjectSpace.CreateObject<CashFlow>(); cfFixee1.TranDate = new DateTime(2016, 03, 03); cfFixee1.Account = account; cfFixee1.AccountCcyAmt = 600; cfFixee1.Activity = activity; cfFixee1.FixRank = 2; cfFixee1.Fix = fix1; cfFixee1.DateUnFix = cfFixee1.TranDate; cfFixee1.FixActivity = cfFixee1.Activity; var cfFixee2 = ObjectSpace.CreateObject<CashFlow>(); cfFixee2.TranDate = new DateTime(2016, 03, 03); cfFixee2.Account = account; cfFixee2.AccountCcyAmt = 500; cfFixee2.Activity = activity; cfFixee2.FixRank = 2; cfFixee2.Fix = fix1; cfFixee2.DateUnFix = cfFixee2.TranDate; cfFixee2.FixActivity = cfFixee2.Activity; var cfFixer1 = ObjectSpace.CreateObject<CashFlow>(); cfFixer1.TranDate = new DateTime(2016, 03, 31); cfFixer1.Account = account; cfFixer1.AccountCcyAmt = 1400; cfFixer1.Activity = activity; cfFixer1.FixRank = 3; cfFixer1.FixFromDate = new DateTime(2016, 03, 1); cfFixer1.FixToDate = new DateTime(2016, 03, 31); cfFixer1.Fix = fix1; cfFixer1.DateUnFix = cfFixer1.TranDate; cfFixer1.FixActivity = cfFixer1.Activity; #endregion #region Act var paramObj = ObjectSpace.CreateObject<CashFlowFixParam>(); paramObj.FromDate = new DateTime(2016, 01, 01); paramObj.ToDate = new DateTime(2016, 12, 31); paramObj.ApayableLockdownDate = new DateTime(2016, 03, 18); paramObj.ApayableNextLockdownDate = new DateTime(2016, 03, 25); paramObj.ApReclassActivity = fixActivity; paramObj.PayrollLockdownDate = new DateTime(2016, 03, 18); paramObj.PayrollNextLockdownDate = new DateTime(2016, 03, 25); ObjectSpace.CommitChanges(); var fixAlgo = new FixCashFlowsAlgorithm(ObjectSpace, paramObj); var cashFlows = ObjectSpace.GetObjects<CashFlow>(); fixAlgo.ProcessCashFlows(); #endregion #region Assert Assert.AreEqual(5, cashFlows.Count()); Assert.AreEqual(300, cashFlows.Where(x => x.TranDate == new DateTime(2016, 03, 31)) .Sum(x => x.AccountCcyAmt)); #endregion } } }
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"> <data> <import type="android.view.View"/> <variable name="noticeData" type="com.example.sobok_android.domain.model.notice2.NoticeListData2.Data.Info" /> <variable name="noticeMessage" type="String" /> <variable name="isPill" type="Boolean" /> <variable name="isWaiting" type="Boolean" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/rectangle_notice_list" android:layout_marginTop="8dp" android:paddingTop="18dp" android:paddingBottom="18dp"> <ImageView android:id="@+id/iv_notice_list_section_img" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:src="@drawable/ic_share_alarm_22_darkmint" android:src="@{isPill ? @drawable/ic_pill_alarm_22_darkmint : @drawable/ic_share_alarm_22_darkmint}" app:layout_constraintTop_toTopOf="@id/tv_notice_list_title" app:layout_constraintBottom_toBottomOf="@id/tv_notice_list_title" app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="18dp" android:visibility="@{isWaiting ? View.VISIBLE : View.GONE}"/> <TextView android:id="@+id/tv_notice_list_title" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="정관장" android:text="@{isPill ? noticeData.pillName : noticeData.senderName}" android:fontFamily="@font/pretendard_semi_bold" android:textSize="18sp" android:textColor="@color/notice_list_title" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toEndOf="@id/iv_notice_list_section_img" android:layout_marginStart="10dp" android:visibility="@{isWaiting ? View.VISIBLE : View.GONE}"/> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/cl_notice_list_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="@id/tv_notice_list_title" app:layout_constraintBottom_toBottomOf="@id/tv_notice_list_title" app:layout_constraintEnd_toEndOf="parent"> <ImageView android:id="@+id/iv_notice_list_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_more_16_black" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="21dp" android:visibility="visible"/> <TextView android:id="@+id/tv_notice_list_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/notice_detail" android:fontFamily="@font/pretendard_medium" android:textSize="14sp" android:textColor="@color/notice_list_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toStartOf="@id/iv_notice_list_detail" android:layout_marginEnd="5dp" android:visibility="visible"/> </androidx.constraintlayout.widget.ConstraintLayout> <TextView android:id="@+id/tv_notice_list_line" android:layout_width="0dp" android:layout_height="1dp" android:background="@color/notice_list_line" app:layout_constraintTop_toBottomOf="@id/tv_notice_list_title" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="17dp" android:layout_marginHorizontal="18dp" android:visibility="@{isWaiting ? View.VISIBLE : View.GONE}"/> <TextView android:id="@+id/tv_notice_message" android:layout_width="0dp" android:layout_height="wrap_content" tools:text="지민지민지민지민지민지민지민님이 약 알림 일정을 보냈어요" android:text="@{noticeMessage}" android:fontFamily="@font/pretendard_medium" android:textSize="14sp" android:textColor="@color/notice_list_message" app:layout_constraintTop_toBottomOf="@id/tv_notice_list_line" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="8dp" app:layout_goneMarginTop="0dp" android:layout_marginHorizontal="18dp"/> <TextView android:id="@+id/tv_notice_time" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="오후 12:35" android:text="@{noticeData.createdAt}" android:fontFamily="@font/pretendard_medium" android:textSize="12dp" android:textColor="@color/notice_list_time" app:layout_constraintTop_toBottomOf="@id/tv_notice_message" app:layout_constraintStart_toStartOf="@id/tv_notice_message" android:layout_marginTop="4dp"/> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btn_notice_reject" android:stateListAnimator="@null" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@drawable/rectangle_notice_btn_reject" android:text="@string/reject" android:fontFamily="@font/pretendard_semi_bold" android:textSize="13sp" android:textColor="@color/notice_btn_reject" app:layout_constraintTop_toBottomOf="@id/tv_notice_time" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/btn_notice_accept" android:layout_marginTop="12dp" android:layout_marginStart="18dp" android:visibility="@{isWaiting ? View.VISIBLE : View.GONE}"/> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btn_notice_accept" android:stateListAnimator="@null" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@drawable/rectangle_notice_btn_accept" android:text="@string/accept" android:fontFamily="@font/pretendard_semi_bold" android:textSize="13sp" android:textColor="@color/notice_btn_accept" app:layout_constraintTop_toTopOf="@id/btn_notice_reject" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@id/btn_notice_reject" android:layout_marginStart="8dp" android:layout_marginEnd="18dp" android:visibility="@{isWaiting ? View.VISIBLE : View.GONE}"/> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <link rel="stylesheet" href="src/styles.css" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700&family=Poppins:wght@500;700&display=swap" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous" ></script> <script src="https://kit.fontawesome.com/132bdfdafe.js" crossorigin="anonymous" ></script> <title>Husna's Works</title> </head> <body> <div class="container"> <nav class="d-flex justify-content-between"> <a href="/index.html" title="Homepage"> <img src="images/logo.png" class="logo d-none d-md-block" alt="shecodes logo" /> <img src="images/small-logo.png" class="logo d-block d-md-none" alt="" /> <ul> <li> <a href="/index.html" title="Homepage"> Home</a> </li> <li><a href="/about.html" title="About Husna"> About</a></li> <li class="active"> <a href="/work.html" title="Husna's work"> Work </a> </li> <li><a href="/contact.html" title="Contact Husna"> Contact</a></li> </ul> </a> </nav> </div> <div class="content-container container"> <div class="content"> <h1 class="mb-5">Take a look at what I've been working on!</h1> <div class="row"> <div class="col-md-6 mb-4"> <img src="images/yogurt.png" class="img-fluid mb-3 rounded" alt="Yogurt project preview" /> <h3 class="text-center m-0">Yogurt Project</h3> <p class="text-center text-muted">Built with HTML and CSS</p> </div> <div class="col-md-6 mb-4"> <img src="images/weather.png" class="img-fluid mb-3 rounded" alt="Weather app preview" /> <h3 class="text-center m-0">Weather Project</h3> <p class="text-center text-muted"> Built with HTML, CSS and JavaScript </p> </div> <div class="col-md-6 mb-4"> <img src="images/dictionary.png" class="img-fluid mb-3 rounded" alt="Dictionary app preview" /> <h3 class="text-center m-0">Dictionary App</h3> <p class="text-center text-muted">Built with HTML, CSS and React</p> </div> <div class="col-md-6 mb-4"> <img src="images/translation.png" class="img-fluid mb-3" alt="" /> <h3 class="text-center m-0">Translation App</h3> <p class="text-center text-muted"> Built with HTML, CSS, JavaScript and React </p> </div> </div> </div> <footer> <div class="contact-box d-flex justify-content-between mb-5 d-none d-md-flex" > <div> <h3>Work Inquiry</h3> <p class="text-muted"> Let’s work together and i’ll help you by all my best </p> </div> <div> <a href="/contact.html" class="btn btn-branding mt-3" title="Contact Husna" >Contact me</a > </div> </div> <div class="d-flex justify-content-center mb-5"> <a href="mailto:husnarasuli1@gmail.com" class="email-link" title="Email Husna" >husnarasuli1@gmail.com</a > </div> <div class="social-links d-flex justify-content-center"> <a href="https://www.instagram.com" target="_blank" title="Instagram"> <i class="fa-brands fa-instagram"></i ></a> <a href="https://www.github.com/husnasadaat" target="_blank" title="GitHub" ><i class="fa-brands fa-github"></i ></a> <a href="https://www.facebook.com" target="_blank" title="Facebook"> <i class="fa-brands fa-facebook"></i ></a> </div> <p class="text-center mt-5"> 🤞This project is coded by Husna Rasuli, and it is <a href="https://github.com/husnasadaat/Portfolio-project" target="_blank" >open-sourced.</a > </p> </footer> </div> </body> </html>
import React, { useEffect, useState } from "react"; import { useParams, Link } from "react-router-dom"; import Typography from "@mui/material/Typography"; import Button from "@mui/material/Button"; import CircularProgress from "@mui/material/CircularProgress"; import AxiosConnect from "../../../utils/AxiosConnect"; import { Box } from "@mui/material"; import useClientStore from "../../../zustand/ClientStore"; import useSnackbarStore from "../../../zustand/SnackbarStore"; import { CheckCircleOutline } from "@mui/icons-material"; // TODO: Look into: Verification will not work if the user is signed out of their account. function VerifyEmail() { const { token } = useParams(); const [isLoading, setIsLoading] = useState(true); const [status, setStatus] = useState(""); const { verifyEmail, client } = useClientStore(); const { openSnackbar } = useSnackbarStore(); useEffect(() => { const getVerifyEmail = async () => { if (client && client.verified) { setIsLoading(false); setStatus("success"); return; } if (!token) { setIsLoading(false); return; } try { const response = await verifyEmail(token); setStatus(response.data.status); } catch (err) { console.log(err); openSnackbar(err.response.data.msg, "error"); setStatus("error"); } finally { setIsLoading(false); } }; getVerifyEmail(); }, []); const resendVerificationEmail = async () => { try { const response = await AxiosConnect.get( "/gleek/client/resendVerifyEmail", ); openSnackbar(response.data.msg, "success"); } catch (err) { console.log(err); } }; if (isLoading) return ( <Box display="flex" alignItems="center" justifyContent="center"> <CircularProgress /> </Box> ); return ( <Box display="flex" alignItems="center" justifyContent="center"> <Box boxShadow={3} p={3} bgcolor="white" borderRadius={4} textAlign="center" > {(status === "success" || status === "already-verified") && ( <div> <CheckCircleOutline sx={{ fontSize: 48 }} /> <Typography variant="h4" color="primary.dark"> Email Verified! </Typography> <Typography variant="body1"> Start exploring our thoughtfully curated collection of sustainability and employee wellness activities. </Typography> <Button variant="contained" color="tertiary" component={Link} to="/shop" sx={{ mt: 3 }} > Shop </Button> </div> )} {status === "token-expired" && ( <div> <Typography variant="h4">Expired Link</Typography> <Typography variant="body1">Your email link has expired</Typography> <Button variant="contained" color="primary" component={Link} onClick={resendVerificationEmail} > Request New Verification </Button> </div> )} {!token && status !== "success" && ( <div> <Typography variant="h4">Verification Email Sent</Typography> <Typography variant="body1"> An email has been sent to verify your account. </Typography> <Button variant="contained" color="primary" component={Link} onClick={resendVerificationEmail} > Request New Verification </Button> </div> )} </Box> </Box> ); } export default VerifyEmail;
import { View, Text, StyleSheet, ViewStyle, TouchableWithoutFeedback, ScrollView, TouchableOpacity, Pressable, Share, Dimensions, } from "react-native"; import React, { Dispatch, SetStateAction, useContext, useEffect, useRef, useState, } from "react"; import ThemeContext from "../../contexts/themeContext"; import { theme } from "../../config/colors"; import Animated, { FadeIn, FadeInUp, FadeOut, Layout, useAnimatedStyle, useSharedValue, withSpring, withTiming, } from "react-native-reanimated"; import { GestureHandlerRootView, Swipeable, } from "react-native-gesture-handler"; import { MaterialIcons } from "@expo/vector-icons"; import { localTask } from "../../config/types/localTask"; import { timeStampToLocal } from "../../helpers/timeHelpers"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { markTaskDone, markTaskUndone, removeTask, } from "../../redux/slices/taskSlice"; import { SimpleLineIcons } from "@expo/vector-icons"; import stringUtils from "../../utils/stringUtils"; import { selectSwipeToDeleteEnabled, selectShowCompletedTodosEnabled, } from "../../redux/slices/settingsSlice"; import * as Sharing from "expo-sharing"; import moment from "moment"; type renderItemProps = { item: localTask; index: number; key?: string; }; interface Props { data: localTask[]; contentContainerStyle?: ViewStyle; setActiveItem?: Function; setActiveShareItem?: Function; } const AnimatedList: React.FC<Props> = (props) => { const { data, contentContainerStyle, setActiveItem, setActiveShareItem } = props; const { theme } = useContext(ThemeContext); const dispatch = useAppDispatch(); const swipeToDeleteEnabled = useAppSelector(selectSwipeToDeleteEnabled); const showCompletedTodosEnabled = useAppSelector( selectShowCompletedTodosEnabled ); const styles = themeStyles(theme); const handleDelete = (task: localTask) => { dispatch(removeTask(task)); }; const initialMode = useRef<boolean>(true); useEffect(() => { initialMode.current = false; }, []); const RenderItem = (props: renderItemProps) => { const { index, item } = props; if (item.completed && !showCompletedTodosEnabled) return; const [active, setActive] = useState(false); const height = useSharedValue(120); const opacity = useSharedValue(0); const scale = useSharedValue(0); const animatedStyle = useAnimatedStyle(() => { if (active) { height.value = withTiming(200); } else { height.value = withTiming(120); } return { height: height.value, }; }, [active]); const animatedEditContainerStyle = useAnimatedStyle(() => { if (active) { opacity.value = withTiming(1); scale.value = withSpring(1); } else { opacity.value = withTiming(0); scale.value = withSpring(0); } return { opacity: opacity.value, transform: [ { scale: scale.value, }, ], }; }, [active]); const RightAction = () => { return ( <TouchableWithoutFeedback onPress={() => handleDelete(item)}> <Animated.View style={[styles.rightActionStyle, animatedStyle]}> <MaterialIcons name="delete-forever" size={36} color="#FFF" /> <Text accessible={false} style={styles.buttonText}>{`Delete`}</Text> </Animated.View> </TouchableWithoutFeedback> ); }; const handleTouch = () => { setActive(!active); }; const handleEditTouch = () => { setActiveItem?.(item); }; const handleShareTouch = () => { setActiveShareItem?.(item); }; const url = "com.app.RNShowcaseEyepax"; const handleMarkAs = () => { if (!item.completed) { const newTask: localTask = { ...item, completed: true, completedTimestamp: moment.now(), }; dispatch(markTaskDone(newTask)); } else { dispatch(markTaskUndone(item)); } }; return ( <GestureHandlerRootView> <TouchableOpacity activeOpacity={1} onPress={handleTouch}> <Swipeable renderRightActions={swipeToDeleteEnabled ? RightAction : undefined} > <Animated.View style={[styles.listItem, animatedStyle]} entering={ initialMode.current ? FadeIn.delay(100 * index) : FadeIn } exiting={FadeOut} onTouchEnd={undefined} > <Text style={styles.titleText}>{item.title}</Text> {item.description && ( <Text style={styles.descriptionText}>{item.description}</Text> )} <View style={styles.timestamp}> {item.completed && ( <View style={{ flexDirection: "row", justifyContent: "flex-end", alignItems: "center", }} > <MaterialIcons name="done" size={24} color={styles.regularText.color} /> </View> )} <Text style={styles.regularText}> {`${timeStampToLocal(item.createdTimestamp)}`} </Text> </View> <View style={styles.icon}> <Pressable onPress={ handleShareTouch // () => { // Share.share( // { // message: "ABCD" + "\n" + url, // url: "http://www.google.com", // title: "this is abcd", // }, // { // dialogTitle: "abcd dialog title", // excludedActivityTypes: [ // "com.apple.UIKit.activity.PostToTwitter", // ], // } // ); // console.log(item); // } } > <SimpleLineIcons name="share" size={20} color={theme.colors.background} /> </Pressable> </View> <View style={{ flexDirection: "row", position: "absolute", left: 0, bottom: 0, }} > <Animated.View style={[styles.editContainer, animatedEditContainerStyle]} onTouchEnd={handleEditTouch} > <Text style={styles.editText}>{`Edit`}</Text> </Animated.View> {item.type === "todo" && ( <Animated.View style={[styles.todoContainer, animatedEditContainerStyle]} onTouchEnd={handleMarkAs} > <Text style={styles.editText}> {item?.completed ? "Mark as undone" : "Mark as done"} </Text> </Animated.View> )} </View> </Animated.View> </Swipeable> </TouchableOpacity> </GestureHandlerRootView> ); }; return ( <View style={[styles.container]}> <ScrollView style={styles.scrollView} contentContainerStyle={contentContainerStyle} > {data.map((item, index) => ( <RenderItem key={item.id} index={index} item={item} /> ))} </ScrollView> </View> ); }; const themeStyles = (theme: theme) => StyleSheet.create({ container: { flex: 1, }, scrollView: { flex: 1, }, listItem: { height: 120, backgroundColor: theme.colors.primary, width: "90%", marginVertical: 10, borderRadius: 20, alignSelf: "center", padding: 10, elevation: 5, shadowColor: "#000", shadowOpacity: 0.1, shadowOffset: { width: 0, height: 10 }, shadowRadius: 4, }, titleText: { color: theme.colors.text, fontSize: 18, fontWeight: "600", }, descriptionText: { color: theme.colors.text, fontSize: 18, fontWeight: "400", marginTop: 10, }, regularText: { color: theme.colors.text, fontSize: 14, fontWeight: "400", }, rightActionStyle: { height: 120, backgroundColor: theme.colors.secondary, alignSelf: "center", width: 80, marginRight: 20, borderRadius: 20, padding: 10, justifyContent: "center", alignItems: "center", }, buttonText: { color: theme.colors.text, fontWeight: "300", paddingTop: 10, }, timestamp: { flex: 1, alignSelf: "flex-end", justifyContent: "flex-end", }, icon: { position: "absolute", top: 10, right: 10, }, editContainer: { flexDirection: "row", backgroundColor: theme.colors.secondary, bottom: 0, left: 0, borderBottomLeftRadius: 20, padding: 10, }, todoContainer: { flexDirection: "row", backgroundColor: theme.colors.card, bottom: 0, left: 0, padding: 10, justifyContent: "center", marginLeft: 5, width: Dimensions.get("window").width * 0.4, }, editText: { color: theme.colors.text, }, }); export default AnimatedList;
<template> <div class="ma-5"> <!--- input box ---> <v-row> <v-col cols="12" sm="12" md="6" lg="6" xl="6"> <v-card class="text-center" v-if="show"> <v-card-text> <v-sparkline :labels="labels" :value="value" :gradient="gradient" :smooth="radius || false" :padding="padding" :line-width="width" :stroke-linecap="lineCap" :gradient-direction="gradientDirection" :fill="fill" :type="type" :auto-line-width="autoLineWidth" auto-draw ></v-sparkline> </v-card-text> <v-divider></v-divider> <v-card-text> <div class="pt-5 pb-5 text-h5 font-weight-thin"> Total TNBC On Each Interval </div> </v-card-text> </v-card> <v-card v-else> <v-card-text> <v-form v-model="valid" lazy-validation ref="form" @submit.prevent="calculate()" enctype="multipart/form-data"> <v-text-field v-model="interval" label="Intervals" placeholder="6" type="number" class="rounded-0" :rules="validation" outlined required></v-text-field> <v-text-field v-model="invest" label="Base Investment" placeholder="100" type="number" class="rounded-0" :rules="validation" outlined required></v-text-field> <v-text-field v-model="rate" label="Initial Rate" placeholder="0.01" type="number" class="rounded-0" :rules="validation" outlined required></v-text-field> <v-text-field v-model="rateDecrement" label="Decrement Rate" placeholder="0.001" type="number" class="rounded-0" :rules="validation" outlined required></v-text-field> <div class="white--text"> <v-btn type="submit" :disabled="!valid" @click="validate" block tile>Calculate</v-btn> </div> </v-form> </v-card-text> </v-card> </v-col> <v-col cols="12" sm="12" md="6" lg="6" xl="6"> <v-card class="pa-4" v-if="show"> <h3 class="pb-5">Results</h3> <p>Intervals : {{ this.data.interval }}</p> <p>Base Investment : {{ this.data.invest }}</p> <p>Total Investment : {{ this.data.total_Investment }}</p> <p>Initial Rate : {{ this.data.rate }}</p> <p>Rate On {{ interval }}th Interval : {{ this.data.dayRate }}</p> <p>Total TNBC On {{ interval }}th Interval : {{ this.data.total_crypto }}</p> <p>Total Price On {{ interval }}th Interval : {{ this.data.sale_price }}</p> <p>Total PNL : {{ this.data.profit }}</p> </v-card> <v-card class="pa-4" v-else> <h3 class="pb-5">Instructions</h3> <h4>Intervals</h4> <p>How many times you want to invest.</p> <h4>Base Investment</h4> <p>A fixed amount that you want to invest each time.</p> <h4>Initial Rate</h4> <p>The rate that you want to start the investment.</p> <h4>Decrement Rate</h4> <p>It determines the next interval rate. For example: If initial rate is 0.015 and you want to invest again when the price will be decreased to 0.014, than the decreament rate would be 0.001. On each interval the rate would be decreamented by 0.001 and the calculation would be done following this propotion.</p> </v-card> </v-col> </v-row> <!--- End input box ---> <!-- Data Table--> <div v-if="show" class="pt-5"> <v-card> <v-toolbar flat > <v-toolbar-title>Calculation Details</v-toolbar-title> <v-divider class="mx-4" inset vertical></v-divider> <v-text-field v-model="search" append-icon="mdi-magnify" label="Search" color="deep-purple" single-line hide-details ></v-text-field> <v-divider class="mx-4" inset vertical></v-divider> <v-spacer></v-spacer> <v-divider class="mx-4" inset vertical></v-divider> <v-btn small class="mb-2" @click="clear()">Clear</v-btn> <v-divider class="mx-4" inset vertical></v-divider> <v-btn small class="mb-2"><v-icon>mdi-arrow-down-bold-box-outline</v-icon></v-btn> <v-divider class="mx-4" inset vertical></v-divider> </v-toolbar> <!-- datatable --> <v-data-table class="elevation-0" :headers="headers" :items="data.blocks" :search="search" :loading="loading" loading-text="Loading... Please wait" :footer-props="{itemsPerPageOptions: [5,10,15],itemsPerPageText: 'Data Per Page','show-current-page': true,'show-first-last-page': true}"> <template v-slot:[`item.actions`]="{ item }" > <v-icon small color="cyan" class="mr-2" @click="editBtn(item.id)"> mdi-pencil </v-icon> <v-icon small color="red" @click="deleteBtn(item.id)"> mdi-delete </v-icon> </template> </v-data-table> <!-- End datatable --> </v-card> </div> </div> </template> <script> const gradients = [ ['#222'], ['#42b3f4'], ['red', 'orange', 'yellow'], ['purple', 'violet'], ['#00c6ff', '#F0F', '#FF0'], ['#f72047', '#ffd200', '#1feaea'], ] export default { data () { return { width: 2, radius: 10, padding: 8, lineCap: 'round', gradient: gradients[5], labels: [], value: [], gradientDirection: 'top', gradients, fill: true, type: 'bar', autoLineWidth: false, valid: true, show:false, search: '', loading: false, interval: '', invest : '', rate : '', rateDecrement : '', data: [], calculations:[], headers: [ { text: 'Intervals', align: 'start', sortable: true, value: 'interval'}, { text: 'Investment', align: 'start', sortable: false, value: 'invest'}, { text: 'Rate', align: 'start', sortable: true, value: 'rate'}, { text: 'Tnbc', align: 'start', sortable: false, value: 'tnbc'}, { text: 'Total TNBC', align: 'start', value: 'totalCrypto', sortable: false }, { text: 'Total Investment', align: 'start', value: 'totalInvest', sortable: false }, ], validation: [ v => !!v || 'This field is required', ], } }, methods:{ clear(){ console.log('clear'); this.data = []; this.labels = []; this.value = []; this.show = false; }, blocks(interval, invest, rate, rateDecrement){ let blocks = []; let totalCrypto = 0; let totalInvest = 0; for(let i =1; i <= interval; i++){ let tnbc = invest / rate; totalCrypto = totalCrypto + tnbc; totalInvest = totalInvest + invest let floatRate = rate.toFixed(3); let obj = { "interval" : i, "invest" : invest, "rate" : floatRate, "tnbc" : tnbc.toFixed(3), "totalCrypto" : totalCrypto.toFixed(3), "totalInvest" : totalInvest } blocks.push(obj); this.labels.push(floatRate); this.value.push(totalCrypto); rate = rate - rateDecrement; } return blocks; }, validate () { this.$refs.form.validate() }, profit(interval, invest, rate, rateDecrement){ let n = interval - 1; let blocks = this.blocks(interval, invest, rate, rateDecrement); let block = blocks[n]; let dayRate = block.rate; let totalCrypto = block.totalCrypto; let totalInvest = block.totalInvest; let salePrice = dayRate * totalCrypto; let profit = salePrice - totalInvest; let obj = { "blocks" : blocks, "interval" : interval, "invest" : invest, "rate" : rate, "dayRate" : dayRate, "total_Investment" : totalInvest, "total_crypto" : totalCrypto, "sale_price" : salePrice.toFixed(2), "profit" : profit.toFixed(2), } return obj; }, calculate(){ const interval = Number(this.interval); const invest = Number(this.invest); const rate = Number(this.rate); const rateDecrement = Number(this.rateDecrement); // const interval = 2; // const invest = Number(100); // const rate = Number(0.01); // const rateDecrement = Number(0.001); let profit = this.profit(interval, invest, rate, rateDecrement); this.data = profit; this.show = true; } } } </script> <style> </style>
#!/usr/bin/python3 """ This script adds command line arguments to a Python list and saves them to a file. Usage: ./script_name.py arg1 arg2 ... The script uses the 'save_to_json_file' and 'load_from_json_file' functions to save and load the list from a JSON file. """ import sys if __name__ == "__main__": save_to_json_file = __import__('5-save_to_json_file').save_to_json_file load_from_json_file = \ __import__('6-load_from_json_file').load_from_json_file # check if add_item.jsonfile exists try: # load the existing lists from the file my_list = load_from_json_file("add_item.json") except FileNotFoundError: # create a new list if file does not exist my_list = [] # add command line argument to the list my_list.extend(sys.argv[1:]) # save the updated list to add_item.json save_to_json_file(my_list, "add_item.json")
import {EventFilterTypes} from "../Common/constants"; class EventFilters { /** * @param {Event[]} events * @param {string} query * @returns {Event[]} */ static filterEventsByQuery(events, query) { return events.filter(event => { const comparableProperties = [ event.transactionId, event.block.toString(), event.message.toLowerCase(), event.description.toLowerCase(), ]; return comparableProperties.some(prop => prop.includes(query)); }); } /** * @param {Event[]} events * @param {string[]} contractIds * @returns {Event[]} */ static filterEventsByContracts(events, contractIds) { return events.filter(event => { return contractIds.some(id => id === event.contractId); }); } /** * @param {Event[]} events * @param {EventFilter[]} filters * @returns {Event[]} */ static filterEvents(events, filters) { let filteredEvents = events; filters.forEach(filter => { switch (filter.type) { case EventFilterTypes.QUERY: filteredEvents = EventFilters.filterEventsByQuery(filteredEvents, filter.value); break; case EventFilterTypes.CONTRACTS: filteredEvents = EventFilters.filterEventsByContracts(filteredEvents, filter.value); break; default: break; } }); return filteredEvents; } } export default EventFilters;
namespace UnitSystem.Quantities; /// <summary> /// Represents a quantity with a specified amount and unit, allowing for different amount data types such as <see cref="double"/>, <see cref="Vector{T}"/>, or <see cref="Matrix{T}"/>. /// </summary> /// <typeparam name="T">The type of the amount, which must be a struct.</typeparam> public abstract partial class Quantity<T> where T : struct { /// <summary> /// The coherent quantity, which is a standardized representation of the quantity. /// </summary> internal readonly Quantity<T> _coherent; /// <summary> /// The hash code for the quantity. /// </summary> internal readonly int _hashCode; /// <summary> /// Initializes a new instance of the <see cref="Quantity{T}"/> class. /// </summary> /// <param name="amount">The amount of the quantity.</param> /// <param name="unit">The unit of the quantity.</param> protected Quantity(T amount, Unit unit) { Amount = amount; Unit = unit; // ReSharper disable once VirtualMemberCallInConstructor _coherent = ToCoherent(); _hashCode = GenerateHashCode(); } /// <summary> /// Initializes a new instance of the <see cref="Quantity{T}"/> class with a specified coherent quantity. /// </summary> /// <param name="amount">The amount of the quantity.</param> /// <param name="unit">The unit of the quantity.</param> /// <param name="coherent">The coherent quantity.</param> protected Quantity(T amount, Unit unit, Quantity<T> coherent) { Amount = amount; Unit = unit; _coherent = coherent; _hashCode = GenerateHashCode(); } /// <summary> /// Gets the amount of the quantity. /// </summary> public T Amount { get; } /// <summary> /// Gets the unit of the quantity. /// </summary> public Unit Unit { get; } /// <summary> /// Converts the quantity to a specified unit. /// </summary> /// <param name="unit">The target unit to convert to.</param> /// <returns>The converted quantity.</returns> /// <exception cref="InvalidOperationException">Thrown if the units are not of the same dimension.</exception> [Pure] public Quantity<T> Convert(Unit unit) { if (Unit == unit) return this; Check.UnitsAreSameDimension(Unit, unit); return CreateQuantity(_coherent.Amount.Divide(unit.Factor), unit, _coherent); } /// <summary> /// Converts the quantity to its coherent representation. /// </summary> /// <returns>The coherent quantity.</returns> [Pure] internal virtual Quantity<T> ToCoherent() { var unit = Unit; if (unit.IsCoherent) { return this; } var coherentUnit = unit.System.MakeCoherent(unit); return CreateQuantity(Amount.Multiply(unit.Factor), coherentUnit, _coherent); } /// <summary> /// Creates a new instance of the <see cref="Quantity{T}"/> class. /// </summary> /// <param name="amount">The amount of the quantity.</param> /// <param name="unit">The unit of the quantity.</param> /// <param name="coherent">The coherent quantity.</param> /// <returns>A new instance of the <see cref="Quantity{T}"/> class.</returns> [Pure] protected abstract Quantity<T> CreateQuantity(T amount, Unit unit, Quantity<T> coherent); /// <summary> /// Generates a hash code for the quantity. /// </summary> /// <returns>The hash code for the quantity.</returns> [Pure] private int GenerateHashCode() => HashCode.Combine(Amount, Unit, _coherent); }
package com.example.booktrackerapp.widgets import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountBox import androidx.compose.material.icons.filled.AddCircle import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Composable fun CameraControls( modifier: Modifier = Modifier, onTakePicture: () -> Unit, onSwitchCamera: () -> Unit, onCancelPreview: () -> Unit, onOpenGallery: () -> Unit ) { Box(modifier = modifier.fillMaxSize()) { IconButton(onClick = onCancelPreview, modifier = Modifier.align(Alignment.TopStart)) { Icon( imageVector = Icons.Default.Close, contentDescription = "Cancel Preview", tint = Color.White ) } Row( modifier = Modifier.align(Alignment.BottomCenter), verticalAlignment = Alignment.CenterVertically ) { IconButton(onClick = onOpenGallery , modifier = Modifier.size(60.dp)) { Icon( imageVector = Icons.Default.AccountBox, contentDescription = "Switch Camera", tint = Color.White ) } Spacer(modifier = Modifier.width(8.dp)) IconButton(onClick = { onTakePicture() }, modifier = Modifier.size(60.dp)) { Icon( imageVector = Icons.Default.AddCircle, contentDescription = "Take Picture", tint = Color.White ) } Spacer(modifier = Modifier.width(8.dp)) IconButton(onClick = onSwitchCamera, modifier = Modifier.size(60.dp)) { Icon( imageVector = Icons.Default.Refresh, contentDescription = "Switch Camera", tint = Color.White ) } } } }
import React, { useState } from "react"; import Todo from "../Modals/Todo"; import { DropResult } from "react-beautiful-dnd"; //different states of todos to manipilate when change their position using dnd const useTodos = () => { const [todosList, setTodosList] = useState<Todo[]>([]); const [todosPending, setTodosPending] = useState<Todo[]>([]); const [todosCompleted, setTodosCompleted] = useState<Todo[]>([]); const addTodo = (newTodo: Todo) => { setTodosList([...todosList, newTodo]); }; const updateTodo = (newTodo: Todo) => { setTodosList( todosList.map((newItem) => newItem.id === newTodo.id ? newTodo : newItem ) ); }; const deleteTodo = (id: number) => { const newTodosList = todosList.filter((newItem) => newItem.id !== id); setTodosList(newTodosList); }; const toggleTodo = (id: number) => { setTodosList((prevTodos) => prevTodos.map((todo) => todo.id === id ? { ...todo, done: !todo.done } : todo ) ); }; // here i create logic for dnd const onDragEnd = (result: DropResult) => { const { destination, source } = result; if (!destination) { return; } if ( destination.droppableId === source.droppableId && destination.index === source.index ) { return; } let move; if (source.droppableId === "TodosList") { move = todosList[source.index]; todosList.splice(source.index, 1); } else if (source.droppableId === "completedList") { move = todosCompleted[source.index]; todosCompleted.splice(source.index, 1); } else { move = todosPending[source.index]; todosPending.splice(source.index, 1); } if (destination.droppableId === "TodosList") { todosList.splice(destination.index, 0, move); } else if (destination.droppableId === "completedList") { todosCompleted.splice(destination.index, 0, move); } else { todosPending.splice(destination.index, 0, move); } setTodosPending(todosPending); setTodosList(todosList); setTodosCompleted(todosCompleted); }; return { todosList, setTodosList, todosPending, setTodosPending, todosCompleted, setTodosCompleted, addTodo, deleteTodo, updateTodo, toggleTodo, onDragEnd, }; }; export default useTodos;
import React from 'react'; import Task from '../components/task'; import boardState from '../util/board-state'; import { fireEvent, render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { createColumnJson, createKanbanJson, createTaskJson } from '../util/kanban-types'; import { randomString, rightClick } from '../util/test-helpers'; function* taskSetup() { const defaultKanban = createKanbanJson('', [createColumnJson('', [createTaskJson()])]); const defaultColumn = defaultKanban.cols[0]; const defaultTask = defaultColumn.tasks[0]; const wrapper = render( <Task data={defaultTask} index={0} columnId={defaultColumn.id} columnIndex={0} defaultToEdit={false} columnColor={'#ffffff'} /> ); const task = wrapper.container.firstElementChild as HTMLDivElement; yield task; wrapper.unmount(); } jest.mock('react-beautiful-dnd', () => { const dragDropElem = ({ children }: { children: Function }) => children( { draggableProps: { style: {}, }, innerRef: jest.fn(), }, {} ); return { Droppable: dragDropElem, Draggable: dragDropElem, DragDropContext: ({ children }: { children: Function }) => children, }; }); jest.mock('react-markdown', () => (props: any) => { return <>{props.children}</>; }); jest.mock('remark-gfm', () => () => {}); jest.mock('remark-breaks', () => () => {}); describe('<Task>', () => { it('Renders a task', () => { const taskData = createTaskJson(randomString()); const wrapper = render( <Task data={taskData} index={0} columnId={''} columnIndex={0} defaultToEdit={false} columnColor={'#ffffff'} /> ); const task = wrapper.container.firstElementChild as HTMLDivElement; const textArea = task.querySelector('textarea')!; expect(textArea.value).toBe(taskData.text); expect(textArea.style.display).toBe('none'); const displayArea = task.querySelector('.task-display') as HTMLDivElement; expect(displayArea.style.display).not.toBe('none'); wrapper.unmount(); }); it('Can render a task in edit mode', () => { const wrapper = render( <Task data={createTaskJson()} index={0} columnId={''} columnIndex={0} defaultToEdit={true} columnColor={'#ffffff'} /> ); const task = wrapper.container.firstElementChild as HTMLDivElement; const displayArea = task.querySelector('.task-display') as HTMLDivElement; expect(displayArea.style.display).toBe('none'); const textArea = task.querySelector('textarea')!; expect(textArea.style.display).not.toBe('none'); }); it('Is deleted when you click the delete button', () => { const setup = taskSetup(); const task = setup.next().value as HTMLDivElement; const deleteButton = task.querySelector('a.task-delete')!; const removeTaskSpy = jest.spyOn(boardState, 'removeTask'); userEvent.click(deleteButton); jest.runAllTimers(); expect(removeTaskSpy).toHaveBeenCalled(); setup.next(); }); describe('Text Display', () => { function* displayClicking(task: HTMLDivElement) { const displaySection = task.querySelector('.task-display') as HTMLDivElement; const textarea = task.querySelector('textarea')!; userEvent.click(displaySection); userEvent.click(textarea); yield textarea; fireEvent.blur(textarea); } it('Is editable', () => { const setup = taskSetup(); const task = setup.next().value as HTMLDivElement; const clicker = displayClicking(task); const textarea = clicker.next().value as HTMLTextAreaElement; const editSpy = jest.spyOn(boardState, 'setTaskText'); userEvent.type(textarea, 'blah blah'); textarea.blur(); expect(editSpy).toHaveBeenCalled(); setup.next(); }); it('Shows and hides the textarea', () => { const setup = taskSetup(); const task = setup.next().value as HTMLDivElement; const textarea = task.querySelector('textarea')!; expect(textarea.style.display).toBe('none'); const clicker = displayClicking(task); clicker.next(); expect(textarea.style.display).not.toBe('none'); clicker.next(); expect(textarea.style.display).toBe('none'); setup.next(); }); }); // Userevent not working with keyboard shortcuts for some reason });
<section id="idiomas"> <form [formGroup]="form" (ngSubmit)="onEnviar($event)"> <div> <label for="puesto" class="form-label">puesto: </label> <input class="form-control" type="text" formControlName="puesto" [ngClass]="{'is-invalid': Puesto.errors && Puesto.touched, 'is-valid': !Puesto.errors && Puesto.touched}" /> <div *ngIf="Puesto.errors && Puesto.touched" class="invalid-feedback"> <div *ngIf="Puesto.errors['required']">El puesto es requerido</div> </div> </div> <div> <label for="institucion" class="form-label">institucion: </label> <input class="form-control" type="text" formControlName="institucion" [ngClass]="{'is-invalid': Institucion.errors && Institucion.touched, 'is-valid': !Institucion.errors && Institucion.touched}" /> <div *ngIf="Institucion.errors && Institucion.touched" class="invalid-feedback"> <div *ngIf="Institucion.errors['required']">La Institucion es requerida</div> </div> </div> <div> <label for="inicio" class="form-label">inicio: </label> <input class="form-control" type="date" formControlName="inicio" [ngClass]="{'is-invalid': Inicio.errors && Inicio.touched, 'is-valid': !Inicio.errors && Inicio.touched}" /> <div *ngIf="Inicio.errors && Inicio.touched" class="invalid-feedback"> <div *ngIf="Inicio.errors['required']">El Inicio es requerido</div> </div> </div> <div> <label for="fin" class="form-label">fin: </label> <input class="form-control" type="date" formControlName="fin" [ngClass]="{'is-invalid': Fin.errors && Fin.touched, 'is-valid': !Fin.errors && Fin.touched}" /> <div *ngIf="Fin.errors && Fin.touched" class="invalid-feedback"> <div *ngIf="Fin.errors['required']">El Fin es requerido</div> </div> </div> <div> <label for="descripcion" class="form-label">descripcion: </label> <input class="form-control" type="text" formControlName="descripcion" [ngClass]="{'is-invalid': Descripcion.errors && Descripcion.touched, 'is-valid': !Descripcion.errors && Descripcion.touched}" /> <div *ngIf="Descripcion.errors && Descripcion.touched" class="invalid-feedback"> <div *ngIf="Descripcion.errors['required']">La Descripcion es requerida</div> </div> </div> <br /> <div> <button type="submit">Agregar</button> </div> </form> </section>
@extends('layout') @section('title', 'Docentes') @section('content') <div class="row"> <div class="col-xs-8 col-sm-8 col-md-8 col-lg-12"> <div class="text-center mt-4 mb-4"> <h2 class="text-primary font-weight-bold">{{ $title }}</h2> </div> <div class="d-flex justify-content-between align-items-end mb-2"> <a href="{{ route('docentes.create') }}" class="btn btn-primary btn-block"> <span class="oi oi-people"></span> Nuevo Docente</a> </div> </div> </div> @if($docentes->isNotEmpty()) <div class="row"> <div class="col-lg-12"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <thead class="thead-dark"> <tr> <th>ID</th> <th>Nombre</th> <th>Documento</th> <th>Opciones</th> </tr> </thead> <tbody> @foreach($docentes as $docente) <tr> <td>{{ $docente->getId() }}</td> <td>{{ $docente->getNombre() }}</td> <td>{{ $docente->getDni() }}</td> <td> <div class="d-flex align-items-center"> @can('docentes.show') <a href="{{ route('docentes.show', $docente) }}" class="btn btn-link mr-2"> <span class="oi oi-eye"></span> </a> @endcan <a href="{{ route('docentes.edit', $docente) }}" class="btn btn-link mr-2"> <span class="oi oi-pencil"></span> </a> <form action="{{ route('docentes.destroy', $docente) }}" method="POST"> {{ csrf_field() }} {{ method_field('DELETE') }} <button type="submit" class="btn btn-link"> <span class="oi oi-trash"></span> </button> </form> </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> @else <p>No hay docentes registrados</p> @endif @endsection @section('sidebar') @parent @endsection
# 从一个其“与”和“异或”之和等于 K 的数组中计数对 > 原文:[https://www . geeksforgeeks . org/从一个数组中计数对,该数组有两次等于 k 的和/异或/](https://www.geeksforgeeks.org/count-pairs-from-an-array-having-sum-of-twice-of-their-and-and-xor-equal-to-k/) 给定一个由 **N** 个整数和一个整数 **K** 组成的[数组](https://www.geeksforgeeks.org/array-data-structure/)**arr【】**,任务是计算满足等式**2 *(arr[I]&arr[j])+(arr[I]^ arr[j])= k .** **示例:** > **输入:** arr[] = {1,5,4,8,7},K = 9 > **输出:** 2 > **解释:** > > 1. 索引 0 和 3 处的元素,即 arr[i] = 1,arr[j] = 8,满足给定的等式。 > 2. 索引 1 和 2 处的元素,即 arr[i] = 5,arr[j] = 4,满足给定的等式。 > > **输入:** arr[] = {1,2,2,4,5},K = 3 > T3】输出: 2 **天真方法:**最简单的方法是[从数组](https://www.geeksforgeeks.org/find-all-pairs-possible-from-the-given-array/)中生成所有可能的对,并针对每一对,检查该对是否满足给定的等式。 ***时间复杂度:**O(N<sup>2</sup>)* ***辅助空间:** O(1)* **高效方法:**上述方法可以基于以下观察进行优化: > ***观察:*** > > *A + B = (A ^ B) + 2 * (A & B)* > > *计算和时,如果两个位都是 **1** (即 AND 为 1),则合成位是 **0** ,加上 **1** 作为进位,这意味着**和**中的每个位都是* [*左移*](https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/)*1,即**和**的值乘以 **2*** > > 因此,A + B =给定的方程。 > > *因此,这验证了上述观察。* 按照以下步骤解决问题: * 问题现在简化为[两个和问题](https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/),任务简化为计算和等于 **K.** 的对 * 初始化一个[无序映射](https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/),比如说 **mp** ,和一个变量,比如说 **cnt** ,来计算满足给定条件的对的数量。 * [遍历数组](https://www.geeksforgeeks.org/c-program-to-traverse-an-array/),对于每个元素: * 如果**MP[K–arr[I]]**不为零,则将其值添加到 **cnt** 中。 * 更新**地图**中**arr【I】**的频率。 * 打印 **cnt** 作为答案。 下面是上述方法的实现: ## C++ ``` // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to count number of pairs // satisfying the given conditions void countPairs(int arr[], int N, int K) {     // Stores the frequency of array elements     unordered_map<int, int> mp;     // Stores the total number of pairs     int cnt = 0;     // Traverse the array     for (int i = 0; i < N; i++) {         // Add it to cnt         cnt += mp[K - arr[i]];         // Update frequency of         // current array element         mp[arr[i]]++;     }     // Print the count     cout << cnt; } // Driver Code int main() {     // Given array     int arr[] = { 1, 5, 4, 8, 7 };     // Size of the array     int N = sizeof(arr) / sizeof(arr[0]);     // Given value of K     int K = 9;     countPairs(arr, N, K);     return 0; } ``` ## Java 语言(一种计算机语言,尤用于创建网站) ``` // Java program for the above approach import java.io.*; import java.util.*; class GFG {     // Function to count number of pairs     // satisfying the given conditions     static void countPairs(int arr[], int N, int K)     {         // Stores the frequency of array elements         Map<Integer, Integer> mp = new HashMap<>();         // Stores the total number of pairs         int cnt = 0;         // Traverse the array         for (int i = 0; i < N; i++)         {             // Add it to cnt             if (mp.get(K - arr[i]) != null)                 cnt += mp.get(K - arr[i]);             // Update frequency of             // current array element             mp.put(arr[i], mp.get(arr[i]) == null                                ? 1                                : mp.get(arr[i]) + 1);         }         // Print the count         System.out.println(cnt);     }     // Driver Code     public static void main(String[] args)     {         // Given array         int arr[] = { 1, 5, 4, 8, 7 };         // Size of the array         int N = arr.length;         // Given value of K         int K = 9;         countPairs(arr, N, K);     } } // This code is contributed by Dharanendra L V ``` ## 蟒蛇 3 ``` # Python3 program for the above approach from collections import defaultdict # Function to count number of pairs # satisfying the given conditions def countPairs(arr, N, K) :     # Stores the frequency of array elements     mp = defaultdict(int)     # Stores the total number of pairs     cnt = 0     # Traverse the array     for i in range(N):         # Add it to cnt         cnt += mp[K - arr[i]]         # Update frequency of         # current array element         mp[arr[i]] += 1     # Print the count     print(cnt) # Driver Code # Given array arr = [ 1, 5, 4, 8, 7 ] # Size of the array N = len(arr) # Given value of K K = 9 countPairs(arr, N, K) # This code is contributed by sanjoy_62. ``` ## C# ``` // C# program for the above approach using System; using System.Collections.Generic; public class GFG {     // Function to count number of pairs     // satisfying the given conditions     static void countPairs(int[] arr, int N, int K)     {         // Stores the frequency of array elements         Dictionary<int, int> mp             = new Dictionary<int, int>();         // Stores the total number of pairs         int cnt = 0;         // Traverse the array         for (int i = 0; i < N; i++) {             // Add it to cnt             if (mp.ContainsKey(K - arr[i]))                 cnt += mp[K - arr[i]];             // Update frequency of             // current array element             if (mp.ContainsKey(arr[i])) {                 var val = mp[arr[i]];                 mp.Remove(arr[i]);                 mp.Add(arr[i], val + 1);             }             else {                 mp.Add(arr[i], 1);             }         }         // Print the count         Console.WriteLine(cnt);     }     // Driver Code     static public void Main()     {         // Given array         int[] arr = { 1, 5, 4, 8, 7 };         // Size of the array         int N = arr.Length;         // Given value of K         int K = 9;         countPairs(arr, N, K);     } } // This code is contributed by Dharanendra L V ``` ## java 描述语言 ``` <script>     // JavaScript program for the above approach     // Function to count number of pairs     // satisfying the given conditions     function countPairs(arr,N,K)     {         // Stores the frequency of array elements         let mp = new Map();         // Stores the total number of pairs         let cnt = 0;         // Traverse the array         for (let i = 0; i < N; i++) {             // Add it to cnt             if(mp.has(K - arr[i]))             {                 cnt += mp.get(K - arr[i]);             }             // Update frequency of             // current array element             if(mp.has(arr[i]))             {                 mp.set(arr[i], mp.get(arr[i]) + 1);             }             else{                 mp.set(arr[i], 1);             }         }         // Print the count         document.write(cnt);     }     // Driver Code     // Given array     let arr = [ 1, 5, 4, 8, 7 ];     // Size of the array     let N = arr.length;     // Given value of K     let K = 9;     countPairs(arr, N, K); </script> ``` **Output:**  ``` 2 ``` ***时间复杂度:**O(N)* T5**辅助空间:** O(N)
package com.hyunsungkr.pethotel.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.hyunsungkr.pethotel.AllNearbyHotelsActivity; import com.hyunsungkr.pethotel.R; import com.hyunsungkr.pethotel.model.Hotel; import org.w3c.dom.Text; import java.util.ArrayList; public class AllnearhotelAdapter extends RecyclerView.Adapter<AllnearhotelAdapter.ViewHolder> { public interface OnItemClickListener{ void onCardViewClick(int index); } public OnItemClickListener listener; public void setOnItemClickListener(OnItemClickListener listener){ this.listener = listener; } Context context; ArrayList<Hotel> hotelList; public AllnearhotelAdapter(Context context, ArrayList<Hotel> hotelList) { this.context = context; this.hotelList = hotelList; } @NonNull @Override public AllnearhotelAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.search_row, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull AllnearhotelAdapter.ViewHolder holder, int position) { Hotel hotel = hotelList.get(position); holder.txtTitle.setText(hotel.getTitle()); holder.txtAvg.setText(String.format("%.1f", hotel.getAvg())); holder.txtCnt.setText("("+hotel.getCnt()+")"); // ratingBar 채우기 holder.ratingBar.setRating((float) hotel.getAvg()); if(hotel.getFavorite() == 1){ holder.imgFavorite.setImageResource(R.drawable.baseline_favorite_24); }else{ holder.imgFavorite.setImageResource(R.drawable.baseline_favorite_border_24); } Glide.with(context).load(hotel.getImgUrl()).placeholder(R.drawable.icon1).into(holder.imgPhoto); } @Override public int getItemCount() { return hotelList.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ CardView cardView; ImageView imgPhoto; TextView txtTitle; ImageView imgFavorite; RatingBar ratingBar; TextView txtAvg; TextView txtCnt; public ViewHolder(@NonNull View itemView) { super(itemView); cardView = itemView.findViewById(R.id.cardView); imgPhoto = itemView.findViewById(R.id.imgPhoto); txtTitle = itemView.findViewById(R.id.txtTitle); imgFavorite = itemView.findViewById(R.id.imgFavorite); ratingBar = itemView.findViewById(R.id.ratingBar); txtAvg = itemView.findViewById(R.id.txtAvg); txtCnt = itemView.findViewById(R.id.txtCnt); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int index = getAdapterPosition(); listener.onCardViewClick(index); } }); imgFavorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 어느번째의 데이터의 좋아요를 누른 것인지 확인 int index = getAdapterPosition(); ((AllNearbyHotelsActivity)context).favoriteProcess(index); } }); } } }
# 在这里,我并不局限于本题,希望在求解本题的基础上,带给大家更大的提升和拓展。 **除了本文的介绍,个人认为在表达式的处理领域还有非常多经典和值得探讨的问题 大家可以参考[https://blog.csdn.net/qq_21515253/article/details/96484567]() 此文中对整个问题做了详细的分析和总结。** ### 逆波兰算法: **核心思想**是将普通的中缀表达式转换为后缀表达式。(关于表达式的理解可以去查询DS中关于二叉树的遍历的描述,这里不再赘述) **后缀表达式**:运算符在两个操作数的后面。后缀表达式虽然看起来奇怪,不利于人阅读,但利于计算机处理。 #### 1、后缀表达式(逆波兰式)求值 比较简单,直接上伪代码: ``` function suffixToResult: for each element in suffix_expression { if(element is number) { stack.push(element) } else if(element is operator) { num1 = stack.pop() num2 = stack.pop() value = num1 + element + num2 stack.push(value) } return stack.pop() } } ``` #### 2、中缀表达式转化为后缀表达式 这是算法的难点,也是重中之重 **算法思想:** 设置一个stack和一个linear list 其中stack临时存放运算符和左括号的 linear list存放后缀表达式 ``` if number : list.add(number) if (: stack.push('(') if ): while(stack.pop == '(') if operator: if stack.peek() is not operator: stack.push(operator) else : if operator > stack.peek(): stack.push(operator) else while(stack.peek() <= operator) stack.pop() ``` **算法实现** ```java class solution { public void getVlaue(String string) { System.out.println(suffixToResult(infixToSuffix(string))); } private boolean isNumber(char character) { return character >= '0' && character <= '9'; } private boolean isOperator(char character) { return !isNumber(character) && character != '(' && character != ')'; } private int priority(char character) { if (character == '+' || character == '-') { return 1; } else { return 2; } } private Integer toNumber(String expr) { int flag = 0; //["10","6","9","3","+","-11","*","/","*","17","+","5","+"] if (expr.charAt(0) == '-') { expr = expr.substring(1); flag = 1; } int number = 0; int bit = 1; for (int i = expr.length() - 1; i >= 0; i--) { number = number + (expr.charAt(i) - '0') * bit; bit *= 10; } if (flag == 0) { return number; } else { return -1 * number; } } public List<String> infixToSuffix(String expr) { Stack<Character> stack = new Stack<>(); ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < expr.length(); i++) { if (expr.charAt(i) >= '0' && expr.charAt(i) <= '9') { String numExpr = ""; while (i < expr.length() && isNumber(expr.charAt(i))) { numExpr = numExpr + expr.charAt(i); i++; } i--; list.add(numExpr); } else if (expr.charAt(i) == '(') { stack.push(expr.charAt(i)); } else if (expr.charAt(i) == ')') { while (!stack.isEmpty() && stack.peek() != '(') { list.add("" + stack.pop()); } if (!stack.isEmpty()) { stack.pop(); } } else { while (!stack.isEmpty() && isOperator(stack.peek()) && priority(stack.peek()) >= priority(expr.charAt(i))) { //System.out.println(priority(stack.peek())); //System.out.println(priority(expr.charAt(i))); list.add(stack.pop() + ""); } stack.push(expr.charAt(i)); } //System.out.println(stack); //System.out.println(list); //System.out.println("-----"); } while (!stack.isEmpty()) { list.add(stack.pop() + ""); } return list; } public int suffixToResult(List<String> list) { //System.out.println(list); Stack<Integer> stack = new Stack<>(); for (String element : list) { if (isNumber(element.charAt(0)) || (element.length() > 1 && isNumber(element.charAt(1)))) { //System.out.println(toNumber(element)); stack.push(toNumber(element)); } else { //System.out.println(stack); Integer num1 = stack.pop(); Integer num2 = stack.pop(); Integer value = 0; if (element.charAt(0) == '+') { value = num2 + num1; } else if (element.charAt(0) == '-') { value = num2 - num1; } else if (element.charAt(0) == '*') { value = num2 * num1; } else if (element.charAt(0) == '/') { value = num2 / num1; } System.out.println(num2); System.out.println(num1); System.out.println("***" + value); stack.push(value); } } return stack.pop(); } } ``` ### 讨论完逆波兰,还有点意犹未尽,是不是想一起讨论下跟逆波兰有同样作用和地位的递归下降呀。 来了!! ### 递归下降算法 递归下降是编译原理中词法分析的重要方法,而利用递归下降进行表达式求值,也是一个强烈推荐的手段!!!思考简单!!逻辑清晰!!! #### 核心思想 递归下降分析来求表达式的值。表达式的文法如下 ``` expr = term {+、-} term term = factor {*、/} factor factor = (expr) or number ``` ​ 其实原理就这么简单,层层递归即可 #### 代码实现 直接上代码,一看就知 ```java class Solution { int cur = 0; String str = ""; public double cal(String s) { this.str = s; return expression(); } public double expression() { double num1 = term(); double num2; while (cur < str.length() && (str.charAt(cur) == '+' || str.charAt(cur) == '-')) { char op = str.charAt(cur); cur++; num2 = term(); if (op == '+') { num1 += num2; } else { num1 -= num2; } } if (cur < str.length() && str.charAt(cur) == ')') { cur++; } return num1; } public double term() { double num1 = factor(); double num2; while (cur < str.length() && (str.charAt(cur) == '*' || str.charAt(cur) == '/')) { char op = str.charAt(cur); cur++; num2 = factor(); if (op == '*') { num1 *= num2; } else { num1 /= num2; } } return num1; } public double factor() { double result; if (str.charAt(cur) == '(') { cur++; return expression(); } else { String string = ""; while (cur < str.length() && isNumber(str.charAt(cur)) ) { string = string + str.charAt(cur); cur++; } result = toNumber(string); } return result; } private boolean isNumber(char character) { return character >= '0' && character <= '9'; } private Integer toNumber(String expr) { int flag = 0; //["10","6","9","3","+","-11","*","/","*","17","+","5","+"] if (expr.charAt(0) == '-') { expr = expr.substring(1); flag = 1; } int number = 0; int bit = 1; for (int i = expr.length() - 1; i >= 0; i--) { number = number + (expr.charAt(i) - '0') * bit; bit *= 10; } if (flag == 0) { return number; } else { return -1 * number; } } } ```
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use SimpleSoftwareIO\QrCode\Facades\QrCode; class AuthController extends Controller { public function register() { return view('auth/register'); } public function c_register() { return view('auth/coach_register'); } public function p_register($id) { $user = User::where('uuid', $id)->first(); return view('auth/player_register', ['user'=>$user]); } public function registerSave(Request $request) { Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required|confirmed' ])->validate(); User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), 'type' => 0 ]); return redirect()->route('login'); } public function c_registerSave(Request $request) { Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'team_name' => 'required', 'school_name' => 'required', 'sports' => 'required', 'password' => 'required|confirmed' ])->validate(); $number = rand(000000,999999); $baseUrl = $request->root(); $user = User::create([ 'name' => $request->name, 'team_name' => $request->team_name, 'school_name' => $request->school_name, 'sports' => $request->sports, 'email' => $request->email, 'password' => Hash::make($request->password), 'type' => "0", 'uuid'=> $number ]); $baseUrl = $request->root(); $link = url($baseUrl . '/players/registration/' . $user->uuid); $user->link = $link; $user->save(); $qrCodes= QrCode::size(150)->generate($link); return view('auth/registration_confirmation', [ 'user' => $user, 'qrcode' => $qrCodes, 'link' => $link ]); } public function p_registersave(Request $request) { Validator::make($request->all(), [ 'name' => 'required', 'address' => 'required', 'sports' => 'required', 'guardian' => 'required', 'email' => 'required|email', 'emails' => 'required', 'password' => 'required|confirmed', 'photo' => 'required|image|mimes:jpeg,png,jpg|max:5000', ])->validate(); $serializedEmails = json_encode(explode(',', $request->emails)); $photoUrl=null; if ($request->hasFile('photo')) { $file = $request->file('photo'); $ext = $request->photo->getClientOriginalExtension(); $fileName = time() . rand(1, 100) . '.' . $ext; $file->move(public_path('upload'), $fileName); // $banner->image = $fileName; $number = rand(000000,999999); $user = User::create([ 'coach_id' => $request->user_id, 'team_name' => $request->team_name, 'sports' => $request->sports, 'name' => $request->name, 'address' => $request->address, 'parent_name' => $request->guardian, 'email' => $request->email, 'password' => Hash::make($request->password), 'photo'=> $fileName, 'emails' => $serializedEmails, 'type' => 1, 'uuid'=> $number ]); $baseUrl = $request->root(); $link = url($baseUrl . '/donate/' . $user->uuid); return view('auth.player_registered',['link' => $link]); }} public function login(Request $request) { return view('auth/login'); } public function loginAction(Request $request) { Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required' ])->validate(); if (!Auth::attempt($request->only('email', 'password'), $request->boolean('remember'))) { throw ValidationException::withMessages([ 'email' => trans('auth.failed') ]); } $request->session()->regenerate(); if (auth()->user()->type == 1) { return redirect()->route('admin/home'); } else { return redirect()->route('admin/home'); } //return redirect()->route('dashboard'); } public function logout(Request $request) { Auth::guard('web')->logout(); $request->session()->invalidate(); return redirect('/login'); } public function profile() { return view('userprofile'); } }
package book.hfdp.ch04_factory_pattern.abstract_factory_pattern; public class PepperoniPizza extends PizzaV2{ PizzaIngredientFactory ingredientFactory; public PepperoniPizza(PizzaIngredientFactory ingredientFactory) { this.ingredientFactory = ingredientFactory; } @Override void prepare() { System.out.println("준비 중 : " + name); dough = ingredientFactory.createDough(); sauce = ingredientFactory.createSauce(); cheese = ingredientFactory.createChease(); pepperoni = ingredientFactory.createPepperoni(); } }
import homePage from '../pages/home.page.js'; import searchPage from '../pages/search.page.js'; import {searchWord, searchResult} from '../../constants/constants.js'; before(async () => { await homePage.open(); }); describe('Filter Test', () => { it('Search for a product', async () => { await homePage.search(searchWord); expect(searchPage.searchResultLabel()).toHaveTextContaining(searchResult); }); it('Filter by price', async () => { await searchPage.filterResult(1); expect(browser).toHaveUrlContaining('&sort=cheap'); }); it('Validate filtered result', async () => { let result = await searchPage.getFirstSecondItemPrice(); expect(parseFloat(result[1])).toBeGreaterThan(parseFloat(result[0])); }); });
package com.developeriq.metricesapi.services; import com.developeriq.metricesapi.dto.CommitDetailsDto; import com.developeriq.metricesapi.dto.IssuesDetailsDto; import com.developeriq.metricesapi.model.*; import com.developeriq.metricesapi.repository.CommitDetailsRepository; import com.developeriq.metricesapi.repository.IssueDetailsRepository; import com.developeriq.metricesapi.utils.GitHubServices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @Service public class MetricsService { @Autowired GitHubServices gitHubServices; @Autowired CommitDetailsRepository commitDetailsRepository; @Autowired IssueDetailsRepository issueDetailsRepository; public Mono<List<CommitDetailsDto>> fetchCommits(String owner, String reponame) { return gitHubServices.getCommits(owner,reponame) .doOnSuccess(commitDetailsDtos -> commitDetailsDtos.forEach(commitDetailsDto -> { CommitDetails commitDetails = new CommitDetails(); commitDetails.setShaValue(commitDetailsDto.getShaValue()); commitDetails.setNodeId(commitDetailsDto.getNodeId()); commitDetails.setUrl(commitDetailsDto.getUrl()); commitDetails.setHtmlUrl(commitDetailsDto.getHtmlUrl()); commitDetails.setParentCommits(commitDetailsDto.getParents() .stream().map(parent -> { ParentCommits parentCommits = new ParentCommits(); parentCommits.setSha(parent.getSha()); parentCommits.setHtmlUrl(parent.getHtmlUrl()); parentCommits.setUrl(parent.getUrl()); parentCommits.setCommitDetails(commitDetails); return parentCommits; }).collect(Collectors.toList())); CommitDetailsDto.Commit.Person author = commitDetailsDto.getCommit().getAuthor(); commitDetails.setAuthor(PersonDetails.builder().name(author.getName()) .email(author.getEmail()).date(author.getDate()).authorDetails(commitDetails).build()); CommitDetailsDto.Commit.Person commiter = commitDetailsDto.getCommit().getCommitter(); commitDetails.setCommiter(PersonDetails.builder().name(commiter.getName()) .email(commiter.getEmail()).date(commiter.getDate()).committerDetails(commitDetails).build()); commitDetailsRepository.save(commitDetails); })) .doOnError(Throwable::printStackTrace); } public Mono<List<IssuesDetailsDto>> fetchListOfIssues(String owner, String reponame) { return gitHubServices.getIssues(owner,reponame) .doOnSuccess(issuesDetailsDtos -> { issuesDetailsDtos.forEach(issuesDetailsDto -> { IssuesDetailsDto.User user = issuesDetailsDto.getUser(); UserDetails userDetails = UserDetails.builder() .login(user.getLogin()) .nodeId(user.getNodeId()) .avatarUrl(user.getAvatarUrl()) .gravatarId(user.getGravatarId()) .url(user.getUrl()) .htmlUrl(user.getHtmlUrl()) .followUrl(user.getFollowers_url()) .gistsUrl(user.getGistsUrl()) .starredUrl(user.getStarredUrl()) .subscriptionsurl(user.getSubscriptionsUrl()) .organizationsUrl(user.getOrganizationsUrl()) .reposUrl(user.getOrganizationsUrl()) .eventsUrl(user.getEventsUrl()) .receivedEventsUrl(user.getReceivedeventsUrl()) .type(user.getType()) .build(); IssuesDetails.IssuesDetailsBuilder issuDetBuldr= IssuesDetails.builder() .url(issuesDetailsDto.getUrl()) .number(issuesDetailsDto.getNumber()) .title(issuesDetailsDto.getTitle()) .repository_url(issuesDetailsDto.getRepoUrl()) .commentsUrl(issuesDetailsDto.getCommentsUrl()) .htmlUrl(issuesDetailsDto.getHtmlUrl()) .nodeId(issuesDetailsDto.getNodeId()) .state(issuesDetailsDto.getState()) .locked(issuesDetailsDto.isLocked()) .body(issuesDetailsDto.getBody()) .author_association(issuesDetailsDto.getAuthorAssociation()) .createdAt(issuesDetailsDto.getCreatedAt()) .milestone(issuesDetailsDto.getMilestone()) .user(userDetails) .assignee(userDetails) .assignees(Collections.singletonList(userDetails)); IssuesDetails issuesDetails = issuDetBuldr.build(); // THIS IS MAIN ENTITY userDetails.setUserIssuesDetails(issuesDetails); userDetails.setAssigneeIssuesDetails(issuesDetails); userDetails.setAssigneesLst(issuesDetails); issueDetailsRepository.save(issuesDetails); }); }); } }
import React, { useEffect, useState } from "react"; import { FilterCategory, Footer, Navbar, NewsLetter, ServiceHeroSection, } from "../components"; import { WhoWeServeContent } from "../components/Services/index"; import { useParams } from "react-router-dom"; import { doc, getDoc } from "firebase/firestore"; import { db } from "../Firebase"; import Data from '../Data/WhoweserveCategories' export default function WhoWeServer() { const { categoryid } = useParams(); const [servedata, setservedata] = useState(); const decodedCategory = decodeURIComponent(categoryid); const defaultData = Data.find( (item) => item.catgeory === decodedCategory ); useEffect(() => { const fetchData = async () => { const documentRef = doc(db, "WHO-WE-SERVE", categoryid); const documentSnapshot = await getDoc(documentRef); setservedata(documentSnapshot.data()); // console.log(documentSnapshot.data()); }; fetchData(); window.scrollTo(0, 0); }, [categoryid]); return ( <div className="overflow-x-clip"> <main> <Navbar Page={"whatwedo"} /> <ServiceHeroSection image={defaultData.image} Tittle={defaultData.Tittle} Para={defaultData.Para} /> <div className="flex flex-col items-start justify-center gap-10 px-5 mt-4 md:px-12 lg:px-24 lg:flex-row"> <FilterCategory Tittle={"Who We Serve"} Page={"whoweserve"} /> <WhoWeServeContent data={servedata} /> </div> <NewsLetter /> <Footer /> </main> </div> ); }
import { TeamModel } from './../models/team.model'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { v4 as newGuid } from 'uuid'; function init() { return { id: new FormControl(newGuid(), Validators.required), name: new FormControl(null, [Validators.required, Validators.minLength(2)]), picturePath: new FormControl(null), }; } export class TeamForm extends FormGroup { get id() { return this.get('id') as FormControl; } get name() { return this.get('name') as FormControl; } get picturePath() { return this.get('picturePath') as FormControl; } constructor() { super(init()); } public toModel() { return new TeamModel(this.id.value, this.name.value, this.picturePath.value); } }
--- title: Figures for Cyanobook toc: true toc-depth: 3 code-fold: true --- This is the first pass of figures for the Cyano book. Figures are created individually and then combined into multi-part figures. For the largest figure, I show the individual panels one-by-one along with questions. Then at the end I put them together. ## Setup Load packages and data, but only the data we need for these figures. ```{r} #| message: false knitr::opts_chunk$set(out.width = "60%", fig.width = 5, fig.height = 4) library(tidyverse) library(readxl) library(janitor) library(patchwork) cyano <- read_excel("Data/PMODEL_Data for Steff Figs.xlsx", sheet = "Fig_Ch2", skip = 2) |> clean_names() |> select(source, lake, tp_epi, osgood, trophy, afsum, chl, secchi, humic, doc, color, pri_proa, bac, z, tn, coldfish, fishabun) blu <- "blue3" # Standard point colour ``` ## Figure 2.3 This figure only uses values where the anoxic factor is > 0 ```{r} fig2_3 <- filter(cyano, afsum > 0) ``` **Getting the morphometric ratio lines** morphometric ratio (osgood) = z/Ao0.5 afsum = -36.2 + 50.12 * log10(tp_epi) + 0.762 * osgood ```{r} mr <- expand_grid(osgood = seq(0, 30, 2.5), tp_epi = seq(1, 100)) |> mutate(afsum = -36.2 + 50.12 * log10(tp_epi) + 0.762 * osgood) ``` > **Work in Progress**: > > - Need: How are the morphometric ratio lines created? > - Below doesn't look right... ```{r} #| fig-width: 8 #| fig-height: 3 #| fig-dpi: 600 #| out-width: 100% g1 <- ggplot(fig2_3, aes(x = tp_epi, y = afsum)) + theme_classic() + geom_point(na.rm = TRUE) + scale_x_log10(limits = c(5, 100), minor_breaks = c(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)) + scale_y_continuous(limits = c(0, 100)) + geom_line(data = mr, aes(group = osgood), alpha = 0.4) + labs(x = bquote('TP'~(mu*g/L)), y = bquote("Anoxic Factor"~(d/summer))) + annotation_logticks(sides = "b") g2 <- ggplot(drop_na(fig2_3, trophy), aes(x = afsum, y = osgood, size = trophy)) + theme_classic() + geom_point(na.rm = TRUE, alpha = 0.4) + ylim(0, 50) + xlim(0, 100) + labs(x = bquote("Anoxic Factor"~(d/summer)), y = bquote("Morphometric ratio"~(m/km^2)), size = "Tropic level") g1 + g2 + plot_annotation(tag_levels = "A", tag_prefix = "(", tag_suffix = ")") ``` ## Figure 2.4 > **Consider:** > > **Putting the fish plots as a separate plot** > > - They have a different scale of data (TP much more limited) > - The y axis is not log10 > > **Data isn't the same as in the example plots** > > - Is this okay? > - Or should I be filtering data? ### Setup the data ```{r} fig2_4 <- cyano |> drop_na(tp_epi) |> mutate(humic_fct = if_else(humic == 1, "Coloured", "Clear")) ``` ### Get stats ```{r} s <- tibble( y = c("chl", "secchi", "doc", "color", "pri_proa", "bac", "coldfish", "fishabun"), m = list(lm(log10(chl) ~ log10(tp_epi), data = fig2_4), lm(log10(secchi) ~ log10(tp_epi), data = fig2_4), lm(log10(doc) ~ log10(tp_epi), data = fig2_4), lm(log10(color) ~ log10(tp_epi), data = fig2_4), lm(log10(pri_proa) ~ log10(tp_epi), data = fig2_4), lm(log10(bac) ~ log10(tp_epi), data = fig2_4), lm(coldfish ~ log10(tp_epi), data = fig2_4), lm(fishabun ~ log10(tp_epi), data = fig2_4))) |> mutate(r2 = map_dbl(m, \(x) summary(x)$adj.r.squared), p = map_dbl(m, \(x) summary(x)$coefficients[2, 4]), # Get the non-intercept p-value sig = p < 0.05, n = map_dbl(m, \(x) length(residuals(x))), r2 = paste0("R^2 == ", round(r2, 2)), n = paste0("n == ", n), #lab = paste0("atop(", r2, ", ~", n, ")")) lab = paste0(r2, "*';'~", n)) ``` ```{r} gt::gt(select(s, -m)) ``` ### Setup base plots ```{r} tp_lim <- c(10, 30) # Keep 100? y_breaks <- c(0.1, 1, 10, 100, 1000) pnt_alpha <- 0.6 # y-Log base plot g0 <- ggplot(fig2_4, aes(x = tp_epi)) + theme_classic() + theme(plot.margin = margin(), plot.tag.position = c("topleft")) + scale_x_log10(name = bquote('TP'~(mu*g/L)), breaks = c(1, 10, 100, 1000), limits = c(1, 1000)) + scale_y_log10(breaks = y_breaks) + annotation_logticks() # Non-y-log base plot g0.1 <- ggplot(fig2_4, aes(x = tp_epi)) + theme_classic() + theme(plot.margin = margin()) + scale_x_log10(name = bquote('TP'~(mu*g/L)), limits = c(5, 50), breaks = c(1, 10, 20, 30, 40, 50)) + annotation_logticks(sides = "b") ``` ### Create the figures #### Chlorophyl :::{.panel-tabset} ##### Figure ```{r} g1 <- g0 %+% drop_na(fig2_4, chl) + geom_point(aes(y = chl), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = chl), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + #geom_text(data = s[s$y == "chl",], aes(label = lab, x = 1, y = 1000), hjust = 0, vjust = 1, size = 3, parse = TRUE) + labs(y = bquote("Chlorophyll"~(mu*g/L))) g1 ``` ##### Model diagnostics A bit of variability in residuals, probably not a huge problem ```{r} #| fig-width: 8 #| out-width: 100% DHARMa::simulateResiduals(s$m[s$y == "chl"][[1]], plot = TRUE) ``` ::: #### Transparency :::{.panel-tabset} ##### Figure ```{r} g2 <- g0 %+% drop_na(fig2_4, secchi) + theme(legend.title = element_blank(), legend.position = c(0.5, 0.97), legend.direction = "horizontal", legend.background = element_rect(colour = "black"), legend.margin = margin(r = 10)) + geom_point(aes(y = secchi, shape = humic_fct), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = secchi), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + #geom_text(data = s[s$y == "secchi",], aes(label = lab, x = 1, y = 40), hjust = 0, vjust = 1, size = 3, parse = TRUE) + annotate("text", label = "Coloured", x = 3, y = 0.5) + annotate("text", label = "Clear", x = 200, y = 10) + labs(y = bquote("Transparency"~("Secchi, m"))) + scale_shape_manual(values = c("Coloured" = 19, "Clear" = 3)) + scale_y_log10(limits = c(NA, 35), breaks = y_breaks) g2 ``` ##### Model diagnostics A bit of variability in residuals, probably not a huge problem ```{r} #| fig-width: 8 #| out-width: 100% DHARMa::simulateResiduals(s$m[s$y == "secchi"][[1]], plot = TRUE) ``` ::: #### DOC > This is significant, actually... :::{.panel-tabset} ##### Figure ```{r} g3 <- g0 %+% drop_na(fig2_4, doc) + geom_point(aes(y = doc), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = doc), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + #geom_text(data = s[s$y == "doc",], aes(label = lab, x = 1, y = 95), hjust = 0, vjust = 1, size = 3, parse = TRUE) + labs(y = bquote("DOC"~(mg/L))) g3 ``` ##### Model diagnostics A bit of variability in residuals, probably not a huge problem ```{r} #| fig-width: 8 #| out-width: 100% DHARMa::simulateResiduals(s$m[s$y == "doc"][[1]], plot = TRUE) ``` ::: #### Colour :::{.panel-tabset} ##### Figure ```{r} g4 <- g0 %+% drop_na(fig2_4, color) + geom_point(aes(y = color), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = color), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + #geom_text(data = s[s$y == "color",], aes(label = lab, x = 1, y = 400), hjust = 0, vjust = 1, size = 3, parse = TRUE) + labs(y = bquote("Colour"~(HU))) g4 ``` ##### Model diagnostics A bit of variability in residuals, probably not a huge problem ```{r} #| fig-width: 8 #| out-width: 100% DHARMa::simulateResiduals(s$m[s$y == "color"][[1]], plot = TRUE) ``` ::: #### PA :::{.panel-tabset} ##### Figure ```{r} g5 <- g0 %+% drop_na(fig2_4, pri_proa) + geom_point(aes(y = pri_proa), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = pri_proa), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + #geom_text(data = s[s$y == "pri_proa",], aes(label = lab, x = 1, y = 1000), hjust = 0, vjust = 1, size = 3, parse = TRUE) + labs(y = bquote("PA"~(g~C~m^2/yr))) g5 ``` ##### Model diagnostics A bit of variability in residuals, probably not a huge problem ```{r} #| fig-width: 8 #| out-width: 100% DHARMa::simulateResiduals(s$m[s$y == "pri_proa"][[1]], plot = TRUE) ``` ::: #### Bacteria number :::{.panel-tabset} ##### Figure ```{r} g6 <- g0 %+% drop_na(fig2_4, bac) + geom_point(aes(y = bac), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = bac), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + #geom_text(data = s[s$y == "bac",], aes(label = lab, x = 1, y = 25), hjust = 0, vjust = 1, size = 3, parse = TRUE) + labs(y = bquote("Bacteria number"~(10^6/mL))) g6 ``` ##### Model diagnostics A bit of variability in residuals, probably not a huge problem ```{r} #| fig-width: 8 #| out-width: 100% DHARMa::simulateResiduals(s$m[s$y == "bac"][[1]], plot = TRUE) ``` ::: #### Depth ##### Figure ```{r} g7 <- g0 %+% drop_na(fig2_4, z) + geom_point(aes(y = z), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = z), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + labs(y = bquote("Mean Depth"~(m))) g7 ``` #### Total Nitrogen ##### Figure ```{r} g8 <- g0 %+% drop_na(fig2_4, tn) + geom_point(aes(y = tn), colour = blu, na.rm = TRUE, alpha = pnt_alpha) + stat_smooth(aes(y = tn), method = "lm", se = TRUE, na.rm = TRUE, colour = "black") + labs(y = bquote("Total Nitrogen "~(mu*g/L))) g8 ``` ### Combine figures ```{r} #| fig-width: 8 #| fig-height: 9 #| fig-dpi: 600 #| out-width: 100% (g7 + g8) / (g1 + g2) / (g3 + g4) / (g5 + g6) + plot_annotation(tag_levels = "A", tag_prefix = "(", tag_suffix = ")") ``` ### Fish Figures > **Questions** > > - These data don't seem to match the example figures > - By which variables should the symbols be marked? ```{r} #| fig-width: 5 #| fig-height: 5 #| fig-dpi: 600 #| out-width: 50% g7 <- g0.1 + theme(axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank()) + geom_point(aes(y = coldfish), na.rm = TRUE) + labs(y = bquote("Coldwater Fish Species"~("#"))) + geom_vline(xintercept = tp_lim, linetype = "dashed") g8 <- g0.1 + geom_point(aes(y = fishabun), na.rm = TRUE) + labs(y = bquote("Total Fish Species"~("#"))) + geom_vline(xintercept = tp_lim, linetype = "dashed") g7 / g8 + plot_annotation(tag_levels = "A", tag_prefix = "(", tag_suffix = ")") ``` ## Reproducibility ```{r} devtools::session_info() ```
import { IPost } from "../models/interfaces/IPost"; import { useParams } from "react-router-dom"; import { useContext, useEffect, useState } from "react"; import { Context } from ".."; import { ThemeProvider } from "styled-components"; import Avatar from '@mui/material/Avatar'; import Button from '@mui/material/Button'; import CssBaseline from '@mui/material/CssBaseline'; import TextField from '@mui/material/TextField'; import Box from '@mui/material/Box'; import NewspaperIcon from '@mui/icons-material/Newspaper'; import Typography from '@mui/material/Typography'; import Container from '@mui/material/Container'; import { createTheme } from "@mui/material"; import { CommentList } from "../components/lists/comment.list"; import { IComment } from "../models/interfaces/IComment"; import { toJS } from "mobx"; import { GetCurrentTime } from "../utils/time"; import { IUser } from "../models/interfaces/IUser"; const theme = createTheme(); export const PostPage = () => { const { id } = useParams(); const { postStore, commentStore, authStore } = useContext(Context); const [post, setPost] = useState<IPost>({} as IPost); const [author, setAuthor] = useState<IUser>({} as IUser); const [comments, setComments] = useState<IComment[]>([] as IComment[]); const [newComment, setNewComment] = useState<IComment>({ User: toJS(authStore.user) } as IComment); const [updateComments, setUpdateComments] = useState<boolean>(false); const LoadComments = async () => { const currentComments = await commentStore.GetCommentsByPostId(Number(id)); setComments(currentComments); } const Submit = async () => { if (newComment.Text === "") return; newComment.Date = GetCurrentTime(); commentStore.AddComment(newComment); setUpdateComments(true) } useEffect(() => { (async () => { const currentPost = await postStore.GetPost(Number(id)); if (!currentPost) return; setPost(currentPost); setAuthor(currentPost.User) setNewComment({ ...newComment, Post: currentPost }) await LoadComments(); setUpdateComments(false) })(); }, [updateComments]); return ( <ThemeProvider theme={theme}> <Container component="main" maxWidth="md"> <CssBaseline /> <Box sx={{ marginTop: 8, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}> <NewspaperIcon /> </Avatar> <Box component="form" noValidate sx={{ mt: 1 }}> <Typography component="h1" variant="h3" align="center"> {post.Title} </Typography> <Typography component="h1" variant="h5" align="center" marginTop={"25px"}> {post.Content} </Typography> <Typography component="h1" variant="h6" align="center" marginTop={"25px"}> Author: {author.Username} </Typography> </Box> <Box marginTop={"25px"}> <Typography component="h1" variant="h4" align="center"> Comments </Typography> <TextField onChange={e => setNewComment({ ...newComment, Text: e.target.value })} value={newComment.Text || ''} margin="normal" required fullWidth id="email" label="Comment" name="comment" autoFocus /> <Button onClick={Submit} fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} > Comment </Button> </Box> </Box> </Container> <CommentList comments={comments}></CommentList> </ThemeProvider > ); }
import request from 'supertest'; import { app } from '../../src/index'; import { HTTP_STATUSES } from '../../src/common/http-statuses'; import { router } from '../../src/routers'; import { Post } from '../../src/modules/posts/post'; import { User } from '../../src/modules/users/user'; import { Comment } from '../../src/modules/comments/comment'; import { ReqBodyLikeStatus } from '../../src/common/types/reactions'; import { bearerAuth } from '../common/data'; import { createBlog, createComment, createPost, createUser, loginUser } from '../common/tests-helpers'; import { anyString, getErrorsMessages, getPaginationItems } from '../common/helpers'; const createdUsers: User[] = []; const createdPosts: Post[] = []; const createdComments: Comment[] = []; export const testReactionsApi = () => describe('Test reactions', () => { beforeAll(async () => { for (let index = 0; index < 5; index++) { const newUser = await createUser({ isLogin: index === 0, validUserIndex: index }); createdUsers.push(newUser); } const createdBlog = await createBlog(); for (let index = 0; index < 2; index++) { const newPost = await createPost(createdBlog, index); createdPosts.push(newPost); await loginUser(createdUsers[index].login); const newComment = await createComment(createdPosts[0], createdUsers[index]); createdComments.push(newComment); } }); it('Add reaction without auth. Should return 401', async () => { await request(app) .put(`${router.posts}/${createdPosts[0].id}/like-status`) .send({ likeStatus: 'Like' }) .expect(HTTP_STATUSES.UNAUTHORIZED_401); await request(app).get(`${router.posts}/${createdPosts[0].id}`).expect(HTTP_STATUSES.OK_200, createdPosts[0]); await request(app) .put(`${router.comments}/${createdComments[0].id}/like-status`) .send({ likeStatus: 'Like' }) .expect(HTTP_STATUSES.UNAUTHORIZED_401); await request(app) .get(`${router.comments}/${createdComments[0].id}`) .expect(HTTP_STATUSES.OK_200, createdComments[0]); }); it('Add reaction on fakes post and comment. Should return 404', async () => { await request(app) .put(`${router.posts}/fakePostId/like-status`) .set(bearerAuth) .send({ likeStatus: 'Like' }) .expect(HTTP_STATUSES.NOT_FOUND_404); await request(app) .put(`${router.comments}/fakeCommentId/like-status`) .set(bearerAuth) .send({ likeStatus: 'Like' }) .expect(HTTP_STATUSES.NOT_FOUND_404); }); it('Add reaction. Incorrect body cases. Should return 400 and errorsMessages', async () => { const postRes = await request(app) .put(`${router.posts}/${createdPosts[0].id}/like-status`) .set(bearerAuth) .send({ likeStatus: 'invalid' }); expect(postRes.statusCode).toEqual(HTTP_STATUSES.BAD_REQUEST_400); expect(postRes.body).toEqual(getErrorsMessages<ReqBodyLikeStatus>('likeStatus')); expect(postRes.body.errorsMessages).toHaveLength(1); await request(app).get(`${router.posts}/${createdPosts[0].id}`).expect(HTTP_STATUSES.OK_200, createdPosts[0]); const commentRes = await request(app) .put(`${router.comments}/${createdComments[0].id}/like-status`) .set(bearerAuth) .send({ likeStatus: 'invalid' }); expect(commentRes.statusCode).toEqual(HTTP_STATUSES.BAD_REQUEST_400); expect(commentRes.body).toEqual(getErrorsMessages<ReqBodyLikeStatus>('likeStatus')); expect(commentRes.body.errorsMessages).toHaveLength(1); await request(app) .get(`${router.comments}/${createdComments[0].id}`) .expect(HTTP_STATUSES.OK_200, createdComments[0]); }); /* **** Testing Posts *** */ it('Post reaction. Testing by one user', async () => { await loginUser(createdUsers[0].login); const postWithLike: Post = { ...createdPosts[1], extendedLikesInfo: { likesCount: 1, dislikesCount: 0, myStatus: 'Like', newestLikes: [{ login: createdUsers[0].login, addedAt: anyString, userId: createdUsers[0].id }], }, }; const url = `${router.posts}/${createdPosts[1].id}/like-status`; await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); const getRes1 = await request(app).get(`${router.posts}/${createdPosts[1].id}`).set(bearerAuth); expect(getRes1.statusCode).toEqual(HTTP_STATUSES.OK_200); expect(getRes1.body).toEqual(postWithLike); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); const getRes2 = await request(app).get(`${router.posts}/${createdPosts[1].id}`).set(bearerAuth); expect(getRes2.statusCode).toEqual(HTTP_STATUSES.OK_200); expect(getRes2.body).toEqual(postWithLike); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Dislike' }).expect(HTTP_STATUSES.NO_CONTENT_204); const getRes3 = await request(app).get(`${router.posts}/${createdPosts[1].id}`).set(bearerAuth); expect(getRes3.statusCode).toEqual(HTTP_STATUSES.OK_200); expect(getRes3.body).toEqual({ ...postWithLike, extendedLikesInfo: { likesCount: 0, dislikesCount: 1, myStatus: 'Dislike', newestLikes: [] }, }); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'None' }).expect(HTTP_STATUSES.NO_CONTENT_204); const getRes4 = await request(app).get(`${router.posts}/${createdPosts[1].id}`).set(bearerAuth); expect(getRes4.statusCode).toEqual(HTTP_STATUSES.OK_200); expect(getRes4.body).toEqual({ ...postWithLike, extendedLikesInfo: { likesCount: 0, dislikesCount: 0, myStatus: 'None', newestLikes: [] }, }); }); it('Post reaction. Testing by many users', async () => { const url = `${router.posts}/${createdPosts[1].id}/like-status`; await loginUser(createdUsers[0].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[1].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[2].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[3].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[4].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Dislike' }).expect(HTTP_STATUSES.NO_CONTENT_204); const getRes = await request(app).get(`${router.posts}/${createdPosts[1].id}`).set(bearerAuth); expect(getRes.statusCode).toEqual(HTTP_STATUSES.OK_200); expect(getRes.body.extendedLikesInfo.newestLikes.length).toEqual(3); expect(getRes.body).toEqual({ ...createdPosts[1], extendedLikesInfo: { likesCount: 4, dislikesCount: 1, myStatus: 'Dislike', newestLikes: [ { login: createdUsers[3].login, addedAt: anyString, userId: createdUsers[3].id }, { login: createdUsers[2].login, addedAt: anyString, userId: createdUsers[2].id }, { login: createdUsers[1].login, addedAt: anyString, userId: createdUsers[1].id }, ], }, }); }); /* **** Testing Comments *** */ it('Comment reaction. Testing by one user', async () => { await loginUser(createdUsers[0].login); const commentWithLike: Comment = { ...createdComments[1], likesInfo: { likesCount: 1, dislikesCount: 0, myStatus: 'Like' }, }; const url = `${router.comments}/${createdComments[1].id}/like-status`; await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await request(app) .get(`${router.comments}/${createdComments[1].id}`) .set(bearerAuth) .expect(HTTP_STATUSES.OK_200, commentWithLike); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await request(app) .get(`${router.comments}/${createdComments[1].id}`) .set(bearerAuth) .expect(HTTP_STATUSES.OK_200, commentWithLike); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Dislike' }).expect(HTTP_STATUSES.NO_CONTENT_204); await request(app) .get(`${router.comments}/${createdComments[1].id}`) .set(bearerAuth) .expect(HTTP_STATUSES.OK_200, { ...commentWithLike, likesInfo: { likesCount: 0, dislikesCount: 1, myStatus: 'Dislike' }, }); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'None' }).expect(HTTP_STATUSES.NO_CONTENT_204); await request(app) .get(`${router.comments}/${createdComments[1].id}`) .set(bearerAuth) .expect(HTTP_STATUSES.OK_200, { ...commentWithLike, likesInfo: { likesCount: 0, dislikesCount: 0, myStatus: 'None' }, }); }); it('Comment reaction. Testing by many users', async () => { const url = `${router.comments}/${createdComments[1].id}/like-status`; await loginUser(createdUsers[0].login); await request(app) .put(`${router.comments}/${createdComments[0].id}/like-status`) .set(bearerAuth) .send({ likeStatus: 'Like' }) .expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[1].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[2].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[3].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Like' }).expect(HTTP_STATUSES.NO_CONTENT_204); await loginUser(createdUsers[4].login); await request(app).put(url).set(bearerAuth).send({ likeStatus: 'Dislike' }).expect(HTTP_STATUSES.NO_CONTENT_204); const allComments = await request(app).get(`${router.posts}/${createdPosts[0].id}/comments`).set(bearerAuth); expect(allComments.statusCode).toEqual(HTTP_STATUSES.OK_200); expect(allComments.body).toEqual( getPaginationItems({ pagesCount: 1, totalCount: 2, items: expect.arrayContaining([ { ...createdComments[1], likesInfo: { likesCount: 3, dislikesCount: 1, myStatus: 'Dislike' } }, { ...createdComments[0], likesInfo: { likesCount: 1, dislikesCount: 0, myStatus: 'None' } }, ]), }) ); }); afterAll(async () => { await request(app).delete(router.delete_all); }); });
<button class="btn btn-white rounded-4 category-dropdown__button py-1 fw-bold" type="button" data-bs-toggle="dropdown" data-bs-auto-close="false" aria-expanded="false"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="mx-2 bi bi-list" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M2.5 12a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm0-4a.5.5 0 0 1 .5-.5h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5z"/> </svg> دسته‌بندی <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="mx-2 bi bi-chevron-down" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z"/> </svg> </button> <div class="col-11 col-lg-12 category-dropdown dropdown-menu container mt-n2 py-0 overflow-hidden" aria-labelledby="dropdownMenuButton"> <?php $excluded_category_id = 16; $parent_categories = get_categories(array( 'taxonomy' => 'product_cat', 'orderby' => 'name', 'pad_counts' => false, 'hierarchical' => 1, 'hide_empty' => false, 'exclude' => $excluded_category_id, 'parent' => 0 )); ?> <div class="container"> <div class="row justify-content-start"> <div class="col-lg-2 col-7 px-0"> <nav id="myTab" class="nav nav-pills flex-nowrap flex-row flex-lg-column list-group border-end border-1 border-info overflow-x-scroll"> <?php if ($parent_categories) { foreach ($parent_categories as $key => $parent_cat) { $thumbnail_id = get_term_meta($parent_cat->term_id, 'thumbnail_id', true); ?> <a data-bs-toggle="pill" href="#category_tab<?= $key; ?>" class="<?= $key == 1 ? 'active ' : ' '; ?> w--lg-auto d-flex justify-content-between col-2 col-lg gap-2 p-lg-3 py-3 px-2 text-lg-start text-center list-group-item-action text-primary fw-bold category-link"> <?= $parent_cat->name; ?> </a> <?php wp_reset_postdata(); // Reset Query } } ?> </nav> </div> <div class="col-lg-9 tab-content p-3 overflow-scroll"> <?php foreach ($parent_categories as $key => $parent_cat) { $thumbnail_id = get_term_meta($parent_cat->term_id, 'thumbnail_id', true); ?> <article class="tab-pane fade <?= $key == 1 ? 'show active' : ''; ?>" id="category_tab<?= $key; ?>"> <div class="row gap-1 p-lg-4"> <?php // Loop for subcategories $subcategories = get_categories(array( 'taxonomy' => 'product_cat', 'orderby' => 'name', 'parent' => $parent_cat->term_id, 'hide_empty' => false, )); if ($subcategories) { foreach ($subcategories as $sub_cat) { $thumbnail_id_sub = get_term_meta($sub_cat->term_id, 'thumbnail_id', true); ?> <a class="mb-lg-3 mb-4 border-start border-3 border-success ps-2 bg-info bg-opacity-10 text-dark text-opacity-75" href="<?= get_term_link($sub_cat); ?>"><?= $sub_cat->name; ?></a> <?php // Loop for subcategories of the current subcategory $sub_subcategories = get_categories(array( 'taxonomy' => 'product_cat', 'orderby' => 'name', 'parent' => $sub_cat->term_id, 'hide_empty' => false, )); if ($sub_subcategories) { foreach ($sub_subcategories as $sub_sub_cat) { ?> <a class="ps-3 row row-cols-2 row-cols-lg-6 align-items-center " href="<?= get_term_link($sub_sub_cat); ?>"> <div class="p-2 text-opacity-75 hover_text-primary"><?= $sub_sub_cat->name; ?></div> </a> <?php } } ?> <?php } } ?> </div> </article> <?php } ?> </div> </div> </div> </div>
const express = require('express'); const Favorite = require('../models/favorites') const authenticate = require('../authenticate'); const cors = require('./cors'); const favoriteRouter = express.Router(); favoriteRouter.route('/') .options(cors.corsWithOptions, (req, res) => res.sendStatus(200)) .get(cors.cors, authenticate.verifyUser, (req, res, next) => { Favorite.find({ user: req.user._id }) .populate('favorite.user') .populate('favorite.campsites') .then(favorite => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); }) .catch(err => next(err)); }) .post(cors.corsWithOptions, authenticate.verifyUser, (req, res) => { Favorite.findOne({ user: req.user._id }) .then(favorites => { if (favorites) { req.body.forEach(favorite => { if (!favorites.campsites.includes(favorite._id)){ favorites.campsites.push(favorite._id) } }) favorites.save() .then(favorites => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorites); }) } else { Favorite.create({ user: req.user._id, campsites: req.body }) .then(favorites => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorites); }) } }) }) .put(cors.corsWithOptions, authenticate.verifyUser, (req, res) => { res.statusCode = 403; res.end(`PUT operation not supported on /favorites/${req.params.campsiteId}`); }) .delete(cors.corsWithOptions, authenticate.verifyUser, (req, res) => { Favorite.findOneAndDelete({ user: req.user._id }) .then(favorite => { if (favorite) { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorite); } else { res.setHeader('Content-Type', 'test/plain'); res.end('You do not have any favorites to delete.'); } }) }); favoriteRouter.route('/:campsiteId') .options(cors.corsWithOptions, (req, res) => res.sendStatus(200)) .get(cors.cors, authenticate.verifyUser, (req, res, next) => { res.statusCode = 403; res.end(`GET operation not supported on /favorites/${req.params.campsiteId}`); }) .post(cors.corsWithOptions, authenticate.verifyUser, (req, res) => { Favorite.findOne({ user: req.user._id }) .then(favorite => { if(favorite.campsites.includes(req.params.campsiteId)){ res.end("That campsite is already a favorite!") } else if(!favorite){ Favorite.create({ user: req.user._id, campsites: req.body }) .then(favorites => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorites); }) } else{ favorite.campsites.push(req.params.campsiteId); favorite.save() .then(favorites => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(favorites); }) } }) }) .put(cors.corsWithOptions, authenticate.verifyUser, (req, res) => { res.statusCode = 403; res.end(`PUT operation not supported on /favorites/${req.params.campsiteId}`); }) .delete(cors.corsWithOptions, authenticate.verifyUser, (req, res) => { Favorite.findOne({ user: req.user._id }) .then(favorite => { if (favorite) { favorite.campsites = favorite.campsites.filter(campsite => campsite != req.params.campsiteId); favorite.save(); res.end('end') } else { res.setHeader('Content-Type', 'test/plain'); res.end('You do not have any favorites to delete.'); } }) }); module.exports = favoriteRouter;
import { OrderCancelledEvent, OrderStatus } from "@eytickets/common"; import { natsWrapper } from "../../../nats-wrapper"; import { OrderCancelledListener } from "../order-cancelled-listener"; import mongoose, { version } from 'mongoose'; import { Ticket } from "../../../models/ticket"; import { Message } from "node-nats-streaming"; const setup = async () => { const listener = new OrderCancelledListener(natsWrapper.client); const orderId = new mongoose.Types.ObjectId().toHexString(); const ticket = Ticket.build({ title: 'concert', price: 20, userId: new mongoose.Types.ObjectId().toHexString()}); ticket.set({orderId}); await ticket.save(); const data: OrderCancelledEvent['data'] = { id: orderId, version: 0, ticket: { id: ticket.id, } }; //create fake message object //@ts-ignore const msg: Message = { ack: jest.fn(), }; return {listener, data, msg, orderId, ticket} }; it('updates ticket with order id',async () => { const {listener, data, msg, orderId, ticket} = await setup(); await listener.onMessage(data, msg); const updatedTicket = await Ticket.findById(data.ticket.id); expect(updatedTicket?.orderId).not.toBeDefined(); expect(natsWrapper.client.publish).toHaveBeenCalled(); expect(msg.ack).toHaveBeenCalled(); });
@using Loquit.Data.Entities @using Microsoft.AspNetCore.Identity @{ ViewData["Title"] = "Home Page"; } @model IEnumerable<Loquit.Services.DTOs.PostDTO> @inject UserManager<AppUser> UserManager @{ var currentUser = await UserManager.GetUserAsync(User); } <div class="main-container d-flex justify-content-center"> <div class="left-container"> <div class="lr-container-content"> @foreach (var item in Model.Reverse()) { var creator = await UserManager.FindByIdAsync(item.CreatorId); <div class="post container-fluid d-flex justify-content-center flex-column"> <div class="post-header d-flex justify-content-between flex-row"> <div class="post-header-text"> <div class="post-header-info d-flex flex-row justify-content-between"> <a asp-route-username="@creator.UserName" asp-controller="Profile" asp-action="Index" class="post-user d-flex flex-row"> <span class="pfp pfp-small"><img src="~/uploads/@creator.ProfilePictureUrl" loading="lazy" /></span> <span class="post-name">@creator.UserName</span> </a> <div class="post-header-options d-flex justify-content-between flex-row gap-2"> @if(currentUser != null) { <a href="javascript:void(0);" onclick="likePost(@item.Id, this)" class="post-header-option"> <img class="option like" src="@(item.LikedBy.Any(el => el.UserId == currentUser.Id) ? "/img/LikeFull.png" : "/img/Like.png")" loading="lazy" /> <div id="Like">@item.LikedBy.Count</div> </a> <a href="javascript:void(0);" onclick="dislikePost(@item.Id, this)" class="post-header-option"> <img class="option dislike" src="@(item.DislikedBy.Any(el => el.UserId == currentUser.Id) ? "/img/LikeFull.png" : "/img/Like.png")" loading="lazy" /> <div id="Dislike">@item.DislikedBy.Count</div> </a> } else { <a class="post-header-option"> <img class="option like" src="~/img/Like.png" loading="lazy" /> <div id="Like">@item.LikedBy.Count</div> </a> <a class="post-header-option"> <img class="option dislike" src="~/img/Like.png" loading="lazy" /> <div id="Dislike">@item.DislikedBy.Count</div> </a> } <a asp-area="" asp-controller="Posts" asp-action="Details" asp-route-id="@item.Id" class="post-header-option"> <img class="option comment" src="~/img/Comment.png" loading="lazy" /> <div>@item.Comments.Count</div> </a> <div class="post-header-more"> <div class="dropdown"> <button class="more-btn btn btn-secondary" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> <img class="more" src="~/img/more.png" loading="lazy" /> </button> @if (currentUser != null && currentUser.Id == creator.Id) { <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> <li><a asp-action="Delete" asp-controller="Posts" asp-route-id="@item.Id" class="dropdown-item">Delete</a></li> <li><a asp-action="Edit" asp-controller="Posts" asp-route-id="@item.Id" class="dropdown-item">Edit</a></li> </ul> } </div> </div> </div> </div> <a asp-area="" asp-controller="Posts" asp-action="Details" asp-route-id="@item.Id" class="title"> @item.Title </a> <div class="warnings"> @if (item.IsSpoiler) { <div class="spoiler">Spoiler</div> } @if (item.IsNsfw) { <div class="nsfw">NSFW</div> } <div class="time-post"> @item.TimeOfPosting.ToString("HH:mm:ss dd.M.yyyy") </div> </div> </div> </div> @if (!item.IsNsfw && !item.IsSpoiler && item.PictureUrl != null) { <a asp-area="" asp-controller="Posts" asp-action="Details" asp-route-id="@item.Id"> <img class="post-image" src="~/uploads/@item.PictureUrl" loading="lazy" /> </a> } </div> } </div> </div> <div class="right-container"> <div class="lr-container-content"> <form class="post-search d-flex justify-content-center flex-row" method="get"> <div> <input type="text" name="searchQuery" class="post-search-bar form-control" placeholder="Search..."> </div> <button type="submit" class="normal-btn post-search-btn btn btn-primary"> <img src="~/img/lens.png" class="btn-image" /> </button> </form> @if(currentUser != null) { <form class="d-flex justify-content-center flex-row"> <button asp-controller="Posts" asp-action="Create" type="submit" class="highlighted-button create-post-btn btn btn-primary">New Post</button> </form> } </div> </div> </div>
import React, { useEffect, useState } from "react"; import { tableHeads } from "./../../Constants/TableHeads"; const ProductTable = ({ setAllItems, allItems }) => { console.log("items is ", allItems); const handleDelete = (index) => { const updatedData = [...allItems]; updatedData.splice(index, 1); setAllItems(updatedData); localStorage.setItem("items", JSON.stringify(updatedData)); }; console.log({ allItems }); return ( <> <table class="table"> <thead> <tr> {tableHeads.map((title, index) => ( <th className="text-center" key={index} scope="col"> {title} </th> ))} </tr> </thead> <tbody> {allItems.map((item, index) => ( <tr key={index}> <td className="text-center">{item.titleValue}</td> <td className="text-center">{item.quantity}</td> <td className="text-center">{item.price}</td> <td className="text-center">{item.date}</td> <td className="text-center"> <button className="btn btn-danger" onClick={() => handleDelete(index)} > Delete </button> </td> </tr> ))} </tbody> </table> </> ); }; export default ProductTable;
package plugins::Alias; #--------------------------------------------------------------------------- # Copyright (C) 2013 egretsareherons@gmail.com # https://github.com/NOVACyclist/ShaleRocksBot # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #----------------------------------------------------------------------------- use strict; use warnings; use base qw (modules::PluginBaseClass); use modules::PluginBaseClass; use Data::Dumper; my @aliases; sub onBotStart{ my $self = shift; ## Add some default aliases if (!$self->globalCookie("first_run")){ print "Adding default aliases...\n"; my $c = $self->getCollection(__PACKAGE__, 'alias'); if (!$self->botCan("which")){ print "added which\n"; $c->add('which', 'help $* --info', ':system'); } if (!$self->botCan("g")){ print "added g\n"; $c->add('g', 'lucky $*', ':system'); } if (!$self->botCan("gg")){ print "added gg\n"; $c->add('gg', 'google $*', ':system'); } if (!$self->botCan("calc")){ print "added calc\n"; $c->add('calc', 'wa $*', ':system'); } print "Set first_run cookie so this will never run again.\n"; $self->globalCookie("first_run", 1); }else{ print "Not adding default aliases\n"; } } sub plugin_init{ my $self = shift; my $c = $self->getCollection(__PACKAGE__, 'alias'); my @records = $c->getAllRecords(); foreach my $rec (@records){ push @{$self->{aliases}}, {alias=>$rec->{val1}, command=>$rec->{val2}, created_by=>$rec->{val3}}; } return $self; } sub getOutput { my $self = shift; my $cmd = $self->{command}; # the command my $options = $self->{options}; # everything else on the line my $options_unparsed = $self->{options_unparsed}; #with the flags intact my $channel = $self->{channel}; my $mask = $self->{mask}; # the users hostmask, not including the username my $nick = $self->{nick}; my $output = ""; if ($cmd eq 'alias'){ ## Add a new alias if ($self->hasFlag("add")){ my $pname = $self->hasFlagValue("name"); my $pcommand = $self->hasFlagValue("command"); return "-command is required" if (!$pcommand); return "-name is required" if (!$pname); if ($self->botCan($pname)){ return "$self->{BotName} already has a command called $pname."; } my $c = $self->getCollection(__PACKAGE__, 'alias'); if ($c->matchRecords({val1=>$pname})){ return "Alias $pname already exists"; } $c->add($pname, $pcommand, $self->accountNick()); $self->returnType("reloadPlugins"); return "$pname added."; } ## list aliases if ($self->hasFlag("list")){ if (my $palias = $self->hasFlagValue("list")){ foreach my $alias (@{$self->{aliases}}){ if ($alias->{alias} eq $palias){ return "$palias is defined as \"$alias->{command}"; } } return "$palias not found."; } foreach my $alias (@{$self->{aliases}}){ $self->addToList($alias->{alias}); } my $list = $self->getList(); if ($list){ return "Aliases: " . $list; }else{ return "No aliases are defined."; } } ## delete an alias if (my $pname = $self->hasFlagValue("delete")){ my $c = $self->getCollection(__PACKAGE__, 'alias'); my @records = $c->matchRecords({val1=>$pname}); if (@records){ $c->delete($records[0]->{row_id}); $self->returnType("reloadPlugins"); return "Alias $pname deleted"; } return "I couldn't find alias $pname."; } } ## ## If we're here, we called an alias. Figure it out. ## foreach my $alias (@{$self->{aliases}}){ $options = $self->{options_unparsed}; if ($alias->{alias} eq $cmd){ my $acommand = $alias->{command}; my @args; if ($options){ @args = split / /, $options; } my $highest_req = 0; my $highest_opt = 0; while ($alias->{command}=~m/\$([0-9]+)/g){ my $num = $1; if ($highest_req < $num ){ $highest_req = $num ; } } if ($highest_req > @args){ return "Alias $cmd requires $highest_req arguments"; } while ($alias->{command}=~m/\$([0-9]+)/g){ my $num = $1; $acommand=~s/\$$num/$args[$num-1]/g; } while ($alias->{command}=~m/\@([0-9]+)/g){ my $num = $1; if ($highest_opt < $num ){ $highest_opt = $num ; } if ( $num <= @args){ $acommand=~s/\@$num/$args[$num-1]/g; }else{ $acommand=~s/\@$num //g; } } my @remaining; if ($highest_opt){ @remaining = @args[($highest_opt ) .. $#args]; }else{ @remaining = @args[($highest_req ) .. $#args]; } my $r = join " ", @remaining; $acommand=~s/\$\*/$r/; $self->returnType("runBotCommand"); return "$acommand"; } } return $self->help("alias"); } sub listeners{ my $self = shift; my @commands = ('alias'); foreach my $alias (@{$self->{aliases}}){ push @commands, $alias->{alias}; } my @irc_events = [qw () ]; my @preg_matches = [qw () ]; my $default_permissions =[ {command=>"PLUGIN", flag=>"add", require_group => UA_REGISTERED}, ]; return {commands=>\@commands, permissions=>$default_permissions, irc_events=>@irc_events, preg_matches=>@preg_matches}; } ## ## addHelp() ## The help system will pull from here using PluginBaseClass->help(key). ## sub addHelp{ my $self = shift; $self->addHelpItem("[plugin_description]", "Create aliases. When creating, use \$1, \$2, etc., to refer to required arguments. Use \@3, \@4, etc., to refer to optional arguments. Optional argument numbering starts where requirement argument numbering left off. Use \$* to refer to all arguments, or all remaining arguments."); $self->addHelpItem("[alias]", "Create a new alias: alias -add -name=<alias> -command=<command>. List aliases: alias -list. Show an alias definition: alias -list=<alias name>. Delete an alias: alias -delete=<alias>"); $self->addHelpItem("[alias][-add]", "Create a new alias: alias -add -name=<alias> -command=<command>. When adding aliases, use \$1, \$2, etc., to refer to required arguments. Use \@3, \@4, etc., to refer to optional arguments. Optional argument numbering starts where requirement argument numbering left off. Use \$* to refer to all arguments, or all remaining arguments."); foreach my $alias (@{$self->{aliases}}){ $self->addHelpItem("[".$alias->{alias}."]", "The command '$alias->{alias}' is an alias to \"$alias->{command}\", and was created by $alias->{created_by}."); } } 1; __END__
%-------------------------------------------------------------------------% % ASSIGNMENT 03 - (A) %-------------------------------------------------------------------------% % Date: % Author/s: % clear; %% INPUT DATA % Material properties E = 85e9; % Cross-section parameters t1 = 1.5e-3; t2 = 4e-3; h1 = 0.5; h2 = 0.25; b = 0.775; % Other data g = 9.81; L1 = 5; L2 = 10; L = L1+L2; Me = 2550; M = 35000; % Number of elements for each part nel = [3,6, 12, 24, 48, 96]; %% Essential parameters. % Everything is built so that it works by changing Nel's value. Nel = 96; % Number of elements for the "exact" solution n_d = 1; %Problem dimension n_ne = 2; % Nodes in a beam n_i = 2; % DOF per node. % Fixed degrees of freedom % First node can't move upwards or rotate. fixNod = [1 1 0; 1 2 0; ]; %% PRECOMPUTATIONS % Compute section: % A - Section area h_aux = h1/2-h2/2; longitud = sqrt(b^2+h_aux^2); A1 = t2*h1; A2 = t2*h2; A3 = 2*longitud*t1; A = A1 + A2 + A3; % Iz - Section inertia z_cg = (A2*b + A3*b/2)/A; theta = atan((h1/2-h2/2)/b); % Iz inertia moments -> z is the horizontal axis. Izz1 = 1/12*t2*h1^3; Izz2 = 1/12*t2*h2^3; Izz3 = 2*(1/12*t1*longitud^3*sin(theta)^2 + A3/2*(h1/2-longitud/2*sin(theta))^2); Iz = Izz1 + Izz2 + Izz3; %Iy inertia moments -> Vertical axis. Iyy1 = 1/12*h1*t2^3; Iyy2 = 1/12*h2*t2^3; Iyy3 = 1/12*t1*longitud^3*cos(theta)^2; Iyy = (Iyy1 + A1*z_cg^2) + (Iyy2 + A2*(z_cg-b)^2) + 2*(Iyy3 + A3/2*(z_cg-b/2)^2); % Compute parameter l: % l - Equilibrium parameter aux_M = (1.7863e+04); aux_Q = 32/3; %[N] l = (aux_M*g)/aux_Q; u_ext = zeros(size(nel,2),1); % This plot is empty at first fig = plotBeamsInitialize(L1+L2); for k = 1:length(nel) n_nod = nel(k)+1; %Total number of nodes. n_dof = n_nod*n_i; %Total number of degrees of freedom. %% PREPROCESS x = 0:L/nel(k):L; % Material properties matrix mat = [% Young M. Section A. Inertia E, A, Iz; % Material (1) ]; % Material connectivities % Tmat(e) = Row in mat corresponding to the material associated to element e Tn = zeros(nel(k), n_ne); for i = 1:nel(k) Tn(i,:) = [i, i+1]; end %% SOLVER % Compute: % u - Displacements and rotations vector [ndof x 1] % pu - Polynomial coefficients for displacements for each element [nel x 4] % pt - Polynomial coefficients for rotations for each element [nel x 3] % Fy - Internal shear force at each elements's nodes [nel x nne] % Mz - Internal bending moment at each elements's nodes [nel x nne] % Compute Td: Only 2 degrees of freedom per node (deflection and rotation). Td = connectDOFs(nel(k),n_ne,n_i,Tn); % Independent element stiffness matrix [Kel, l_e_vector] = computeKelBar(n_i,nel(k),x,Tn,E, Iz); % Element force vector F_el = computeElementForceVector(n_i, n_nod, nel(k), x, l_e_vector, L1, L2, l, M); % Global matrix [KG, Fext] = assemblyKG(nel(k),n_ne*n_i,n_dof,Td,Kel, F_el); % Apply conditions [vL,vR,uR] = applyCond(n_i,n_dof,fixNod); % System resolution [u,R] = solveSys(vL,vR,uR,KG,Fext); %Internal distributions [Fy, Mz, pu, pt] = computeInternalDistributions(l_e_vector,u, nel(k), n_ne, n_i, Td, Kel); %% POSTPROCESS u_an = zeros(size(u,1)/2,1); theta_an = zeros(size(u,1)/2,1); j = 1; for i = 1:2:size(u,1) u_an(j) = u(i,1); theta_an(j) = u(i+1,1); j = j+1; end Fy_an = zeros(nel(k)+1,1); Mz_an = zeros(nel(k)+1,1); Fy_an(2:nel(k)+1,1) = Fy(:,1); Mz_an(2:nel(k)+1,1) = Mz(:,1); Fy_an(1,1) = Fy(1,1); Mz_an(1,1) = Mz(1,1); % Number of subdivisions and plots nsub = Nel/nel(k); plotBeams1D(fig,x,Tn,nsub,pu,pt,Fy,Mz) drawnow; % Vector acumulating displacement at x = L1 + L2 % 2*nel(k)+2 contains the rotation of the last node u_ext(k, 1) = u(2*nel(k)+1,1); % End of general loop end % Add figure legends figure(fig) legend(strcat('N=',cellstr(string(nel))),'location','northeast'); %% Postprocessing % Error calculus error_vector = zeros(size(u_ext,1),1); % Taking into account the deflection at the wing tip % The last value is the one for Nel = 96 -> 'Exact solution' for i = 1:size(u_ext,1) error_vector(i,1) = abs((u_ext(i,1) - u_ext(length(u_ext)))/u_ext(length(u_ext))); end figure semilogx(nel, error_vector); xlabel('log_{10}(n_{el})'); ylabel('Relative error'); title('Relative error along the number of elements'); %% VON MISES CRITERION % Bending moment in z axis. % Axial stress -> h1/2 is the maximum value of y. sig_max = (h1/2)*Mz(1,1)/Iz; Sy = Fy(1,1); const = Sy/Iz; % Shear stress % Calculate Qs0 % Normal distance from x_cg to upper and lower bars. u1 = 1/(sqrt(z_cg^2 + (h1/2)^2)) * [z_cg, h1/2]; u2 = [cos(theta) sin(theta)]; mu = acos(dot(u1,u2)); dn = sqrt(z_cg^2 + (h1/2)^2)*sin(mu); % Qopen definite integrals % Most solicitated position expected at 2-3. q01f = @(x) -const*t2*x; q12f = @(x) -const*t1*(h2/2+x*sin(theta)); q23f = @(x) -const*t2*(h1/2-x); q34f = @(x) -const*t1*(-h1/2+x*sin(theta)); q40f = @(x) -const*t2*(-h2/2+x); q1op = integral(q01f, 0, h2/2); q2op = q1op + integral(q12f, 0, longitud); q3op = q2op + integral(q23f, 0, h1); q4op = q3op + integral(q34f, 0, longitud); % Qopen shear flow moment differentials in indefinite integrals (function_handle) syms x q01op_m_ind = matlabFunction(-(b-z_cg)*int(-const*t2*x)); q12op_m_ind = matlabFunction(-dn*(int(-const*t1*(h2/2+x*sin(theta)))+q1op)); q23op_m_ind = matlabFunction(-(-z_cg)*(int(-const*t2*(h1/2-x))+q2op)); q34op_m_ind = matlabFunction(-dn*(int(-const*t1*(-h1/2+x*sin(theta)))+q3op)); q40op_m_ind = matlabFunction(-(b-z_cg)*(int(-const*t2*(-h2/2+x))+q4op)); % q01op_m_ind = matlabFunction((b-z_cg)*int(const*t2*x)); % q12op_m_ind = matlabFunction(dn*(int(const*t1*(h2/2+x*sin(theta)))+q1op)); % q23op_m_ind = matlabFunction(-z_cg*(int(const*t2*(h1/2-x))+q2op)); % q34op_m_ind = matlabFunction(dn*(int(const*t1*(-h1/2+x*sin(theta)))+q3op)); % q40op_m_ind = matlabFunction((b-z_cg)*(int(const*t2*(-h2/2+x))+q4op)); % Shear flow (open) moment definite integrals q01op_m = integral(q01op_m_ind, 0, h2/2); q12op_m = integral(q12op_m_ind, 0, longitud); q23op_m = integral(q23op_m_ind, 0, h1); q34op_m = integral(q34op_m_ind, 0, longitud); q40op_m = integral(q40op_m_ind, 0, h2/2); % Final calculus. M_total = q01op_m + q12op_m + q23op_m + q34op_m +q40op_m; A_in = b*((h1-h2)/2) + b*h2; Qs0 = M_total/(2*A_in); q1op = q1op + Qs0; q2op = q2op + Qs0; q3op = q3op + Qs0; q4op = q4op + Qs0; tau_max = q2op/t1; sigma_eq = sqrt(sig_max^2 + 3*tau_max^2); % Sigma_eq (root) = 4.8281e+08
// 1. 옵셔널 파라미터(Optional Parameters) // extra는 있을 수도 있고 없을 수도 있다고 ? 를 추가해서 옵셔널로 지정 export function printIngredient(quantity: string, ingredient: string, extra?: string) { console.log(`${quantity} ${ingredient} ${extra ? `${extra}` : ""}`); } // 2. 옵셔널 필드(Optional Fields) interface User { id: string, info? : { email? : string; } } export function getEmail(user: User): string { return user?.info?.email ?? "No Email"; // 널 병합 연산자 } // 3. 옵셔널 콜백(Optional Callback) function addWithCallback(x: number, y: number, callback?: () => void): void { console.log([x, y]); callback?.(); }
import numpy as np import gpytorch import torch import sys # sys.path.append("/app") # sys.path.append("./Predictive-Validation-proper-horizon/tools") from numpy.random import RandomState from makey_glass import mackey_glass, MackeyGlassDataset from gpr import GPRModel # from scores import get_uct_metrics import matplotlib.pyplot as plt import numpy as np class GPRUncInputs: def __init__(self, base_gp_model, starting_point: np.ndarray) -> None: """ Implements iterative GP time series prediction with uncertain inputs: Prediction at an Uncertain Input for Gaussian Processes and Relevance Vector Machines Application to Multiple-Step Ahead Time-Series http://quinonero.net/Publications/QuiGirRas03.pdf :param base_gp_model: GP model that is used to produce posteriory based on input :param starting_point: The first L points of test time series, from which interative prediction process starts. We are certain about these points, i.e mean vector u=starting_point, S - zero matrix """ self.base_gp_model = base_gp_model self.Lambda = np.diag( self.base_gp_model.model.covar_module.lengthscale.cpu().detach().numpy()[0] ** 2 ) self.Lambda_inv = np.diag( 1 / ( base_gp_model.model.covar_module.lengthscale.cpu().detach().numpy()[0] ** 2 ) ) self.u = starting_point self.L = self.u.shape[0] self.S = np.zeros((self.L, self.L)) self.train_points = self.base_gp_model.model.train_inputs[0].numpy() self.train_targets = self.base_gp_model.model.train_targets.numpy() self.Sigma = ( base_gp_model.model.covar_module(self.base_gp_model.model.train_inputs[0]) .to_dense() .detach() .numpy() ) # self.Sigma_inv = np.linalg.inv(self.Sigma) self.nose_estimate = self.base_gp_model.model.likelihood.noise.item() K = self.Sigma + self.nose_estimate * np.identity(self.train_points.shape[0]) self.K_inv = np.linalg.inv(K + 10**-5 * np.identity(self.train_points.shape[0])) self.beta = self.K_inv @ self.train_targets self.random_input_part_size = 0 # part of input vector u, which is random. # at first whole vector u is deterministic @staticmethod def compute_quadratic_form(A, x): x_outer = x[..., :, np.newaxis] * x[..., np.newaxis, :] return np.sum(A[..., :, :] * x_outer, axis=(-1, -2)) def compute_l(self): # see eqs. (33) l_norm = np.linalg.det(self.Lambda_inv @ self.S + np.identity(self.L)) ** -0.5 s_l_inv = np.linalg.inv(self.S + self.Lambda) diff = self.u[np.newaxis, :] - self.train_points qw_form = self.compute_quadratic_form(s_l_inv, diff) l = l_norm * np.exp(-0.5 * qw_form) # u = torch.tensor(self.u, dtype=torch.float64)[np.newaxis,:] #torch.zeros(L, dtype=torch.float64)[np.newaxis,:] # train_points = self.base_gp_model.model.train_inputs[0] # k = gpr_model.model.covar_module(u,train_points).to_dense().detach().numpy() return l def compute_L_matrix(self): # see eqs. (37) L_norm = ( np.linalg.det(2 * self.Lambda_inv @ self.S + np.identity(self.L)) ** -0.5 ) x_d = ( self.train_points[np.newaxis, :, :] + self.train_points[:, np.newaxis, :] ) / 2 x_minis = ( self.train_points[np.newaxis, :, :] - self.train_points[:, np.newaxis, :] ) u_minis_x_d = self.u[np.newaxis, np.newaxis, :] - x_d Lambda_plus_S_inv = np.linalg.inv(self.Lambda / 2 + self.S) Lambda_inv_half = self.Lambda_inv / 2 return L_norm * np.exp( -0.5 * ( self.compute_quadratic_form(Lambda_plus_S_inv, u_minis_x_d) + self.compute_quadratic_form(Lambda_inv_half, x_minis) ) ) def compute_k(self): u = torch.tensor(self.u, dtype=torch.float64)[np.newaxis, :] train_points = torch.tensor(self.train_points, dtype=torch.float64) k = ( self.base_gp_model.model.covar_module(u, train_points) .to_dense() .detach() .numpy()[0] ) return k def predict_with_unc_inputs(self): # predicts next point mean and variance based on current uncertain input # see eqs. (30) for the mean and (35) for the variance # http://quinonero.net/Publications/QuiGirRas03.pdf # compute mean self.l = self.compute_l() m = np.dot(self.beta, self.l) # compute variance # 1. get GP variance y_pred_gp, v_gp = self.base_gp_model.predict(self.u[np.newaxis, :]) v_gp = v_gp[0] ** 2 # 2. get anxilary marixes self.k = self.compute_k() self.L_matrix = self.compute_L_matrix() k_outer = self.k[np.newaxis, :] * self.k[:, np.newaxis] l_outer = self.l[np.newaxis, :] * self.l[:, np.newaxis] beta_outer = self.beta[np.newaxis, :] * self.beta[:, np.newaxis] v = ( v_gp + np.trace(self.K_inv @ (k_outer - self.L_matrix)) + np.trace(beta_outer @ (self.L_matrix - l_outer)) ) # update matrix S and mean vector self.update_input_distr(v, m) return m, v**0.5 def update_input_distr(self, v_pred, m_pred): # update covariance matrix S and mean vector u after new predicted point will be added # see eqs. (53) # at first iterations not whole vector u is random # thus we want to compute variances between new predicted point y_{T+K} and random part # of vector u u_new = np.zeros_like(self.u) S_new = np.zeros_like(self.S) # update vector u u_new[0] = m_pred u_new[1:] = self.u[:-1] # update matrix S S_Lambda_inv = np.linalg.inv(self.S + self.Lambda) lambda_train = ((self.S @ S_Lambda_inv) @ self.train_points.T).T c_j = lambda_train + ((self.Lambda @ S_Lambda_inv) @ self.u)[np.newaxis, :] cov = np.sum( self.beta[:, np.newaxis] * self.l[:, np.newaxis] * (c_j - self.u[np.newaxis, :]), axis=0, ) S_new[0, 0] = v_pred + self.nose_estimate S_new[1:, 1:] = self.S[:-1, :-1] S_new[0, 1:] = cov[:-1] S_new[1:, 0] = cov[:-1] self.S = S_new self.u = u_new self.random_input_part_size += 1 return if __name__ == "__main__": L = 50 nose_std = (0.001) ** 0.5 seed = 7 makey_train_ds = MackeyGlassDataset( length=8000, size=100, L=L, seed=seed, nose_std=nose_std ) # create test point rs = RandomState(seed) n = 170 x0 = 0.5 + 0.05 * (-1 + 2 * rs.random(n)) x = mackey_glass(length=100 + L, tau=17.0, sample=1.0, n=n, x0=x0) test_points = (x - makey_train_ds.mean) / makey_train_ds.std test_points += rs.normal(0, nose_std, size=len(test_points)) gpr_model = GPRModel(normalize_data=False, training_iter=500, use_scale=False) x_train = makey_train_ds.train_set_x y_train = makey_train_ds.train_set_y # fit gpr_model.fit(np.flip(x_train, 1).copy(), y_train) # test unc model model = GPRUncInputs(gpr_model, test_points[:L][::-1].copy()) predictions = [] stds = [] for i in range(len(test_points) - L): next_x, next_std = model.predict_with_unc_inputs() predictions.append(next_x) stds.append(next_std) predictions = np.array(predictions) stds = np.array(stds) val_low = predictions - 2 * stds val_high = predictions + 2 * stds # predict gpr predictions_gpr = [] stds_gpr = [] x_test = test_points[:L][::-1].tolist() for i in range(len(test_points) - L): next_x, next_std = gpr_model.predict(np.array(x_test)[np.newaxis, :]) predictions_gpr.append(next_x[0]) stds_gpr.append(next_std[0]) x_test = [next_x[0]] + x_test[:-1] predictions_gpr = np.array(predictions_gpr) stds_gpr = np.array(stds_gpr) val_low_gpr = predictions_gpr - 2 * stds_gpr val_high_gpr = predictions_gpr + 2 * stds_gpr plt.figure(figsize=(8, 5), dpi=300) time_future = np.arange(len(test_points) - L) plt.plot( time_future, test_points[L:], label="true", linewidth=2, linestyle="-", marker="o", markersize=2, ) plt.plot( time_future, predictions_gpr, label="GPR", linewidth=2, linestyle="--", marker="o", markersize=2, ) plt.plot( time_future, predictions, label="UncInputGPR", linewidth=2, linestyle="--", marker="o", markersize=2, ) plt.fill_between(time_future, val_low, val_high, alpha=0.2) plt.fill_between(time_future, val_low_gpr, val_high_gpr, alpha=0.2) plt.xticks(fontsize=14, rotation=60) plt.yticks(fontsize=14) plt.xlabel("time step", fontsize=18) plt.ylabel("target", fontsize=18) plt.legend(fontsize=14) plt.savefig("./test.png") # print([model.Lambda[i][i] for i in range(L)]) # plt.savefig("/app/outputs/unc_inputs/test.png") # print("/app/outputs/unc_inputs/test.png") # d = get_uct_metrics(test_points[L:], predictions, stds) # d_gpr = get_uct_metrics(test_points[L:], predictions_gpr, stds_gpr)
import { useState } from "react"; import { View, Image, Text, StyleSheet, Dimensions, useWindowDimensions, ScrollView } from "react-native"; import PrimaryButton from "../components/ui/PrimaryButton"; import Title from "../components/ui/Title"; import Colors from "../constants/colors"; function GameOverScreen(props) { const { width, height } = useWindowDimensions(); let imageSize = 300; let imageHorizontalMargin = 25 if (width < 380) { imageSize = 150; imageHorizontalMargin = 140 } if (height < 400) { imageSize = 200; imageHorizontalMargin = 280 } const imageStyle = { width: imageSize, height: imageSize, borderRadius: imageSize / 2, marginHorizontal: imageHorizontalMargin } return ( <ScrollView style={styles.screen}> <View style={styles.rootContainer}> <Title>GAME OVER!</Title> <View style={[styles.imageContainer, imageStyle]}> <Image style={styles.image} source={require("../assets/images/success.png")} /> </View> <Text style={styles.summaryText}> Your Phone needed <Text style={styles.highLight}>{props.roundsNumber}</Text> rounds to guess the number <Text style={styles.highLight}>{props.userChosenNumber}</Text>. </Text> <PrimaryButton onPressButton={props.onStartNewGame}>Start New Game</PrimaryButton> </View> </ScrollView> ); } export default GameOverScreen; // const deviceWidth = Dimensions.get("window").width; const styles = StyleSheet.create({ screen: { flex: 1 }, rootContainer: { flex: 1, padding: 24, justifyContent: "center", alignContent: "center" }, imageContainer: { // width: deviceWidth < 380 ? 150 : 300, // height: deviceWidth < 380 ? 150 : 300, // borderRadius: deviceWidth < 380 ? 75 : 150, borderWidth: 3, borderColor: Colors.blue, overflow: "hidden", // marginHorizontal: 25, marginVertical: 50 }, image: { width: "100%", height: "100%", // alignSelf: 'center' }, summaryText: { fontFamily: "open-sans-regular", fontSize: 24, textAlign: "center", marginBottom: 24 }, highLight: { fontFamily: "open-sans-bold", color: Colors.blue } });
import { parse } from 'csv-parse' import fs from 'node:fs' const csvPath = new URL('./tasks.csv', import.meta.url); const stream = fs.createReadStream(csvPath).on('error', () => { console.log("Path not found!") }); const csvParse = parse({ delimiter: ',', skipEmptyLines: true, fromLine: 2 }); async function run() { const linesParse = stream.pipe(csvParse) .on('end', () => { console.log('File imported successfully!') }) for await (const line of linesParse) { const [title, description] = line; console.log(line) await fetch('http://localhost:3000/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title, description, }) }) await wait(2000) } } function wait(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) } run()
import React from 'react'; import { Route, Routes, useNavigate } from 'react-router-dom'; import Frame from './components/_Frame/Frame'; import Account from './pages/Account/Account'; import Chat from './pages/Chat/Chat'; import Department from './pages/Department/Department'; import Institutes from './pages/Institutes/Institutes'; import Login from './pages/Login/Login'; import Master from './pages/Master/Master'; import NotFound from './pages/NotFound/NotFound'; import Questions from './pages/Questions/Questions'; import Teacher from './pages/Teacher/Teacher'; import Teachers from './pages/Teachers/Teachers'; import { useAppDispatch, useAppSelector } from './store/hooks/redux'; import { checkLogin } from './store/reducers/ActionCreators' const App = () => { const dispatch = useAppDispatch() const navigate = useNavigate() const { user } = useAppSelector(state => state.authReducer) React.useEffect(() => { const localStorageToken = localStorage.getItem('token') const localStorageUser = localStorage.getItem('user') if (localStorageToken || localStorageUser) return dispatch(checkLogin()) if (!localStorageToken || !localStorageUser) return navigate('/login') }, []) return ( <div className="wrapper"> <main> <div className="app"> <div className="app__container"> <Routes> <Route path='/login' element={<Login />} /> <Route path='/' element={<Frame />} > <Route index element={<Chat />} /> <Route path='/teachers' element={<Teachers />} /> <Route path='/teachers/:name' element={<Teacher />} /> <Route path='/institutes' element={<Institutes />} /> <Route path='/institutes/:department' element={<Department />} /> <Route path='/account' element={<Account />} /> <Route path='/questions' element={<Questions />} /> <Route path='*' element={<NotFound />} /> {user?.master ? <Route path='/master' element={<Master />} /> : null} </Route> </Routes> </div> </div> </main > </div > ); } export default App;
# Import necessary modules and libraries from . import db from flask_login import UserMixin # Create the table for the User model class User(db.Model, UserMixin): ''' Attributes: id (int): Primary key username (str): Unique password (str): Encripted Password notes (relationship): One-to-many with the notes table ''' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), unique=True, nullable=False) password = db.Column(db.String(100), nullable=False) notes = db.relationship('Note') # Create the table for Note model class Note(db.Model): ''' Attributes: id (int): Primary key title (str): title note user_id (int): Foreign key referencing the id column of User table ''' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
<?php namespace App\Http\Controllers; use App\Models\ContactUs; use Illuminate\Support\Str; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class ContactUsController extends Controller { /** * Middleware * * */ public function __construct() { $this->middleware(['auth', 'permission:contact_us_management']); \config_set('theme.cdata', [ 'title' => 'Contact Us Management table', 'model' => 'Contact Us', 'route-name-prefix' => 'admin.contact-us', 'back' => \back_url(), 'breadcrumb' => [ [ 'name' => 'Dashboard', 'link' => route('admin.dashboard') ], [ 'name' => 'Contact Us Management Table', 'link' => false ], ], 'add' => \route('admin.contact-us.create') ]); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { \config_set('theme.cdata', [ 'description' => 'Display a listing of Contact Us in Database.', ]); // seo $this->seo()->setTitle(config('theme.cdata.title')); $this->seo()->setDescription(\config('theme.cdata.description')); $collection = ContactUs::cacheData(); // $collection = ContactUs::all(); // dd($collection); return \view('pages.admin.contact-us.index', \compact('collection')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { \config_set('theme.cdata', [ 'title' => 'Create New Contact Us Information', 'breadcrumb' => [ [ 'name' => 'Dashboard', 'link' => route('admin.dashboard') ], [ 'name' => 'Contact Us Table', 'link' => route(config('theme.cdata.route-name-prefix') . '.index') ], [ 'name' => 'Create New Contact Us Information', 'link' => false ], ], 'add' => false, 'description' => 'Create new Contact Us Information in a database.', ]); // seo $this->seo()->setTitle(config('theme.cdata.title')); $this->seo()->setDescription(\config('theme.cdata.description')); return \view('pages.admin.contact-us.create_edit'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'name' => 'required', 'phone' => 'required', 'subject' => 'required', 'description' => 'required', ]); $data = $request->all(); $data['created'] = date('d M Y'); $contactUs = ContactUs::create($data); // flash message Session::flash('success', 'Successfully Stored New Contact Us Information.'); return \redirect()->route(config('theme.cdata.route-name-prefix') . '.index'); } /** * Display the specified resource. * * @param \App\Models\ContactUs $contactUs * @return \Illuminate\Http\Response */ public function show(ContactUs $contactUs) { return \view('pages.admin.contact-us.show', ['item' => $contactUs]); } /** * Show the form for editing the specified resource. * * @param \App\Models\ContactUs $contactUs * @return \Illuminate\Http\Response */ public function edit(ContactUs $contactUs) { \config_set('theme.cdata', [ 'title' => 'Edit Contact Us Information', 'breadcrumb' => [ [ 'name' => 'Dashboard', 'link' => route('admin.dashboard') ], [ 'name' => 'ContactUs Table', 'link' => route(config('theme.cdata.route-name-prefix') . '.index') ], [ 'name' => 'Edit Contact Us Information', 'link' => false ], ], 'add' => false, 'edit' => route(config('theme.cdata.route-name-prefix') . '.edit', $contactUs->id), 'update' => route(config('theme.cdata.route-name-prefix') . '.update', $contactUs->id), 'description' => 'Edit existing Contact Us Information.' ]); // seo $this->seo()->setTitle(config('theme.cdata.title')); $this->seo()->setDescription(\config('theme.cdata.description')); return \view('pages.admin.contact-us.create_edit', ['item' => $contactUs]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\ContactUs $contactUs * @return \Illuminate\Http\Response */ public function update(Request $request, ContactUs $contactUs) { $request->validate([ 'name' => 'required', 'phone' => 'required', 'subject' => 'required', 'description' => 'required', ]); $data = $request->all(); $contactUs->update($data); // flash message Session::flash('success', 'Successfully Updated Contact Us Information .'); return \redirect()->route(config('theme.cdata.route-name-prefix') . '.index'); } /** * Remove the specified resource from storage. * * @param \App\Models\ContactUs $contactUs * @return \Illuminate\Http\Response */ public function destroy(ContactUs $contactUs) { $contactUs->delete(); // flash message Session::flash('success', 'Successfully deleted Contact Us Information.'); return \redirect()->route(config('theme.cdata.route-name-prefix') . '.index'); } }
<template> <div class="navbar"> <hamburger :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" /> <breadcrumb class="breadcrumb-container" /> <!-- 修改密码弹框 --> <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="35%"> <el-form ref="form" :model="form"> <el-form-item label="原始密码:" prop="old_pw"> <el-input v-model="form.old_pw" type="password" placeholder="请输入原始密码" autocomplete="off" /> </el-form-item> <el-form-item label="新密码:" prop="new_pw1"> <el-input v-model="form.new_pw1" type="password" placeholder="请输入新密码" autocomplete="off" /> </el-form-item> <el-form-item label="确认密码:" prop="new_pw2"> <el-input v-model="form.new_pw2" type="password" placeholder="请再次输入密码" autocomplete="off" /> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogFormVisible = false">取 消</el-button> <el-button type="primary" @click="modify">确 定</el-button> </div> </el-dialog> <!-- 修改密码框 --> <div class="right-menu"> <el-dropdown class="avatar-container" trigger="click"> <div class="avatar-wrapper"> <img :src="avatar+'?imageView2/1/w/80/h/80'" class="user-avatar"> <i class="el-icon-caret-bottom" /> </div> <el-dropdown-menu slot="dropdown" class="user-dropdown"> <router-link to="/"> <el-dropdown-item> Home </el-dropdown-item> </router-link> <el-dropdown-item divided @click.native="changePass"> <span style="display:block;">Change Pass</span> </el-dropdown-item> <el-dropdown-item divided @click.native="logout"> <span style="display:block;">Log Out</span> </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> </div> </template> <script> import { mapGetters } from 'vuex' import Breadcrumb from '@/components/Breadcrumb' import Hamburger from '@/components/Hamburger' import { resetPass } from '@/api/user' export default { components: { Breadcrumb, Hamburger }, data() { return { form: { new_pw1: '', new_pw2: '', old_pw: '' }, dialogFormVisible: false } }, computed: { ...mapGetters([ 'sidebar', 'avatar' ]) }, methods: { modify() { this.$refs.form.validate(valid => { if (valid) { resetPass(this.form).then(() => { this.$message({ message: "修改密码成功", type: 'success' }) this.dialogFormVisible = false }) } }) }, resetForm() { this.form = { new_pw1: '', old_pw: '', new_pw2: '' } }, changePass() { this.resetForm() this.dialogFormVisible = true }, toggleSideBar() { this.$store.dispatch('app/toggleSideBar') }, async logout() { await this.$store.dispatch('user/logout') this.$router.push(`/login?redirect=${this.$route.fullPath}`) } } } </script> <style lang="scss" scoped> .navbar { height: 50px; overflow: hidden; position: relative; background: #fff; box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08); .hamburger-container { line-height: 46px; height: 100%; float: left; cursor: pointer; transition: background 0.3s; -webkit-tap-highlight-color: transparent; &:hover { background: rgba(0, 0, 0, 0.025); } } .breadcrumb-container { float: left; } .right-menu { float: right; height: 100%; line-height: 50px; &:focus { outline: none; } .right-menu-item { display: inline-block; padding: 0 8px; height: 100%; font-size: 18px; color: #5a5e66; vertical-align: text-bottom; &.hover-effect { cursor: pointer; transition: background 0.3s; &:hover { background: rgba(0, 0, 0, 0.025); } } } .avatar-container { margin-right: 30px; .avatar-wrapper { margin-top: 5px; position: relative; .user-avatar { cursor: pointer; width: 40px; height: 40px; border-radius: 10px; } .el-icon-caret-bottom { cursor: pointer; position: absolute; right: -20px; top: 25px; font-size: 12px; } } } } } </style>
[Home](../) - [Reference Guide](index.md) # methodPrefix method configuration It is possible to configure which method prefix is used for the builders. If the `@Builder` annotation property is defined then this value is used, otherwise the compiler argument is used. If neither are present then the the prefix `with` will be used. ## Examples ### fluent methods using no prefix ```java @Builder(methodPrefix = "") public class NoPrefix { private boolean booleanField; private final String stringField; public NoPrefix(String stringField) { this.stringField = stringField; } public String getStringField() { return stringField; } public boolean getBooleanField() { return booleanField; } public void setBooleanField(boolean booleanField) { this.booleanField = booleanField; } } ``` will generate a Builder with the following methods: ```java public class NoPrefixBuilder<PARENT> { private boolean booleanField; private String stringField; private PARENT parent; public NoPrefixBuilder() { } public NoPrefixBuilder(PARENT parent) { this.parent = parent; } public NoPrefixBuilder<PARENT> booleanField(boolean booleanField) { this.booleanField = booleanField; return this; } public NoPrefixBuilder<PARENT> stringField(String stringField) { this.stringField = stringField; return this; } /* followed by build method, end method, etc. */ } ``` ### methods using a different prefix ```java @Builder(methodPrefix = "set") public class SetPrefix { private boolean booleanField; private final String stringField; public SetPrefix(String stringField) { this.stringField = stringField; } public String getStringField() { return stringField; } public boolean getBooleanField() { return booleanField; } public void setBooleanField(boolean booleanField) { this.booleanField = booleanField; } } ``` will generate a Builder with the following methods: ```java public class SetPrefixBuilder<PARENT> { private boolean booleanField; private String stringField; private PARENT parent; public SetPrefixBuilder() { } public SetPrefixBuilder(PARENT parent) { this.parent = parent; } public SetPrefixBuilder<PARENT> setBooleanField(boolean booleanField) { this.booleanField = booleanField; return this; } public SetPrefixBuilder<PARENT> setStringField(String stringField) { this.stringField = stringField; return this; } /* followed by build method, end method, etc. */ } ```
"use client"; import Loader from "@/components/loader/Loader"; import Button from "@/components/utilities/button/Button"; import Input from "@/components/utilities/input/Input"; import SelectInput from "@/components/utilities/select/SelectInput"; import TextArea from "@/components/utilities/textarea/TextArea"; import { movieAvaliabilityOptions, movieQualityOptions, } from "@/constants/movie.constants"; import fetcher from "@/libs/fetcher"; import { MovieCreationSchemaType, moviecreationschema, } from "@/schema/movie.schema"; import { zodResolver } from "@hookform/resolvers/zod"; import axios from "axios"; import { useRouter } from "next/navigation"; import React, { useEffect, useState } from "react"; import { useForm, FieldValues, SubmitHandler } from "react-hook-form"; import { toast } from "react-hot-toast"; import { MultiSelect } from "react-multi-select-component"; import useSWR, { mutate } from "swr"; type multiselectType = { label: string; value: string }; const Page = () => { const [selectedGenre, setSelectedGenre] = useState<multiselectType[]>([]); const [isLoading, setIsLoading] = useState<boolean>(false); const { data, error, isLoading: isGenreLoading, } = useSWR("/api/genre", fetcher); const router = useRouter(); const { register, handleSubmit, setValue, reset, formState: { errors }, } = useForm<FieldValues>({ resolver: zodResolver(moviecreationschema), defaultValues: { name: "", isSeries: "", mainImg: "", coverImg: "", trailer: "", description: "", releaseDate: "", genre: [], casts: "", duration: "", country: "", production: "", quality: "", imdbRating: "", availability: "", downloadLink: "", }, }); useEffect(() => { const genreValue = selectedGenre.map((item: any) => item.value); setValue("genre", genreValue, { shouldDirty: true, shouldTouch: true, shouldValidate: true, }); }, [selectedGenre, setValue]); let genreOptions = []; if (data) { genreOptions = data.map((item: any) => ({ label: item.name, value: item._id, })); } const onSubmitHandler: SubmitHandler< FieldValues | MovieCreationSchemaType > = async (data) => { try { setIsLoading(true); let { coverImg, mainImg, ...payload } = data; const mainFormData = new FormData(); mainFormData.append("file", mainImg[0]); mainFormData.append( "upload_preset", process.env.NEXT_PUBLIC_UNSIGNED_PRESET as string ); const coverFormData = new FormData(); coverFormData.append("file", coverImg[0]); coverFormData.append( "upload_preset", process.env.NEXT_PUBLIC_UNSIGNED_PRESET as string ); const mainImgResponseData = await axios.post( process.env.NEXT_PUBLIC_CLOUDINARY_API as string, mainFormData ); const coverImgResponseData = await axios.post( process.env.NEXT_PUBLIC_CLOUDINARY_API as string, coverFormData ); axios .post("/api/movie", { coverImg: coverImgResponseData.data.secure_url, mainImg: mainImgResponseData.data.secure_url, ...payload, }) .then(() => { toast.success("movie created"); reset(); mutate("/api/movie"); router.refresh(); }) .catch((err) => { console.log(err); toast.error(`Something went wrong`); }); } catch (err: any) { console.log(err); toast.error("ERROR CREATING MOVIE!!!"); } finally { setIsLoading(false); } }; if (error) { throw new Error("Failed to fetch genres, can't create movie"); } return ( <> <Loader loading={isLoading} /> <h1 className="text-2xl text-gray-500">Create Movie Page</h1> <form className="mt-4 flex flex-col gap-6" onSubmit={handleSubmit(onSubmitHandler)} > <Input id={"name"} label={"Name"} disabled={false} required={true} errors={errors} register={register} /> <SelectInput id={"isSeries"} label="Is this a Series" disabled={false} required={true} errors={errors} register={register} options={[ { label: "Yes", value: "true" }, { label: "No", value: "false" }, ]} defaultValue={"false"} /> <Input id={"mainImg"} label={"Main Image"} disabled={false} required={true} type="file" errors={errors} register={register} /> <Input id={"coverImg"} label={"Cover Image"} disabled={false} type="file" required={true} errors={errors} register={register} /> <Input id={"trailer"} label={"Trailer (link to url)"} disabled={false} required={true} errors={errors} register={register} /> <TextArea id={"description"} label={"Description"} disabled={false} required={true} errors={errors} rows={3} register={register} /> <Input id={"releaseDate"} label={"Release Date"} type="date" disabled={false} required={true} errors={errors} register={register} /> {/*@ts-ignore */} <small className="text-rose-500">{errors.genre?.message}</small> <MultiSelect isLoading={isGenreLoading} options={genreOptions} value={selectedGenre} onChange={setSelectedGenre} labelledBy={"Select Genre"} hasSelectAll={false} isCreatable={false} /> <TextArea id={"casts"} label={"Casts. e.g; Paul Walker, Will Smith"} disabled={false} required={true} errors={errors} register={register} rows={3} /> <Input id={"duration"} label={"Duration (in mins)"} disabled={false} type="number" required={true} errors={errors} register={register} /> <TextArea id={"country"} rows={3} label={"Country(ies) Filmed"} disabled={false} required={true} errors={errors} register={register} /> <Input id={"production"} label={"Production Company. e.g; Sony, Paramount"} disabled={false} required={true} errors={errors} register={register} /> <SelectInput id={"quality"} label={"Movie Quality. e.g; POOR/AVERAGE/GOOD/EXCELLENT"} disabled={false} required={true} errors={errors} register={register} options={movieQualityOptions} defaultValue={"AVERAGE"} /> <Input id={"imdbRating"} label={"IMDB Rating (optional)"} type="number" step={0.01} min={0} max={10} disabled={false} required={true} errors={errors} register={register} /> <SelectInput defaultValue={"available"} id={"availability"} options={movieAvaliabilityOptions} label={"Availability"} disabled={false} required={true} errors={errors} register={register} /> <Input id={"downloadLink"} label={"Download Link"} disabled={false} required={true} errors={errors} register={register} /> <div> <Button isSmall sec disable={isLoading}> SAVE </Button> </div> </form> </> ); }; export default Page;
// Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 import { encrypt, decrypt } from '_shared/cryptography/keystore'; import { entropyToMnemonic, entropyToSerialized, mnemonicToEntropy, toEntropy, validateEntropy, } from '_shared/utils/bip39'; export const LATEST_VAULT_VERSION = 1; export type StoredData = string | { v: number; data: string }; /** * Holds the mnemonic of the wallet and provides functionality to create/encrypt/decrypt it. */ export class Vault { public readonly entropy: Uint8Array; public static async from( password: string, data: StoredData, onMigrateCallback?: (vault: Vault) => Promise<void> ) { let entropy: Uint8Array | null = null; let doMigrate = false; if (typeof data === 'string') { entropy = mnemonicToEntropy( Buffer.from(await decrypt<string>(password, data)).toString( 'utf-8' ) ); doMigrate = true; } else if (data.v === 1) { entropy = toEntropy(await decrypt<string>(password, data.data)); } else { throw new Error( "Unknown data, provided data can't be used to create a Vault" ); } if (!validateEntropy(entropy)) { throw new Error("Can't restore Vault, entropy is invalid."); } const vault = new Vault(entropy); if (doMigrate && typeof onMigrateCallback === 'function') { await onMigrateCallback(vault); } return vault; } constructor(entropy: Uint8Array) { this.entropy = entropy; } public async encrypt(password: string) { return { v: LATEST_VAULT_VERSION, data: await encrypt(password, entropyToSerialized(this.entropy)), }; } public getMnemonic() { return entropyToMnemonic(this.entropy); } }
<!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>MNTN</title> <!-- style css --> <link rel="stylesheet" href="./css/main.css"> </head> <body> <header class="header"> <nav class="nav-wrapper"> <div class="container-wide"> <div class="row space-between align-center"> <h2 class="logo">MNTN</h2> <div class="nav "> <ul> <li><a href="#">Equipment</a></li> <li><a href="#">About us</a></li> <li><a href="#">Blog</a></li> </ul> </div> <a href="#" class="account">Account</a> </div> </div> </nav> <a href="#" class="hero"> <div class="hero-catigory"> A Hiking guide </div> <h1 class="hero-title"> Be prepared for the Mountains and beyond! </h1> <p class="hero-scroll">scroll down</p> </a> </header> <main class="main"> <div class="container"> <article class="article"> <div class="article-text" data-number="01"> <div class="article-subtitle">Get Started</div> <h2 class="article-title">What level of hiker are you?</h2> <p>Determining what level of hiker you are can be an important tool when planning future hikes. This hiking level guide will help you plan hikes according to different hike ratings set by various websites like All Trails and Modern Hiker. What type of hiker are you – novice, moderate, advanced moderate, expert, or expert backpacker? </p> <a href="#" class="article-read-more">read more</a> </div> <div class="article-imag"> <img src="./img/picture/01.jpg" alt=" What level of hiker are you?"> </div> </article> </article> <article class="article"> <div class="article-text" data-number="02"> <div class="article-subtitle">Hiking Essentials</div> <h2 class="article-title">Picking the right Hiking Gear!</h2> <p>The nice thing about beginning hiking is that you don’t really need any special gear, you can probably get away with things you already have. Let’s start with clothing. A typical mistake hiking beginners make is wearing jeans and regular clothes, which will get heavy and chafe wif they get sweaty or wet. </p> <a href="#" class="article-read-more">read more</a> </div> <div class="article-imag"> <img src="./img/picture/02.jpg" alt=" Hiking Essentials"> </div> </article> <article class="article"> <div class="article-text" data-number="03"> <div class="article-subtitle">where you go is the key</div> <h2 class="article-title">Understand Your Map & Timing</h2> <p>To start, print out the hiking guide and map. If it’s raining, throw them in a Zip-Lock bag. Read over the guide, study the map, and have a good idea of what to expect. I like to know what my next landmark is as I hike. For example, I’ll read the guide and know that say, in a mile, I make a right turn at the junction.. </p> <a href="#" class="article-read-more">read more</a> </div> <div class="article-imag"> <img src="./img/picture/03.jpg" alt="where you go is the key"> </div> </article> </div> </main> <footer class="footer"> <div class="container"> <div class="row space-between"> <div class="footer-copyright"> <div class="footer-copyright-logo"> <div class="logo">MNTN</div> <p class="footer-copyright-desc">Get out there & discover your next slope, mountain & destination!</p> </div> <p class="footer-copyright-terms">Copyright 2019 MNTN, Inc. Terms & Privacy</p> </div> <div class="footer-nav-wrapper"> <div class="footer-nav"> <h4 class="footer-nav-title">More on The Blog</h4> <ul> <li><a href="#">About MNTN</a></li> <li><a href="#">Contributors & Writers</a></li> <li><a href="#">Write For Us </a></li> <li><a href="#"> Contact Us</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div> <div class="footer-nav"> <h4 class="footer-nav-title"> More on MNTN</h4> <ul> <li><a href="#">The Team</a></li> <li><a href="#">Jobs</a></li> <li><a href="#">Press </a></li> </ul> </div> </div> </div> </div> </footer> </body> </html>
'use strict'; import {Controller, Get, Response, HttpStatus, Param, Query, Body, Post, Request, Patch, Delete} from '@nestjs/common'; import {PostService} from './post.service'; import {PostEditModel} from './models/postEdit.model'; @Controller('posts') export class PostController { constructor(private readonly postService: PostService) {} /** * find posts by query string * @param res response * @param query req.query */ @Get('find') public async findPosts(@Response() res, @Query() query) { const where = this.postService.castQuery(query); const posts = await this.postService.find(where); return res.status(HttpStatus.OK).json(posts); } /** * find post by id * @param res response * @param param req.param * @param param._id post ID */ @Get(':_id') public async findUserById(@Response() res, @Param() param) { const post = await this.postService.findById(param._id); return res.status(HttpStatus.OK).json(post); } /** * create a post * @param res response * @param postEditModel */ @Post() public async createPost(@Response() res, @Body() postEditModel: PostEditModel) { const post = await this.postService.create(postEditModel); return res.status(HttpStatus.OK).json(post); } /** * update a post by id * @param param * @param res response * @param body req.body */ @Patch(':_id') public async updatePost(@Param() param, @Response() res, @Body() body) { const post = await this.postService.update(param._id, body); return res.status(HttpStatus.OK).json(post); } }
''' Given an expression string x. Examine whether the pairs and the orders of {,},(,),[,] are correct in exp. For example, the function should return 'true' for exp = [()]{}{[()()]()} and 'false' for exp = [(]). Note: The drive code prints "balanced" if function return true, otherwise it prints "not balanced". Example 1: Input: {([])} Output: true Explanation: { ( [ ] ) }. Same colored brackets can form balanced pairs, with 0 number of unbalanced bracket. Example 2: Input: () Output: true Explanation: (). Same bracket can form balanced pairs, and here only 1 type of bracket is present and in balanced way.''' class Solution: #Function to check if brackets are balanced or not. def ispar(self,x): # code here stack = [] for char in x: if char in '([{': stack.append(char) else: if not stack: return False top = stack.pop() if (top == '(' and char != ')') or \ (top == '[' and char != ']') or \ (top == '{' and char != '}'): return False return len(stack) == 0
import { TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; import { MenuComponent } from './core/menu/menu.component'; describe('AppComponent', () => { beforeEach(() => TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [ AppComponent, MenuComponent, // il faut bien penser à déclarer tous les components utilisés dans le template ], errorOnUnknownElements: true, errorOnUnknownProperties: true, })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); });
package com.example.wemakepass.view.board.main; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.widget.NestedScrollView; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import com.example.wemakepass.R; import com.example.wemakepass.adapter.PostListAdapter; import com.example.wemakepass.data.enums.ErrorCode; import com.example.wemakepass.data.model.dto.BoardDTO; import com.example.wemakepass.data.model.dto.PostDTO; import com.example.wemakepass.data.model.dto.response.PostPageResponse; import com.example.wemakepass.databinding.FragmentBoardMainBinding; import com.example.wemakepass.util.DialogUtils; import com.example.wemakepass.util.MessageUtils; import com.example.wemakepass.view.board.BoardActivity; import com.example.wemakepass.view.board.post.search.PostSearchFragment; import com.example.wemakepass.view.board.post.viewer.PostViewerFragment; import com.example.wemakepass.view.board.post.editor.PostEditorFragment; import com.google.android.material.tabs.TabLayout; import java.util.ArrayList; import java.util.List; /** * - 특정 게시판의 홈페이지 역할을 하는 Fragment다. * - 페이징을 위한 page 변수의 경우 ViewModel에 영향을 받지 않도록 View 단에 선언했다. 화면에 리프레쉬 될 경우 * 게시글 목록도 같이 리프레쉬되도록 하기 위함이다. * * @author BH-Ku * @since 2023-11-30 */ public class BoardMainFragment extends Fragment { private FragmentBoardMainBinding binding; private BoardMainViewModel viewModel; private PostListAdapter postListAdapter; private BoardDTO boardDTO; // 표시할 게시판 정보 private int pageNo; // 페이징을 수행하기 위한 변수로 현재 출력하고 있는 페이지를 나타낸다. private boolean lastPage; // 마지막에 조회한 페이지가 마지막 페이지인지 여부 private final String TAG = "TAG_BoardMainFragment"; public static BoardMainFragment newInstance(BoardDTO boardDTO) { BoardMainFragment fragment = new BoardMainFragment(); Bundle bundle = new Bundle(); bundle.putSerializable(BoardActivity.ARG_SELECTED_BOARD, boardDTO); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); assert bundle != null; boardDTO = (BoardDTO) bundle.getSerializable(BoardActivity.ARG_SELECTED_BOARD); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_board_main, container, false); binding.setLifecycleOwner(this); viewModel = new ViewModelProvider(this).get(BoardMainViewModel.class); binding.setViewModel(viewModel); // 로딩이 끝날 때까지 터치 방지 requireActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initToolbar(); initPostRecyclerView(); initNestedScrollViewScrollListener(); initObserver(); initEventListener(); initFragmentResultListener(); viewModel.loadCategory(boardDTO.getBoardNo()); } /** * Toolbar를 초기화한다. */ private void initToolbar() { binding.fragmentBoardMainToolbar.setTitle(boardDTO.getBoardName()); binding.fragmentBoardMainToolbar.setNavigationOnClickListener(v -> requireActivity().finish()); binding.fragmentBoardMainToolbar.setOnMenuItemClickListener(item -> { ((BoardActivity)requireActivity()).addFragment( PostSearchFragment.newInstance(boardDTO, viewModel.getCategoryArray()), R.anim.slide_from_bottom, R.anim.slide_to_bottom); return true; }); // 검색 버튼 추가 } /** * - TabLayout에 대한 초기화를 수행한다. * - 이 화면이 실행되면 표시하려는 게시판의 카테고리 목록을 불러온다. 데이터가 조회될 경우에 이 메서드가 * 호출되어 불러온 카테고리 목록을 기반으로 TabLayout을 구성한다. * - 첫 번째 탭은 반드시 "전체"가 된다. * * @param categoryList */ private void initTabLayout(List<String> categoryList) { TabLayout tabLayout = binding.fragmentBoardMainTabLayout; tabLayout.addTab(tabLayout.newTab().setText("전체")); for(String category : categoryList) tabLayout.addTab(tabLayout.newTab().setText(category)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { /** * 새로운 탭이 선택되었다는 것은 특정 카테고리가 선택되었기 때문에 새로운 목록을 조회해야 함을 뜻한다. * 따라서 pageNo를 0으로 초기화하고 게시글 RecyclerView을 초기화한다. * * @param tab The tab that was selected */ @Override public void onTabSelected(TabLayout.Tab tab) { lastPage = false; // 마지막 페이지 여부 초기화 pageNo = 0; // 페이지 초기화 postListAdapter.submitList(null); // 리스트 초기화 binding.fragmentBoardMainPostLoadingProgressBar.setVisibility(View.VISIBLE); viewModel.loadPosts(boardDTO.getBoardNo(), pageNo++, tabLayout.getSelectedTabPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) {} @Override public void onTabReselected(TabLayout.Tab tab) {} }); } /** * - 게시글 목록 RecylcerView를 초기화한다. * - 각 아이템을 선택하면 게시글 내용이나 댓글 등의 데이터를 띄어주는 프래그먼트를 실행한다. */ private void initPostRecyclerView() { RecyclerView recyclerView = binding.fragmentBoardMainPostRecyclerView; postListAdapter = new PostListAdapter(); postListAdapter.setOnItemClickListener(position -> { ((BoardActivity)requireActivity()).addFragment(PostViewerFragment.newInstance( boardDTO.getBoardName(), postListAdapter.getCurrentList().get(position).getPostNo()), R.anim.slide_from_end, R.anim.slide_to_end); }); LinearLayoutManager layoutManager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setAdapter(postListAdapter); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), RecyclerView.VERTICAL)); } /** * 무한 로딩을 수행하기 위해서 스크롤 리스너를 구현하였다. 스크롤이 될 때 스크롤의 위치를 확인하여 끝까지 * 내려왔다면 ContentLoadingProgressBar를 표시하고 다음 데이터를 요청한다. */ private void initNestedScrollViewScrollListener(){ binding.fragmentBoardMainNestedScrollView.setOnScrollChangeListener( (NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> { // 스크롤이 끝까지 내려왔음. if(scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()){ // 마지막에 조회한 데이터가 마지막 페이지였을 경우 추가 조회를 수행하지 않음. if(lastPage) { MessageUtils.showSnackbar(binding.getRoot(), "마지막 페이지입니다."); return; } binding.fragmentBoardMainPostLoadingProgressBar.setVisibility(View.VISIBLE); viewModel.loadPosts(boardDTO.getBoardNo(), pageNo++, binding.fragmentBoardMainTabLayout.getSelectedTabPosition()); } }); } /** * - PostEditorFragment에서 게시글 작성에 성공할 경우 게시글 목록을 다시 로딩하기 위해 * FragmentResultListener를 설정한다. * - 목록을 갱신은 반드시 전체 카테고리를 기준으로 하기 때문에 현재 TabLayout에 선택된 Tab이 "전체"라면 * page를 초기화하여 목록 갱신을, "전체"가 아니라면 Tab을 강제로 변경한다. */ private void initFragmentResultListener() { getParentFragmentManager() .setFragmentResultListener(PostEditorFragment.RESULT_REQUEST_CODE_POST_EDITOR_FRAGMENT, requireActivity(), (requestKey, result) -> { if(result.getBoolean(PostEditorFragment.ARG_WRITE_STATUS)){ TabLayout tabLayout = binding.fragmentBoardMainTabLayout; if(tabLayout.getSelectedTabPosition() == 0){ lastPage = false; viewModel.loadPosts(boardDTO.getBoardNo(), pageNo = 0, 0); } else { tabLayout.selectTab(tabLayout.getTabAt(0)); } } }); } /** * LiveData와 직접적인 연관이 없는 View에 대한 이벤트를 설정하는 메서드. */ private void initEventListener() { // 게시글 작성 binding.fragmentBoardMainPostWriteFab.setOnClickListener(v -> { if(viewModel.getCategoryListLiveData().getValue() == null) return; ((BoardActivity) requireActivity()). addFragment(PostEditorFragment.newInstance(boardDTO.getBoardNo(), viewModel.getCategoryArray()), R.anim.slide_from_end, R.anim.slide_to_end); }); } /** * LiveData에 대한 옵저빙을 설정한다. */ private void initObserver() { // 게시판의 카테고리를 읽어 오는 것을 관찰하고 데이터가 감지되면 TabLayout을 초기화한다. viewModel.getCategoryListLiveData().observe(this, categoryList -> { initTabLayout(categoryList); requireActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); viewModel.loadPosts(boardDTO.getBoardNo(), pageNo++, 0); }); // 게시글 조회에 성공했을 경우 처리를 위한 메서드를 호출한다. viewModel.getPostListLiveData().observe(this, this::setPostList); viewModel.getNetworkErrorLiveData().observe(this, errorResponse -> { String errorCode = errorResponse.getCode(); if(errorCode.equals(ErrorCode.POST_LIST_LOADING_FAILED.name()) || errorCode.equals(ErrorCode.BOARD_CATEGORY_LOADING_FAILED.name()) ) { // 네트워크 오류로 인한 카테고리 로딩 실패, 네트워크 오류로 인한 게시글 로딩 실패 DialogUtils.showAlertDialog(requireContext(), errorResponse.getMessage(), dialog -> requireActivity().finish()); return; } MessageUtils.showToast(requireContext(), errorResponse.getMessage()); }); } /** * - 게시글 조회에 성공했을 경우 이 메서드가 호출되며 조회한 데이터를 기반으로 RecyclerView를 갱신한다. * - 조회한 데이터의 페이지 번호가 0이고 읽어온 데이터가 없을 경우 해당 게시판, 카테고리에 등록된 게시글이 * 없다고 판단하고 메시지를 출력한다. * - 조회한 페이지가 마지막일 경우 상태(lastPage)를 저장하여 카테고리가 변경되기 전까지는 추가 조회가 발생하지 * 않도록 한다. * - 조회한 페이지 번호가 0일 경우 조회한 데이터 목록을 그대로 submit하여 갱신하고 0이 아닐 경우 추가 조회된 * 데이터라고 판단, 기존 리스트와 새로 조회된 리스트를 병합하여 submit한다. * * @param postPageResponse */ private void setPostList(PostPageResponse postPageResponse) { binding.fragmentBoardMainPostLoadingProgressBar.setVisibility(View.GONE); if(postPageResponse.getPageNo() == 0 && postPageResponse.getPostList().size() == 0){ MessageUtils.showToast(requireContext(), "등록된 게시물이 없습니다."); return; } // 특정 Board, Category에 대한 게시물이 전혀 없음. lastPage = postPageResponse.isLast(); // 현재 읽은 페이지가 마지막 페이지 if(postPageResponse.getPageNo() == 0){ postListAdapter.submitList(postPageResponse.getPostList()); return; } // 첫 페이지 List<PostDTO> list = new ArrayList<>(postListAdapter.getCurrentList().size() + postPageResponse.getPostList().size()); list.addAll(postListAdapter.getCurrentList()); list.addAll(postPageResponse.getPostList()); postListAdapter.submitList(list); } }
const dbConnection = require("@database/databaseConnection"); const { knex } = dbConnection(); /** * Retrieves base historical recoveries to be combined in the final query. * * @param {string} fiscal - Fiscal year value to filter the report. * @returns {Knex.QueryBuilder} Knex query builder for fetching report data. */ const baseQueries = { projectRecoveryHistorical: knex("historical_projects") .select({ project_number: "historical_projects.project_number", project_name: "historical_projects.project_name", total_project_budget: "historical_projects.total_project_budget", fiscal_id: "fiscal_year.id", budget_fiscal: "fiscal_year.fiscal_year", q1: "historical_project_billing.q1", q2: "historical_project_billing.q2", q3: "historical_project_billing.q3", q4: "historical_project_billing.q4", total_recovered: knex.raw( "cast( COALESCE(Q1, '0') + COALESCE(Q2, '0') + COALESCE(Q3, '0') + COALESCE(Q4, '0') as money)" ), }) .innerJoin("fiscal_year", "historical_projects.fiscal_year", "fiscal_year.id") .innerJoin( "historical_project_billing", "historical_projects.project_number", "historical_project_billing.project_number" ) .groupBy( "historical_projects.project_number", "historical_projects.project_name", "historical_projects.total_project_budget", "fiscal_year.id", "fiscal_year.fiscal_year", "historical_project_billing.q1", "historical_project_billing.q2", "historical_project_billing.q3", "historical_project_billing.q4" ), projectRecovery: knex("fiscal_year") .select({ project_id: "project.id", project_number: "project.project_number", project_name: "project.project_name", total_project_budget: "project.total_project_budget", fiscal_id: "fiscal_year.id", fiscal_year: "fiscal_year.fiscal_year", q1: knex.raw(`sum(case when quarter = '1' then amount else null end)`), q2: knex.raw(`sum(case when quarter = '2' then amount else null end)`), q3: knex.raw(`sum(case when quarter = '3' then amount else null end)`), q4: knex.raw(`sum(case when quarter = '4' then amount else null end)`), total_recovered: knex.sum("jv.amount"), }) .innerJoin("jv", "fiscal_year.id", "jv.fiscal_year_id") .innerJoin("project", "jv.project_id", "project.id") .groupBy( "project.id", "project.project_number", "project.total_project_budget", "fiscal_year.id", "fiscal_year.fiscal_year" ), }; /** * Retrieves final historical recoveries for the report. * * @param {number | string | Array} fiscal - The fiscal year(s) to retrieve totals for. * @returns {Knex.QueryBuilder} Knex query builder for fetching report data. */ const reportQueries = { report: (fiscal) => knex .select({ budget_fiscal: "project_recovery_historical.budget_fiscal", project_number: "project_recovery_historical.project_number", project_name: "project_recovery_historical.project_name", total_project_budget: "project_recovery_historical.total_project_budget", q1: "project_recovery_historical.q1", q2: "project_recovery_historical.q2", q3: "project_recovery_historical.q3", q4: "project_recovery_historical.q4", total_recovered: knex.raw( "cast( COALESCE(Q1, '0') + COALESCE(Q2, '0') + COALESCE(Q3, '0') + COALESCE(Q4, '0') as money)" ), }) .from(baseQueries.projectRecoveryHistorical.as("project_recovery_historical")) .where("fiscal_id", fiscal) .unionAll([ knex .select({ budget_fiscal: "project_recovery.fiscal_year", project_number: "project_recovery.project_number", project_name: "project_recovery.project_name", total_project_budget: "project_recovery.total_project_budget", q1: "q1", q2: "q2", q3: "q3", q4: "q4", total_recovered: "total_recovered", }) .from(baseQueries.projectRecovery.as("project_recovery")) .where("fiscal_id", fiscal) .orderBy("project_number"), ]), report_totals: (fiscal) => knex .from(baseQueries.projectRecoveryHistorical.as("project_recovery_historical")) .select({ q1_total: knex.sum("q1"), q2_total: knex.sum("q2"), q3_total: knex.sum("q3"), q4_total: knex.sum("q4"), grand_total: knex.sum("total_recovered"), }) .where("fiscal_id", fiscal), }; module.exports = { required: ["fiscal"], getAll: async ({ fiscal }) => { const [report, report_totals] = await Promise.all([ reportQueries.report(fiscal), reportQueries.report_totals(fiscal), ]); return { report, report_totals }; }, };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="create.css"> </head> <body> <nav> <button>about</button> <button>credit</button> </nav> <input type="checkbox" id="flip"> <div class="card"> <div class="cover"> <label for="flip"></label> </div> <div class="page" id="page"> <div id="ms"> <h1 id="title" contenteditable="true"></h1> <p id="body" contenteditable="true" aria-placeholder="enter your wish..">Wishing you a Christmas filled with the love of family and friends</p> <h3 id="name" contenteditable="true">-name</h3> </div> </div> <div class="back_cover"></div> </div> <div id="edit"> <fieldset id="temps"> <legend>Templates</legend> <button id="btn1" onclick="set1()"></button> <button id="btn2" onclick="set2()"></button> <button id="btn3" onclick="set3()"></button> <button id="btn4" onclick="set4()"></button> <button id="btn5" onclick="set5()"></button> </fieldset> <fieldset id="edit_txt"> <legend>Edit text</legend> <button id="edit_title">Titile</button> <button id="edit_body">Body</button> <button id="edit_from">From</button> <input type="text" id="input" placeholder="Enter the text..."> </fieldset> <button id="create_btn">Create</button> </div> <p>To edit the text click on the reqired text or you can use the text input for entering text</p> <div id="pop"> <h5>Copy the link and share with your friends and family</h5> <input type="text" id="link"> <button id="copy">Copy</button> </div> <div id="block"> </div> <script src="script.js"></script> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js"; import { getDatabase, set, ref, child, update, remove, push, get } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-database.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "AIzaSyC4trdI5PrJs3W6yoWSGn39S4KFwL41N8A", authDomain: "wish-box-ca6ea.firebaseapp.com", databaseURL: "https://wish-box-ca6ea-default-rtdb.asia-southeast1.firebasedatabase.app", projectId: "wish-box-ca6ea", storageBucket: "wish-box-ca6ea.appspot.com", messagingSenderId: "1043895090410", appId: "1:1043895090410:web:c0827e3d7d10d0461cab93" }; // Initialize Firebase const app = initializeApp(firebaseConfig); var db = getDatabase(); const dbref = ref(db); console.log(db); var template = document.getElementById("page"); var h1 = document.getElementById("title"); var temp = 0; function set1() { template.style.background = "url('tem4.jpg')"; template.style.backgroundSize = "100% 100%"; h1.innerText = ""; template.style.color = "black"; temp = 0; } function set2() { template.style.background = "url('temp5.jpg')"; template.style.backgroundSize = "100% 100%"; template.style.color = "black"; h1.innerText = "Title"; temp = 1; } function set3() { template.style.background = "url('temp6.jpg')"; template.style.backgroundSize = "100% 100%"; template.style.color = "black"; h1.innerText = "Title"; temp = 2; } function set4() { template.style.background = "url('temp2.jpg')"; template.style.backgroundSize = "100% 100%"; template.style.color = "white"; h1.innerText = "Title"; temp = 3; } function set5() { template.style.background = "url('temp3.jpg')"; template.style.backgroundSize = "100% 100%"; template.style.color = "black"; h1.innerText = "Title"; temp = 4; } var input = document.getElementById("input"); let current; document.getElementById("edit_title").addEventListener("click", () => { current = 1; }) document.getElementById("edit_body").addEventListener("click", () => { current = 2; }) document.getElementById("edit_from").addEventListener("click", () => { current = 3; }) input.addEventListener("keyup", () => { if (current == 1) { document.getElementById("title").innerText = input.value; document.getElementById("title").style.textAlign = "center"; } else if (current == 2) { document.getElementById("body").innerText = input.value; } else { document.getElementById("from").innerText = input.value; } }) document.getElementById("block").addEventListener("click", () => { document.getElementById("block").style.display = "none"; document.getElementById("pop").style.display = "none"; }) var userno; window.onload = () => { get(child(dbref, 'Userno')).then((snapshot) => { userno = Object.values(snapshot.val()); console.log(userno); }) } document.getElementById("create_btn").addEventListener("click", () => { var newuser = "ID" + (userno[0] + 1); set(ref(db, "cards/ID" + (userno[0]+ 1)), { template: temp, title: document.getElementById("title").innerText, wish: document.getElementById("body").innerText, from: document.getElementById("name").innerText, }).then(() => { document.getElementById("pop").style.display = "block"; document.getElementById("block").style.display = "block"; document.getElementById("link").value = window.location.href + "?" + newuser; set(ref(db,"Userno"), { no:(userno[0]+ 1) }) get(child(dbref, 'Userno')).then((snapshot) => { userno = Object.values(snapshot.val()); console.log(userno); }) }) }) document.getElementById("copy").addEventListener("click", () => { var copyText = document.getElementById("link"); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); alert("Copied the text: " + copyText.value); }) </script> </body> </html>
<div> <mat-toolbar> <button mat-icon-button class="example-icon" aria-label="Example icon-button with menu icon"> <mat-icon>menu</mat-icon> </button> <span id="logo" routerLink="/home">movieDB v2</span> <span class="example-spacer"></span> <form class="example-form"> <mat-form-field class="example-full-width"> <input type="text" (input)="search($event.target.value)" placeholder="Search" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"> <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete"> <mat-option *ngFor="let option of _options" [value]="option['title']" (onSelectionChange)="enter(option['type'], option['id'])" [routerLink]="['/content', option['type'], option['id']]"> {{ option['title'] || option['name'] }} <span class="right">{{ option['year'].substring(0,4) }}</span> </mat-option> </mat-autocomplete> </mat-form-field> </form> <span class="example-spacer"></span> <button class="transition" routerLink="/genres/movie" [ngStyle]="{background: param==='movie'?'red':'tv'?'':''}" mat-raised-button>Movies</button> <button class="transition" routerLink="/genres/tv" (mouseenter)="trigger.closeMenu()" [ngStyle]="{background: param==='tv'?'red':''}" mat-raised-button>Tv Shows</button> <button class="transition" routerLink="/home" *ngIf="!userData['name'] || !(user.auth|async)" mat-raised-button (click)="user.login()">Sign In</button> <!-- <button [matMenuTriggerFor]="menu" #trigger="matMenuTrigger" (mouseenter)="trigger.openMenu()" (mouseleave)="trigger.closeMenu()">Menu</button> --> <button mat-icon-button id="margin" *ngIf="userData['name'] && user.auth|async" class="transition" [matMenuTriggerFor]="menu" #trigger="matMenuTrigger" (mouseover)="trigger.openMenu()"> {{ userData['name'] }} <img mat-card-avatar [matBadge]="listCount" class="avatar" matBadgeColor="warn" [src]="userData['photoURL']" (mouseleave)="trigger.closeMenu()"> <!-- <mat-icon [matBadge]="listCount" matBadgeColor="warn" class="favorite">favorite</mat-icon> --> </button> <mat-menu #menu="matMenu" class="mat-menu-panel myMenu" [hasBackdrop]="false" overlapTrigger="false" xPosition="after"> <div (mouseleave)="trigger.closeMenu()"> <button mat-menu-item routerLink="/watchlist"> Watchlist <mat-icon [matBadge]="listCount" matBadgeColor="warn" class="favorite">favorite</mat-icon> </button> <button mat-menu-item (click)="user.logout()"> Logout </button> </div> </mat-menu> <!-- <div class="watchlist" routerLink="/watchlist"> <span>Watchlist</span> <button mat-icon-button class="example-icon favorite-icon" aria-label="Example icon-button with heart icon"> <mat-icon [matBadge]="listCount" matBadgeColor="warn">favorite</mat-icon> </button> </div> --> <!-- <button mat-icon-button class="example-icon" aria-label="Example icon-button with share icon"> <mat-icon>share</mat-icon> </button> --> </mat-toolbar> </div>
import React, { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { FetchTypeGet } from "../../lib/utils"; import { useEffect } from "react"; const UserAccounts = () => { const [users, setUsers] = useState([]); const user = useSelector((state) => state.user.currentUser); const changeValidity = async (id, validity) => { console.log(id, validity); if(!validity) return; validity=Boolean(validity); console.log(validity); const res = await fetch( `https://vast-pink-moth-toga.cyclic.app/accounts/changeValidity/${id} `, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: `Bearer ${user.token}`, }, body: JSON.stringify({valid:validity }), } ); const data = await res.json(); }; useEffect(() => { const fetchUser = async () => { if (!user) return; const data = await FetchTypeGet( "https://vast-pink-moth-toga.cyclic.app/accounts", user.token ); setUsers(data); console.log(data); }; fetchUser(); }, []); return ( <div className=" font-space"> <h1 className="text-white text-2xl text-center p-5">User Accounts</h1> <div> {user?.user?.admin ? ( <> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 "> {users.map((user) => ( <div key={user._id} className="flex flex-col text-white border overflow-hidden border-gray-500 rounded-md " > <h1 className="text-2xl text-center bg-gray-500">{user.username}</h1> <div className="flex items-center justify-between"> <div className="mb-4 rounded-md mt-3"> <h1 className="ml-2">Email : {user.email}</h1> <h1 className="ml-2">Batch : {user.batch}</h1> <h1 className="ml-2">Program : {user.program}</h1> <h1 className="ml-2"> Admin : {user.admin ? "true" : "false"} </h1> <h1 className="ml-2"> Teacher : {user.teacher ? "true" : "false"} </h1> <h1 className="ml-2"> Valid : {user.valid ? "true" : "false"} </h1> </div> <img src={`https://robohash.org/${ Math.random() * 100 }?set=set5&size=100x100`} alt="user" className="w-20 h-20 rounded-full mx-auto" /> </div> <div className="px-2 py-2"> <select onChange={(e) => changeValidity(user._id, e.target.value)} className="appearance-none text-white px-2 py-1 w-full bg-green-500 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500' focus:border-transparent " name="change type" id="" > <option value="valid">select option</option> {user.valid ? ( <option value="false">change to invalid</option> ) : ( <option value="true">change to valid</option> )} {user.teacher ? ( <option value="true">change to user</option> ) : ( <option value="true">change to teacher</option> )} </select> </div> </div> ))} </div> </> ) : ( <h1>Not Admin</h1> )} </div> </div> ); }; export default UserAccounts;
package dev.passerby.tourtestproject.domain.models data class TourModel( val toursContent: List<TourItem>, val error: Any?, val success: Boolean, val time: String ) { data class TourItem( val date: BaseDateModel, val duration: Duration, val home: Home, val id: Int, val image: BaseImageModel, val location: String, val price: Price, val title: String, val url: String ) { data class Duration( val day: Int?, val night: Int ) data class Home( val base: Base, val id: Int, val image: BaseImageModel, val name: String, val night: Int, val type: String, val url: String ) { data class Base( val id: Int, val name: String, val url: String ) } data class Price( val currency: String, val factPrice: Int, val price: Int, val typePrice: String ) } }
import { defineStore } from 'pinia' interface ItemsOrder { value: string label: string quantity: number bvalue: string blabel: string } interface Order { firstName: string middleName: string lastName: string country: string stateRegion: string province: string city: string barangay: string line1: string line2: string postal: number | null mobile: string telephone: string items: Array<ItemsOrder> } export const useOrderStore = defineStore('order', { state: () => ({ firstName: '', middleName: '', lastName: '', country: '', stateRegion: '', province: '', city: '', barangay: '', line1: '', line2: '', postal: 0, mobile: '', telephone: '', items: [], } as Order), getters: { GET_CUSTOMER_INFO: (state) => ({ firstName: state.firstName, middleName: state.middleName, lastName: state.lastName, country: state.country, stateRegion: state.stateRegion, province: state.province, barangay: state.barangay, city: state.city, line1: state.line1, line2: state.line2, postal: state.postal, mobile: state.mobile, telephone: state.telephone, }), GET_ITEMS_ORDER: (state) => { return state.items }, IS_MISSING_FIELDS: (state) => { return ( (state.firstName.length > 1 && state.country.length > 1 && state.stateRegion.length > 1 && state.province.length > 1 && state.city.length > 1 && state.line1.length > 1 && state.barangay.length > 1 && state.postal! > 0) ?? 'false' ) }, }, actions: { FILL_CUSTOMER_INFO(data: any) { ;(this.firstName = data.firstName), (this.middleName = data.middleName), (this.lastName = data.lastName), (this.country = data.country), (this.stateRegion = data.stateRegion), (this.province = data.province), (this.city = data.city), (this.barangay = data.barangay), (this.line1 = data.line1), (this.line2 = data.line2), (this.postal = data.postal), (this.mobile = data.mobile), (this.telephone = data.telephone) }, FILL_ITEMS_ORDER(data: any) { this.items.push(data) }, REMOVE_ITEM_ORDER(data: number) { this.items.splice(data, 1) }, }, })
class HotelInfo { final int id; final String name; final String tags; final double rating; final int discount; final String primaryImage; final double distance; HotelInfo({ required this.id, required this.name, required this.tags, required this.rating, required this.discount, required this.primaryImage, required this.distance, }); factory HotelInfo.fromJson(Map<String, dynamic> json) { return HotelInfo( id: json['id'] ?? 0, name: json['name'] ?? '', tags: json['tags'] ?? '', rating: (json['rating'] ?? 0.0).toDouble(), discount: json['discount'] ?? 0, primaryImage: json['primary_image'] ?? '', distance: (json['distance'] ?? 0.0).toDouble(), ); } @override String toString() { return 'HotelInfo{id: $id, name: $name, tags: $tags, rating: $rating, ' 'discount: $discount, primaryImage: $primaryImage, distance: $distance}'; } }
/* * Copyright 2023 Michael Johnston * * 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 * * https://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 com.github.mrbean355.bulldog.home import com.github.mrbean355.bulldog.gsi.Dota2 import com.github.mrbean355.bulldog.gsi.GameStateMonitor import com.github.mrbean355.bulldog.localization.getString import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch class HomeViewModel( private val viewModelScope: CoroutineScope ) { private val _showInstall = MutableStateFlow(false) val showInstall: StateFlow<Boolean> = _showInstall.asStateFlow() val header = MutableStateFlow(getString("home.header.waiting")) val showProgressIndicator = MutableStateFlow(true) val subHeader = MutableStateFlow(getString("home.subheader.waiting")) fun init() { viewModelScope.launch { val installed = Dota2.isValidPathSaved() _showInstall.value = !installed if (installed) { Dota2.installGameStateIntegration() GameStateMonitor.getLatestState().filterNotNull().first() header.value = getString("home.header.connected") showProgressIndicator.value = false subHeader.value = getString("home.subheader.connected") } } } }
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class PostsService { constructor(private http: HttpClient) {} private url = 'https://jsonplaceholder.typicode.com/posts'; getPosts() { return this.http.get<string[]>(this.url); } createPost(post: any) { return this.http.post(this.url, JSON.stringify(post)); } updatePosts(post: any) { const updatedData = { title: 'updated' }; return this.http.patch(this.url + '/' + post.id, updatedData); } deletePosts(post: any) { return this.http.delete(this.url + '/' + post.id).pipe( catchError((error) => { console.error('An error occurred:', error); return throwError('Something went wrong while deleting the post.'); }) ); } }
import React, { Component } from "react"; import { Table, Tag, Space, Input, Avatar } from "antd"; import {CheckOutlined, CloseOutlined} from "@ant-design/icons" import { connect } from "react-redux"; import { fetchCategories, deleteCategory } from "../../../actions/categories"; import { Link, withRouter } from "react-router-dom"; import PropTypes from "prop-types"; const { Search } = Input; class ListCategory extends Component { constructor() { super(); this.state = { columns: [ // { // title: "ID", // dataIndex: "_id", // key: "_id", // }, { title: "Name", dataIndex: "name", key: "name", render: (text) => <div> {text} </div> }, { title: "Description", key: "description", dataIndex: "description", render: (text) => <div> {text} </div> }, { title: "Action", key: "action", render: ({ _id , root }) => ( <Space size="middle"> {/* <a>View</a> */} {/* <a onClick={() => this.onEditUser(id)}>Edit</a> */} <Link to={`/categories/edit/${_id}`}>Edit</Link> <a onClick={()=> this.onDeleteCategory(_id)} >Delete</a> </Space> ), }, ], key: "", current: 1, pageSize: 10, }; this.onSearchDebounce = this.debounce(this.onSearch, 1000); } onEditUser = (id) => { console.log(id); setTimeout(() => { this.props.history.push(`/users/edit/${id}`); }, 2000); }; onDeleteCategory = (id) => { console.log(id); deleteCategory(id) this.forceUpdateHandler() const { key, current, pageSize } = this.state; this.props.fetchCategories({ key, current, pageSize }); this.forceUpdateHandler() } componentDidMount() { const { key, current, pageSize } = this.state; this.props.fetchCategories({ key, current, pageSize }); } onfetchProducts = (key, current, category) => { // const { key, current } = this.state; const { pageSize } = this.state; this.props.fetchCategories({ key, current, pageSize, category }); }; onPageChange = (current) => { this.setState({ current }); this.fetchCategories(this.state.key, current, this.state.category); }; onSearch = (key) => { this.setState({ key, current: 1 }); this.fetchCategories(key, 1, this.state.category); }; onSearchChange = (event) => { let key = event.target.value; if (!key) { key = ""; } this.onSearchDebounce(key); }; // debounce = (func, wait) => { // let timeout; // return (key) => { // clearTimeout(timeout); // timeout = setTimeout(() => { // func(key); // }, wait); // }; // }; debounce = (func, wait) => { var timeout; return function () { const context = this; var args = arguments; var executeFunction = function () { func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(executeFunction, wait); }; }; forceUpdateHandler(){ this.forceUpdate(); }; render() { const { columns, current, pageSize } = this.state; const { list } = this.props; return ( <> {console.log('render')} <Search placeholder="input search text" onSearch={this.onSearch} onChange={this.onSearchChange} enterButton style={{ width: 300, margin: "10px 0" }} /> <Table loading={list.loading} columns={columns} dataSource={list.categories} pagination={{ pageSize, current, total: list.total, onChange: this.onPageChange, }} /> </> ); } } function mapStateToProps(state) { return { list: state.categories.list, }; } export default connect(mapStateToProps, { fetchCategories , deleteCategory})(withRouter(ListCategory));
"use client"; import { Navbar, NavbarContent, NavbarItem } from "@nextui-org/react"; import Link from "next/link"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { resolveHref } from "@/sanity/lib/utils"; import { MenuItem } from "@/types"; interface MenuProps { menuItems?: MenuItem[]; pathname?: string; } export function Menu({ menuItems, pathname }: MenuProps) { return ( <Navbar className="hidden border-t bg-secondary lg:block"> <div className="mx-auto w-full max-w-screen-xl px-4 py-4 lg:grid lg:grid-cols-2"> <NavbarContent className="mt-0 flex w-full flex-row items-start space-x-8" justify="start" > {menuItems && menuItems.map((menuItem, key) => { if (!menuItem?._type) { return null; } if (menuItem?.reference?._type === "home") { return ( <NavbarItem key={key}> <Link href="/" legacyBehavior passHref className={cn( "transition-colors duration-200 ease-in-out hover:text-primary dark:text-foreground/60 dark:hover:text-primary", pathname === "/" ? "text-primary" : "text-foreground/90 dark:text-foreground/60", buttonVariants({ variant: "link", size: "sm" }), )} > {menuItem?.reference?.title} </Link> </NavbarItem> ); } const href = resolveHref( menuItem?._type, menuItem?.reference?.slug, ); if (!href) { return null; } const isActive = pathname === href; return ( <NavbarItem key={key}> <Link href={href} legacyBehavior passHref className={cn( "transition-colors duration-200 ease-in-out hover:text-primary dark:text-foreground/60 dark:hover:text-primary", isActive ? "text-primary" : "text-foreground/90 dark:text-foreground/60", buttonVariants({ variant: "link", size: "sm" }), )} > {menuItem?.reference?.title} </Link> </NavbarItem> ); })} </NavbarContent> </div> </Navbar> ); }
/// <reference path="./references.ts" /> type GatewayConfiguration = { success: boolean; native_apm: { gateway: { customer_action_image_url: string; customer_action_message: string; display_name: string; logo_url: string; }; invoice: { amount: string; currency_code: string; }; parameters: Array<NativeApmInputData>; }; }; type PrefilledData = Record<string, string>; type NativeApmPaymentResponse = { success: boolean; native_apm: { parameterDefinitions: Array<NativeApmInputData>; parameterValues?: Record<string, string>; state: string; }; error_type?: string; invalid_fields?: Array<Record<string, string>>; message?: string; }; type NativeApmCapturePaymentResponse = { native_apm?: { state: string; }; success: boolean; message?: string; }; /** * ProcessOut module/namespace */ module ProcessOut { /** * ProcessOut Native APM class */ export class NativeApm { /** * ProcessOut instance * @type {ProcessOut} */ processOutInstance: ProcessOut; /** * Instance of JS library which handles markdown * @type {any} */ markdownLibraryInstance: any; /** * Native APM container element for mounting the widget * @type {Element} */ napmContainer: Element; /** * Native APM widget wrapper element for styling purposes * @type {Element} */ widgetWrapper: Element; /** * Configuration of Native APM payment * @type {NativeApmPaymentConfig} */ paymentConfig: NativeApmPaymentConfig; /** * Configuration of Native APM gateway * @type {GatewayConfiguration} */ gatewayConfiguration: GatewayConfiguration; /** * Theme of the Native APM widget * @type {NativeApmThemeConfig} */ theme: NativeApmThemeConfig; /** * Prefilled data of the user * @type {PrefilledData} */ prefilledData: PrefilledData = {}; /** * Date of first capture * @type {number} */ captureStart = null; /** * NativeAPM constructor * @param {NativeApmConfig} config */ constructor( processOutInstance: ProcessOut, paymentConfig: NativeApmConfigType ) { this.processOutInstance = processOutInstance; this.paymentConfig = new NativeApmPaymentConfig(paymentConfig); this.theme = new NativeApmThemeConfig(); this.loadMarkdownLibrary(); } /** * This function mounts the Native APM widget on the page * @param {string} containerSelector */ public mount(containerSelector: string) { this.napmContainer = document.querySelector(containerSelector); if (!this.napmContainer) { throw new Exception( "default", "Element with this selector does not exist. You must provide valid element selector" ); } this.loadView(new NativeApmSpinner(this.theme).getSpinnerElement()); this.getGatewayConfiguration({ onFetch: EventsUtils.dispatchWidgetLoadingEvent, onSuccess: this.onGatewayConfigurationSuccess.bind(this), onError: this.onGatewayConfigurationError.bind(this), }); } /** * This function gets gateway configuration of the Native APM widget */ private getGatewayConfiguration(actions: { onFetch: Function; onSuccess: Function; onError: Function; }) { const paymentConfig = this.paymentConfig.getConfig(); actions.onFetch(); this.processOutInstance.apiRequest( "GET", `invoices/${paymentConfig.invoiceId}/native-payment/${paymentConfig.gatewayConfigurationId}`, {}, actions.onSuccess.bind(this), actions.onError.bind(this) ); } private onGatewayConfigurationSuccess(data: GatewayConfiguration) { if (!data.success) { const errorView = new NativeApmErrorView({}, this.theme); EventsUtils.dispatchGatewayConfigurationErrorEvent(data); return this.loadView(errorView.getViewElement()); } this.gatewayConfiguration = data; if ( this.gatewayConfiguration.native_apm && this.gatewayConfiguration.native_apm.parameters.length ) { const nativeApmFormView = new NativeApmFormView( this.gatewayConfiguration.native_apm, this.proceedPayment.bind(this), this.theme, this.prefilledData ); EventsUtils.dispatchWidgetReadyEvent(); return this.loadView(nativeApmFormView.getViewElement()); } if ( this.gatewayConfiguration.native_apm && this.gatewayConfiguration.native_apm.parameters.length === 0 ) { const pendingView = new NativeApmPendingView( this.gatewayConfiguration, this.markdownLibraryInstance, this.theme, this.capturePayment.bind(this) ); EventsUtils.dispatchPaymentInitEvent(); return this.loadView(pendingView.getViewElement()); } } private onGatewayConfigurationError(req: XMLHttpRequest, e: ProgressEvent, errorCode: ApiRequestError) { const errorView = new NativeApmErrorView({}, this.theme); let errorData = req.response; if (!req.response && errorCode) errorData = { success: false, error_type: errorCode, message: Translator.translateError(errorCode) }; EventsUtils.dispatchGatewayConfigurationErrorEvent(errorData); return this.loadView(errorView.getViewElement()); } /** * This function proceeds Native APM payment */ public proceedPayment( paymentData: Record<string, string>, onFormSubmitFinished: Function, onFormApiValidationError: Function ) { const paymentConfig = this.paymentConfig.getConfig(); const handlePaymentSuccessCallback = (data: NativeApmPaymentResponse) => this.handlePaymentSuccess( data, onFormSubmitFinished, onFormApiValidationError ); this.processOutInstance.apiRequest( "POST", `invoices/${paymentConfig.invoiceId}/native-payment`, { gateway_configuration_id: paymentConfig.gatewayConfigurationId, native_apm: { parameter_values: paymentData, }, }, handlePaymentSuccessCallback, this.handlePaymentError.bind(this) ); } /** * This function handles success response of payment */ private handlePaymentSuccess( data: NativeApmPaymentResponse, onFormSubmitFinished: Function, onFormApiValidationError: Function ) { onFormSubmitFinished(); if (ErrorsUtils.isFieldsValidationError(data)) { return onFormApiValidationError(data.invalid_fields); } if (ErrorsUtils.isValidationError(data)) { const errorView = new NativeApmErrorView( this.gatewayConfiguration.native_apm, this.theme ); EventsUtils.dispatchPaymentErrorEvent(data); return this.loadView(errorView.getViewElement()); } if (!data.success) { const errorView = new NativeApmErrorView( this.gatewayConfiguration.native_apm, this.theme ); EventsUtils.dispatchPaymentErrorEvent(data); return this.loadView(errorView.getViewElement()); } if (data.native_apm && data.native_apm.state === "CUSTOMER_INPUT") { const customerInputView = new NativeApmFormView( { gateway: this.gatewayConfiguration.native_apm.gateway, parameters: data.native_apm.parameterDefinitions, invoice: this.gatewayConfiguration.native_apm.invoice, }, this.proceedPayment.bind(this), this.theme, this.prefilledData ); EventsUtils.dispatchPaymentAdditionalInputEvent(); return this.loadView(customerInputView.getViewElement()); } if (data.native_apm && data.native_apm.state === "PENDING_CAPTURE") { this.updatePaymentProviderLogo( data.native_apm.parameterValues["provider_logo_url"] ); const pendingView = new NativeApmPendingView( this.gatewayConfiguration, this.markdownLibraryInstance, this.theme, this.capturePayment.bind(this) ); EventsUtils.dispatchPaymentInitEvent(); return this.loadView(pendingView.getViewElement()); } } /** * This function handles error response of payment */ private handlePaymentError(req: XMLHttpRequest, e: ProgressEvent, errorCode: ApiRequestError) { const errorView = new NativeApmErrorView( this.gatewayConfiguration.native_apm, this.theme ); let errorData = req.response; if (!req.response && errorCode) errorData = { success: false, error_type: errorCode, message: Translator.translateError(errorCode) }; EventsUtils.dispatchPaymentErrorEvent(errorData); this.loadView(errorView.getViewElement()); } /** * This function captures Native APM payment */ public capturePayment() { const paymentConfig = this.paymentConfig.getConfig(); if (!this.captureStart) { this.captureStart = new Date(); } this.processOutInstance.apiRequest( "POST", `invoices/${paymentConfig.invoiceId}/capture`, { source: paymentConfig.gatewayConfigurationId, }, this.handleCaptureSuccess.bind(this), this.handleCaptureError.bind(this) ); } private checkIfCaptureTimeout() { const MAX_CAPTURE_TIMEOUT_IN_SECONDS = 180; const now = new Date(); const differenceInSeconds = (now.getTime() - this.captureStart.getTime()) / 1000; return differenceInSeconds >= MAX_CAPTURE_TIMEOUT_IN_SECONDS; } /** * This function handles Native APM capture success */ private handleCaptureSuccess(data: NativeApmCapturePaymentResponse) { if ( data.success && data.native_apm && data.native_apm.state === "PENDING_CAPTURE" && !this.checkIfCaptureTimeout() ) { return this.capturePayment(); } if ( data.success && data.native_apm && data.native_apm.state === "PENDING_CAPTURE" && this.checkIfCaptureTimeout() ) { this.captureStart = null; return EventsUtils.dispatchPaymentErrorEvent(data); } if (!data.success) { this.captureStart = null; const errorView = new NativeApmErrorView( this.gatewayConfiguration.native_apm, this.theme ); EventsUtils.dispatchPaymentErrorEvent(data); return this.loadView(errorView.getViewElement()); } this.captureStart = null; const successView = new NativeApmSuccessView( this.gatewayConfiguration, this.markdownLibraryInstance, this.theme ); EventsUtils.dispatchPaymentSuccessEvent(); return this.loadView(successView.getViewElement()); } /** * This function handles Native APM capture error */ private handleCaptureError(req: XMLHttpRequest, e: ProgressEvent, errorCode: ApiRequestError) { const errorView = new NativeApmErrorView( this.gatewayConfiguration.native_apm, this.theme ); let errorData = req.response; if (!req.response && errorCode) errorData = { success: false, error_type: errorCode, message: Translator.translateError(errorCode) }; EventsUtils.dispatchPaymentErrorEvent(errorData); this.loadView(errorView.getViewElement()); } /** * This function sets theme of the Native APM widget * @param {NativeApmThemeConfigType} themeConfig */ public setTheme(themeConfig: NativeApmThemeConfigType) { return this.theme.setTheme(themeConfig); } /** * This function prefills user data * @param {PrefilledData} data */ public prefillData(data: PrefilledData) { this.prefilledData = data; } /** * This function loads view of the widget */ private loadView(view: HTMLElement) { if (this.widgetWrapper) { this.napmContainer.removeChild(this.widgetWrapper); } this.widgetWrapper = this.createWidgetWrapper(); this.widgetWrapper.appendChild(view); this.napmContainer.appendChild(this.widgetWrapper); } /** * This function updates payment provider logo */ private updatePaymentProviderLogo(logoUrl?: string) { if (logoUrl) { this.gatewayConfiguration = { ...this.gatewayConfiguration, native_apm: { ...this.gatewayConfiguration.native_apm, gateway: { ...this.gatewayConfiguration.native_apm.gateway, logo_url: logoUrl, }, }, }; } } /** * This function creates widget wrapper for styling purposes */ private createWidgetWrapper() { const widgetWrapper = document.createElement("div"); const styleElement = this.theme.createInitialStyleTag(); widgetWrapper.setAttribute("class", "native-apm-widget-wrapper"); widgetWrapper.appendChild(styleElement); StylesUtils.styleElement(widgetWrapper, this.theme.wrapper); return widgetWrapper; } /** * This function loads markdown JS library to handle custommer action messages */ private loadMarkdownLibrary() { const markdownScript = document.createElement("script"); markdownScript.src = "https://js.processout.ninja/js/libraries/showdown.min.js"; markdownScript.onload = () => { this.markdownLibraryInstance = window.globalThis && window.globalThis.showdown ? new window.globalThis.showdown.Converter() : null; }; document.head.appendChild(markdownScript); } } }
<!DOCTYPE html> <html lang="fr"> <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 name="description" content="Visionneuse images de planettes Star-Wars"> <title>Visionneuse</title> <link rel="stylesheet" href="css/style.css"> <!-- Fonts --> <link href="http://fonts.cdnfonts.com/css/sf-distant-galaxy" rel="stylesheet"> <!-- BootStrap, jQuery, Popper --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script defer src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script defer src="https://cdn.jsdelivr.net/npm/popper.js@1.14.3/dist/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script defer src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <!-- Code JavaScript--> <script defer src="js/scrtipt.js"></script> </head> <body> <div class="container"> <div id="title" class="text-center text-warning m-5"> <h1>LES PLANETTES DE STAR WARS</h1> </div> <div class="row justify-content-center m-5"> <div class="dropdown"> <button class="btn btn-warning dropdown-toggle" type="button" id="movies" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Choisissez un Film</button> <div class="dropdown-menu" id="moviesList" aria-labelledby="movies"> </div> </div> </div> <div class="row justify-content-center m-3"> <div class="col-8 d-flex align-items-center justify-content-center" id="imagePosition"> <div class="col-4" id="image"> <img src="images/death-star-spin.gif" class="img-fluid" id="planet" alt="Death Star spinning"> <p class="text-center" id="planetName">Chargement...</p> </div> </div> <div class="col-8 d-grid gap-3 d-flex justify-content-center m-3 control"> <button type="button" class="btn btn-outline-primary m-3" id="precedent">Précédent</button> <button type="button" class="btn btn-outline-danger m-3" id="boutonRotation">Arrêter</button> <button type="button" class="btn btn-outline-primary m-3" id="suivant">Suivant</button> </div> <div class="col-4 p-2 control"> <div id="speedTitle" class="col-12 text-center text-warning mt-3"> <h5>Vitesse du diaporama:</h5> </div> <div class="col-12 d-grid gap-3 d-flex justify-content-center m-3"> <div class="col-3 custom-control custom-radio m-3"> <input class="custom-control-input" type="radio" name="speed" id="slow"> <label class="custom-control-label" for="slow">Lente</label> </div> <div class="col-3 custom-control custom-radio m-3"> <input class="custom-control-input" type="radio" name="speed" id="medium" checked="checked"> <label class="custom-control-label" for="medium">Moyenne</label> </div> <div class="col-3 custom-control custom-radio m-3"> <input class="custom-control-input" type="radio" name="speed" id="fast"> <label class="custom-control-label" for="fast">Rapide</label> </div> </div> </div> </div> </div> </body> </html>
package com.example.yamigo; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager2.widget.ViewPager2; import android.os.Bundle; import android.view.MenuItem; import com.example.yamigo.adapter.ViewPager2FragmentAdapter; import com.example.yamigo.fragment.SettingFragment; import com.example.yamigo.fragment.HomeFragment; import com.example.yamigo.fragment.DeviceFragment; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationBarView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private HomeFragment homeFragment; private DeviceFragment deviceFragment; private SettingFragment settingFragment; private ViewPager2 main_page_viewpage2; private BottomNavigationView main_page_bottom_nav; private ViewPager2FragmentAdapter adapter; private List<Fragment> fragmentList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_page_bottom_nav = findViewById(R.id.main_page_bottom_nav); main_page_viewpage2 = findViewById(R.id.main_page_viewpage2); // 初始化FragmentList fragmentList = initFragmentList(); // 初始化ViewPager2 initViewPager2(main_page_viewpage2); // 监听滑动事件 main_page_viewpage2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { super.onPageSelected(position); switch (position) { case 0: main_page_bottom_nav.setSelectedItemId(R.id.home); break; case 1: main_page_bottom_nav.setSelectedItemId(R.id.device); break; case 2: main_page_bottom_nav.setSelectedItemId(R.id.setting); break; } } }); // 监听底部栏点击事件 main_page_bottom_nav.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.home: main_page_viewpage2.setCurrentItem(0); break; case R.id.device: main_page_viewpage2.setCurrentItem(1); break; case R.id.setting: main_page_viewpage2.setCurrentItem(2); break; } return true; } }); } private List<Fragment> initFragmentList() { List<Fragment> fragmentList = new ArrayList<>(); homeFragment = HomeFragment.newInstance("主页",""); deviceFragment = DeviceFragment.newInstance("设备", ""); settingFragment = SettingFragment.newInstance("设置", ""); fragmentList.add(homeFragment); fragmentList.add(deviceFragment); fragmentList.add(settingFragment); return fragmentList; } private void initViewPager2(ViewPager2 viewpage2) { adapter = new ViewPager2FragmentAdapter(this, fragmentList); viewpage2.setAdapter(adapter); } }
import { Component } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { ToastController } from '@ionic/angular'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { public formGroup: FormGroup; constructor( protected formBuilder: FormBuilder, protected toastController: ToastController ) { } ngOnInit() { this.formGroup = this.getTextArea(); } public getTextArea() { return this.formBuilder.group({ textArea: [{ value: undefined, disabled: false }], }); } public results() { const form = this.formGroup.get('textArea').getRawValue().toUpperCase(); if (form.match(/\d+/g)) { this.formGroup.reset(); return alert('Não pode inserir números!'); } else { const results = form.split('').map(val => val.charCodeAt()); return results; } } public async cypher() { const cypheredCharCodes = this.cypherText(this.results()); const resultMessage = this.transformIntoLetters(cypheredCharCodes); const toast = await this.toastController.create({ message: `${resultMessage} Criptografada!`, duration: 3500, }); await toast.present(); this.formGroup.reset(); }; public async deCypher() { const cypheredCharCodes = this.deCypherText(this.results()); const resultMessage = this.transformIntoLetters(cypheredCharCodes); const toast = await this.toastController.create({ message: `${resultMessage} Descriptografada!`, duration: 3500, }); await toast.present(); this.formGroup.reset(); }; public cypherText(textAreaArray) { return textAreaArray.map((charCode) => { if (charCode >= 88) { charCode -= 26; } charCode += 3; return charCode; }); } public deCypherText(textAreaArray) { return textAreaArray.map((charCode) => { if (charCode <= 67) { charCode += 26; } charCode -= 3; return charCode; }); } public transformIntoLetters(textAreaArray: number[]) { const value = textAreaArray.map(t => String.fromCharCode(t)).join(''); return value.replace(/[-\/\\^$*#+?.()|[\]{}[0-9]/g, '\n'); } }
<?php namespace App\Http\Controllers\blocks; use App\Http\Controllers\Controller; use App\Http\Requests\StoreBlockRequest; use App\Models\Block; use App\Models\Profile; use Exception; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Yajra\DataTables\DataTables; class AliasController extends Controller { /** * Process datatables ajax request. * * @return JsonResponse * @throws Exception */ public function getData(): JsonResponse { $blocks = Block::whereNull('block_id'); return Datatables::of($blocks) // id // name ->addColumn('linked', fn($block) => $block->children->count()) ->addColumn('fmptype', fn($block) => $block->profile->fmptype->name) ->addColumn('profile', fn($block) => $block->profile->getTitle()) ->addColumn('action', function ($block) { $showRoute = route('aliases.edit', [ 'mode' => config('global.show'), 'alias' => $block->getKey(), 'block_id' => $block->getKey(), 'sid' => session()->getId() ]); $linkRoute = route('aliases.create', [ 'block_id' => $block->getKey(), 'sid' => session()->getId() ]); $actions = ''; $actions .= "<a href=\"{$showRoute}\" class=\"btn btn-primary btn-sm float-left me-5\" " . "data-toggle=\"tooltip\" data-placement=\"top\" title=\"Просмотр\">\n" . "<i class=\"fas fa-eye\"></i>\n" . "</a>\n"; $actions .= "<a href=\"{$linkRoute}\" class=\"btn btn-primary btn-sm float-left mr-1\" " . "data-toggle=\"tooltip\" data-placement=\"top\" title=\"Связать новый блок с текущим\">\n" . "<i class=\"fas fa-link\"></i>\n" . "</a>\n"; return $actions; }) ->make(true); } /** * Show the form for creating a new resource. * * @return Application|Factory|View */ public function create(Request $request) { if($request->has('block_id')) { // Создание ссылочного блока - предок уже выбран $block_id = $request->block_id; $context = session('context'); $profile_id = $context['profile']; return view('blocks.alias.create', compact('block_id', 'profile_id')); } else { // Выбор предка для нового ссылочного блока $count = Block::whereNull('block_id')->count(); return view('blocks.alias.index', compact('count')); } } /** * Не маршрут! * * @param Request $request */ public static function store(array $data): Block { $block = Block::create($data); $block->sort_no = PHP_INT_MAX; $block->save(); return $block; } /** * Show the form for editing the specified resource. * * @param Request $request * @param int $id * @return Application|Factory|View */ public function edit(Request $request, int $id) { $mode = $request->mode; $block = Block::findOrFail($id); if ($block->block_id) { // Редактирование / просмотр ссылочного блока $view = 'blocks.alias.edit'; } else { // Просмотр предка $view = 'blocks.alias.parent'; } return view($view, compact('block', 'mode')); } /** * Не маршрут! * * @param array $params * @param int $id */ public static function update(array $params, int $id): string { $block = Block::findOrFail($id); $name = $block->name; $block->update([ 'name' => $params['name'] ]); return $name; } /** * Не маршрут! * * @param int $id * @return bool */ public static function destroy($id): bool { $block = Block::findOrFail($id); return $block->delete(); } }
import * as yup from "yup"; export const LeadSchema = yup.object({ firstName: yup.string().required("First name is required").max(50, "max characters is 50"), lastName: yup.string().required("Last name is required").max(50, "max characters is 50"), company: yup.string().optional().nullable(), title: yup.string().optional().nullable(), email: yup.string().email("Enter a valid email").required(), phone: yup.string().optional().nullable(), location: yup.string().optional().nullable(), comment: yup.string().optional().nullable(), owner: yup .object({ identifier: yup.string().optional().nullable(), userId: yup.string().optional().nullable(), }) .optional(), status: yup.string(), }); export const DealSchema = yup.object({ forecast: yup.number().required("Forecast is required"), value: yup.number().optional().nullable(), owner: yup .object({ identifier: yup.string().optional().nullable(), userId: yup.string().optional().nullable(), }) .optional(), stage: yup.string().optional().nullable(), comment: yup.string().optional().nullable(), lead: yup.string().optional().nullable(), }); export const ActivitySchema = yup.object({ owner: yup .object({ identifier: yup.string().optional().nullable(), userId: yup.string().optional().nullable(), }) .optional(), date: yup.date().required("Date is required"), status: yup.string().optional().nullable(), lead: yup.string().optional().nullable(), description: yup.string().optional().nullable(), title: yup.string().required("Title is required"), location: yup.string().optional().nullable(), }); export const DictionarySchema = yup.object({ label: yup.string().required("Label is required"), value: yup.string().required("Value is required"), type: yup.string().required("Type is required"), }); export type DictionaryType = yup.InferType<typeof DictionarySchema>; export type DealType = yup.InferType<typeof DealSchema>; export type LeadType = yup.InferType<typeof LeadSchema>; export type ActivityType = yup.InferType<typeof ActivitySchema>;
import React from 'react'; import { ICredit } from './types'; import * as S from './ContentsMeta.style'; export const ContentsMeta = ({ genres, credits }: { genres: string[]; credits: ICredit[]; }) => ( <S.Meta> <div className="credits"> <strong>주연:</strong> <ul> {credits.map((credit, idx) => { const toggleComma = idx !== credits.length - 1 ? ',' : ''; return ( <li key={`credits-${idx}`}> <span> {credit.name} {toggleComma} </span> </li> ); })} </ul> </div> <div className="genres"> <strong>장르:</strong> <ul> {genres.map((genre, idx) => { return <li key={`genres-${idx}`}>{genre}</li>; })} </ul> </div> </S.Meta> );
using System.Text.Json; using Task.Data; using Task.Data.Entities; using Task.Models; using Task.Services.ResponseProceso; namespace Task.Services.Task.PutTaskService { public class PutTaskService : IPutTaskService { private readonly ILogger<PutTaskService> _logger; private readonly SeeriContext _context; private ResponseGeneralModel<string> responseProcess; private IResponse response; private int stateCodeFail = 404; private int stateCodeTrue = 200; public PutTaskService(ILogger<PutTaskService> logger, SeeriContext seeriContext) { _logger = logger; _context = seeriContext; response = new Response(); responseProcess = new ResponseGeneralModel<string>(); } /// <summary> /// Este método valida la tarea a actualziar-. /// </summary> /// <param name="dataTask">Es el modelo del request solicitado para crear la tarea</param> /// <returns>Devuelve como respuesta un modelo de ResponseModel y una variable int que se toma como el estado HTTP</returns> public ResponseGeneralModel<string> UpdateTask(RequestTask dataTask) { try { TaskEntity resultTask = _context.Tasks.FirstOrDefault(x => x.TaskId == (int)dataTask.TaskId); if (resultTask != null) { resultTask.Titulo = dataTask.Titulo; resultTask.Descripcion = dataTask.Descripcion; resultTask.State = dataTask.State; resultTask.UpdateDate = DateTime.Now; responseProcess = ValidateUpdateDataTask(resultTask); } else { responseProcess = response.ResponseFalse("Error, la tarea no esta creado", stateCodeFail, JsonSerializer.Serialize(dataTask)); } } catch (Exception ex) { _logger.LogInformation("Error en ejecución de consulta de db " + ex); responseProcess = response.ResponseFalse("Error en ejecución de consulta de db " + ex, stateCodeFail, ""); } return responseProcess; } /// <summary> /// Este método valida si el tipo de dato existe. /// </summary> /// <param name="task">modelo de tarea</param> /// <returns>Devuelve como respuesta un modelo de ResponseModel y una variable int que se toma como el estado HTTP</returns> private ResponseGeneralModel<string> ValidateUpdateDataTask(TaskEntity task) { try { TypeStateEntity typeState = _context.TypeStates.FirstOrDefault(x => x.TypeStateId == task.State); if (typeState != null) { responseProcess = ProcessUpdateTask(task); } else { responseProcess = response.ResponseFalse("Error el tipo de dato no esta creado", stateCodeFail, JsonSerializer.Serialize(task)); } } catch (Exception ex) { _logger.LogInformation("Error en ejecución de consulta de db " + ex); responseProcess = response.ResponseFalse("Error en ejecución de consulta de db " + ex, stateCodeFail, ""); } return responseProcess; } /// <summary> /// Actualiza o crea la tarea. /// </summary> /// <param name="task">es la tarea que sae va a crear</param> /// <returns>Devuelve como respuesta un modelo de ResponseModel y una variable int que se toma como el estado HTTP</returns> /// <exception cref="Exception">Cuando la consulta no se puede realizar a la base de datos</exception> private ResponseGeneralModel<string> ProcessUpdateTask(TaskEntity task) { try { _context.Update(task); _context.SaveChanges(); responseProcess = response.ResponseTrue("Proceso ejecutado", stateCodeTrue, JsonSerializer.Serialize(task)); } catch (Exception ex) { _logger.LogInformation("Error en ejecución del proceso de db: " + ex); responseProcess = response.ResponseFalse("Error en ejecución del proceso de db: " + ex, stateCodeFail, JsonSerializer.Serialize(task)); } return responseProcess; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://unpkg.com/swiper@8/swiper-bundle.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="css/style.css" /> <script defer src="index.js"></script> <title>Kushal Kothari</title> </head> <body> <header class="header "> <img src="images/logo.png" alt="Main Logo" class="logo" /> <nav class="navbar"> <ul class="navbar-lists"> <li><a href="#" class="navbar-link home-link">Home</a></li> <li><a href="./about.html" class="navbar-link about-link">About</a></li> <li><a href="./service.html" class="navbar-link service-link">Services</a></li> <li><a href="#" class="navbar-link portfolio-link">Portfolio</a></li> <li><a href="./contact.html" class="navbar-link contact-link">Contact</a></li> </ul> </nav> <div class="mobile-navbar-btn"> <ion-icon name="menu-outline" class="mobile-nav-icon"></ion-icon> <ion-icon name="close-outline" class="mobile-nav-icon"></ion-icon> </div> </header> <!-- Main Section --> <main> <section class="section-hero section"> <div class="container grid grid-two-column"> <div class="section-hero-data"> <p class="hero-top-data">this is me</p> <h1 class="hero-heading">Kushal Kothari</h1> <p class="hero-para"> I'm Kushal Kothari. A Front End Developer have worked E-commerce website. </p> <div> <a href="#" class="btn hireme-btn">Hire Me</a> </div> </div> <div class="section-hero-image"> <img src="/Portfolio/images/hero.jpg" alt="This is me Kushal Kothari" class="hero-img" /> </div> </div> </section> </main> <!-- CV Section --> <section class="section-cv section"> <div class="container grid grid-two-column"> <div class="cv-image"> <img class="lazy-img" data-src="images/biodata.jpg" src="images/lazy1.jpg" alt="my cv image" loading="lazy" /> </div> <!-- cv right side --> <div class="cv-data"> <h2 class="common-heading">My CV</h2> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. A accusamus dignissimos accusantium porro dolor labore facilis! Dolor ducimus dicta suscipit laboriosam praesentium itaque tempora nesciunt numquam, explicabo, nisi temporibus ut. </p> <br /> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum doloremque nostrum, voluptatum numquam asperiores perspiciatis eveniet! </p> <div class="cv-data-stats"> <div class="cv-stats"> <h3>HTML</h3> <div class="cv-progress-bar"> <span>75%</span> </div> </div> <div class="cv-stats"> <h3>CSS</h3> <div class="cv-progress-bar cv-progress-1"> <span>70%</span> </div> </div> <div class="cv-stats"> <h3>JavaScript</h3> <div class="cv-progress-bar cv-progress-2"> <span>75%</span> </div> </div> <div class="cv-stats"> <h3>React.JS</h3> <div class="cv-progress-bar cv-progress-3"> <span>75%</span> </div> </div> <div class="cv-stats"> <h3>Jquery</h3> <div class="cv-progress-bar cv-progress-4"> <span>80%</span> </div> </div> <div class="cv-stats"> <h3>BootStrap</h3> <div class="cv-progress-bar cv-progress-5"> <span>80%</span> </div> </div> </div> <div class="cv-data-btn"> <a href="" class="btn">Download CV</a> </div> </div> </div> </section> <!-- Projects --> <section class="section section-portfolio" id="portfolio-section"> <div class="container"> <h2 class="common-heading">Latest Work</h2> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Explicabo alias molestiae itaque, eius sapiente blanditiis ullam dolor porro vero mollitia. </p> </div> <div class="p-btns"> <div class="btn p-btn" data-btn-num="1">React</div> <div class="btn p-btn" data-btn-num="2">JavaScript</div> </div> <div class="container grid grid-three-column portfolio-images"> <div class="img-ovelay p-btn--1"> <img src="images/folio/1.jpg" alt="my works" /> <div class="overlay"> <a href="" target="_blank" class="common-heading">Project 1</a> </div> </div> <div class="img-ovelay p-btn--1"> <img src="images/folio/4.jpg" alt="my works" /> <div class="overlay"> <a href="" target="_blank" class="common-heading">Project 2</a> </div> </div> <div class="img-ovelay p-btn--2"> <img src="images/folio/3.jpg" alt="my works" /> <div class="overlay"> <a href="" target="_blank" class="common-heading">Project 3</a> </div> </div> </div> </section> <!-- Animated Number section Work Counter --> <section class="section section-work-data"> <div class="container grid grid-four-column"> <div> <h2 class="counter-number" data-number="2000">0+</h2> <p>Project Completed</p> </div> <div> <h2 class="counter-number" data-number="6000">0+</h2> <p>Happy Clients</p> </div> <div> <h2 class="counter-number" data-number="5000">0+</h2> <p>Cups of Coffee</p> </div> <div> <h2 class="counter-number" data-number="3000">0+</h2> <p>real profesional</p> </div> </div> </section> <!-- Service Section with water effect --> <section class="section section-services"> <div class="container"> <h2 class="common-heading">Services Offers</h2> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime commodi voluptatibus dolorum. Magni neque, voluptas numquam error officia rem est. </p> </div> <!-- services offers card --> <div class="container grid grid-three-column"> <div class="service-card"> <ion-icon name="desktop-sharp" class="service-icon"></ion-icon> <h3>Web Design</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta, corporis.</p> </div> <div class="service-card"> <ion-icon name="camera-sharp" class="service-icon"></ion-icon> <h3>Photography</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta, corporis.</p> </div> <div class="service-card"> <ion-icon name="logo-react" class="service-icon"></ion-icon> <h3>Mobile Apps</h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta, corporis.</p> </div> </div> </section> <!-- testimony --> <section class="section section-testimonial"> <div class="container"> <h2 class="common-heading">Happy Clients Works</h2> </div> <div class="swiper mySwiper container"> <div class="swiper-wrapper"> <div class="swiper-slide"> <div class="swiper-client-msg"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus eaque nihil amet tempora enim dignissimos? Atque tempora quia vitae!</p> </div> <div class="swiper-client-data grid grid-two-column"> <figure> <img src="images/clients/a.jpg" alt="Client Review"> </figure> <div class="client-data-details"> <p>Kushal Kothari</p> <p>Entreprenuer</p> </div> </div> </div> <div class="swiper-slide"> <div class="swiper-client-msg"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus eaque nihil amet tempora enim dignissimos? Atque tempora quia vitae!</p> </div> <div class="swiper-client-data grid grid-two-column"> <figure> <img src="images/clients/b.jpg" alt="Client Review"> </figure> <div class="client-data-details"> <p>Kushal Kothari</p> <p>Entreprenuer</p> </div> </div> </div> <div class="swiper-slide"> <div class="swiper-client-msg"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus eaque nihil amet tempora enim dignissimos? Atque tempora quia vitae!</p> </div> <div class="swiper-client-data grid grid-two-column"> <figure> <img src="images/clients/c.jpg" alt="Client Review"> </figure> <div class="client-data-details"> <p>Kushal Kothari</p> <p>Entreprenuer</p> </div> </div> </div> <div class="swiper-slide"> <div class="swiper-client-msg"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus eaque nihil amet tempora enim dignissimos? Atque tempora quia vitae!</p> </div> <div class="swiper-client-data grid grid-two-column"> <figure> <img src="images/clients/d.jpg" alt="Client Review"> </figure> <div class="client-data-details"> <p>Kushal Kothari</p> <p>Entreprenuer</p> </div> </div> </div> <div class="swiper-slide"> <div class="swiper-client-msg"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus eaque nihil amet tempora enim dignissimos? Atque tempora quia vitae!</p> </div> <div class="swiper-client-data grid grid-two-column"> <figure> <img src="images/clients/e.jpg" alt="Client Review"> </figure> <div class="client-data-details"> <p>Kushal Kothari</p> <p>Entreprenuer</p> </div> </div> </div> </div> <div class="swiper-pagination"></div> </div> </section> <!-- Paralex Effect --> <section class="section section-fulltime"> <div class="overlay"></div> <div class="container"> <h2>I am <span>available</span> for Full Time Oportunity</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ex quasi sit quia expedita earum facere?</p> <a href="/contact.html" class="btn">Hire Me</a> </div> </section> <!-- Contact Us--> <section class="section section-contact"> <div class="container"> <h2 class="common-heading">Contact Us</h2> </div> <div class="section-contact-main contact-container"> <form action="https://formspree.io/f/mrgjrnyl" method="POST"> <div class="grid grid-two-column"> <div> <label for="username"></label> <input type="text" name="username" placeholder="Enter UserName" id="username" required autocomplete="off"> </div> <div> <label for="email"></label> <input type="email" name="email" placeholder="Enter email" id="email" autocomplete="off" required> </div> </div> <div> <label for="subject"></label> <input type="text" name="subject" id="subject" placeholder="subject" autocomplete="off" required min="10"> </div> <div> <label for="textarea"></label> <textarea name="textarea" id="textarea" placeholder="Message" cols="30" rows="10" autocomplete="off" required></textarea> </div> <div> <input type="submit" name="subject" id="subject" class="btn" value="Send Message"> </div> </form> </div> </section> <!-- Footer Section --> <footer class="section-footer section"> <div class="container grid grid-four-column"> <div class="f-about"> <h3>About</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo dolorem pariatur quia.</p> </div> <div class="f-link"> <h3>links</h3> <ul> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Home</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">About</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Services</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Portfolio</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Contact</a> </li> </ul> </div> <div class="f-services"> <h3>Services</h3> <ul> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Web desing</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Web Development</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Mern Project</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">JavaScript Projects</a> </li> <li> <span><ion-icon name="arrow-forward-outline"></ion-icon></span> <a href="">Redux Projects</a> </li> </ul> </div> <div class="f-address"> <h3>Have a Question</h3> <address> <div> <p> <span><ion-icon name="location-outline"></ion-icon></span> Nagpur, India </p> </div> <div> <p> <span><ion-icon name="call-outline"></ion-icon></span> <a href="tel:+91123456789">+91 123456789</a> </p> </div> <div> <p> <span><ion-icon name="mail-outline"></ion-icon></span> <a href="mailto:kushal.v.kothari@gmail.com">kushal.v.kothari@gmail.com</a> </p> </div> </address> </div> </div> <div class="container"> <div class="f-social-icons"> <a href="https://www.instagram.com/?hl=en" target="_blank"><ion-icon class="icons" name="logo-instagram"></ion-icon></a> <a href="https://www.linkedin.com/" target="_blank"><ion-icon class="icons" name="logo-linkedin"></ion-icon></a> <a href="https://www.youtube.com/" target="_blank"><ion-icon class="icons" name="logo-youtube"></ion-icon></a> </div> <div class="f-credits"> <p> copyright © 2022 </p> </div> </div> </footer> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> <script src="https://unpkg.com/swiper@8/swiper-bundle.min.js"></script> </body> </html>
pragma solidity ^0.5.0; contract MyToken { /* 10000,"eilinge",4,"lin" msg.sender:0x14723a09acff6d2a60dcdf7aa4aff308fddc160c 0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,20 0x583031d1113ad414f02576bd6afabfb302140225,40 0xdd870fa1b7c4700f2bd7f44238821c26f7392148,60 "0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db","0xdd870fa1b7c4700f2bd7f44238821c26f7392148",10 */ /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => mapping (address => uint)) public spentAllowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event ReceiveApproval(address _from, uint256 _value, address _token, bytes _extraData); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor(uint256 initialSupply, string memory tokenName, uint8 decimalUnits, string memory tokenSymbol) public{ balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /* Send coins */ function transfer(address _to, uint256 _value) payable public{ if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) { allowance[msg.sender][_spender] = _value; //emit ReceiveApproval(msg.sender, _value, this, _extraData); } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public payable returns(bool) { if (balanceOf[_from] < _value) revert(); // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows if (spentAllowance[_from][msg.sender] + _value > allowance[_from][msg.sender]) revert(); // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient spentAllowance[_from][msg.sender] += _value; emit Transfer(msg.sender, _to, _value); } /* This unnamed function is called whenever someone tries to send ether to it */ function () payable external{ revert(); // Prevents accidental sending of ether } }
interface result { periodLength: number; trainingDays: number; success: boolean; rating?: number; ratingDescription: string; target?: number; average: number; } export function calculateExercises( dailyExercise: number[], rating?: number ): result { const trainingDays = dailyExercise.filter((hours) => hours !== 0).length; const sum = dailyExercise.reduce((a, b) => a + b, 0); const average = sum / trainingDays; let returned: result; if (rating) { returned = { periodLength: dailyExercise.length, trainingDays, success: sum > 20 ? true : false, rating: rating, ratingDescription: sum > 20 ? "You did well! Keep it up!" : "not too bad but could be better", target: rating, average, }; } else { returned = { periodLength: dailyExercise.length, trainingDays, success: sum > 20 ? true : false, ratingDescription: sum > 20 ? "You did well! Keep it up!" : "not too bad but could be better", average, }; } return returned; } const args = process.argv.slice(2); let numbersArr: number[]; try { numbersArr = args.map((arg) => { return parseInt(arg); }); console.log(calculateExercises(numbersArr, 2)); } catch (error) { console.log("All args must be number"); }
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Google Inc. 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 * OWNER 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. * */ 'use strict'; var async = require('async'); var fs = require('fs'); var GoogleAuth = require('google-auth-library'); var parseArgs = require('minimist'); var strftime = require('strftime'); var _ = require('underscore'); var grpc = require('../..'); var PROTO_PATH = __dirname + '/pubsub.proto'; var pubsub = grpc.load(PROTO_PATH).tech.pubsub; function PubsubRunner(pub, sub, args) { this.pub = pub; this.sub = sub; this.args = args; } PubsubRunner.prototype.getTestTopicName = function() { var base_name = '/topics/' + this.args.project_id + '/'; if (this.args.topic_name) { return base_name + this.args.topic_name; } var now_text = strftime('%Y%m%d%H%M%S%L'); return base_name + process.env.USER + '-' + now_text; }; PubsubRunner.prototype.getTestSubName = function() { var base_name = '/subscriptions/' + this.args.project_id + '/'; if (this.args.sub_name) { return base_name + this.args.sub_name; } var now_text = strftime('%Y%m%d%H%M%S%L'); return base_name + process.env.USER + '-' + now_text; }; PubsubRunner.prototype.listProjectTopics = function(callback) { var q = ('cloud.googleapis.com/project in (/projects/' + this.args.project_id + ')'); this.pub.listTopics({query: q}, callback); }; PubsubRunner.prototype.topicExists = function(name, callback) { this.listProjectTopics(function(err, response) { if (err) { callback(err); } else { callback(null, _.some(response.topic, function(t) { return t.name === name; })); } }); }; PubsubRunner.prototype.createTopicIfNeeded = function(name, callback) { var self = this; this.topicExists(name, function(err, exists) { if (err) { callback(err); } else{ if (exists) { callback(null); } else { self.pub.createTopic({name: name}, callback); } } }); }; PubsubRunner.prototype.removeTopic = function(callback) { var name = this.getTestTopicName(); console.log('... removing Topic', name); this.pub.deleteTopic({topic: name}, function(err, value) { if (err) { console.log('Could not delete a topic: rpc failed with', err); callback(err); } else { console.log('removed Topic', name, 'OK'); callback(null); } }); }; PubsubRunner.prototype.createTopic = function(callback) { var name = this.getTestTopicName(); console.log('... creating Topic', name); this.pub.createTopic({name: name}, function(err, value) { if (err) { console.log('Could not create a topic: rpc failed with', err); callback(err); } else { console.log('created Topic', name, 'OK'); callback(null); } }); }; PubsubRunner.prototype.listSomeTopics = function(callback) { console.log('Listing topics'); console.log('-------------_'); this.listProjectTopics(function(err, response) { if (err) { console.log('Could not list topic: rpc failed with', err); callback(err); } else { _.each(response.topic, function(t) { console.log(t.name); }); callback(null); } }); }; PubsubRunner.prototype.checkExists = function(callback) { var name = this.getTestTopicName(); console.log('... checking for topic', name); this.topicExists(name, function(err, exists) { if (err) { console.log('Could not check for a topics: rpc failed with', err); callback(err); } else { if (exists) { console.log(name, 'is a topic'); } else { console.log(name, 'is not a topic'); } callback(null); } }); }; PubsubRunner.prototype.randomPubSub = function(callback) { var self = this; var topic_name = this.getTestTopicName(); var sub_name = this.getTestSubName(); var subscription = {name: sub_name, topic: topic_name}; async.waterfall([ _.bind(this.createTopicIfNeeded, this, topic_name), _.bind(this.sub.createSubscription, this.sub, subscription), function(resp, cb) { var msg_count = _.random(10, 30); // Set up msg_count messages to publish var message_senders = _.times(msg_count, function(n) { return _.bind(self.pub.publish, self.pub, { topic: topic_name, message: {data: new Buffer('message ' + n)} }); }); async.parallel(message_senders, function(err, result) { cb(err, result, msg_count); }); }, function(result, msg_count, cb) { console.log('Sent', msg_count, 'messages to', topic_name + ',', 'checking for them now.'); var batch_request = { subscription: sub_name, max_events: msg_count }; self.sub.pullBatch(batch_request, cb); }, function(batch, cb) { var ack_id = _.pluck(batch.pull_responses, 'ack_id'); console.log('Got', ack_id.length, 'messages, acknowledging them...'); var ack_request = { subscription: sub_name, ack_id: ack_id }; self.sub.acknowledge(ack_request, cb); }, function(result, cb) { console.log( 'Test messages were acknowledged OK, deleting the subscription'); self.sub.deleteSubscription({subscription: sub_name}, cb); } ], function (err, result) { if (err) { console.log('Could not do random pub sub: rpc failed with', err); } callback(err, result); }); }; function main(callback) { var argv = parseArgs(process.argv, { string: [ 'host', 'oauth_scope', 'port', 'action', 'project_id', 'topic_name', 'sub_name' ], default: { host: 'pubsub-staging.googleapis.com', oauth_scope: 'https://www.googleapis.com/auth/pubsub', port: 443, action: 'listSomeTopics', project_id: 'stoked-keyword-656' } }); var valid_actions = [ 'createTopic', 'removeTopic', 'listSomeTopics', 'checkExists', 'randomPubSub' ]; if (_.some(valid_actions, function(action) { return action === argv.action; })) { callback(new Error('Action was not valid')); } var address = argv.host + ':' + argv.port; (new GoogleAuth()).getApplicationDefault(function(err, credential) { if (err) { callback(err); return; } if (credential.createScopedRequired()) { credential = credential.createScoped(argv.oauth_scope); } var updateMetadata = grpc.getGoogleAuthDelegate(credential); var ca_path = process.env.SSL_CERT_FILE; fs.readFile(ca_path, function(err, ca_data) { if (err) { callback(err); return; } var ssl_creds = grpc.Credentials.createSsl(ca_data); var options = { credentials: ssl_creds, 'grpc.ssl_target_name_override': argv.host }; var pub = new pubsub.PublisherService(address, options, updateMetadata); var sub = new pubsub.SubscriberService(address, options, updateMetadata); var runner = new PubsubRunner(pub, sub, argv); runner[argv.action](callback); }); }); } if (require.main === module) { main(function(err) { if (err) { throw err; } }); } module.exports = PubsubRunner;
import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:chatterbox_app/provider/ThemeProvider.dart'; import 'package:chatterbox_app/views/component/NoInternetComponent.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:provider/provider.dart'; import '../../helper/AuthHelper.dart'; import '../../provider/ConnectionProvider.dart'; class SignupPage extends StatefulWidget { const SignupPage({super.key}); @override State<SignupPage> createState() => _SignupPageState(); } class _SignupPageState extends State<SignupPage> { final GlobalKey<FormState> signupKey = GlobalKey<FormState>(); final TextEditingController SignUpEmailController = TextEditingController(); final TextEditingController SignUpPasswordController = TextEditingController(); final TextEditingController SignUpNameController = TextEditingController(); final TextEditingController SignUpConfirmPasswordController = TextEditingController(); int intialIndex = 0; late bool _passwordVisible; @override void initState() { Provider.of<ConnectionProvider>(context, listen: false) .checkInternetConnectivity(); _passwordVisible = true; } @override Widget build(BuildContext context) { Size s = MediaQuery.of(context).size; double h = s.height; double w = s.width; return (defaultTargetPlatform == TargetPlatform.android) ? (Provider.of<ConnectionProvider>(context) .connectivityModel .connectivityStatus == "waiting") ? const NoInternetAndroidComponent() : Scaffold( appBar: AppBar( leading: IconButton( onPressed: () { Navigator.of(context).pop(); }, icon: const Icon( Icons.arrow_back, ), ), actions: [ IconButton( onPressed: () { Provider.of<ThemeProvider>(context, listen: false) .changeTheme(); }, icon: Provider.of<ThemeProvider>(context).isDarkView ? const Icon( Icons.dark_mode, ) : const Icon( Icons.sunny, ), ), ], ), body: Center( child: Padding( padding: EdgeInsets.all( h * 0.02, ), child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ AnimatedTextKit( animatedTexts: [ TyperAnimatedText( "SIGNUP", textStyle: TextStyle( fontWeight: FontWeight.bold, fontSize: h * 0.025, ), speed: const Duration(milliseconds: 100), ), ], ), SizedBox(height: h * 0.03), SvgPicture.asset( "assets/icons/signup.svg", height: h * 0.24, ), SizedBox(height: h * 0.025), Form( key: signupKey, child: Column( children: [ SizedBox( height: h * 0.062, width: w * 0.85, child: TextFormField( validator: (value) => (value!.isEmpty) ? "Enter a Email" : null, textInputAction: TextInputAction.next, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.transparent, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.black, ), ), border: const OutlineInputBorder(), prefixIcon: Icon( Icons.person, ), hintText: "Email", filled: true, fillColor: Colors.grey.withOpacity(0.15), ), controller: SignUpEmailController, ), ), SizedBox(height: h * 0.025), SizedBox( height: h * 0.062, width: w * 0.85, child: TextFormField( validator: (value) => (value!.isEmpty) ? "Enter a Name" : null, textInputAction: TextInputAction.next, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.transparent, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.black, ), ), border: const OutlineInputBorder(), prefixIcon: Icon( Icons.person, ), hintText: "Name", filled: true, fillColor: Colors.grey.withOpacity(0.15), ), controller: SignUpNameController, ), ), SizedBox(height: h * 0.025), SizedBox( height: h * 0.062, width: w * 0.85, child: TextFormField( validator: (value) => (value!.isEmpty) ? "Enter a Password" : null, textInputAction: TextInputAction.next, keyboardType: TextInputType.visiblePassword, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.transparent, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.black, ), ), border: const OutlineInputBorder(), prefixIcon: Icon( Icons.lock, ), hintText: "Password", filled: true, fillColor: Colors.grey.withOpacity(0.15), suffixIcon: IconButton( icon: Icon( _passwordVisible ? Icons.visibility : Icons.visibility_off, ), onPressed: () { setState(() { _passwordVisible = !_passwordVisible; }); }, ), ), controller: SignUpPasswordController, obscureText: !_passwordVisible, ), ), SizedBox(height: h * 0.025), SizedBox( height: h * 0.062, width: w * 0.85, child: TextFormField( validator: (value) => (value!.isEmpty) ? "Enter a Confirm Password" : null, textInputAction: TextInputAction.next, keyboardType: TextInputType.visiblePassword, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.transparent, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: const BorderSide( color: Colors.black, ), ), border: const OutlineInputBorder(), prefixIcon: Icon( Icons.lock, ), hintText: "Confirm Password", filled: true, fillColor: Colors.grey.withOpacity(0.15), ), controller: SignUpConfirmPasswordController, ), ), ], ), ), SizedBox(height: h * 0.03), SizedBox( height: h * 0.062, width: w * 0.85, child: OutlinedButtonTheme( data: OutlinedButtonThemeData( style: ButtonStyle( shape: MaterialStatePropertyAll( RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), ), backgroundColor: MaterialStateProperty.all( Colors.deepPurple, ), ), ), child: OutlinedButton( onPressed: () { if (signupKey.currentState!.validate()) { AuthHelper.auth_helper.SignUp( username: SignUpNameController.text, email: SignUpEmailController.text, password: SignUpConfirmPasswordController.text, ); Navigator.of(context) .pushNamedAndRemoveUntil( '/', (route) => false); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text("Something went Wrong..."), ), ); } }, child: const Text( "SIGNUP", style: TextStyle( color: Colors.white, ), ), ), ), ), SizedBox( height: h * 0.02, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Don't Have an Account ?", style: TextStyle( fontWeight: FontWeight.normal, fontSize: h * 0.02, ), ), SizedBox( width: w * 0.022, ), GestureDetector( onTap: () { Navigator.of(context).pushNamed('LoginPage'); }, child: Text( "Sign In", style: TextStyle( fontWeight: FontWeight.bold, fontSize: h * 0.02, ), ), ), ], ), SizedBox( height: h * 0.02, ), const Text("OR"), SizedBox( height: h * 0.02, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ GestureDetector( onTap: () async { UserCredential res = await AuthHelper .auth_helper .signInWithFacebook(); if (res != null) { Navigator.of(context) .pushNamedAndRemoveUntil( '/', (route) => false); } else {} }, child: SvgPicture.asset( color: Provider.of<ThemeProvider>(context) .isDarkView ? Colors.white : Colors.black, "assets/icons/facebook.svg", height: h * 0.03, ), ), SvgPicture.asset( color: Provider.of<ThemeProvider>(context) .isDarkView ? Colors.white : Colors.black, "assets/icons/twitter.svg", height: h * 0.03, ), GestureDetector( onTap: () async { User? res = await AuthHelper.auth_helper .signInWithGoogle(); if (res != null) { Navigator.of(context) .pushNamedAndRemoveUntil( '/', (route) => false); } else {} }, child: SvgPicture.asset( color: Provider.of<ThemeProvider>(context) .isDarkView ? Colors.white : Colors.black, "assets/icons/google-plus.svg", height: h * 0.03, ), ), ], ), ], ), ), ), ), ) : (Provider.of<ConnectionProvider>(context) .connectivityModel .connectivityStatus == "waiting") ? const NoInternetIosComponent() : CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( trailing: CupertinoButton( child: const Icon( CupertinoIcons.moon, ), onPressed: () { Provider.of<ThemeProvider>(context).changeTheme(); }, ), middle: Text( "IOS", style: TextStyle( fontWeight: FontWeight.bold, ), ), ), child: Text( "Disconnected", style: TextStyle( fontSize: h * 0.03, fontWeight: FontWeight.bold, ), ), ); } }
/************************************************************************************************** * Copyright (c) 2023 Calypso Networks Association https://calypsonet.org/ * * * * See the NOTICE file(s) distributed with this work for additional information regarding * * copyright ownership. * * * * This program and the accompanying materials are made available under the terms of the Eclipse * * Public License 2.0 which is available at http://www.eclipse.org/legal/epl-2.0 * * * * SPDX-License-Identifier: EPL-2.0 * **************************************************************************************************/ #pragma once #include <cstdint> #include <memory> #include <ostream> #include <string> #include <vector> /* Calypsonet Terminal Calypso */ #include "CalypsoCard.h" #include "DirectoryHeader.h" #include "ElementaryFile.h" /* Calypsonet Terminal Card */ #include "ApduResponseApi.h" #include "CardSelectionResponseApi.h" #include "SmartCardSpi.h" /* Keyple Card Calypso */ #include "CalypsoCardClass.h" #include "CmdCardGetDataFci.h" #include "ElementaryFileAdapter.h" #include "KeypleCardCalypsoExport.h" /* Keyple Core Util */ #include "LoggerFactory.h" namespace keyple { namespace card { namespace calypso { using namespace calypsonet::terminal::calypso::card; using namespace calypsonet::terminal::card; using namespace calypsonet::terminal::card::spi; using namespace keyple::core::util::cpp; /* Forward declaration */ class CmdCardGetDataFci; /** * (package-private)<br> * Implementation of CalypsoCard. * * @since 2.0.0 */ class KEYPLECARDCALYPSO_API CalypsoCardAdapter final : public CalypsoCard, public SmartCardSpi, public std::enable_shared_from_this<CalypsoCardAdapter> { public: /** * Constructor. * * @since 2.0.0 */ CalypsoCardAdapter(); /** * Post-construction initialization function * * /!\ C++ specific * * @since 2.3.3 */ void initialize(const std::shared_ptr<CardSelectionResponseApi> cardSelectionResponse); /** * (package-private)<br> * Initializes or post-initializes the object with the application FCI data. * * @param cmdCardGetDataFci The command containing the parsed FCI data. * @throws IllegalArgumentException If the FCI is inconsistent. * @since 2.2.3 */ void initializeWithFci(const std::shared_ptr<CmdCardGetDataFci> cmdCardGetDataFci); /** * {@inheritDoc} * * @since 2.0.0 */ const CalypsoCard::ProductType& getProductType() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isHce() const override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::vector<uint8_t>& getDfName() const override; /** * (package-private)<br> * Gets the full Calypso serial number including the possible validity date information in the * two MSB. * * <p>The serial number to be used as diversifier for key derivation.<br> * This is the complete number returned by the card in its response to the Select command. * * @return A byte array containing the Calypso Serial Number (8 bytes) * @since 2.0.0 */ const std::vector<uint8_t>& getCalypsoSerialNumberFull() const; /** * {@inheritDoc} * * @since 2.0.0 */ const std::vector<uint8_t> getApplicationSerialNumber() const override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::vector<uint8_t>& getStartupInfoRawData() const override; /** * (package-private)<br> * Gets the maximum length of data that an APDU in this card can carry. * * @return An int * @since 2.0.0 */ uint8_t getPayloadCapacity() const; /** * (package-private)<br> * Tells if the change counter allowed in session is established in number of operations or * number of bytes modified. * * <p>This varies depending on the product type of the card. * * @return True if the counter is number of bytes * @since 2.0.0 */ bool isModificationsCounterInBytes() const; /** * (package-private)<br> * Indicates the maximum number of changes allowed in session. * * <p>This number can be a number of operations or a number of commands (see * isModificationsCounterInBytes) * * @return The maximum number of modifications allowed * @since 2.0.0 */ int getModificationsCounter() const; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getPlatform() const override; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getApplicationType() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isExtendedModeSupported() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isRatificationOnDeselectSupported() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isSvFeatureAvailable() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isPinFeatureAvailable() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isPkiModeSupported() const override; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getApplicationSubtype() const override; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getSoftwareIssuer() const override; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getSoftwareVersion() const override; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getSoftwareRevision() const override; /** * {@inheritDoc} * * @since 2.0.0 */ uint8_t getSessionModification() const override; /** * {@inheritDoc} * * @since 2.1.0 */ const std::vector<uint8_t> getTraceabilityInformation() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isDfInvalidated() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isDfRatified() const override; /** * {@inheritDoc} * * @since 2.1.1 */ int getTransactionCounter() const override; /** * (package-private)<br> * Sets the transaction counter. * * @param transactionCounter The counter value. * @since 2.1.1 */ void setTransactionCounter(const int transactionCounter); /** * (package-private)<br> * Sets the Stored Value data from the SV Get command * * @param svKvc The KVC value. * @param svGetHeader A not empty array. * @param svGetData A not empty array. * @param svBalance the current SV balance. * @param svLastTNum the last SV transaction number. * @param svLoadLogRecord the SV load log record (it may be null if not available). * @param svDebitLogRecord the SV debit log record (it may be null if not available). * @since 2.0.0 */ void setSvData(const uint8_t svKvc, const std::vector<uint8_t>& svGetHeader, const std::vector<uint8_t>& svGetData, const int svBalance, const int svLastTNum, const std::shared_ptr<SvLoadLogRecord> svLoadLogRecord, const std::shared_ptr<SvDebitLogRecord> svDebitLogRecord); /** * {@inheritDoc} * * @since 2.0.0 */ int getSvBalance() const override; /** * {@inheritDoc} * * @since 2.0.0 */ int getSvLastTNum() const override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::shared_ptr<SvLoadLogRecord> getSvLoadLogRecord() override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::shared_ptr<SvDebitLogRecord> getSvDebitLogLastRecord() override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::vector<std::shared_ptr<SvDebitLogRecord>> getSvDebitLogAllRecords() const override; /** * (package-private)<br> * Sets the ratification status * * @param dfRatified true if the session was ratified. * @since 2.0.0 */ void setDfRatified(const bool dfRatified); /** * (package-private)<br> * Gets the current card class. * * @return A not null reference. * @since 2.0.0 */ CalypsoCardClass getCardClass() const; /** * {@inheritDoc} * * @since 2.0.0 */ const std::shared_ptr<DirectoryHeader> getDirectoryHeader() const override; /** * (package-private)<br> * Sets the DF metadata.<br> * Updates the invalidation flag. * * @param directoryHeader the DF metadata (should be not null). * @return the current instance. * @since 2.0.0 */ CalypsoCard& setDirectoryHeader(const std::shared_ptr<DirectoryHeader> directoryHeader); /** * {@inheritDoc} * * @since 2.0.0 */ const std::shared_ptr<ElementaryFile> getFileBySfi(const uint8_t sfi) const override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::shared_ptr<ElementaryFile> getFileByLid(const uint16_t lid) const override; /** * {@inheritDoc} * * @since 2.0.0 * @deprecated */ const std::map<const uint8_t, const std::shared_ptr<ElementaryFile>> getAllFiles() const override; /** * {@inheritDoc} * * @since 2.1.0 */ const std::vector<std::shared_ptr<ElementaryFile>>& getFiles() const override; /** * {@inheritDoc} * * @since 2.0.0 */ bool isPinBlocked() const override; /** * {@inheritDoc} * * @since 2.0.0 */ int getPinAttemptRemaining() const override; /** * (package-private)<br> * Sets the PIN attempts counter.<br> * The PIN attempt counter is interpreted to give the results of the methods {@link #isPinBlocked} * and {@link #getPinAttemptRemaining}. * * @param pinAttemptCounter the number of remaining attempts to present the PIN code. * @since 2.0.0 */ void setPinAttemptRemaining(const int pinAttemptCounter); /** * (package-private)<br> * Sets the provided ileHeaderAdapter} to the current selected file.<br> * If EF does not exist, then it is created. * * @param sfi the SFI. * @param header the file header (should be not null). * @since 2.0.0 */ void setFileHeader(const uint8_t sfi, const std::shared_ptr<FileHeaderAdapter> header); /** * (package-private)<br> * Set or replace the entire content of the specified record #numRecord of the current selected * file by the provided content.<br> * If EF does not exist, then it is created. * * @param sfi the SFI. * @param numRecord the record number (should be {@code >=} 1). * @param content the content (should be not empty). * @since 2.0.0 */ void setContent(const uint8_t sfi, const uint8_t numRecord, const std::vector<uint8_t>& content); /** * (package-private)<br> * Sets a counter value in record #1 of the current selected file.<br> * If EF does not exist, then it is created. * * @param sfi the SFI. * @param numCounter the counter number (should be {@code >=} 1). * @param content the counter value (should be not null and 3 bytes length). * @since 2.0.0 */ void setCounter(const uint8_t sfi, const uint8_t numCounter, const std::vector<uint8_t>& content); /** * (package-private)<br> * Set or replace the content at the specified offset of record #numRecord of the current * selected file by a copy of the provided content.<br> * If EF does not exist, then it is created.<br> * If actual record content is not set or has a size {@code <} offset, then missing data will be * padded with 0. * * @param sfi the SFI. * @param numRecord the record number (should be {@code >=} 1). * @param content the content (should be not empty). * @param offset the offset (should be {@code >=} 0). * @since 2.0.0 */ void setContent(const uint8_t sfi, const uint8_t numRecord, const std::vector<uint8_t>& content, const int offset); /** * (package-private)<br> * Fills the content at the specified offset of the specified record of the current selected * file using a binary OR operation with the provided content.<br> * If EF does not exist, then it is created.<br> * If actual record content is not set or has a size {@code <} offset + content size, then * missing data will be completed by the provided content. * * @param sfi the SFI. * @param numRecord the record number (should be {@code >=} 1). * @param content the content (should be not empty). * @param offset the offset (should be {@code >=} 0). * @since 2.1.0 */ void fillContent(const uint8_t sfi, const uint8_t numRecord, const std::vector<uint8_t>& content, const int offset); /** * (package-private)<br> * Add cyclic content at record #1 by rolling previously all actual records contents (record * #1 -> record #2, record #2 -> record #3,...) of the current selected file.<br> * This is useful for cyclic files. Note that records are infinitely shifted.<br> * <br> * If EF does not exist, then it is created. * * @param sfi the SFI. * @param content the content (should be not empty). * @since 2.0.0 */ void addCyclicContent(const uint8_t sfi, const std::vector<uint8_t> content); /** * (package-private)<br> * Make a backup of the Elementary Files.<br> * This method should be used before starting a card secure session. * * @since 2.0.0 */ void backupFiles(); /** * (package-private)<br> * Restore the last backup of Elementary Files.<br> * This method should be used when SW of the card close secure session command is unsuccessful * or if secure session is aborted. * * @since 2.0.0 */ void restoreFiles(); /** * {@inheritDoc} * * @since 2.0.0 */ const std::string& getPowerOnData() const override; /** * {@inheritDoc} * * @since 2.0.0 */ const std::vector<uint8_t> getSelectApplicationResponse() const override; /** * (package-private)<br> * Sets the challenge received in response to the GET CHALLENGE command. * * @param cardChallenge A not empty array. * @since 2.0.0 */ void setCardChallenge(const std::vector<uint8_t>& cardChallenge); /** * (package-private)<br> * Sets the traceability information received in response to the GET DATA command for the tag * GetDataTag::TRACEABILITY_INFORMATION}. * * @param traceabilityInformation The traceability information. * @since 2.1.0 */ void setTraceabilityInformation(const std::vector<uint8_t>& traceabilityInformation); /** * (package-private)<br> * Sets the SV signature. * * @param svOperationSignature A not empty array. * @since 2.0.0 */ void setSvOperationSignature(const std::vector<uint8_t>& svOperationSignature); /** * (package-private)<br> * Gets the challenge received from the card * * @return An array of bytes containing the challenge bytes (variable length according to the * product type of the card). May be null if the challenge is not available. * @since 2.0.0 */ const std::vector<uint8_t>& getCardChallenge() const; /** * (package-private)<br> * Gets the SV KVC from the card * * @return The SV KVC byte. * @since 2.0.0 */ uint8_t getSvKvc() const; /** * (package-private)<br> * Gets the SV Get command header * * @return A byte array containing the SV Get command header. * @throws IllegalStateException If the requested data has not been set. * @since 2.0.0 */ const std::vector<uint8_t>& getSvGetHeader() const; /** * (package-private)<br> * Gets the SV Get command response data * * @return A byte array containing the SV Get command response data. * @throws IllegalStateException If the requested data has not been set. * @since 2.0.0 */ const std::vector<uint8_t>& getSvGetData() const; /** * (package-private)<br> * Gets the last SV Operation signature (SV Reload, Debit or Undebit) * * @return A byte array containing the SV Operation signature or null if not available. * @since 2.0.0 */ const std::vector<uint8_t>& getSvOperationSignature() const; /** * (package-private)<br> * Indicates if the response of the Increase/Decrease counter command is postponed to the close * secure session (old revision 2 cards). * * @return true if the response of the Increase/Decrease counter command is postponed. * @since 2.2.4 */ bool isCounterValuePostponed() const; /** * */ friend KEYPLECARDCALYPSO_API std::ostream& operator<<(std::ostream& os, const CalypsoCardAdapter& cca); /** * */ friend KEYPLECARDCALYPSO_API std::ostream& operator<<( std::ostream& os, const std::shared_ptr<CalypsoCardAdapter> cca); private: /** * (private)<br> * POJO containing card specificities to be applied according to startup info. */ class Patch { public: /** * */ friend class CalypsoCardAdapter; /** * */ virtual void apply(CalypsoCardAdapter* calypsoCard) = 0; private: /** * */ const uint64_t mStartupInfo; /** * */ const uint64_t mMask = ~0; /** * */ Patch(const std::string& startupInfo); /** * */ Patch(const std::string& startupInfo, const std::string& mask); /** * */ bool isApplicableTo(const uint64_t startupInfo) const; }; /** * (private)<br> * POJO containing card rev 3 specificities to be applied according to startup info. */ class PatchRev3 : public Patch { public: /** * */ friend class CalypsoCardAdapter; /** * */ virtual ~PatchRev3() = default; /** * */ void apply(CalypsoCardAdapter* calypsoCard) override; private: /** * */ std::shared_ptr<int> mPayloadCapacity; /** * */ PatchRev3(const std::string& startupInfo); /** * */ PatchRev3(const std::string& startupInfo, const std::string& mask); /** * */ PatchRev3& setPayloadCapacity(const int payloadCapacity); }; /** * (private)<br> * POJO containing card rev 1 & 2 specificities to be applied according to startup info. */ class PatchRev12 : public Patch { public: /** * */ friend class CalypsoCardAdapter; /** * */ virtual ~PatchRev12() = default; /** * */ void apply(CalypsoCardAdapter* calypsoCard) override; private: /** * */ std::shared_ptr<bool> mIsCounterValuePostponed; /** * */ PatchRev12(const std::string& startupInfo); /** * */ PatchRev12(const std::string& startupInfo, const std::string& mask); /** * */ PatchRev12& setCounterValuePostponed(); }; /** * */ const std::unique_ptr<Logger> mLogger = LoggerFactory::getLogger(typeid(CalypsoCardAdapter)); /** * */ static const std::string PATTERN_1_BYTE_HEX; static const std::string PATTERN_2_BYTES_HEX; /** * */ static const int CARD_REV1_ATR_LENGTH; static const int REV1_CARD_DEFAULT_WRITE_OPERATIONS_NUMBER_SUPPORTED_PER_SESSION; static const int REV2_CARD_DEFAULT_WRITE_OPERATIONS_NUMBER_SUPPORTED_PER_SESSION; static const int SI_BUFFER_SIZE_INDICATOR; static const int SI_PLATFORM; static const int SI_APPLICATION_TYPE; static const int SI_APPLICATION_SUBTYPE; static const int SI_SOFTWARE_ISSUER; static const int SI_SOFTWARE_VERSION; static const int SI_SOFTWARE_REVISION; static const int DEFAULT_PAYLOAD_CAPACITY; /** * Application type bitmasks features */ static const uint8_t APP_TYPE_WITH_CALYPSO_PIN; static const uint8_t APP_TYPE_WITH_CALYPSO_SV; static const uint8_t APP_TYPE_RATIFICATION_COMMAND_REQUIRED; static const uint8_t APP_TYPE_CALYPSO_REV_32_MODE; static const uint8_t APP_TYPE_WITH_PUBLIC_AUTHENTICATION; /** * Buffer indicator to buffer size lookup table */ static const std::vector<int> BUFFER_SIZE_INDICATOR_TO_BUFFER_SIZE; /** * */ std::shared_ptr<ApduResponseApi> mSelectApplicationResponse; /** * */ std::string mPowerOnData; /** * */ bool mIsExtendedModeSupported = false; /** * */ bool mIsRatificationOnDeselectSupported = false; /** * */ bool mIsSvFeatureAvailable = false; /** * */ bool mIsPinFeatureAvailable = false; /** * */ bool mIsPkiModeSupported = false; /** * */ bool mIsDfInvalidated = false; /** * */ CalypsoCardClass mCalypsoCardClass = CalypsoCardClass::UNKNOWN; /** * */ std::vector<uint8_t> mCalypsoSerialNumber; /** * */ std::vector<uint8_t> mStartupInfo; /** * */ CalypsoCard::ProductType mProductType = ProductType::UNKNOWN; /** * */ std::vector<uint8_t> mDfName; /** * */ int mModificationsCounterMax = 0; /** * */ bool mIsModificationCounterInBytes = true; /** * */ std::shared_ptr<DirectoryHeader> mDirectoryHeader; /** * */ std::vector<std::shared_ptr<ElementaryFile>> mFiles; /** * */ std::vector<std::shared_ptr<ElementaryFile>> mFilesBackup; /** * */ std::shared_ptr<ElementaryFileAdapter> mCurrentEf; /** * */ std::shared_ptr<bool> mIsDfRatified; /** * */ std::shared_ptr<int> mTransactionCounter = nullptr; /** * */ std::shared_ptr<int> mPinAttemptCounter; /** * */ std::shared_ptr<int> mSvBalance; /** * */ int mSvLastTNum = 0; /** * */ std::shared_ptr<SvLoadLogRecord> mSvLoadLogRecord; /** * */ std::shared_ptr<SvDebitLogRecord> mSvDebitLogRecord; /** * */ bool mIsHce = false; /** * */ std::vector<uint8_t> mCardChallenge; /** * */ std::vector<uint8_t> mTraceabilityInformation; /** * */ uint8_t mSvKvc = 0; /** * */ std::vector<uint8_t> mSvGetHeader; /** * */ std::vector<uint8_t> mSvGetData; /** * */ std::vector<uint8_t> mSvOperationSignature; /** * */ uint8_t mApplicationSubType = 0; /** * */ uint8_t mApplicationType = 0; /** * */ uint8_t mSessionModification = 0; /** * */ int mPayloadCapacity = DEFAULT_PAYLOAD_CAPACITY; /** * */ bool mIsCounterValuePostponed = false; /** * */ static const std::vector<std::shared_ptr<PatchRev3>> mPatchesRev3; /** * */ static const std::vector<std::shared_ptr<PatchRev12>> mPatchesRev12; /** * Resolve the card product type from the application type byte * * @param applicationType The application type (field of startup info). * @return The product type. */ CalypsoCard::ProductType computeProductType(const int applicationType) const; /** * (private)<br> * Returns a reference to the currently selected EF.<br> * If the file having the provided non-zero SFI or LID does not exist, then a new EF is created. * <br> * If the SFI and LID are both equal to 0, then the previously selected EF is returned. * * @param sfi The SFI (0 if not specified in the current command). * @param lid The LID (0 if not specified in the current command). * @return a not null reference. */ const std::shared_ptr<ElementaryFileAdapter> getOrCreateFile(const uint8_t sfi, const uint16_t lid); /** * (private)<br> * Copy a set of ElementaryFile to another one by cloning each element. * * @param src the source (should be not null). * @param dest the destination (should be not null). */ static void copyFiles(const std::vector<std::shared_ptr<ElementaryFile>>& src, std::vector<std::shared_ptr<ElementaryFile>>& dest); /** * (private)<br> * Initializes the object with the card power-on data. * * <p>This method should be invoked only when no response to select application is available. * * @param powerOnData The card's power-on data. * @throw IllegalArgumentException If powerOnData is inconsistent. * @since 2.0.0 */ void initializeWithPowerOnData(const std::string& powerOnData); /** * (private)<br> * Initializes or post-initializes the object with the application FCI data. * * @param selectApplicationResponse The select application response. * @throws IllegalArgumentException If the FCI is inconsistent. * @since 2.0.0 */ void initializeWithFci(const std::shared_ptr<ApduResponseApi> selectApplicationResponse); /** * */ static const std::vector<std::shared_ptr<PatchRev12>> initPatchRev12(); /** * */ static const std::vector<std::shared_ptr<PatchRev3>> initPatchRev3(); /** * (private)<br> * Some cards have specific features that need to be taken into account. This method identifies * them and applies the necessary modifications. */ void applyPatchIfNeeded(); /** * */ void applyPatchIfNeededForRevision(const std::vector<std::shared_ptr<Patch>>& patches, const uint64_t startupInfoLong); }; } } }
mdast-util-mdx-expression [![Build](https://github.com/syntax-tree/mdast-util-mdx-expression/workflows/main/badge.svg)](https://github.com/syntax-tree/mdast-util-mdx-expression/actions) [![Coverage](https://img.shields.io/codecov/c/github/syntax-tree/mdast-util-mdx-expression.svg)](https://codecov.io/github/syntax-tree/mdast-util-mdx-expression) [![Downloads](https://img.shields.io/npm/dm/mdast-util-mdx-expression.svg)](https://www.npmjs.com/package/mdast-util-mdx-expression) [![Size](https://img.shields.io/bundlephobia/minzip/mdast-util-mdx-expression.svg)](https://bundlephobia.com/result?p=mdast-util-mdx-expression) [![Sponsors](https://opencollective.com/unified/sponsors/badge.svg)](https://opencollective.com/unified) [![Backers](https://opencollective.com/unified/backers/badge.svg)](https://opencollective.com/unified) [![Chat](https://img.shields.io/badge/chat-discussions-success.svg)](https://github.com/syntax-tree/unist/discussions) Extension for [`mdast-util-from-markdown`](https://github.com/syntax-tree/mdast-util-from-markdown) and/or [`mdast-util-to-markdown`](https://github.com/syntax-tree/mdast-util-to-markdown) to support MDX (or MDX.js) expressions. When parsing (`from-markdown`), must be combined with [`micromark-extension-mdx-expression`](https://github.com/micromark/micromark-extension-mdxjs-esm). This utility handles parsing and serializing. See [`micromark-extension-mdx-expression`](https://github.com/micromark/micromark-extension-mdxjs-esm) for how the syntax works. You probably should use either [`micromark-extension-mdx`](https://github.com/micromark/micromark-extension-mdx) or [`micromark-extension-mdxjs`](https://github.com/micromark/micromark-extension-mdxjs) with [`mdast-util-mdx`](https://github.com/syntax-tree/mdast-util-mdx) (which both include this package) to support all of MDX (or MDX.js). Or use it all through `remark-mdx` or `remark-mdxjs` (**[remark](https://github.com/remarkjs/remark)**). Install ------- [npm](https://docs.npmjs.com/cli/install): npm install mdast-util-mdx-expression Use --- Say we have an MDX.js file, `example.mdx`: { a + 1 } b {true}. And our script, `example.js`, looks as follows: var fs = require('fs') var acorn = require('acorn') var syntax = require('micromark-extension-mdx-expression') var fromMarkdown = require('mdast-util-from-markdown') var toMarkdown = require('mdast-util-to-markdown') var mdxExpression = require('mdast-util-mdx-expression') var doc = fs.readFileSync('example.mdx') var tree = fromMarkdown(doc, { extensions: [syntax({acorn: acorn, addResult: true})], mdastExtensions: [mdxExpression.fromMarkdown] }) console.log(tree) var out = toMarkdown(tree, {extensions: [mdxExpression.toMarkdown]}) console.log(out) Now, running `node example` yields (positional info removed for brevity): { type: 'root', children: [ { type: 'mdxFlowExpression', value: '\na + 1\n', data: { estree: { type: 'BinaryExpression', left: {type: 'Identifier', name: 'a'}, operator: '+', right: {type: 'Literal', value: 1} } } }, { type: 'paragraph', children: [ {type: 'text', value: 'b '}, { type: 'mdxTextExpression', value: 'true', data: { estree: {type: 'Literal', value: true} } }, {type: 'text', value: '.'} ] } ] } { a + 1 } b {true}. API --- ### `mdxExpression.fromMarkdown` ### `mdxExpression.toMarkdown` > Note: the separate extensions are also available at `mdast-util-mdx-expression/from-markdown` and `mdast-util-mdx-expression/to-markdown`. Support MDX (or MDX.js) expressions. The exports are extensions, respectively for [`mdast-util-from-markdown`](https://github.com/syntax-tree/mdast-util-from-markdown) and [`mdast-util-to-markdown`](https://github.com/syntax-tree/mdast-util-to-markdown). When using the [syntax extension with `addResult`](https://github.com/micromark/micromark-extension-mdxjs-esm), nodes will have a `data.estree` field set to an [ESTree](https://github.com/estree/estree). The indent of the value of `MDXFlowExpression`s is stripped. Syntax tree ----------- The following interfaces are added to **[mdast](https://github.com/syntax-tree/mdast)** by this utility. ### Nodes #### `MDXFlowExpression` interface MDXFlowExpression <: Literal { type: "mdxFlowExpression" } **MDXFlowExpression** (**[Literal](https://github.com/syntax-tree/mdast#literal)**) represents a JavaScript expression embedded in flow (block). It can be used where **[flow](#flowcontent-mdx-expression)** content is expected. Its content is represented by its `value` field. For example, the following markdown: { 1 + 1 } Yields: {type: 'mdxFlowExpression', value: '\n1 + 1\n'} #### `MDXTextExpression` interface MDXTextExpression <: Literal { type: "mdxTextExpression" } **MDXTextExpression** (**[Literal](https://github.com/syntax-tree/mdast#literal)**) represents a JavaScript expression embedded in text (span, inline). It can be used where **[phrasing](#phrasingcontent-mdx-expression)** content is expected. Its content is represented by its `value` field. For example, the following markdown: a {1 + 1} b. Yields: {type: 'mdxTextExpression', value: '1 + 1'} ### Content model #### `FlowContent` (MDX expression) type FlowContentMdxExpression = MDXFlowExpression | FlowContent #### `PhrasingContent` (MDX expression) type PhrasingContentMdxExpression = MDXTextExpression | PhrasingContent Related ------- - [`remarkjs/remark`](https://github.com/remarkjs/remark) — markdown processor powered by plugins - `remarkjs/remark-mdx` — remark plugin to support MDX - `remarkjs/remark-mdxjs` — remark plugin to support MDX.js - [`syntax-tree/mdast-util-from-markdown`](https://github.com/syntax-tree/mdast-util-from-markdown) — mdast parser using `micromark` to create mdast from markdown - [`syntax-tree/mdast-util-to-markdown`](https://github.com/syntax-tree/mdast-util-to-markdown) — mdast serializer to create markdown from mdast - [`syntax-tree/mdast-util-mdx`](https://github.com/syntax-tree/mdast-util-mdx) — mdast utility to support MDX - [`micromark/micromark`](https://github.com/micromark/micromark) — the smallest commonmark-compliant markdown parser that exists - [`micromark/micromark-extension-mdx-expression`](https://github.com/micromark/micromark-extension-mdxjs-esm) — micromark extension to parse MDX expressions Contribute ---------- See [`contributing.md` in `syntax-tree/.github`](https://github.com/syntax-tree/.github/blob/HEAD/contributing.md) for ways to get started. See [`support.md`](https://github.com/syntax-tree/.github/blob/HEAD/support.md) for ways to get help. This project has a [code of conduct](https://github.com/syntax-tree/.github/blob/HEAD/code-of-conduct.md). By interacting with this repository, organization, or community you agree to abide by its terms. License ------- [MIT](license) © [Titus Wormer](https://wooorm.com)
#include <iostream> using namespace std; int main() { /* Basic Data Types: */ int a = 0; // a number between -2 ^ 31 and 2 ^ 31 bool b = true; // true or false char c = 'c'; // ONE character long d = 3; // a number between -2 ^ 63 and 2 ^ 63 - 1 /* Floating Point Data Types: */ float e = 2.3; // a decimal number between -3.4 * 10 ^ 38 and 3.4 * 10 ^ 38 double f = 2.333; // a decimal number between -1.7 * 10 ^ 308 and 1.7 * 10 ^ 308 //********************************************************* // NOTE: // There is one more difference between float and double // and that is that double can hold 15 significant figures // or more but float can hold only 6 or 7. //********************************************************* }
import { MongoClient } from 'mongodb'; import { app } from "./app.js"; import 'dotenv/config'; // process.env.PORT indicates to Heroku where to run in the destiniy server. // Otherwise, the server will be run in the local host 4000 const port = process.env.PORT || 4000; const client = new MongoClient(process.env.REACT_APP_MONGOURI as string); async function start() { try{ await client.connect(); //1. Connect with client const db = client.db('tennis-lesson-planner'); app.locals.ddbbClient = { usersCol: db.collection('users'), tokenCol: db.collection('validate-token') // client: client }; //2. Save it in Locals to access from routes app.listen(port, () => console.log(`🔥Server running on port ${port}🔥`)); }catch(err){ console.error('Error on server: ', err); } } async function stop() { console.log('Closing server'); await client.close() // Closing conexion with DDBB } process.on('SIGINT', stop); // O.S events like Ctrl+C process.on('SIGTERM', stop); start(); // Calling start function that initializes both DDBB and Express Server
<template> <div id="app"> <h1>ToDoList</h1> <add-list :editname="editname" :item="item" @addList="AddItem" @changeList="EditItem" /> <list-nav :nowtab="nowtab" @TabSwitch="TabChange" /> <div class="list-group" v-for="i in ListFilter" :key="i.id"> <to-do-item :item="item" :labelid="i.id" :labelname="i.name" :labeldone="i.completed" @editList="Edit" @removeList="Remove" @BoolChanged="ItemUpdate" /> </div> </div> </template> <script> import ToDoItem from "./components/ToDoItem"; import AddList from "./components/AddList"; import ListNav from "./components/ListNav"; export default { name: "App", components: { ToDoItem, AddList, ListNav, }, data() { return { item: [ { id: 1, name: "9:00打工", completed: false, }, { id: 2, name: "帶狗狗去散步", completed: true, }, ], nowtab: "ALL", editname: {}, arrlength: 2, }; }, methods: { AddItem(value) { this.item.push({ id: this.arrlength + 1, name: value, completed: false, }); this.arrlength++; }, EditItem(value) { const index = this.item.findIndex((list) => list.id === value.id); this.item[index] = value; }, Edit(value) { const index = this.item.findIndex((list) => list.id === value); this.editname = this.item[index]; }, Remove(value) { const i = this.item.findIndex((list) => list.id === value); this.item.splice(i, 1); }, ItemUpdate(value) { this.item = value; }, TabChange(value) { this.nowtab = value; }, }, computed: { ListFilter() { if (this.nowtab == "DONE") { const donefilter = this.item.filter((i) => i.completed); return donefilter; } else if (this.nowtab == "TODO") { const undonefilter = this.item.filter((i) => !i.completed); return undonefilter; } return this.item; }, }, // watch: { // item: { // handler(val) { // var itemstorage; // for (var i = 0; i < val.length; i++) { // console.log(val[i].id); // console.log(`${val[i].id},`); // itemstorage += JSON.parse(`${val[i].id},`); // } // localStorage.setItem("id", itemstorage); // }, // deep: true, // }, // }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; /* margin-top: 60px; */ padding: 3% 15%; background-color: #547b68; } body, html { background-color: #547b68; } h1 { color: #e15b67; } .nav-link, .nav-pills .nav-link.active, .nav-pills .show > .nav-link { color: #ffffff !important; border: #ffffff 1px solid !important; margin-right: 10px; } @media (max-width: 820px) { #app { padding: 5% 5%; } } </style>
## ## Program: Visualization Toolkit ## Module: vtkProjectPointsToPlane.h ## ## Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen ## All rights reserved. ## See Copyright.txt or http://www.kitware.com/Copyright.htm for details. ## ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ## PURPOSE. See the above copyright notice for more information. ## ## * ## @class vtkProjectPointsToPlane ## @brief project all input points to a plane ## ## vtkProjectPointsToPlane is a filter that operates on a vtkPointSet (and ## its subclasses), projecting all input points to a plane. There are ## multiple options as to what plane to project to: The user may specify one ## of the x-y-z planes, the best coordinate plane, a user-defined plane, or ## the closest fitting plane (using a least-squares method). On output, the ## points will lie on the specified plane, and any cells connected to the ## points (if any) will be deformed accordingly. On output, the filter will ## not modify dataset topology, nor modify point or cell attributes. Only the ## point coordinates (geometry) will be modified. (Note that the filter will ## operate on input point sets with or without cells.) ## ## @warning ## It is possible that cells connected to the projected points will become ## invalid after the projection operation. ## ## @sa ## vtkPlane ## import vtkFiltersPointsModule, vtkPointSetAlgorithm type vtkProjectPointsToPlane* {.importcpp: "vtkProjectPointsToPlane", header: "vtkProjectPointsToPlane.h", bycopy.} = object of vtkPointSetAlgorithm ## /@{ ## * ## Standard methods for instantiation, obtaining type information, and ## printing. ## vtkProjectPointsToPlane* {.importc: "vtkProjectPointsToPlane".}: VTK_NEWINSTANCE proc New*(): ptr vtkProjectPointsToPlane {.importcpp: "vtkProjectPointsToPlane::New(@)", header: "vtkProjectPointsToPlane.h".} type vtkProjectPointsToPlaneSuperclass* = vtkPointSetAlgorithm proc IsTypeOf*(`type`: cstring): vtkTypeBool {. importcpp: "vtkProjectPointsToPlane::IsTypeOf(@)", header: "vtkProjectPointsToPlane.h".} proc IsA*(this: var vtkProjectPointsToPlane; `type`: cstring): vtkTypeBool {. importcpp: "IsA", header: "vtkProjectPointsToPlane.h".} proc SafeDownCast*(o: ptr vtkObjectBase): ptr vtkProjectPointsToPlane {. importcpp: "vtkProjectPointsToPlane::SafeDownCast(@)", header: "vtkProjectPointsToPlane.h".} ## !!!Ignored construct: * NewInstance ( ) const { return vtkProjectPointsToPlane :: SafeDownCast ( this -> NewInstanceInternal ( ) ) ; } static vtkIdType GetNumberOfGenerationsFromBaseType ( const char * type ) { if ( ! strcmp ( thisClass , type ) ) { return 0 ; } return 1 + vtkPointSetAlgorithm :: GetNumberOfGenerationsFromBaseType ( type ) ; } vtkIdType GetNumberOfGenerationsFromBase ( const char * type ) override { return this -> vtkProjectPointsToPlane :: GetNumberOfGenerationsFromBaseType ( type ) ; } public : protected : vtkObjectBase * NewInstanceInternal ( ) const override { return vtkProjectPointsToPlane :: New ( ) ; } public : ; ## Error: identifier expected, but got: *!!! proc PrintSelf*(this: var vtkProjectPointsToPlane; os: var ostream; indent: vtkIndent) {. importcpp: "PrintSelf", header: "vtkProjectPointsToPlane.h".} type vtkProjectPointsToPlanePlaneProjectionType* {.size: sizeof(cint), importcpp: "vtkProjectPointsToPlane::PlaneProjectionType", header: "vtkProjectPointsToPlane.h".} = enum X_PLANE = 1, Y_PLANE = 2, Z_PLANE = 3, SPECIFIED_PLANE = 4, BEST_COORDINATE_PLANE = 5, BEST_FIT_PLANE = 6 proc SetProjectionType*(this: var vtkProjectPointsToPlane; _arg: cint) {. importcpp: "SetProjectionType", header: "vtkProjectPointsToPlane.h".} proc GetProjectionTypeMinValue*(this: var vtkProjectPointsToPlane): cint {. importcpp: "GetProjectionTypeMinValue", header: "vtkProjectPointsToPlane.h".} proc GetProjectionTypeMaxValue*(this: var vtkProjectPointsToPlane): cint {. importcpp: "GetProjectionTypeMaxValue", header: "vtkProjectPointsToPlane.h".} ## !!!Ignored construct: virtual int GetProjectionType ( ) VTK_FUTURE_CONST { vtkDebugWithObjectMacro ( this , << returning << ProjectionType of << this -> ProjectionType ) ; return this -> ProjectionType ; } ; ## Error: expected ';'!!! proc SetProjectionTypeToXPlane*(this: var vtkProjectPointsToPlane) {. importcpp: "SetProjectionTypeToXPlane", header: "vtkProjectPointsToPlane.h".} proc SetProjectionTypeToYPlane*(this: var vtkProjectPointsToPlane) {. importcpp: "SetProjectionTypeToYPlane", header: "vtkProjectPointsToPlane.h".} proc SetProjectionTypeToZPlane*(this: var vtkProjectPointsToPlane) {. importcpp: "SetProjectionTypeToZPlane", header: "vtkProjectPointsToPlane.h".} proc SetProjectionTypeToSpecifiedPlane*(this: var vtkProjectPointsToPlane) {. importcpp: "SetProjectionTypeToSpecifiedPlane", header: "vtkProjectPointsToPlane.h".} proc SetProjectionTypeToBestCoordinatePlane*(this: var vtkProjectPointsToPlane) {. importcpp: "SetProjectionTypeToBestCoordinatePlane", header: "vtkProjectPointsToPlane.h".} proc SetProjectionTypeToBestFitPlane*(this: var vtkProjectPointsToPlane) {. importcpp: "SetProjectionTypeToBestFitPlane", header: "vtkProjectPointsToPlane.h".} proc SetOrigin*(this: var vtkProjectPointsToPlane; _arg1: cdouble; _arg2: cdouble; _arg3: cdouble) {.importcpp: "SetOrigin", header: "vtkProjectPointsToPlane.h".} proc SetOrigin*(this: var vtkProjectPointsToPlane; _arg: array[3, cdouble]) {. importcpp: "SetOrigin", header: "vtkProjectPointsToPlane.h".} proc SetOriginNormal*(this: var vtkProjectPointsToPlane; _arg1: cdouble; _arg2: cdouble; _arg3: cdouble) {.importcpp: "SetOriginNormal", header: "vtkProjectPointsToPlane.h".} proc SetOriginNormal*(this: var vtkProjectPointsToPlane; _arg: array[3, cdouble]) {. importcpp: "SetOriginNormal", header: "vtkProjectPointsToPlane.h".} ## !!!Ignored construct: virtual double * GetOrigin ( ) VTK_SIZEHINT ( 3 ) { vtkDebugWithObjectMacro ( this , << returning << Origin pointer << this -> Origin ) ; return this -> Origin ; } VTK_WRAPEXCLUDE virtual void GetOrigin ( double & _arg1 , double & _arg2 , double & _arg3 ) { _arg1 = this -> Origin [ 0 ] ; _arg2 = this -> Origin [ 1 ] ; _arg3 = this -> Origin [ 2 ] ; vtkDebugWithObjectMacro ( this , << returning << Origin = ( << _arg1 << , << _arg2 << , << _arg3 << ) ) ; } VTK_WRAPEXCLUDE virtual void GetOrigin ( double _arg [ 3 ] ) { this -> GetOrigin ( _arg [ 0 ] , _arg [ 1 ] , _arg [ 2 ] ) ; } ; ## Error: expected ';'!!! ## !!!Ignored construct: virtual double * GetOriginNormal ( ) VTK_SIZEHINT ( 3 ) { vtkDebugWithObjectMacro ( this , << returning << Normal pointer << this -> Normal ) ; return this -> Normal ; } VTK_WRAPEXCLUDE virtual void GetOriginNormal ( double & _arg1 , double & _arg2 , double & _arg3 ) { _arg1 = this -> Normal [ 0 ] ; _arg2 = this -> Normal [ 1 ] ; _arg3 = this -> Normal [ 2 ] ; vtkDebugWithObjectMacro ( this , << returning << Normal = ( << _arg1 << , << _arg2 << , << _arg3 << ) ) ; } VTK_WRAPEXCLUDE virtual void GetOriginNormal ( double _arg [ 3 ] ) { this -> GetOriginNormal ( _arg [ 0 ] , _arg [ 1 ] , _arg [ 2 ] ) ; } ; ## Error: expected ';'!!! proc SetOutputPointsPrecision*(this: var vtkProjectPointsToPlane; _arg: cint) {. importcpp: "SetOutputPointsPrecision", header: "vtkProjectPointsToPlane.h".} ## !!!Ignored construct: virtual int GetProjectionTypeOutputPointsPrecision ( ) VTK_FUTURE_CONST { vtkDebugWithObjectMacro ( this , << returning << OutputPointsPrecision of << this -> OutputPointsPrecision ) ; return this -> OutputPointsPrecision ; } ; ## Error: expected ';'!!!
package com.Spring.Entity; import java.util.List; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JOptionPane; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityTransaction; import jakarta.persistence.Persistence; public class EmployeeLogic { Scanner sc = new Scanner(System.in); EntityManagerFactory emf = null; EntityManager em = null; EntityTransaction et = null; { emf = Persistence.createEntityManagerFactory("ProjectUnit"); em = emf.createEntityManager(); et = em.getTransaction(); } JFrame jp = new JFrame(); public boolean addEmployee() { et.begin(); //Scanner sc = new Scanner(System.in); Employee1 e1 = new Employee1(); System.out.println("Enter Employee First name"); String f_name=sc.next(); e1.setE_F_name(f_name); System.out.println("Enter Employee Last name"); String L_name=sc.next(); e1.setE_L_name(L_name); System.out.println("Enter Employee Date of birth(dd/mm/yyyy)"); String DOB=sc.next(); e1.setE_DOB(DOB); System.out.println("Enter Employee Gender(M/F)"); char Gender=sc.next().charAt(0); e1.setE_Gender(Gender); System.out.println("Enter Employee City"); String City=sc.next(); e1.setE_City(City); System.out.println("Enter Employee Phone"); long phone=sc.nextLong(); e1.setE_Phone(phone); System.out.println("Enter Employee Designation"); String Designation=sc.next(); e1.setE_Designation(Designation); System.out.println("Enter Employee Department"); String Department=sc.next(); e1.setE_Department(Department); System.out.println("Enter Employee date of joining(dd/mm/yyyy"); String DOJ=sc.next(); e1.setE_DOJ(DOJ); System.out.println("Enter Employee Grade"); char Grade=sc.next().charAt(0); e1.setE_Grade(Grade); em.persist(e1); //sc.close(); et.commit(); JOptionPane.showMessageDialog(jp, "Succeussfully Inserted..", "Alert",JOptionPane.INFORMATION_MESSAGE); return true; } public void viewEmployees() { et.begin(); System.out.println("Employee Id"); int id=sc.nextInt(); Employee1 f1 = em.find(Employee1.class,id); System.out.println("\n**************************Employee Details**************************"); System.out.println("--------------------------------------------------------------------- "); System.out.println("\nEmployee f_name: "+f1.getE_F_name()); System.out.println("Employee L_name: "+f1.getE_L_name()); System.out.println("Employee City: "+f1.getE_City()); System.out.println("Employee Department: "+f1.getE_Department()); System.out.println("Employee DEsignation: "+f1.getE_Designation()); //sc.close()? et.commit(); } public boolean updateEmployeesName() { et.begin(); //Employee1 e1 = new Employee1(); System.out.println("Employee Id"); int id=sc.nextInt(); Employee1 f1 = em.find(Employee1.class,id); System.out.println("\nEnter employee first name to change :- "); String changeFName = sc.next(); f1.setE_F_name(changeFName); System.out.println("Enter employee last name to change :- "); String changeLName = sc.next(); f1.setE_F_name(changeLName); //sc.close(); et.commit(); JOptionPane.showMessageDialog(jp, "Succeussfully Updated..", "Alert",JOptionPane.INFORMATION_MESSAGE); return true; } public void deleteEmployees() { et.begin(); System.out.println("\nEmployee Id to Delete the Employee details"); int id=sc.nextInt(); Employee1 e4 = em.find(Employee1.class, id); em.remove(e4); et.commit(); JOptionPane.showMessageDialog(jp, "Succeussfully Deleted..", "Alert",JOptionPane.INFORMATION_MESSAGE); //sc.close(); } public void viewAll() { @SuppressWarnings("unchecked") List<Employee1> listEmployee = em.createQuery("SELECT e FROM Employee1 e").getResultList(); if (listEmployee == null) { System.out.println("No employee found . "); } else { System.out.println("\n\t************************Employee Details************************ "); System.out.println("--------------------------------------------------------------------"); System.out.println("Employee id \t\tEmployee firstName\t\t Employee LastName " ); for (Employee1 empl : listEmployee) { System.out.println(empl.getE_id()+"\t\t\t " + empl.getE_F_name() + "\t\t\t " + empl.getE_L_name()); } } } }
package alicloud import ( "fmt" "testing" "github.com/aliyun/alibaba-cloud-sdk-go/services/polardb" "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func TestAccAliCloudPolarDBAccount_update(t *testing.T) { var v *polardb.DBAccount rand := acctest.RandIntRange(10000, 999999) name := fmt.Sprintf("tf-testAccdbaccount-%d", rand) var basicMap = map[string]string{ "db_cluster_id": CHECKSET, "account_name": "tftestnormal", "account_password": "YourPassword_123", "account_type": "Normal", } resourceId := "alicloud_polardb_account.default" ra := resourceAttrInit(resourceId, basicMap) serviceFunc := func() interface{} { return &PolarDBService{testAccProvider.Meta().(*connectivity.AliyunClient)} } rc := resourceCheckInitWithDescribeMethod(resourceId, &v, serviceFunc, "DescribePolarDBAccount") rac := resourceAttrCheckInit(rc, ra) testAccCheck := rac.resourceAttrMapUpdateSet() testAccConfig := resourceTestAccConfigFunc(resourceId, name, resourcePolarDBAccountConfigDependence) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, // module name IDRefreshName: resourceId, Providers: testAccProviders, CheckDestroy: rac.checkResourceDestroy(), Steps: []resource.TestStep{ { Config: testAccConfig(map[string]interface{}{ "db_cluster_id": "${alicloud_polardb_cluster.cluster.id}", "account_name": "tftestnormal", "account_password": "YourPassword_123", "account_type": "Normal", "kms_encrypted_password": "${alicloud_kms_ciphertext.default.ciphertext_blob}", "kms_encryption_context": map[string]string{ "name": name, }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(nil), ), }, { ResourceName: resourceId, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"account_password", "kms_encrypted_password", "kms_encryption_context"}, }, { Config: testAccConfig(map[string]interface{}{ "account_description": "from terraform", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "account_description": "from terraform", }), ), }, { Config: testAccConfig(map[string]interface{}{ "account_password": "YourPassword_1234", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "account_password": "YourPassword_1234", }), ), }, { Config: testAccConfig(map[string]interface{}{ "account_description": "tf test", "account_password": "YourPassword_123", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "account_description": "tf test", "account_password": "YourPassword_123", }), ), }, }, }) } func TestAccAliCloudPolarDBAccount_update_forSuper(t *testing.T) { var v *polardb.DBAccount rand := acctest.RandIntRange(10000, 999999) name := fmt.Sprintf("tf-testAccdbaccount-%d", rand) var basicMap = map[string]string{ "db_cluster_id": CHECKSET, "account_name": "tftestsuper", "account_password": "YourPassword_123", "account_type": "Super", } resourceId := "alicloud_polardb_account.default" ra := resourceAttrInit(resourceId, basicMap) serviceFunc := func() interface{} { return &PolarDBService{testAccProvider.Meta().(*connectivity.AliyunClient)} } rc := resourceCheckInitWithDescribeMethod(resourceId, &v, serviceFunc, "DescribePolarDBAccount") rac := resourceAttrCheckInit(rc, ra) testAccCheck := rac.resourceAttrMapUpdateSet() testAccConfig := resourceTestAccConfigFunc(resourceId, name, resourcePolarDBAccountConfigDependence) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, // module name IDRefreshName: resourceId, Providers: testAccProviders, CheckDestroy: rac.checkResourceDestroy(), Steps: []resource.TestStep{ { Config: testAccConfig(map[string]interface{}{ "db_cluster_id": "${alicloud_polardb_cluster.cluster.id}", "account_name": "tftestsuper", "account_password": "YourPassword_123", "account_type": "Super", "kms_encrypted_password": "${alicloud_kms_ciphertext.default.ciphertext_blob}", "kms_encryption_context": map[string]string{ "name": name, }, }), Check: resource.ComposeTestCheckFunc( testAccCheck(nil), ), }, { ResourceName: resourceId, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"account_password", "kms_encrypted_password", "kms_encryption_context"}, }, { Config: testAccConfig(map[string]interface{}{ "account_description": "from terraform super", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "account_description": "from terraform super", }), ), }, { Config: testAccConfig(map[string]interface{}{ "account_password": "YourPassword_12345", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "account_password": "YourPassword_12345", }), ), }, { Config: testAccConfig(map[string]interface{}{ "account_description": "tf test super", "account_password": "YourPassword_1234", }), Check: resource.ComposeTestCheckFunc( testAccCheck(map[string]string{ "account_description": "tf test super", "account_password": "YourPassword_1234", }), ), }, }, }) } func resourcePolarDBAccountConfigDependence(name string) string { return fmt.Sprintf(` %s variable "name" { default = "%s" } data "alicloud_polardb_node_classes" "this" { db_type = "MySQL" db_version = "8.0" pay_type = "PostPaid" zone_id = local.zone_id category = "Normal" } resource "alicloud_polardb_cluster" "cluster" { db_type = "MySQL" db_version = "8.0" pay_type = "PostPaid" db_node_class = data.alicloud_polardb_node_classes.this.classes.0.supported_engines.0.available_resources.0.db_node_class vswitch_id = local.vswitch_id description = "${var.name}" } data "alicloud_kms_keys" "default" { status = "Enabled" } resource "alicloud_kms_key" "default" { count = length(data.alicloud_kms_keys.default.ids) > 0 ? 0 : 1 description = var.name status = "Enabled" pending_window_in_days = 7 } resource "alicloud_kms_ciphertext" "default" { key_id = length(data.alicloud_kms_keys.default.ids) > 0 ? data.alicloud_kms_keys.default.ids.0 : concat(alicloud_kms_key.default.*.id, [""])[0] plaintext = "YourPassword1234" encryption_context = { "name" = var.name } } `, PolarDBCommonTestCase, name) }
const { EmbedBuilder, AuditLogEvent, Events } = require("discord.js"); require("dotenv").config(); module.exports = { name: Events.MessageBulkDelete, description: "Log bulk deleted Messages.", once: false, async execute(messages) { const { Application } = require("../../core/application/Application"); const { DevCheck } = require("../../tools/functions/devCheck"); const { DateTime } = require("luxon"); // SQLite const { Get, Set, Del } = require("../../tools/functions/sqlite/prepare"); const msgs = messages.map(function(obj) { return obj; }); const getGuildID = msgs[0].guildId; const logChannel = await DevCheck.LogChannel(getGuildID); if (logChannel === "0") return; // eslint-disable-next-line no-undef const guild = await globalclient.guilds.fetch(getGuildID); const fetchedLogs = await guild.fetchAuditLogs({ limit: 1, type: AuditLogEvent.MessageBulkDelete }); const botLog = fetchedLogs.entries.first(); const getBotConfigID = `${guild.id}-${guild.shard.id}`; let dataLang; dataLang = Get.botConfig(getBotConfigID); if (dataLang == null) dataLang = { Lang: "./data/lang/en_US.json" }; const lang = require(`../../.${dataLang.Lang}`); const { LanguageConvert } = require("../../tools/functions/languageConvert"); const { executor, id, extra } = botLog; // Data Null let dataAuditLog; // Data Get dataAuditLog = Get.auditLogs(botLog.id); const MessageDelEmbed = new EmbedBuilder() .setColor(Application.colors().logEmbedColor.delete) .setTimestamp(new Date()); let icon2 = executor.avatarURL(); if (executor.avatar == null) icon2 = "https://i.imgur.com/CN6k8gB.png"; if (dataAuditLog.AuditLogID === id && dataAuditLog.Count < extra.count) { // Highter counter + New Message MessageDelEmbed.setAuthor({ name: `${executor.tag} (ID: ${executor.id})`, iconURL: `${icon2}` }) .setDescription(LanguageConvert.lang(lang.logs.bulkdeleted2, messages.size, msgs[0].channelId)); dataAuditLog = { AuditLogID: `${id}`, GuildID: `${getGuildID}`, Type: "Message_Delete", Count: `${extra.count}`, Date: `${botLog.createdTimestamp}` }; Set.auditLogs(dataAuditLog); // eslint-disable-next-line no-undef globalclient.channels.cache.get(logChannel).send({ embeds: [MessageDelEmbed] }); } if (dataAuditLog == null) { // New AuditLog Entry + New Message MessageDelEmbed.setAuthor({ name: `@${executor.username} (ID ${executor.id})`, iconURL: icon2 }) .setDescription(LanguageConvert.lang(lang.logs.bulkdeleted1, messages.size, msgs[0].channelId)); dataAuditLog = { AuditLogID: `${id}`, GuildID: `${getGuildID}`, Type: "Message_Delete", Count: `${extra.count}`, Date: `${botLog.createdTimestamp}` }; Set.auditLogs(dataAuditLog); // eslint-disable-next-line no-undef globalclient.channels.cache.get(logChannel).send({ embeds: [MessageDelEmbed] }); } const dataAuditLogDate = Get.allAuditLogs("Message_Delete"); if (dataAuditLogDate.length < 4) { return; } else { dataAuditLogDate.forEach(date => { const dtRemove = DateTime.now().minus({ days: 20 }); const timeNew = dtRemove.toMillis(); if (timeNew >= date.Date) { Del.auditLogs(date.AuditLogID); } }); } } };
import numpy as np def get_amplitude(x, win_length): """ Compute estimates of instantaneous amplitude of the signal Parameters ---------- x: ndarray(N) Original audio samples win_length: int Window length to use for energy calculations Returns ------- ndarray(N-win_length) Amplitude estimates in each window """ energy = np.cumsum(x**2) return np.sqrt((energy[win_length::] - energy[0:-win_length])/win_length) def sonify_pure_tone(x, freqs, hop_length, sr): """ Sonify instantaneous frequency estimates with numerical integration inside of a pure cosine Parameters ---------- x: ndarray(N) Original audio samples freqs: ndarray(N//hop_length) List of frequencies in each hop. Nan if not confident enough hop_length: int Hop length between frequency estimates sr: int Audio sample rate """ freqs = np.array(freqs) freqs = freqs[:, None]*np.ones((1, hop_length)) freqs = freqs.flatten() freqs[np.isnan(freqs)] = 0 y = np.cos(2*np.pi*np.cumsum(freqs)/sr) amp = 1 if len(x) > 0: amp = get_amplitude(x, hop_length) N = min(y.size, amp.size) amp, y = amp[0:N], y[0:N] return amp*y def get_scale(root_note, major, fmin=100, fmax=2000): """ Compute a list of frequencies that are involved in a scale Parameters ---------- root_note: str Root note of scale (e.g. "A Flat", "A Sharp") major: bool If True, use a major version of the scale. If False, use a minor version fmin: float Minimum frequency to consider (in hz) fmax: float Maximum frequency to consider (in hz) Returns ------- freqs: ndarray(N) List of frequencies corresponding to allowed notes """ root = root_note.split()[0].lower() roots = {"a":0, "b":2, "c":3, "d":5, "e":7, "f":8, "g":10} intervals = [[2, 1, 2, 2, 1, 2, 2], [2, 2, 1, 2, 2, 2, 1]][major] lower = [] start = roots[root] if "flat" in root_note.lower(): start -= 1 if "sharp" in root_note.lower(): start += 1 note = start i = -1 f = 440*2**(note/12) while f > fmin: i = (i + len(intervals))%len(intervals) note -= intervals[i] i -= 1 f = 440*2**(note/12) if f >= fmin: lower.append(f) lower.reverse() upper = [] note = start f = 440*2**(note/12) i = 0 while f < fmax: f = 440*2**(note/12) upper.append(f) i = (i + len(intervals))%len(intervals) note += intervals[i] i += 1 return np.array(lower + upper) def autotune(x, freqs, hop_length, allowed_notes, hop_scale=8, n_iters=10, wiggle_amt=np.inf, wiggle_len=None): """ Parameters ---------- x: ndarray(N) Original audio samples freqs: ndarray(N//hop_length) List of frequencies in each hop. Nan if not confident enough hop_length: int Hop length between frequency estimates allowed_notes: list of float Allowed notes in the autotuner hop_scale: int Factor by which to interpolate the hop length for better results with Griffin Lim n_iters: int Number of iterations of Griffin Lim wiggle_amt: int If there's a jump by more than this amount, then wiggle wiggle_len: int Length of samples to wiggle. If None, use hop_scale*4 """ from audiotools import stft, griffin_lim ## Step 1: Expand frequencies by a factor of hop_scale freqs = (freqs[:, None]*np.ones((1, hop_scale))).flatten() win_length = hop_length*2 hop_length = hop_length//hop_scale ## Step 2: Figure out frequency ratios by rounding to the nearest allowed frequency in a scale allowed_notes = np.array(allowed_notes) idx = np.argmin(np.abs(allowed_notes[:, None] - freqs[None, :]), axis=0) ## Step 2b: Wiggle notes if requested for that signature effect if np.isfinite(wiggle_amt): if not wiggle_len: wiggle_len = 4*hop_scale i = 0 while i < len(idx): di = (idx[i] - idx[i-1]) if np.abs(di) > wiggle_amt: idx[i:i+wiggle_len] += np.random.choice([1, -1]) i += wiggle_len idx[i:i+wiggle_len] += np.random.choice([1, -1]) i += wiggle_len else: i += 1 notes = allowed_notes[idx] ratios = freqs/notes ratios[np.isnan(ratios)] = 1 # If there was not a confident frequency estimate, don't shift anything ## Step 3: Do interpolation and apply griffin lim S = np.abs(stft(x, win_length, hop_length)) S2 = np.zeros((S.shape[0], min(S.shape[1], ratios.size))) f = np.arange(S.shape[0]) for j in range(S2.shape[1]): S2[:, j] = np.interp(f*ratios[j], f, S[:, j]) return notes, griffin_lim(S2, win_length, hop_length, n_iters) def fm_synth(x, freqs, hop_length, sr, ratio=1, I=8): """ Do fm synthesis using an estimated instantaneous frequency in freqs and an envelope based on instantaneous amplitude estimates Parameters ---------- x: ndarray(N) Original audio samples freqs: ndarray(N//hop_length) List of frequencies in each hop. Nan if not confident enough hop_length: int Hop length between frequency estimates sr: int Audio sample rate ratio: int Ratio of harmonics I: float Bandwidth index for envelope scaling. Higher values make it "scratchier" Returns ------- ndarray(<=N) FM synth approximation of x """ env = get_amplitude(x, hop_length) freqs = np.array(freqs) freqs = freqs[:, None]*np.ones((1, hop_length)) freqs = freqs.flatten() freqs[np.isnan(freqs)] = 0 f = np.cumsum(freqs)/sr N = min(f.size, env.size) f = f[0:N] env = env[0:N] return env*np.cos(2*np.pi*f + I*env*np.sin(2*np.pi*ratio*f))
# Flow. SharedFlow. StateFlow У `SharedFlow` есть два отдельных интерфейса: * `MutableSharedFlow` - для отправителей, * `SharedFlow` - для получателей (аналогично с MutableLiveData и LiveData). Для отправителей мы создаем `MutableSharedFlow`: ```kotlin val _eventBus = MutableSharedFlow<Event>() ``` Методом emit можно отправлять данные: ```kotlin _eventBus.emit(event) // emit is suspend fun ``` Получатели используют suspend метод collect, чтобы подписаться на получение данных. ```kotlin eventBus.collect { // ... } ``` **`SharedFlow` все время жив и готов принимать данные от отправителей**Если со стороны получателя необходимо **отменить подписку** и перестать получать данные, то мы просто **отменяем корутину**, в которой вызван collect получателя. ## Параметры MutableSharedFlow ### параметр replay. Кэш и буфер Параметр `replay` включает буфер указанного размера. `Буфер хранит элементы для медленных получателей, чтобы не задерживать всех остальных. Быстрые получатели будут получать данные сразу, минуя буфер.` ```kotlin val _eventBus = MutableSharedFlow<Event>(replay = 3) ``` Кроме буфера, параметр `replay` включает кэш (хранит список последних полученных данных). Размер кэша = значению `replay`. Кэш обновляется с каждым получением новых данных. Каждый новый подписчик сразу получит эти значения. Буфер и кэш не являются одним и тем же. Буфер может быть пустым, если все получатели достаточно быстрые, но кэш при этом будет полным. `Т.е. буфер нужен, чтобы компенсировать работу медленных получателей. А кэш нужен, чтобы новые получатели сразу смогли получить несколько пришедших ранее данных.` ```kotlin eventBus.replayCache // посмотреть содержимое кэша _eventBus.resetReplayCache() // отчистка кэша. Может только отправитель (MutableSharedFlow) ``` ### Параметр extraBufferCapacity. Увеличение буфера, с учетом replay ```kotlin // размер буфера будет равен сумме значений этих параметров: 3+4=7. Но размер кэша будет равен 3. val _eventBus = MutableSharedFlow<Event>(replay = 3, extraBufferCapacity = 4) // Размер буфера в этом случае будет равен 4. А размер кэша - 0. val _eventBus = MutableSharedFlow<Event>(extraBufferCapacity = 4) ``` ### Параметр onBufferOverflow. задает поведение SharedFlow Задает поведение `SharedFlow`, когда отправитель шлет данные, но буфер уже заполнен. Возможны три режима: 1. `SUSPEND` - метод emit на стороне отправителя будет приостанавливать корутину, пока не появятся свободные слоты в буфере. Т.е. пока самый медленный получатель не получит значение, данные не будут удалены из буфера. Даже быстрым получателям придется ждать новых данных. Данные просто не смогут пройти минуя буфер. **Этот режим используется по умолчанию.** Можно избежать приостановки используя `tryEmit`(не suspend). Метор вернет true если в буфере есть места, и false если нет. 2. `DROP_OLDEST` - метод emit будет удалять из заполненного буфера наиболее старые элементы и добавлять новые. Плюс в том, что методу emit больше не придется ждать. Отправка будет мгновенной. С другой стороны, до медленных получателей дойдут не все отправленные данные. 3. `DROP_LATEST` - метод emit не будет отправлять новые значения, если буфер заполнен. Метод emit в этом случае также не приостанавливает корутину и отрабатывает быстро. Но все получатели будут пропускать новые данные, если особо медленные получатели все обрабатывают старые данные. ### Параметр subscriptionCount. Следит за количеством подписчиков SharedFlow. Для этого надо подписаться на `StateFlow`, который мы получаем в `subscriptionCount`. ```kotlin sharedFlow.subscriptionCount .map { count -> count > 0 } // преобразует количество подписчиков в boolean флаг (есть подписчики или нет) .distinctUntilChanged() // уберет срабатывания, если значение флага не менялось (чтобы при каждом новом подписчике мы не получали значение true) .onEach { isActive -> // configure an action if (isActive) onActive() else onInactive() } .launchIn(scope) // launch it //В итоге метод onActive будет вызываться при появлении первого подписчика, а onInactive - при отключении последнего. ``` ### Параметр shareIn. Из Flow сделать SharedFlow. Пример - `Flow`, который возвращает текущие координаты. Он подключается к системному сервису, получает от него данные и возвращает нам в виде `Flow`. Учитывая то как работает `Flow`, каждый кто вызовет `collect` будет создан отдельный `Flow`. И все эти Flow будут передавать абсолютно одни и те же данные. С помощью `shareIn` можно сделать так, чтобы был только один `Flow` на всех подписчиков: ```kotlin val locationSharedFlow = locationFlow.shareIn( scope = viewModelScope, started = SharingStarted.Lazily, replay = 3 ) ``` #### Параметры shareIn 1. scope - чтобы запустить корутину нужен scope (ЖЦ SharedFlow = ЖЦ scope) 2. started - когда стартовать. * **Eagerly** - работа в Flow стартует сразу при создании SharedFlow, даже если еще нет подписчиков. В этом случае данные пойдут в никуда (и в кэш). * **Lazily** - стартует при появлении первого подписчика. * **WhileSubscribed** - стартует при появлении первого подписчика. При уходе последнего подписчика - останавливается. Т.е. отменяется подкапотная корутина, в которой работал оригинальный Flow. Имеет свои параметры: * stopTimeoutMillis - сколько времени ждать до остановки работы с момента ухода последнего подписчика * replayExpirationMillis - как долго живет replay кэш после остановки работы 3. replay - Задает размер буфера и кэша. Обратите внимание, что нельзя явно задать параметры extraBufferCapacity и onBufferOverflow. По умолчанию они будут иметь значения (64 - replay) и SUSPEND. Но есть возможность задать эти параметры неявно, с помощью оператора buffer перед shareIn: ```kotlin val locationSharedFlow = locationFlow .buffer(capacity = 4, onBufferOverflow = BufferOverflow.DROP_OLDEST) .shareIn( /*...*/) ``` В получившемся SharedFlow будут применены параметры из buffer. **BroadcastChannel** SharedFlow позиционируется как замена BroadcastChannel. В [официальной документации](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/) можно найти инструкцию по миграции: - конструктор BroadcastChannel(capacity) меняем на MutableSharedFlow(0, extraBufferCapacity=capacity) - вызовы send и offer меняем соответственно на emit и tryEmit - код подписчиков меняем на вызов collect ## StateFlow - частный случай SharedFlow ```kotlin // SharedFlow с поведением StateFlow val shared = MutableSharedFlow( replay = 1, // буфер и кэш = 1 onBufferOverflow = BufferOverflow.DROP_OLDEST // новые данные будут заменять старые ) shared.tryEmit(initialValue) // постим начальное значение val state = shared.distinctUntilChanged() // отсеивает повторы данных ``` `StateFlow` - всегда хранит в кэше одно (последнее полученное) значение, которое будет получать каждый новый подписчик. А вновь пришедшее значение всегда будет в буфере заменять старое. Получателям мы отдаем StateFlow версию: ```kotlin val progress = _progress.asStateFlow() // получатель вызывает collect progress.collect { // ... } // последнее значение отправленное в StateFlow, мы используем value: val currentProgressValue = progress.value ``` `У SharedFlow был метод replayCache, чтобы посмотреть содержимое кэша. В случае StateFlow этот метод просто вернет список из одного элемента value.` #### stateIn - Из обычного Flow можно сделать StateFlow ```kotlin flow { // ... }.stateIn(viewModelScope, Eagerly, 0) ``` #### ConflatedBroadcastChannel `StateFlow` позиционируется как замена `ConflatedBroadcastChannel`. В официальной документации можно найти инструкцию по миграции: - конструктор `ConflatedBroadcastChannel(capacity)` меняем на `MutableStateFlow(initialValue)` - вызовы send и `offer` меняем на `value` - код подписчиков меняем на вызов `collect` # Заключение Вся разница между `Flow` и `SharedFlow` `(StateFlow)` сводится к разнице между **cold** и **hot** источниками данных. `SharedFlow` может иметь несколько получателей (и отправителей) данных, и будет работать в одном экземпляре. А обычный Flow будет создавать новый экземпляр себя под каждого нового подписчика. В RxJava похожую разницу имеют Flowable и Subject. А также одним из мощных достоинств `SharedFlow` является то, что он потокобезопасен. Мы свободно можем использовать его в разных корутинах.