text
stringlengths 184
4.48M
|
|---|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" errorPage="../OtherJSP/Error.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<style>
body {
margin:0;
background-color: #f8e6e1;
}
h1 {
font-size: 40px;
font-family: 'Lora', serif;
transition: .5s linear;
color: #6c6363;
}
h2 {
font-family: monospace;
color: #606060;
font-size: 25px;
}
ul {
list-style: none;
margin: 0 auto;
}
a {
text-decoration: none;
font-family: 'Lora', serif;
transition: .5s linear;
}
i {
margin-right: 10px;
}
nav {
display: block;
width: 100%;
margin: 0 auto 30px;
}
.one ul {
padding: 1em 0;
background: #ECDAD6;
}
.one a {
padding: 1em;
background: rgba(177, 152, 145, .3);
border-right: 1px solid #b19891;
color: #695753;
}
.one a:hover {background: #b19891;}
.one li {
display: inline;
}
.table {
width: 80%;
border: none;
margin-bottom: 20px;
}
.table thead th {
font-weight: bold;
text-align: left;
border: none;
padding: 10px 15px;
background: #B19891FF;
font-size: 14px;
}
.table thead tr th:first-child {
border-radius: 8px 0 0 8px;
}
.table thead tr th:last-child {
border-radius: 0 8px 8px 0;
}
.table tbody td {
text-align: left;
border: none;
padding: 10px 15px;
font-size: 14px;
vertical-align: top;
}
.table tbody tr:nth-child(even){
background: #ECDAD6FF;
}
.table tbody tr td:first-child {
border-radius: 8px 0 0 8px;
}
.table tbody tr td:last-child {
border-radius: 0 8px 8px 0;
}
</style>
<title>Car Management Application</title>
</head>
<body>
<center>
<h1 align="left">Car management</h1>
<nav class="one" align="left">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/newCar">Add new car</a></li>
<li><a href="/listCar">List all cars</a></li>
</ul>
</nav>
</center>
<div align="center">
<table border="1" cellpadding="5" class="table">
<caption><h2>List of Cars</h2></caption>
<thead>
<tr>
<th>carId</th>
<th>Name</th>
<th>Model</th>
<th>Engine</th>
<th>Complectation</th>
<th>Year</th>
<th>Quantity</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="car" items="${listCar}">
<tr>
<td><c:out value="${car.carId}" /></td>
<td><c:out value="${car.name}" /></td>
<td><c:out value="${car.model}" /></td>
<td><c:out value="${car.engine}" /></td>
<td><c:out value="${car.complectation}" /></td>
<td><c:out value="${car.year}" /></td>
<td><c:out value="${car.quantity}" /></td>
<td><c:out value="${car.price}" /></td>
<td>
<a href="/editCar?carId=<c:out value='${car.carId}' />">Edit</a>
<a href="/deleteCar?carId=<c:out value='${car.carId}' />">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
|
#include <iostream>
using namespace std;
class Counter {
private:
unsigned int count;
public:
Counter() : count(0) { }
Counter(int c) : count(c) { }
unsigned int get_count() { return count; }
Counter operator++() {
++count;
return Counter(count);
}
};
int main() {
Counter c1, c2;
cout << "\nc1=" << c1.get_count();
cout << "\nc2=" << c2.get_count();
++c1;
c2 = ++c1;
++c2;
Counter c3 = 3;
cout << "\nc1=" << c1.get_count();
cout << "\nc2=" << c2.get_count() << endl;
return 0;
}
|
import express from "express";
import mainRoutes from "./routes/main.route";
import APIRoutes from "./routes/userAPI.route";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import configViewEngine from "./config/viewEngine";
import connectDB from "./config/connectDB";
import cors from "cors";
import mongoose from "mongoose";
import { generateToken, verifyJWT } from "./utils/auth.utils";
require("dotenv").config();
const app = express();
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", process.env.REACT_URL);
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With, content-type"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
app.use(cors({ credentials: true, origin: true }));
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.use(cookieParser());
// mongoose.connect(process.env.MONGODB_URL);
configViewEngine(app);
app.use("/", mainRoutes);
app.use("/v1/api", APIRoutes);
connectDB();
const port = process.env.PORT || 2619;
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
|
package IEC62325.MarketOperations.ParticipantInterfaces;
import IEC61970.Base.Domain.Integer;
import IEC61970.Base.Domain.String;
import IEC62325.MarketOperations.MktDomain.YesNo;
import IEC61970.Base.Domain.Float;
import IEC61970.Base.Domain.Boolean;
/**
* Energy bid for generation, load, or virtual type for the whole of the market-
* trading period (i.e., one day in day ahead market or one hour in the real time
* market).
* @created 28-Dec-2023 5:23:21 PM
*/
public class ResourceBid extends Bid {
/**
* Aggregation flag
* 0: individual resource level
* 1: Aggregated node location
* 2: Aggregated price location)
*/
public Integer aggregationFlag;
public String bidStatus;
/**
* Energy product (commodity) type:
* 'En' - Energy
* 'Ru' - Regulation Up
* 'Rd' - Regulation Dn
* 'Sr' - Spinning Reserve
* 'Nr' - Non-Spinning Reserve
* 'Or' - Operating Reserve
*/
public String commodityType;
/**
* contingent operating reserve availiability (Yes/No). Resource is availiable to
* participate with capacity only in contingency dispatch.
*/
public YesNo contingencyAvailFlag;
/**
* A Yes indicates that this bid was created by the ISO.
*/
public YesNo createdISO;
/**
* Maximum amount of energy per day which can be produced during the trading
* period in MWh
*/
public Float energyMaxDay;
/**
* Minimum amount of energy per day which has to be produced during the trading
* period in MWh
*/
public Float energyMinDay;
/**
* Market Separation Flag
*
* 'Y' - Enforce market separation constraints for this bid
* 'N' - Don't enforce market separation constraints for this bid.
*/
public String marketSepFlag;
/**
* minimum number of consecutive hours a resource shall be dispatched if bid is
* accepted
*/
public Integer minDispatchTime;
/**
* Resource loading curve type
* 1 - step-wise continuous loading
* 2 - piece-wise linear continuous loading
* 3 - block loading
*/
public Integer resourceLoadingType;
/**
* Maximum number of shutdowns per day.
*/
public Integer shutDownsMaxDay;
/**
* Maximum number of shutdowns per week.
*/
public Integer shutDownsMaxWeek;
/**
* Maximum number of startups per day.
*/
public Integer startUpsMaxDay;
/**
* Maximum number of startups per week.
*/
public Integer startUpsMaxWeek;
/**
* True if bid is virtual. Bid is assumed to be non-virtual if attribute is absent
*/
public Boolean virtual;
public BidError BidError;
public ResourceBid(){
}
}//end ResourceBid
|
from typing import List
from isaac_ros_apriltag_interfaces.msg import AprilTagDetectionArray
from timeutil import timestamp
# no longer localizes. now just extracts april tag positions.
# rip bad name, will eventually fix
class ROSNTTranslator:
"""
Takes in an `AprilTagDetectionArray` and outputs a `List[float]`
concatenated_positions[0] is always the timestamp.
concatenated_positions[1-7] are the position/rotation of the first apriltag,
in this format:
position.x,
position.y,
position.z,
rotation.x,
rotation.y,
rotation.z,
rotation.w
concatenated_positions[8-14] are the second apriltag, and so on.
"""
def __call__(self, april_tag_detection_array: AprilTagDetectionArray) -> List[float]:
concatenated_positions: List[float] = []
concatenated_positions.append( timestamp(april_tag_detection_array) )
for detection in april_tag_detection_array.detections:
position = detection.pose.pose.pose.position
rotation = detection.pose.pose.pose.orientation
concatenated_positions.extend((
position.x,
position.y,
position.z,
rotation.x,
rotation.y,
rotation.z,
rotation.w,
))
return concatenated_positions
|
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-3">
<div class="container px-4 px-lg-5">
<a class="navbar-brand" href="#!">Start Bootstrap</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0 ms-lg-4">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#!">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#!">About</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Shop</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#!">All Products</a></li>
<li><hr class="dropdown-divider" /></li>
<li><a class="dropdown-item" href="#!">Popular Items</a></li>
<li><a class="dropdown-item" href="#!">New Arrivals</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{ route('index') }}">Home</a>
</li>
@auth
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{ route('profile') }}">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{ route('logout') }}">Logout</a>
</li>
@else
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{ route('login') }}">Login</a>
</li>
@if (Route::has('register'))
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{{ route('register') }}">Register</a>
</li>
@endif
@endauth
</ul>
<form class="d-flex">
<button class="btn btn-outline-dark" type="submit">
<i class="bi-cart-fill me-1"></i>
Cart
<span class="badge bg-dark text-white ms-1 rounded-pill">0</span>
</button>
</form>
</div>
</div>
</nav>
|
#!/usr/bin/python3
"""
Write a class Square that defines a square by: (based on 3-square.py)
"""
class Square:
"""
Private instance attribute: size:
property def size(self): to retrieve it
property setter def size(self, value):
Instantiation with optional size: def __init__(self, size=0):
Public instance method: def area(self):
"""
def __init__(self, size=0):
self.__size = size
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
@property
def size(self):
return self.__size
@size.setter
def size(self, size):
self.__size = size
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
def area(self):
return self.__size * self.__size
def my_print(self):
if self.__size > 0:
for i in range(self.__size):
for j in range(self.__size):
print("#", end="")
print("")
else:
print("")
|
import 'package:c2_antonio_hany/data_classes/provider_classes.dart';
import 'package:c2_antonio_hany/data_classes/user_skill.dart';
import 'package:c2_antonio_hany/fragments/profile_page/wrappers/profile_page_panel_wrapper.dart';
import 'package:c2_antonio_hany/globals.dart';
import 'package:c2_antonio_hany/managers/main_api_repo.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
class SkillsFragment extends StatefulWidget {
late List<UserSkill> userSkills;
SkillsFragment({Key? key, required this.userSkills}) : super(key: key);
@override
_SkillsFragmentState createState() => _SkillsFragmentState();
}
class _SkillsFragmentState extends State<SkillsFragment> {
String currentSkill = "";
String currentlyEditing = "";
final TextEditingController _controller = TextEditingController();
late List<String?> skills;
late bool inEditMode;
@override
void initState() {
skills = widget.userSkills.map((e) => e.name).toList();
super.initState();
}
@override
Widget build(BuildContext context) {
inEditMode = context.read<UserIdWrapper>().value == gLoggedUser!.userId;
return Column(
children: [
Center(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: TextField(
enabled: inEditMode,
controller: _controller,
style: Theme.of(context).textTheme.headline4,
cursorColor: Colors.white,
decoration: const InputDecoration(
hoverColor: Colors.white,
fillColor: Colors.white,
label: Text(
"Skill",
style: TextStyle(color: Colors.white),
),
enabledBorder: OutlineInputBorder(
// width: 0.0 produces a thin "hairline" border
borderSide: BorderSide(color: Colors.white),
),
border: OutlineInputBorder(),
hintText: "Insert Skill",
hintStyle: TextStyle(color: Colors.white),
focusColor: Colors.white),
onChanged: (value) {
currentSkill = value;
},
onSubmitted: (value) {
currentSkill = value;
if (mounted) {
setState(() {
if (currentlyEditing != "") {
skills[skills.indexOf(currentlyEditing)] = currentSkill;
} else {
skills.add(currentSkill);
}
currentlyEditing = "";
currentSkill = "";
_controller.text = "";
});
}
},
),
),
),
Padding(
padding: const EdgeInsets.all(30.0),
child: Container(
height: 300,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.white)),
child: Wrap(
children: skills
.map((e) => Padding(
padding: const EdgeInsets.all(8.0),
child: Chip(
label: Text(e!),
onDeleted: inEditMode
? () {
if (mounted) {
setState(() {
skills.remove(e);
});
}
}
: null,
),
))
.toList(),
),
),
),
Visibility(
visible: inEditMode,
child: TextButton(
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(const Size(90, 40)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: const BorderSide(
color: Color.fromRGBO(0, 133, 254, 1.0)))),
foregroundColor: MaterialStateProperty.all(Colors.white),
backgroundColor: MaterialStateProperty.all(
const Color.fromRGBO(0, 133, 254, 1.0)),
textStyle: MaterialStateProperty.all(
Theme.of(context).textTheme.headline4),
),
onPressed: () async {
List<UserSkill> userSkills =
skills.map((e) => UserSkill(e)).toList();
Map<String, dynamic>? responseData = await MainApiRepo
.profileApiRepo
.updateUserSkills(gLoggedUser!.userId, userSkills);
String stringToShow = "";
if (responseData == null ||
responseData.containsKey("errorMessage")) {
stringToShow = "Something went wrong, please try again";
if (responseData != null) {
stringToShow = responseData["errorMessage"];
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(stringToShow),
backgroundColor: Colors.red,
));
} else if (!responseData["success"]) {
stringToShow = responseData["message"];
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(stringToShow),
backgroundColor: Colors.red,
));
} else {
stringToShow = "Skill are successfully saved.";
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(stringToShow,
style: Theme.of(context).textTheme.headline4),
backgroundColor: const Color.fromRGBO(0, 133, 254, 1.0),
));
}
},
child: const Text("Save")),
)
],
);
}
}
|
/**
* 给你一个下标从 0 开始的二维整数数组 flowers ,其中 flowers[i] = [starti, endi] 表示第 i 朵花的 花期 从
* starti 到 endi (都 包含)。同时给你一个下标从 0 开始大小为 n 的整数数组 people ,people[i] 是第 i 个人来看花的时间。
* <p>
* 请你返回一个大小为 n 的整数数组 answer ,其中 answer[i]是第 i 个人到达时在花期内花的 数目 。
* <p>
* <p>
* <p>
* 示例 1:
* <p>
* <p>
* <p>
* <p>
* 输入:flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11]
* 输出:[1,2,2,2]
* 解释:上图展示了每朵花的花期时间,和每个人的到达时间。
* 对每个人,我们返回他们到达时在花期内花的数目。
* <p>
* <p>
* 示例 2:
* <p>
* <p>
* <p>
* <p>
* 输入:flowers = [[1,10],[3,3]], people = [3,3,2]
* 输出:[2,2,1]
* 解释:上图展示了每朵花的花期时间,和每个人的到达时间。
* 对每个人,我们返回他们到达时在花期内花的数目。
* <p>
* <p>
* <p>
* <p>
* 提示:
* <p>
* <p>
* 1 <= flowers.length <= 5 * 10⁴
* flowers[i].length == 2
* 1 <= starti <= endi <= 10⁹
* 1 <= people.length <= 5 * 10⁴
* 1 <= people[i] <= 10⁹
* <p>
* <p>
* Related Topics 数组 哈希表 二分查找 有序集合 前缀和 排序 👍 96 👎 0
*/
package com.makersy.leetcode.editor.cn;
import java.util.Arrays;
class NumberOfFlowersInFullBloom {
public static void main(String[] args) {
// Solution solution = new NumberOfFlowersInFullBloom().new Solution();
}
// leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] fullBloomFlowers(int[][] flowers, int[] persons) {
int n = flowers.length;
int[] starts = new int[n];
int[] ends = new int[n];
for (int i = 0; i < n; i++) {
starts[i] = flowers[i][0];
ends[i] = flowers[i][1];
}
Arrays.sort(starts);
Arrays.sort(ends);
int m = persons.length;
int[] ans = new int[m];
for (int i = 0; i < m; i++) {
int x = binarySearch(starts, persons[i] + 1);
int y = binarySearch(ends, persons[i]);
ans[i] = x - y;
}
return ans;
}
int binarySearch(int[] arr, int target) {
int res = arr.length;
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (arr[mid] >= target) {
res = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return res;
}
}
// leetcode submit region end(Prohibit modification and deletion)
}
|
<script setup lang="ts">
import {computed, ref, watchPostEffect} from 'vue';
const props = defineProps({
modelValue: {
type: String,
required: true
},
placeholder: {
type: String
},
disabled: {
type: Boolean,
default: false
},
clearable: {
type: Boolean,
default: false
},
type: {
type: String,
default: 'text',
validator(value: string): boolean {
return ['text', 'password'].indexOf(value) >= 0;
}
},
showPassword: {
type: Boolean,
default: false
},
error: {
type: String
},
success: {
type: String
}
});
const emits = defineEmits<{
(e: 'update:modelValue', value: string): void
}>();
const clear = ref(props.clearable);
const inputWrapper = ref<HTMLInputElement>();
const inputType = ref(props.type);
const showPwd = ref(props.showPassword);
const name = computed(() => {
return inputType.value === 'password' ? '-un-' : '-';
});
const clearValue = () => emits('update:modelValue', '');
const toggelType = () => {
inputType.value = inputType.value === 'text' ? 'password' : 'text';
};
watchPostEffect(() => {
if (!props.clearable && !props.showPassword) return;
if (!inputWrapper.value) return;
if (props.modelValue.length > 0) {
inputWrapper.value.onmouseenter = () => {
clear.value = true;
showPwd.value = true;
};
inputWrapper.value.onmouseleave = () => {
clear.value = false;
showPwd.value = false;
};
}
});
const messageTips = computed(() => {
if (props.error) return {type: 'error', value: props.error};
if (props.success) return {type: 'success', value: props.success};
return false;
});
const onInput = (e: Event) => {
emits('update:modelValue', (e.target! as HTMLInputElement).value);
};
</script>
<template>
<div class="gulu-input-wrapper" ref="inputWrapper">
<input :type="inputType"
class="gulu-input"
:class="{['gulu-input-error']:error}"
:value="modelValue"
:disabled="disabled"
@input="onInput"
:placeholder="placeholder"
/>
<span class="gulu-input-clear"
v-if="type==='text'&&clearable && clear && modelValue.length>0"
@click="clearValue"
/>
<span v-if="type==='password'&&showPassword && showPwd && modelValue.length>0"
@click="toggelType"
class="gulu-input-show-pwd">
<i class="gulu-iconfont" :class="`g${name}show-pwd`"/>
</span>
<template v-if="messageTips && messageTips.type">
<i class="gulu-iconfont gulu-input-icon" :class="`g-${messageTips.type}`"/>
<span :class="`gulu-input-${messageTips.type}-message`">{{ messageTips.value }}</span>
</template>
</div>
</template>
<style lang="scss">
@import "../../assets/helper";
@import "iconfont";
.gulu-input-wrapper {
position: relative;
display: inline-flex;
align-items: center;
.gulu-input {
height: 32px;
width: 100%;
padding: 5px 3em 5px 8px;
font-size: inherit;
border-radius: 4px;
border: 1px solid $color-border;
&:hover {
border-color: darken($color-border, 20%);
}
&:focus {
border-color: $color-button-normal;
outline: none;
}
&[disabled] {
color: darken($color-border, 20%);
background: $color-input-disabled;
cursor: not-allowed;
&:hover {
border-color: $color-border;
}
}
&.gulu-input-error {
border-color: $color-button-danger;
}
}
.gulu-input-clear {
position: absolute;
right: 8px;
width: 0.9em;
height: 0.9em;
border: 1px solid $color-border;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
cursor: pointer;
&::after, &::before {
content: "";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(45deg);
width: 0.8px;
height: 0.4em;
background-color: $color-border;
}
&::after {
transform: translate(-50%, -50%) rotate(135deg);
}
}
.gulu-input-show-pwd {
display: flex;
justify-self: center;
align-items: center;
position: absolute;
right: 8px;
width: 1em;
height: 1em;
cursor: pointer;
}
.gulu-input-icon {
display: inline-flex;
justify-content: center;
align-items: center;
width: 1.5em;
height: 1em;
margin: 0 0.3em 0 0.5em;
}
.gulu-input-error-message,
.gulu-input-success-message {
white-space: nowrap;
font-size: 12px;
color: $color-button-danger;
}
.gulu-input-success-message {
color: $color-button-success;
}
}
</style>
|
package com.example.database.dao
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import com.example.database.entity.CategoryEntity
import kotlinx.coroutines.flow.Flow
const val DEFAULT_CATEGORIES_USER_ID = "default_categories"
@Dao
interface CategoryDao {
@Query("""Select * from CategoryEntity where createdUser = :userID or createdUser = "$DEFAULT_CATEGORIES_USER_ID"""")
fun getAllCategoriesOfUser(
userID: String,
): Flow<List<CategoryEntity>>
@Query("Select count(*) from CategoryEntity")
suspend fun getCategoryCount(): Int
@Upsert
suspend fun insert(vararg categories: CategoryEntity)
suspend fun insert(categories: List<CategoryEntity>) {
insert(*categories.toTypedArray())
}
}
|
package ar.unrn.tp.controllers;
import ar.unrn.tp.api.ClienteService;
import ar.unrn.tp.modelo.Cliente;
import ar.unrn.tp.modelo.TarjetaDeCredito;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import static org.springframework.http.HttpStatus.OK;
@RestController
@RequestMapping("clientes")
public class ClienteController {
@Autowired
private ClienteService clienteService;
public ClienteController(){}
@PostMapping("/crear")
@Operation(summary = "Agregar un cliente")
public ResponseEntity<?> create(@RequestBody Cliente cliente) {
this.clienteService.crearCliente(cliente.getNombre(),cliente.getApellido(),cliente.getDni(),cliente.getEmail());
return ResponseEntity.status(OK).body("El cliente se añadió con éxito!");
}
@PutMapping("/actualizar")
@Operation(summary = "Actualizar un cliente")
public ResponseEntity<?> update(@RequestBody Cliente cliente) {
this.clienteService.modificarCliente(cliente.getId(),cliente.getNombre());
return ResponseEntity.status(OK).body("El cliente se actualizó con éxito!");
}
@PutMapping("/agregar-tarjeta/{id}")
@Operation(summary = "Añadir tarjeta a un cliente")
public ResponseEntity<?> update(@PathVariable Long id, @RequestBody TarjetaDeCredito tarjeta) {
this.clienteService.agregarTarjeta(id,tarjeta.getNumero(),tarjeta.getNombre());
return ResponseEntity.status(OK).body("La tarjeta se añadió con éxito!");
}
@GetMapping("/listar-tarjetas/{id}")
@Operation(summary = "Obtener tarjetas de un cliente")
public ResponseEntity<?> findAllTarjetasDeCreditoDeCliente(@PathVariable Long id) {
return ResponseEntity.status(OK).body(this.clienteService.listarTarjetas(id));
}
@GetMapping("/listar")
@Operation(summary = "Listar todos los clientes")
public ResponseEntity<?> findAll() {
return ResponseEntity.status(OK).body(this.clienteService.listarClientes());
}
}
|
package in.trees;
class Node
{
int data;
Node left;
Node right;
public Node(int data)
{
this.data=data;
left=null;
right=null;
}
}
class Tree1
{
Node root;
public Tree1()
{
root=null;
}
public void insert(int data)
{
root=insertRecursive(root,data);
}
private Node insertRecursive(Node current,int data)
{
if(current==null)
{
return new Node(data);
}
if(data<current.data)
{
current.left=insertRecursive(current.left,data);
}
else if(data>current.data)
{
current.right=insertRecursive(current.right,data);
}
return current;
}
public boolean contains(int data)
{
return containsRecursive(root,data);
}
private boolean containsRecursive(Node current ,int data)
{
if(current==null)
{
return false;
}
if(data==current.data)
{
return true;
}
else if(data<current.data)
{
return containsRecursive(current.left , data);
}
else
{
return containsRecursive(current.right , data);
}
}
public void delete(int data)
{
root=deleteRecursive(root,data);
}
private Node deleteRecursive(Node current,int data)
{
if(current==null)
{
return null;
}
if(data==current.data)
{
if(current.left==null && current.right==null)
{
return null;
}
if(current.left==null)
{
return current.right;
}
if(current.right==null)
{
return current.left;
}
int smallestValue=findSmallestValue(current.right);
current.data=smallestValue;
current.right=deleteRecursive(current.right,smallestValue);
return current;
}
if(data<current.data)
{
current.left=deleteRecursive(current.left,data);
}
else
{
current.right=deleteRecursive(current.right,data);
}
return current;
}
private int findSmallestValue (Node root)
{
return root.left==null?root.data:findSmallestValue(root.left);
}
public void inorderTraversal()
{
inorderRecursive(root);
}
private void inorderRecursive(Node current)
{
if(current!=null)
{
inorderRecursive(current.left);
System.out.println(current.data+" ");
inorderRecursive(current.right);
}
}
public static void main(String[] args)
{
Tree1 t=new Tree1();
t.insert(5);
t.insert(3);
t.insert(8);
t.insert(1);
t.insert(4);
System.out.println(t.contains(4));
System.out.println(t.contains(2));
t.delete(3);
System.out.println("inorder traversal");
t.inorderTraversal();
}
}
|
import React from "react";
import { useSelector } from "react-redux";
const filterByColor = (colors) => (product) =>
!colors.length || colors.includes(product.color);
const filterPrices = (prices) => (product) =>
(!prices.max || product.price <= prices.max) &&
(!prices.min || product.price >= prices.min);
const composeFilters = (filters) => (product) =>
filters.every((filter) => filter(product));
const filterProducts = ({ products }) => {
const { data = [], filters } = products;
return data.filter(
composeFilters([
filterByColor(filters.colors),
filterPrices(filters.prices),
]),
);
};
const Products = () => {
const data = useSelector(filterProducts);
return (
<table>
<thead>
<tr>
<th>nome</th>
<th>cor</th>
<th>preco</th>
</tr>
</thead>
<tbody>
{data.map(({ id, name, color, price }) => (
<tr key={id}>
<td>{name}</td>
<td>{color}</td>
<td>{price}</td>
</tr>
))}
</tbody>
</table>
);
};
export default Products;
|
//
// CreaateNewPostViewController.swift
// ios100ToyExample
//
// Created by 신지훈 on 2021/09/20.
//
import UIKit
import SkyFloatingLabelTextField
class CreaateNewPostViewController: UIViewController {
///게시물의 제목을 적을 텍스트 필드 입니다.
private let titleField: SkyFloatingLabelTextField = {
let field = SkyFloatingLabelTextField()
field.placeholder = "제목"
field.title = "제목을 작성해 주세요."
field.returnKeyType = .next
field.leftViewMode = .always
//자동으로 대문자가 되지 않게 설정합니다. / 자동완성기능으로 인해 글자가 수정되는 일이 없도록 하겠습니다.
field.autocapitalizationType = .words
field.autocorrectionType = .no
field.tintColor = .darkGray
field.selectedTitleColor = .darkGray
field.selectedLineColor = .darkGray
field.textColor = .label
field.lineColor = .lightGray
field.lineHeight = 1.0
field.selectedLineHeight = 2.0
field.layer.masksToBounds = true
return field
}()
///게시물 상단에 자리할 이미지 입니다
private let headerImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "기본이미지")
imageView.clipsToBounds = true
imageView.isUserInteractionEnabled = true
imageView.layer.cornerRadius = 10
imageView.backgroundColor = .tertiarySystemBackground
return imageView
}()
private var selectedHeaderImage: UIImage?
///게시물의 내용을 적을 텍스트 뷰입니다.
private let textView: UITextView = {
let textView = UITextView()
textView.isEditable = true
textView.font = .systemFont(ofSize: 20)
return textView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
view.addSubview(headerImageView)
view.addSubview(titleField)
view.addSubview(textView)
let tap = UITapGestureRecognizer(target: self, action: #selector(didTapHeader))
headerImageView.addGestureRecognizer(tap)
configureButton()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
titleField.frame = CGRect(x: 20, y: view.safeAreaInsets.top, width: view.width-40, height: 50)
headerImageView.frame = CGRect(x: 5, y: titleField.bottom+5, width: view.width-10, height: 300)
textView.frame = CGRect(x: 20, y: headerImageView.bottom+10, width: view.width-40, height: view.height-210-view.safeAreaInsets.top)
}
private func configureButton() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "닫기",
style: .done,
target: self,
action: #selector(didTapCancel))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "게시",
style: .done,
target: self,
action: #selector(didTapPost))
}
@objc private func didTapHeader() {
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.delegate = self
present(picker,animated: true)
}
@objc private func didTapCancel() {
dismiss(animated: true, completion: nil)
}
@objc private func didTapPost() {
guard let title = titleField.text,
let body = textView.text,
let headerImage = selectedHeaderImage,
let email = UserDefaults.standard.string(forKey: "email"),
!title.trimmingCharacters(in: .whitespaces).isEmpty,
!body.trimmingCharacters(in: .whitespaces).isEmpty else {
let alert = UIAlertController(title: "게시물의 세부 정보를 입력하십시오.", message: "제목과 글,사진이 정상적으로 작성되었는지 확인 하여 주세요.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "닫기", style: .cancel, handler: nil))
present(alert, animated: true)
return
}
print("게시물을 작성했습니다...")
let newPostId = UUID().uuidString
//헤더 이미지 업로드
StorageManager.shared.uploadBlogHeaderImage(email: email, image: headerImage, postId: newPostId) { success in
guard success else {
return
}
StorageManager.shared.downloadUrlForPostHeader(email: email, postId: newPostId) { url in
guard let headerUrl = url else {
print("URL을 업로드 하는것에 실패 했습니다. - Post")
return
}
//DB에 게시물 삽입
let post = BlogPost(identifier: newPostId,
title: title,
timestamp: Date().timeIntervalSince1970,
headerImageUrl: headerUrl,
text: body)
DatabaseManager.shared.insert(blogPost: post, email: email) { [weak self] posted in
guard posted else {
print("새로운 게시물을 올리지 못했습니다. - Post")
return
}
DispatchQueue.main.async {
self?.didTapCancel()
}
}
}
}
}
}
extension CreaateNewPostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let image = info[.originalImage] as? UIImage else {
return
}
selectedHeaderImage = image
headerImageView.image = image
}
}
|
import random
playing = True
#generates and returns deck of 108 cards of colors and numbers with repeats of everything
#except 0 per the game setup, and with 4 of each wild cards
def BuildCardDeck():
card_deck = []
card_colors = ["Red", "Green", "Blue", "Yellow"]
card_values = [0,1,2,3,4,5,6,7,8,9, "Draw 2", "Draw 4", "Skip", "Reverse"]
card_wilds = ["Select Color", "Select Color & Draw 4"]
for color in card_colors:
for value in card_values:
card_value = "{} {}". format(color, value)
card_deck.append(card_value)
if value != 0:
card_deck.append(card_value)
for i in range(4):
card_deck.append(card_wilds[0])
card_deck.append(card_wilds[1])
return card_deck
#manually shuffles deck and swaps position with random card position
def ShuffleCardDeck(deck):
for card_position in range(len(deck)):
random_position = random.randint(0,107)
temp = deck[card_position]
deck[card_position] = deck[random_position]
deck[random_position] = temp
return deck
#draws cards for start of game for player 1
def DrawStartCardsPlayer1():
num_cards = 7
start_deck_1 = []
for x in range(num_cards):
start_deck_1.append(total_deck.pop(x))
return start_deck_1
#draws cards for start of game for player 2
def DrawStartCardsPlayer2():
num_cards = 7
start_deck_2 = []
for x in range(num_cards):
start_deck_2.append(total_deck.pop(x))
return start_deck_2
#shows the player the current hand of cards
def ShowHand(start_deck):
print("Current hand: ", start_deck)
#allows a user to place down a card from the deck if matching the color/number/is a wild card
def PlaceCardDown(last_card, card_to_play):
if ["Select Color", "Draw"] in card_to_play:
card_to_play_parts = card_to_play
else:
last_card_parts = last_card.split()
card_to_play_parts = card_to_play.split()
#if the color matches
if last_card_parts[0] == card_to_play_parts[0]:
print("Color:", card_to_play_parts[0], ",", "Number:", card_to_play_parts[1])
#if the number matches
elif last_card_parts[1] == card_to_play_parts[1]:
print("Color:", card_to_play_parts[0], ",", "Number:", card_to_play_parts[1])
#if its a wild card
elif ["Select Color", "Select Color & Draw 4", "Draw 2", "Draw 4"] in card_to_play_parts:
new_color = input("What color do you want to change to?")
print("Color: " + new_color, "Also, next player draw cards!")
#if the card is none of the above
else:
print("This card is not eligible to be put down!")
#takes a new card if player's cards do not match last card's color/number/not wild card
#or if other player puts down a +2 or +4
def AddNewCard(deck, last_card):
#if last card was a draw card, add to existiing deck
if ["Draw 2"] in last_card:
deck.append(total_deck.pop())
deck.append(total_deck.pop())
if ["Draw 4"] in last_card:
deck.append(total_deck.pop())
deck.append(total_deck.pop())
deck.append(total_deck.pop())
deck.append(total_deck.pop())
#else, just take from total deck
else:
deck.append(total_deck.pop())
PlaceCardDown()
return 0
#skips/reverses players turn if either player puts down a skip or reverse card
def Skip():
return 0
#panel of choices for the user to select
def commandSelect(choice):
if choice == 1:
PlaceCardDown()
if choice == 2:
AddNewCard()
playing = False
while playing:
total_deck = BuildCardDeck()
total_deck = ShuffleCardDeck(total_deck)
start_deck_1 = DrawStartCardsPlayer1()
start_deck_2 = DrawStartCardsPlayer2()
print("Welcome to Uno Simulator!")
print("First, player 1 will go.")
ShowHand()
print("Player 1, please select what choice you would like to make: ")
print("1: place down a card from deck")
print("2: take a new card")
choice = int(input("Which choice?"))
commandSelect(choice)
print("Now, player 2 will go.")
ShowHand()
print("Player 2, please select what choice you would like to make: ")
print("1: place down a card from deck")
print("2: take a new card")
choice = int(input("Which choice?"))
commandSelect(choice)
|
//
// ContentModel.swift
// LearningApp
//
// Created by Corrigan, John on 10/6/22.
//
import Foundation
class ContentModel: ObservableObject {
@Published var modules = [Module]()
var styleData: Data?
init(){
getLocalData()
}
func getLocalData() {
//parse the local json file
let jsonUrl = Bundle.main.url(forResource: "data", withExtension: "json")
do {
//get a url to the json file
let jsonData = try Data(contentsOf: jsonUrl!)
let jsonDecoder = JSONDecoder()
let modules = try jsonDecoder.decode([Module].self, from: jsonData)
//assign parsed modules to module property
self.modules = modules
} catch{
print("couldn't parse local data")
}
//parse the style data
let styleUrl = Bundle.main.url(forResource: "style", withExtension: "html")
do{
let styleData = try Data(contentsOf: styleUrl!)
self.styleData = styleData
}catch{
print("couldn't parse style data")
}
}
}
|
package edu.matc.persistence;
import edu.matc.entity.User;
import org.apache.log4j.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Access users in the user table.
*
* @author pwaite
*/
public class UserData {
private final Logger logger = Logger.getLogger(this.getClass());
public List<User> getAllUsers() {
String sql = "SELECT * FROM users";
List<User> users = new ArrayList<User>();
Database database = Database.getInstance();
Connection connection = null;
try {
database.connect();
connection = database.getConnection();
Statement selectStatement = connection.createStatement();
ResultSet results = selectStatement.executeQuery(sql);
while (results.next()) {
User employee = createUserFromResults(results);
users.add(employee);
}
database.disconnect();
} catch (SQLException e) {
logger.error("SearchUser.getAllUsers()...SQL Exception: " + e);
} catch (Exception e) {
logger.error("SearchUser.getAllUsers()...Exception: " + e);
}
return users;
}
public List<User> getOneUser(String enteredLastName) {
String sql = ("SELECT * FROM users WHERE last_name LIKE \'" + enteredLastName + "\';");
logger.info("In getOneUser");
logger.error("demonstrating error level");
List<User> users = new ArrayList<User>();
Database database = Database.getInstance();
Connection connection = null;
try {
database.connect();
connection = database.getConnection();
Statement selectStatement = connection.createStatement();
ResultSet results = selectStatement.executeQuery(sql);
while (results.next()) {
User employee = createUserFromResults(results);
users.add(employee);
}
database.disconnect();
} catch (SQLException e) {
logger.error("SearchUser.getAllUsers()...SQL Exception: " + e);
} catch (Exception e) {
logger.error("SearchUser.getAllUsers()...Exception: " + e);
}
return users;
}
private User createUserFromResults(ResultSet results) throws SQLException {
User user = new User();
user.setLastName(results.getString("last_name"));
user.setFirstName(results.getString("first_name"));
user.setUserid(results.getString("id"));
user.setDateOfBirth(results.getString("date_of_birth"));
return user;
}
}
|
<template>
<h2>Fullname - {{ firstName }} {{ lastName }}</h2>
<h2>Computed fullname: {{ fullName }}</h2>
<button @click="changeFullname">Change fullname</button>
<p>Total: {{ items.reduce((total, current) => (total = total + current.price), 0) }}</p>
<p>Computed Total: {{ total }}</p>
<p>Method Total: {{ getTotal() }}</p>
<button @click="items.push({ id: 4, price: 50 })">Add item</button>
<div>
<input type="text" v-model="country" />
</div>
<template v-for="item in items" :key="item.id">
<h2 v-if="item.price > 100">{{ item.title }} {{ item.price }}</h2>
</template>
<h2 v-for="item in expensiveItems" :key="item.id">{{ item.title }} {{ item.price }}</h2>
</template>
<script>
export default {
data() {
return {
firstName: "Tuan",
lastName: "Le",
items: [
{ id: 1, title: "Samsung", price: 150 },
{ id: 2, title: "Apple", price: 200 },
{ id: 3, title: "Xiaomi", price: 100 },
],
country: "",
};
},
methods: {
getTotal() {
console.log("method");
return this.items.reduce((total, current) => (total = total + current.price), 0);
},
changeFullname() {
this.fullName = "Le Tuan";
},
},
computed: {
// fullName() {
// return `${this.firstName} ${this.lastName}`;
// },
fullName: {
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
const names = value.split(" ");
this.firstName = names[0];
this.lastName = names[1];
},
},
total() {
console.log("computed");
return this.items.reduce((total, current) => (total = total + current.price), 0);
},
expensiveItems() {
return this.items.filter((item) => item.price > 150);
},
},
};
</script>
<style></style>
|
defmodule FooBank.AccountsTest do
use FooBank.DataCase
alias FooBank.Accounts
describe "users" do
import FooBank.AccountsFixtures
alias FooBank.Accounts.User
@invalid_attrs %{name: nil, surname: nil, document_number: nil, password: nil}
test "create_user/1 with valid data creates a user" do
valid_attrs = %{
name: "some name",
surname: "some surname",
document_number: "973.323.340-46",
password: "Dev@1234"
}
assert {:ok, %User{} = user} = Accounts.create_user(valid_attrs)
assert user.name == valid_attrs.name
assert user.surname == valid_attrs.surname
assert user.document_number == valid_attrs.document_number
refute user.password == valid_attrs.password
end
test "create_user/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Accounts.create_user(@invalid_attrs)
end
end
end
|
import { Component, Input, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Movimentacao } from 'src/app/interfaces/movimentacao.model';
import { CategoriasModel } from 'src/app/services/api/interfaces/categorias.model';
import { MovimentacaoService } from 'src/app/services/api/movimentacao.service';
import { ToastService } from 'src/app/services/bootstrap/toast.service';
import { ModalMovimentacaoComponent } from '../modal-movimentacao/modal-movimentacao.component';
@Component({
selector: 'app-tela-base',
templateUrl: './tela-base.component.html',
styleUrls: ['./tela-base.component.scss']
})
export class TelaBaseComponent implements OnInit {
@Input() tipoMovimentacao!: string;
mes: number = new Date().getMonth() + 1;
ano: number = new Date().getFullYear();
movimentacoes?: Movimentacao[];
categorias!: CategoriasModel;
textCss!: string;
btnCss!: string;
legendaBtnAdd!: string;
textPassados!: string;
constructor(
private movimentacaoService: MovimentacaoService,
private toastService: ToastService,
private modalService: NgbModal
) { }
ngOnInit(): void {
this.obterMovimentacoes(
this.mes,
this.ano
);
this.obterCategorias();
this.textCss = this.tipoMovimentacao == 'RECEITA' ? 'text-success' : 'text-danger';
this.btnCss = this.tipoMovimentacao == 'RECEITA' ? 'btn btn-success' : 'btn btn-danger';
this.legendaBtnAdd = this.tipoMovimentacao == 'RECEITA' ? 'Nova Receita' : 'Nova Despesa';
this.textPassados = this.tipoMovimentacao == 'RECEITA' ? 'Recebidos' : 'Pagos';
}
obterMovimentacoes(mes: number, ano: number) {
this.movimentacaoService.obter({
mes,
ano,
tipoMovimentacao: this.tipoMovimentacao
})
.subscribe({
next: (val) => {
this.movimentacoes = val;
},
error: (val) => {
this.toastService.show('Ocorreu um erro ao obter as movimentações', { classname: 'bg-danger text-white' });
}
});
}
pesquisaMovimentacoes(e: any) {
this.mes = e.mes;
this.ano = e.ano;
this.obterMovimentacoes(e.mes, e.ano);
}
somaPendentes() {
let valor = 0.00;
for (const mov of this.movimentacoes?.filter(x => new Date(x.dataEntrada) >= new Date()) || []) {
valor += mov.valor;
}
return valor;
}
somaPassados() {
let valor = 0.00;
for (const mov of this.movimentacoes?.filter(x => new Date(x.dataEntrada) <= new Date()) || []) {
valor += mov.valor;
}
return valor;
}
somaTotal() {
let valor = 0.00;
for (const mov of this.movimentacoes || []) {
valor += mov.valor;
}
return valor;
}
obterCategorias() {
this.movimentacaoService.obterCategorias()
.subscribe({
next: (res) => {
this.categorias = res;
},
error: (res) => {
}
});
}
abrirModal(movimentacao?: Movimentacao) {
const modalRef = this.modalService.open(ModalMovimentacaoComponent);
modalRef.componentInstance.tipo = this.tipoMovimentacao;
modalRef.componentInstance.categorias = this.tipoMovimentacao == 'RECEITA' ? this.categorias.receita : this.categorias.despesa;
modalRef.componentInstance.movimentacao = movimentacao;
modalRef.componentInstance.edicao = movimentacao !== undefined;
modalRef.componentInstance.adicionadoEvent.subscribe(() => {
this.obterMovimentacoes(this.mes, this.ano);
});
}
deletaMovimentacao(id: string) {
if (confirm('Tem certeza que deseja deletar esta movimentação?')) {
this.movimentacaoService.deletar(id)
.subscribe({
next: (res) => {
this.toastService.show('Deletado com sucesso', { classname: 'bg-success text-white' });
this.obterMovimentacoes(this.mes, this.ano);
},
error: (res) => {
this.toastService.show('Ocorreu um erro ao tentar deletar', { classname: 'bg-danger text-white' });
}
});
}
}
}
|
package 泛型方法;
public class GenericMethodTest {
public static void main(String[] args) {
泛型方法.GenericsMethod example = new 泛型方法.GenericsMethod();
// 使用第一个泛型方法,传入整数并打印返回值
Integer intValue = example.printAndReturn(123);
System.out.println("Returned Integer value: " + intValue);
// 使用第一个泛型方法,传入字符串并打印返回值
String strValue = example.printAndReturn("Hello, Generics!");
System.out.println("Returned String value: " + strValue);
// 使用第二个泛型方法,传入不同类型的参数并组合成字符串
String combinedValue = example.combine("key", 456);
System.out.println("Combined value: " + combinedValue);
}
}
|
import 'package:app_delivery_mobx/components/contador.dart';
import 'package:app_delivery_mobx/models/item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
class Cartao extends StatelessWidget {
const Cartao({super.key, required this.item});
final Item item;
@override
Widget build(BuildContext context) {
return Card(
color: const Color(0xFFF6F6F6),
elevation: 0,
clipBehavior: Clip.hardEdge,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 134),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image(
image: AssetImage(item.url),
width: double.infinity,
height: 50,
fit: BoxFit.cover,
),
Padding(
padding: const EdgeInsets.all(8),
child: FittedBox(
child: Text(
item.nome,
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text("R\$ ${item.preco.toStringAsFixed(2)}"),
),
Observer(
builder: (_) => Contador(
item: item,
)),
],
),
),
);
}
}
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:to_do/gui/to_do_list/todo_card_widget.dart';
import 'package:to_do/gui/to_do_list/todo_list_view_model.dart';
import 'package:to_do/helper/router_helper.dart';
import 'package:to_do/models/status.dart';
import 'package:to_do/models/to_do_item.dart';
class ToDoListScreen extends StatefulWidget {
const ToDoListScreen({Key? key}) : super(key: key);
@override
State<ToDoListScreen> createState() => _ToDoListScreenState();
}
class _ToDoListScreenState extends State<ToDoListScreen> {
var selectedTabIndex = 0;
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('Todo List'),
actions: [IconButton(onPressed: onPressAddTodo, icon: const Icon(Icons.add))],
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(icon: Icon(Icons.language), label: "All"),
BottomNavigationBarItem(icon: Icon(Icons.language), label: "Incomplete"),
BottomNavigationBarItem(icon: Icon(Icons.done_all), label: "Completed"),
],
currentIndex: selectedTabIndex,
onTap: (index) {
setState(() {
selectedTabIndex = index;
});
},
),
// bottomNavigationBar:
body: _selectedListViewWidget(),
),
);
}
void onPressAddTodo() async {
var todoItem = await Navigator.of(context).push(RouterFactory.addTodoPageRoute());
if (todoItem != null) {
Provider.of<TodoListViewModel>(context, listen: false).onAddTodoItem(todoItem);
}
}
Widget _selectedListViewWidget() {
return Consumer<TodoListViewModel>(builder: (_, model, __) {
List<ToDoItem> todoItems = [];
switch (selectedTabIndex) {
case 0:
todoItems = model.allTodoItems;
break;
case 1:
todoItems = model.incompleteItems;
break;
case 2:
todoItems = model.completedItems;
break;
default:
return Container();
}
if (todoItems.isEmpty) {
return Center(
child: TextButton(
child: const Text(
"Empty list.\nClick here to add new one.",
style: TextStyle(color: Colors.grey, fontSize: 16, fontWeight: FontWeight.normal),
textAlign: TextAlign.center,
),
onPressed: onPressAddTodo,
),
);
} else {
return _listViewWidget(todoItems, model);
}
});
}
Widget _listViewWidget(List<ToDoItem> todoItems, TodoListViewModel model) {
return ListView.builder(
itemCount: todoItems.length,
itemBuilder: (itemContext, index) {
return TodoCardWidget(
item: todoItems[index],
onChanged: (value) {
model.onUpdateItemStatus(
todoItems[index],
value ? Status.completed : Status.incomplete,
);
});
},
);
}
}
|
import { createMachine, assign } from "xstate";
export const redditMachine = createMachine<
{
subreddit: null | string;
posts: null | Record<string, any>[];
},
{ type: "SELECT"; name: string }
>({
id: "reddit",
initial: "idle",
context: {
subreddit: null,
posts: null,
},
states: {
idle: {},
selected: {
initial: "loading",
states: {
loading: {
invoke: {
id: "fetch-subreddit",
src: (context) => {
return fetch(`https://www.reddit.com/r/${context.subreddit}.json`)
.then((res) => res.json())
.then((json) =>
json.data.children.map((child: any) => child.data)
);
},
onDone: {
target: "loaded",
actions: assign({
posts: (context, event) => event.data,
}),
},
onError: "failed",
},
},
loaded: {},
failed: {},
},
},
},
on: {
SELECT: {
target: ".selected",
actions: assign({
subreddit: (context, event) => event.name,
}),
},
},
});
|
import unittest
from unittest.mock import patch
from django.core.exceptions import ValidationError
from food.models.food import Food
from restaurant.models.restaurant import Restaurant
class TestFoodModel(unittest.TestCase):
def setUp(self):
self.restaurant = Restaurant.objects.create(name='Test Restaurant')
self.food = Food.objects.create(name='Test Food', min_time_to_delivery=15, max_time_to_delivery=30, price=10.99, category='Test Category', restaurant=self.restaurant)
def test_generate_random_stars(self):
with patch('food.utils.save_food_utility.generate_random_stars',):
self.food.save()
lower_bound = 1.0
upper_bound = 5.0
self.assertGreaterEqual(self.food.stars, lower_bound)
self.assertLessEqual(self.food.stars, upper_bound)
def test_generate_random_stars_count(self):
with patch('food.utils.save_food_utility.generate_random_stars_count',):
self.food.save()
lower_bound = 5.0
upper_bound = 1000.0
self.assertGreaterEqual(self.food.stars_count, lower_bound)
self.assertLessEqual(self.food.stars_count, upper_bound)
def test_generate_random_delivery_times(self):
with patch('food.utils.save_food_utility.generate_random_delivery_times',):
self.food.save()
lower_bound = 15.0
upper_bound = 75.0
self.assertGreaterEqual(self.food.min_time_to_delivery, lower_bound)
self.assertLessEqual(self.food.min_time_to_delivery, upper_bound)
lower_bound = 30.0
upper_bound = 90.0
self.assertGreaterEqual(self.food.max_time_to_delivery, lower_bound)
self.assertLessEqual(self.food.max_time_to_delivery, upper_bound)
def test_validate_time_range_valid(self):
with patch('food.utils.validate_time_range.validate_time_range'):
self.food.min_time_to_delivery = 10
self.food.max_time_to_delivery = 50
self.food.save()
def test_validate_time_range_invalid(self):
with patch('food.utils.validate_time_range.validate_time_range') as mock_validate_time_range:
mock_validate_time_range.side_effect = ValidationError("Invalid time range")
self.food.min_time_to_delivery = 60
self.food.max_time_to_delivery = 30
with self.assertRaises(ValidationError):
self.food.save()
def test_save_no_stars_no_stars_count_no_delivery_times(self):
with patch('food.utils.save_food_utility.generate_random_stars',), \
patch('food.utils.save_food_utility.generate_random_stars_count', ), \
patch('food.utils.save_food_utility.generate_random_delivery_times', ), \
patch('food.utils.validate_time_range'):
self.food.save()
lower_bound = 1.0
upper_bound = 5.0
self.assertGreaterEqual(self.food.stars, lower_bound)
self.assertLessEqual(self.food.stars, upper_bound)
lower_bound = 1.0
upper_bound = 1000.0
self.assertGreaterEqual(self.food.stars_count, lower_bound)
self.assertLessEqual(self.food.stars, upper_bound)
lower_bound = 15.0
upper_bound = 75.0
self.assertGreaterEqual(self.food.min_time_to_delivery, lower_bound)
self.assertLessEqual(self.food.min_time_to_delivery, upper_bound)
lower_bound = 30.0
upper_bound = 90.0
self.assertGreaterEqual(self.food.max_time_to_delivery, lower_bound)
self.assertLessEqual(self.food.max_time_to_delivery, upper_bound)
def test_save_no_stars_but_stars_count_and_delivery_times_given(self):
self.food.stars_count = 100
self.food.min_time_to_delivery = 20
self.food.max_time_to_delivery = 50
with patch('food.utils.save_food_utility.generate_random_stars',), \
patch('food.utils.validate_time_range'):
self.food.save()
lower_bound = 1.0
upper_bound = 5.0
self.assertGreaterEqual(self.food.stars, lower_bound)
self.assertLessEqual(self.food.stars, upper_bound)
lower_bound = 5
upper_bound = 1000
self.assertGreaterEqual(self.food.stars_count, lower_bound)
self.assertLessEqual(self.food.stars_count, upper_bound)
self.assertEqual(self.food.min_time_to_delivery, 20)
self.assertEqual(self.food.max_time_to_delivery, 50)
if __name__ == '__main__':
unittest.main()
|
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/html">
<body>
<th:block th:fragment="cartListItem">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title flex flex-wrap">
<a th:href="@{|/product/${cart.product.id}|}" class="mr-auto">
<i class="fa-solid fa-book-open"></i>
<span th:text="${cart.product.subject}"></span>
</a>
<div class="flex">
<svg width="20" height="20" th:data-jdenticon-value="${cart.product.author.jdenticon}"></svg>
<div th:text="${cart.product.author.name}"></div>
</div>
</h2>
<div th:text="|₩ ${@ut.nf(cart.product.salePrice)}|"></div>
<div th:utext="${cart.product.extra_productTagLinks}"></div>
<div class="flex justify-end">
<div class="badge badge-outline">
<i class="fa-solid fa-pen"></i>
<span class="ml-2"
th:text="${#temporals.format(cart.product.createDate, 'yy-MM-dd HH:mm')}"></span>
</div>
</div>
<div th:if="${cart.product.createDate != cart.product.modifyDate}" class="flex justify-end">
<div class="badge">
<i class="fa-solid fa-eraser"></i>
<span class="ml-2"
th:text="${#temporals.format(cart.product.modifyDate, 'yy-MM-dd HH:mm')}"></span>lear
</div>
</div>
<div class="card-actions justify-end">
<form th:action="@{|/cart/remove/${cart.product.id}|}" class="btn btn-sm" method="post" onsubmit="return confirm('장바구니에서 삭제하시겠습니까?');">
<i class="fa-solid fa-cart-plus"></i>
<button type="submit" class="ml-2">삭제</button>
</form>
<a th:href="@{|/product/${cart.product.id}|}" class="btn btn-sm">
<i class="fa-solid fa-eye"></i>
<span class="ml-2">보기</span>
</a>
</div>
</div>
</div>
</th:block>
</body>
</html>
|
<form [formGroup]="formulario" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Nombre</label>
<div class="row">
<div class="col-11">
<input type="text" class="form-control" formControlName="nombre">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.nombre.valid && formulario.controls.nombre.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
<p class="error" *ngIf="formulario.controls.nombre.errors?.required && formulario.controls.nombre.touched">
El campo Nombre es obligatorio.
</p>
<p class="error" *ngIf="formulario.controls.nombre.errors?.maxlength && formulario.controls.nombre.dirty">
El campo Nombre no puede tener más de {{formulario.controls.nombre.errors.maxlength.requiredLength}}
caracteres y has escrito
{{formulario.controls.nombre.errors.maxlength.actualLength}} caracteres.
</p>
</div>
<div class="form-group">
<label>Apellidos</label>
<div class="row">
<div class="col-11">
<input type="text" class="form-control" formControlName="apellidos">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.apellidos.valid && formulario.controls.apellidos.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
</div>
<p class="error" *ngIf="formulario.controls.apellidos.errors?.required && formulario.controls.apellidos.touched">
El campo Apellidos es obligatorio.
</p>
<div class="form-group">
<label>Email</label>
<div class="row">
<div class="col-11">
<input type="text" class="form-control" formControlName="email">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.email.valid && formulario.controls.email.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
<p class="error" *ngIf="formulario.controls.email.errors?.required && formulario.controls.email.touched">
El campo Email es obligatorio.
</p>
<p class="error" *ngIf="formulario.controls.email.errors?.pattern && formulario.controls.email.touched">
El campo Email debe ser un email válido.
</p>
</div>
<div class="form-group">
<label>Edad</label>
<div class="row">
<div class="col-11">
<input type="text" class="form-control" formControlName="edad">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.edad.valid && formulario.controls.edad.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
<p class="error" *ngIf="formulario.controls.edad.errors?.required && formulario.controls.edad.touched">
El campo Edad es obligatorio.
</p>
<p class="error" *ngIf="formulario.controls.edad.errors?.edadvalidator && formulario.controls.edad.touched">
El campo Edad tiene que estar entre {{formulario.controls.edad.errors.edadvalidator.min}} y
{{formulario.controls.edad.errors.edadvalidator.max}} años.
</p>
</div>
<div class="form-group">
<label>DNI</label>
<div class="row">
<div class="col-11">
<input type="text" class="form-control" formControlName="dni">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.dni.valid && formulario.controls.dni.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
<p class="error" *ngIf="formulario.controls.dni.errors?.required && formulario.controls.dni.touched">
El campo DNI es obligatorio.
</p>
<p class="error" *ngIf="formulario.controls.dni.errors?.dnivalidator && formulario.controls.dni.touched">
{{formulario.controls.dni.errors.dnivalidator.msg}}
</p>
</div>
<div class="form-group">
<label>Password</label>
<div class="row">
<div class="col-11">
<input type="password" class="form-control" formControlName="password">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.password.valid && formulario.controls.password.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
<p class="error" *ngIf="formulario.controls.password.errors?.required && formulario.controls.password.touched">
El campo Password es obligatorio.
</p>
<p class="error" *ngIf="formulario.controls.password.errors?.pattern && formulario.controls.password.touched">
El campo Password tiene que contener entre 4 y 8 caracteres y al menos uno de ellos debe ser numérico.
</p>
</div>
<div class="form-group">
<label>Repetir Password</label>
<div class="row">
<div class="col-11">
<input type="password" class="form-control" formControlName="repite_password">
</div>
<div class="col-1">
<img *ngIf="formulario.controls.repite_password.valid && formulario.controls.repite_password.dirty"
src="https://mallaventura.pe/santaanita/wp-content/uploads/sites/2/2019/09/check-verde-1.png"
width="40" height="40">
</div>
</div>
<p class="error"
*ngIf="formulario.controls.repite_password.errors?.required && formulario.controls.repite_password.touched">
El campo Repite Password es obligatorio.
</p>
<p class="error"
*ngIf="formulario.controls.repite_password.errors?.pattern && formulario.controls.repite_password.touched">
El campo Repite Password tiene que contener entre 4 y 8 caracteres y al menos uno de ellos debe ser
numérico.
</p>
</div>
<p class="error" *ngIf="formulario.errors?.passwordvalidator && formulario.controls.repite_password.touched">
Los campos Password y Repite Password deben ser iguales.
</p>
<div class="row">
<div class="col-11">
<input type="submit" value="Enviar" class="btn btn-block btn-success" [disabled]="!formulario.valid">
</div>
</div>
</form>
|
import numpy as np
import math
def ascii_to_number(ch): return ord(
ch) - (ord('a') if ch.lower() else ord('A'))
def number_to_ascii(num): return chr(ord('a') + num)
np_number_to_ascii = np.vectorize(number_to_ascii)
np_mod = np.vectorize(lambda x: x % 26)
def generate_key_matrix(key):
n = len(key)
while math.sqrt(n) != math.floor(math.sqrt(n)):
n += 1
mat_size = int(math.sqrt(n))
key_list = list(key)
key_list.extend(['Z' for _ in range(n-len(key))])
res = [[] for _ in range(mat_size)]
for i, _ in enumerate(res):
for _ in range(mat_size):
res[i].append(ascii_to_number(key_list.pop(0)))
return np.array(res)
def generate_plain_text_matrix(plain_text: str, matrix_width):
plain_text_list = list(plain_text)
res = []
while plain_text_list:
temp = []
for _ in range(matrix_width):
temp.append(ascii_to_number(plain_text_list.pop(0) if len(
plain_text_list) > 0 else 'z'))
res.append(temp)
return np.matrix.transpose(np.array(res))
plain_text = input("Enter plain text:")
key = input("Enter key:")
key_matrix = generate_key_matrix(key)
plain_text_matrix = generate_plain_text_matrix(plain_text, len(key_matrix))
print(key_matrix, plain_text_matrix)
resultant_matrix = np.dot(key_matrix, plain_text_matrix)
resultant_matrix = np.matrix.transpose(resultant_matrix)
resultant_matrix = np_mod(resultant_matrix)
resultant_matrix = np_number_to_ascii(resultant_matrix)
print(resultant_matrix)
|
package com.moneyminions.mvvmtemplate.ui
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.moneyminions.mvvmtemplate.R
import com.moneyminions.mvvmtemplate.base.BaseFragment
import com.moneyminions.mvvmtemplate.databinding.FragmentPreferenceBinding
import com.moneyminions.mvvmtemplate.databinding.FragmentRecyclerviewBinding
import com.moneyminions.mvvmtemplate.util.NavigationUtil
import com.moneyminions.mvvmtemplate.viewmodel.GithubViewModel
import com.moneyminions.mvvmtemplate.viewmodel.PrefenceViewModel
import dagger.hilt.android.AndroidEntryPoint
private const val TAG = "차선호"
@AndroidEntryPoint
class PreferenceFragment : BaseFragment<FragmentPreferenceBinding>(
FragmentPreferenceBinding::bind,
R.layout.fragment_preference
) {
private val preferenceViewModel: PrefenceViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
NavigationUtil.hideBottomNavigation(mActivity.bottomNavigationView)
Log.d(TAG, "현재 preference의 access-token : ${preferenceViewModel.getAccessToken()}")
initView()
initListener()
}
private fun initView(){
binding.apply {
textviewResult.text = preferenceViewModel.getAccessToken()
}
}
override fun initListener() {
binding.apply {
edittextAccesstoken.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(value: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(value: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun afterTextChanged(value: Editable?) {
preferenceViewModel.setAccessToken(value.toString())
Log.d(TAG, "현재 preference의 access-token : ${preferenceViewModel.getAccessToken()}")
}
})
buttonAccesstoken.setOnClickListener {
preferenceViewModel.putAccessToken()
textviewResult.text = preferenceViewModel.getAccessToken()
}
}
}
}
|
<!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>Avalie sua mentoria</title>
<link rel="stylesheet" href="style.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=Poppins&family=Staatliches&display=swap" rel="stylesheet">
</head>
<body>
<div class="page">
<header>
<h1>Mentoria</h1>
<p>Preencha o formulário abaixo para agendar a sua mentoria</p>
</header>
<form id="mentForm">
<fieldset>
<div class="fieldsetWrapper">
<legend> Informações pessoais </legend>
<div class="fullName">
<div class="inputWrapper">
<label for="name">Nome</label>
<input type="text" id="name" required>
</div>
<div class="inputWrapper">
<label for="lastName">Sobrenome</label>
<input type="text" id="lastName" required>
</div>
</div>
<div class="inputWrapper">
<label for="email">E-mail <span>(digite um email válido)</span></label>
<input type="email" id="email" required>
</div>
<div class="inputWrapper">
<label for="password">Senha <span>(mínimo de 6 caracteres)</span></label>
<input type="password" id="password" required minlength="6">
</div>
</div>
<div class="fieldsetWrapper">
<legend> Informações do mentor </legend>
<div class="inputWrapper">
<label for="mentName">Nome do seu mentor <span>(só o primeiro nome)</span> </label>
<input type="text" id="mentName" required>
</div>
</div>
</fieldset>
<fieldset>
<div class="fieldsetWrapper">
<legend>Seus horários disponíveis</legend>
<legend class="subtittle"> Primeira Mentoria</legend>
<div class="ThreeCol">
<div class="inputWrapper">
<label for="mentDate1"> Data </span></label>
<input type="date" id="mentDate1" required/>
</div>
<div class="inputWrapper">
<label for="eventBegin1"> Das </span></label>
<input type="time" id="eventBegin1" required/>
</div>
<div class="inputWrapper">
<label for="eventEnd1"> Até </span></label>
<input type="time" id="eventEnd1" required/>
</div>
</div>
<legend class="subtittle"> Segunda Mentoria</legend>
<div class="ThreeCol">
<div class="inputWrapper">
<label for="eventDate2"> Data </span></label>
<input type="date" id="eventDate2" required/>
</div>
<div class="inputWrapper">
<label for="eventBegin2"> Das </span></label>
<input type="time" id="eventBegin2" required/>
</div>
<div class="inputWrapper">
<label for="eventEnd2"> Até </span></label>
<input type="time" id="eventEnd2" required/>
</div>
</div>
</div>
</fieldset>
</form>
<footer>
<input class="button" type="submit" form="mentForm" value="Salvar evento">
</footer>
</div>
</body>
</html>
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:image_picker/image_picker.dart';
import 'package:seru_testing_app/view/register_summary_page.dart';
import 'package:seru_testing_app/widget/button.dart';
class RegisterPage3 extends StatefulWidget {
const RegisterPage3({super.key});
@override
State<RegisterPage3> createState() => _RegisterPage3State();
}
class _RegisterPage3State extends State<RegisterPage3> {
File? image;
Future<void> pickImage() async {
final ImagePicker picker = ImagePicker();
XFile? pickedImage;
try {
pickedImage = await picker.pickImage(source: ImageSource.gallery);
} catch (e) {
print("Error picking image: $e");
}
setState(() {
image = File(pickedImage!.path);
});
}
@override
Widget build(BuildContext context) {
final args =
ModalRoute.of(context)!.settings.arguments as RegisterPage3Arguments;
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(
"R E G I S T R A T I O N",
style: GoogleFonts.poppins(
fontSize: 20,
fontWeight: FontWeight.w700,
color: Colors.blueGrey,
),
),
),
),
body: Form(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Step 3 of 3",
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w400,
color: Colors.black,
),
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: Container(
height: 6,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.blueGrey,
),
),
),
const SizedBox(width: 8),
Expanded(
child: Container(
height: 6,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.blueGrey,
),
),
),
const SizedBox(width: 8),
Expanded(
child: Container(
height: 6,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.blueGrey,
),
),
),
],
),
const SizedBox(height: 32),
Text(
"Picture",
style: GoogleFonts.poppins(
fontSize: 26,
fontWeight: FontWeight.w700,
color: Colors.blueGrey,
),
),
const SizedBox(height: 32),
image == null
? Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.blueGrey),
child: const Icon(
Icons.person,
size: 150,
color: Colors.white,
),
)
: Image.file(
image!,
height: MediaQuery.of(context).size.width,
width: MediaQuery.of(context).size.width / 2,
),
const SizedBox(height: 16),
Align(
alignment: Alignment.centerRight,
child: InkWell(
onTap: pickImage,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.blueGrey,
),
child: Text(
image == null ? "Upload Picture" : "Upload Ulang",
style: GoogleFonts.poppins(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
),
const SizedBox(height: 64),
DefaultButton(
text: "SUMMARY",
onPressed: () {
if (image != null) {
Navigator.pushNamed(
context,
"/register-summary",
arguments: RegisterSummaryPageArguments(
args.firstName,
args.lastName,
args.biodata,
args.province,
args.city,
args.district,
args.area,
image!,
),
);
}
},
),
],
),
),
),
),
);
}
}
class RegisterPage3Arguments {
const RegisterPage3Arguments(
this.firstName,
this.lastName,
this.biodata,
this.province,
this.city,
this.district,
this.area,
);
final String firstName;
final String lastName;
final String biodata;
final String province;
final String city;
final String district;
final String area;
}
|
import { useState, useEffect } from 'react'
import './App.css'
import Header from './components/Header'
import Form from './components/Form'
import ListadoPacientes from './components/ListadoPacientes'
function App() {
const pacientesLS = JSON.parse(localStorage.getItem('pacientes')) ?? [];
const [pacientes, setPacientes] = useState(pacientesLS);
const [patient, setPatient] = useState({});
useEffect(()=> {
localStorage.setItem('pacientes', JSON.stringify(pacientes))
}, [pacientes])
const deletePatient = id => {
setPacientes((prevState) => {
let notDeleted = prevState.filter((item) => item.id !== id );
return [...notDeleted];
});
}
return (
<>
<Header/>
<div className='flex w-100 flex-wrap md:flex-nowrap justify-center'>
<Form setPacientes={setPacientes} setPatient={setPatient} pacientes={pacientes} patient={patient} />
<ListadoPacientes setPacientes={setPacientes} pacientes={pacientes} setPatient={setPatient} deletePatient={deletePatient} />
</div>
</>
)
}
export default App
|
using Microsoft.AspNetCore.Identity;
using TeduBlog.Core.Domains.Identity;
namespace TeduBlog.Data;
public class SeedData
{
public async Task SeedAsync(TeduBlogDbContext context)
{
var passwordHasher = new PasswordHasher<AppUser>();
var rootAdminRoleId = Guid.NewGuid();
if (!context.Roles.Any())
{
await context.Roles.AddAsync(new AppRole()
{
Id = rootAdminRoleId,
Name = "Admin",
NormalizedName = "ADMIN",
DisplayName = "Administrator"
});
await context.SaveChangesAsync();
}
if (!context.Users.Any())
{
var userId = Guid.NewGuid();
var user = new AppUser()
{
Id = userId,
FirstName = "Nguyen",
LastName = "Duy",
Email = "duynguyendev810@gmail.com",
NormalizedEmail = "DUYNGUYENDEV810@GMAIL.COM",
UserName = "admin",
NormalizedUserName = "ADMIN",
IsActive = true,
SecurityStamp = Guid.NewGuid().ToString(),
LockoutEnabled = false,
CreatedDate = DateTime.Now
};
user.PasswordHash = passwordHasher.HashPassword(user, "123qwe");
await context.Users.AddAsync(user);
await context.UserRoles.AddAsync(new IdentityUserRole<Guid>()
{
RoleId = rootAdminRoleId,
UserId = userId
});
await context.SaveChangesAsync();
}
}
}
|
//
// UIViewExt.swift
// SwiftExample
//
// Created by jianmei on 2023/3/31.
//
import UIKit
let kScreenW = UIScreen.main.bounds.size.width
let kScreenH = UIScreen.main.bounds.size.height
public extension UIView {
/// SwifterSwift: Height of view.
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Check if view is in RTL format.
var isRightToLeft: Bool {
if #available(iOS 10.0, macCatalyst 13.0, tvOS 10.0, *) {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
} else {
return false
}
}
/// SwifterSwift: Take screenshot of view (if applicable).
var screenshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
/// SwifterSwift: Size of view.
var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Get view's parent view controller
var parentViewController: UIViewController? {
weak var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
/// SwifterSwift: Width of view.
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
/// SwifterSwift: x origin of view.
var x: CGFloat {
get {
return frame.origin.x
}
set {
frame.origin.x = newValue
}
}
/// SwifterSwift: y origin of view.
var y: CGFloat {
get {
return frame.origin.y
}
set {
frame.origin.y = newValue
}
}
}
|
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendAdminAlertMail extends Mailable
{
use Queueable, SerializesModels;
public $message;
/**
* Create a new message instance.
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
from: new Address('hello@autopilotbot.io', 'Autopilot Bot'),
subject: 'Issue with Sending Mails to Users',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
markdown: 'emails.admin_alert',
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}
|
import {
faAws,
faBootstrap,
faCloudflare,
faDiscourse,
faDrupal,
faGithub,
faGoogle,
faJava,
faJoomla,
faMagento,
faMicrosoft,
faPhp,
faReact,
faShopify,
faSquarespace,
faUbuntu,
faVimeo,
faVuejs,
faWikipediaW,
faWordpress,
IconDefinition
} from "@fortawesome/free-brands-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
const iconsByService: { [key: string]: IconDefinition } = {
wordpress: faWordpress,
drupal: faDrupal,
joomla: faJoomla,
phpbb: faPhp,
discourse: faDiscourse,
magento: faMagento,
shopify: faShopify,
mediawiki: faWikipediaW,
squarespace: faSquarespace,
'google tag manager': faGoogle,
'google analytics': faGoogle,
react: faReact,
'vue.js': faVuejs,
bootstrap: faBootstrap,
vimeo: faVimeo,
cloudflare: faCloudflare,
'aws-cloudfront': faAws,
aspnet: faMicrosoft,
kestrel: faMicrosoft,
ubuntu: faUbuntu,
java: faJava,
php: faPhp,
github: faGithub,
'github pages': faGithub,
};
export const ServiceIcon = ({ name }: { name: string }) => {
const icon = iconsByService[name.toLowerCase()];
return icon ? <FontAwesomeIcon icon={icon} /> : <></>;
};
|
package com.hendisantika.abcbank.controller;
import com.hendisantika.abcbank.AbcBankApplication;
import com.hendisantika.abcbank.entity.Account;
import com.hendisantika.abcbank.model.*;
import com.hendisantika.abcbank.util.AppUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.util.UriComponentsBuilder;
import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Created by IntelliJ IDEA.
* Project : ABC-BANK
* User: hendisantika
* Email: hendisantika@gmail.com
* Telegram : @hendisantika34
* Date: 12/23/23
* Time: 05:53
* To change this template use File | Settings | File Templates.
*/
@SpringBootTest(classes = {AbcBankApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-test.properties")
public class AbcBankControllerTest {
@LocalServerPort
int randomServerPort;
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void testTransferOneAccountToAnother() {
Account a1 = Account.builder().acountHolder("A1").balance(new BigDecimal("29.80")).build();
Account a2 = Account.builder().acountHolder("A2").balance(new BigDecimal("39.80")).build();
// create account
a1 = createAccount(a1);
a2 = createAccount(a2);
BigDecimal a1BalBeforeTransfer = a1.getBalance();
String url = "/transfer";
// URI (URL) parameters
Map<String, String> uriParams = new HashMap<>();
TransferToAccountModel requestObject = TransferToAccountModel.builder().fromAccountNumber(a1.getAccountNumber())
.toAccountNumber(a2.getAccountNumber()).transferAmount(new BigDecimal("10.80")).build();
URI uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(uriParams).toUri();
ResponseEntity<?> transferResponseEntity = this.testRestTemplate.exchange(uri, HttpMethod.POST,
AppUtil.getEntityWithHttpHeader(requestObject), Object.class);
Assertions.assertEquals(HttpStatus.OK, transferResponseEntity.getStatusCode());
// load account1 again
ResponseEntity<Account> responseEntity = this.testRestTemplate.exchange("/accounts/" + a1.getAccountNumber(),
HttpMethod.GET,
AppUtil.getHttpHeader(),
Account.class);
// verify
Assertions.assertEquals(a1BalBeforeTransfer.subtract(new BigDecimal("10.80")),
responseEntity.getBody().getBalance());
}
@Test
public void testTransactionHistory() {
Account a1 = Account.builder().acountHolder("A1").balance(new BigDecimal("29.80")).build();
a1 = createAccount(a1);
BigDecimal a1BalBeforeTransfer = a1.getBalance();
String url = "/withdraw";
// URI (URL) parameters
Map<String, String> uriParams = new HashMap<>();
WithdrawFromAccountModel requestObject = WithdrawFromAccountModel.builder()
.fromAccountNumber(a1.getAccountNumber()).withdrawlAmount(new BigDecimal("10.80")).build();
URI uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(uriParams).toUri();
ResponseEntity<?> transferResponseEntity = this.testRestTemplate.exchange(uri, HttpMethod.POST,
AppUtil.getEntityWithHttpHeader(requestObject), Object.class);
Assertions.assertEquals(HttpStatus.OK, transferResponseEntity.getStatusCode());
// load account1 again
Account account = getAccount(a1.getAccountNumber());
// verify
Assertions.assertEquals(a1BalBeforeTransfer.subtract(new BigDecimal("10.80")),
account.getBalance());
// verify the transaction history record
ResponseEntity<List<TransactionHistory>> txHistoryResponse = this.testRestTemplate.exchange(
"/transaction-history", HttpMethod.GET, AppUtil.getHttpHeader(),
new ParameterizedTypeReference<List<TransactionHistory>>() {
});
List<TransactionHistory> txHistoryResponseBodyList = txHistoryResponse.getBody();
Optional<TransactionHistory> txForCurrAccountOpn = txHistoryResponseBodyList.stream()
.filter(x -> x.getAccountNumber().equals(account.getAccountNumber())).findAny();
Assertions.assertTrue(txForCurrAccountOpn.isPresent());
Assertions.assertEquals(new BigDecimal("10.80").negate(), txForCurrAccountOpn.get().getWithdrawl());
}
@Test
public void testForNotSufficientBalValidationException() {
Account a1 = Account.builder().acountHolder("A1").balance(new BigDecimal("29.80")).build();
a1 = createAccount(a1);
String url = "/withdraw";
// URI (URL) parameters
Map<String, String> uriParams = new HashMap<>();
WithdrawFromAccountModel reqModel = WithdrawFromAccountModel.builder().fromAccountNumber(a1.getAccountNumber())
.withdrawlAmount(new BigDecimal("30.00")).build();
URI uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(uriParams).toUri();
ResponseEntity<?> transferResponseEntity = this.testRestTemplate.exchange(uri, HttpMethod.POST,
AppUtil.getEntityWithHttpHeader(reqModel), Object.class);
Assertions.assertEquals(HttpStatus.CONFLICT, transferResponseEntity.getStatusCode());
}
@Test
public void testAccountTransactionHistory() {
Account a1 = Account.builder().acountHolder("A1").balance(new BigDecimal("29.80")).build();
a1 = createAccount(a1);
BigDecimal a1BalBeforeTransfer = a1.getBalance();
String url = "/withdraw";
// URI (URL) parameters
Map<String, String> uriParams = new HashMap<>();
WithdrawFromAccountModel requestObject = WithdrawFromAccountModel.builder()
.fromAccountNumber(a1.getAccountNumber()).withdrawlAmount(new BigDecimal("10.80")).build();
URI uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(uriParams).toUri();
ResponseEntity<?> transferResponseEntity = this.testRestTemplate.exchange(uri, HttpMethod.POST,
AppUtil.getEntityWithHttpHeader(requestObject), Object.class);
Assertions.assertEquals(HttpStatus.OK, transferResponseEntity.getStatusCode());
// deposit 10.80 back to account
String urlDeposit = "/deposit";
// URI (URL) parameters
Map<String, String> uriParamsForDeposit = new HashMap<>();
DepositToAccountModel requestObjectForDeposit = DepositToAccountModel.builder()
.depositorAccountNumber(a1.getAccountNumber()).depositAmount(new BigDecimal("10.80")).build();
this.testRestTemplate.exchange(
UriComponentsBuilder.fromUriString(urlDeposit).buildAndExpand(uriParamsForDeposit).toUri(),
HttpMethod.POST,
AppUtil.getEntityWithHttpHeader(requestObjectForDeposit), Object.class);
// load account1 again
Account accout = getAccount(a1.getAccountNumber());
// verify
Assertions.assertEquals(a1BalBeforeTransfer, accout.getBalance());
// verify the transaction history record
ResponseEntity<List<AccountTransactionHistory>> txHistoryResponse = this.testRestTemplate.exchange(
"/account-transaction-history", HttpMethod.GET, AppUtil.getHttpHeader(),
new ParameterizedTypeReference<List<AccountTransactionHistory>>() {
});
List<AccountTransactionHistory> txHistoryResponseBodyList = txHistoryResponse.getBody();
List<AccountTransactionHistory> txAccountList = txHistoryResponseBodyList.stream()
.filter(x -> x.getAccountNumber().equals(accout.getAccountNumber())).collect(Collectors.toList());
Assertions.assertEquals(2, txAccountList.size());
// Assert.assertEquals(new BigDecimal("10.80").negate(), txForCurrAccountOpn.get().getWithdrawl());
}
private Account createAccount(Account acc) {
ResponseEntity<Account> responseEntity = this.testRestTemplate.exchange("/accounts", HttpMethod.POST,
AppUtil.getEntityWithHttpHeader(acc), Account.class);
acc = responseEntity.getBody();
return acc;
}
private Account getAccount(String accNumber) {
ResponseEntity<Account> responseEntity = this.testRestTemplate.exchange("/accounts/" + accNumber,
HttpMethod.GET, AppUtil.getHttpHeader(), Account.class);
return responseEntity.getBody();
}
}
|
module Html exposing
( Html, Attribute
, text, node, map
, h1, h2, h3, h4, h5, h6
, div, p, hr, pre, blockquote
, span, a, code, em, strong, i, b, u, sub, sup, br
, ol, ul, li, dl, dt, dd
, img, iframe, canvas, math
, form, input, textarea, button, select, option
, section, nav, article, aside, header, footer, address, main_
, figure, figcaption
, table, caption, colgroup, col, tbody, thead, tfoot, tr, td, th
, fieldset, legend, label, datalist, optgroup, output, progress, meter
, audio, video, source, track
, embed, object, param
, ins, del
, small, cite, dfn, abbr, time, var, samp, kbd, s, q
, mark, ruby, rt, rp, bdi, bdo, wbr
, details, summary, menuitem, menu
)
{-| This file is organized roughly in order of popularity. The tags which you'd
expect to use frequently will be closer to the top.
# Primitives
@docs Html, Attribute, text, node, map
# Tags
## Headers
@docs h1, h2, h3, h4, h5, h6
## Grouping Content
@docs div, p, hr, pre, blockquote
## Text
@docs span, a, code, em, strong, i, b, u, sub, sup, br
## Lists
@docs ol, ul, li, dl, dt, dd
## Embedded Content
@docs img, iframe, canvas, math
## Inputs
@docs form, input, textarea, button, select, option
## Sections
@docs section, nav, article, aside, header, footer, address, main_
## Figures
@docs figure, figcaption
## Tables
@docs table, caption, colgroup, col, tbody, thead, tfoot, tr, td, th
## Less Common Elements
### Less Common Inputs
@docs fieldset, legend, label, datalist, optgroup, output, progress, meter
### Audio and Video
@docs audio, video, source, track
### Embedded Objects
@docs embed, object, param
### Text Edits
@docs ins, del
### Semantic Text
@docs small, cite, dfn, abbr, time, var, samp, kbd, s, q
### Less Common Text Tags
@docs mark, ruby, rt, rp, bdi, bdo, wbr
## Interactive Elements
@docs details, summary, menuitem, menu
-}
import VirtualDom
-- CORE TYPES
{-| The core building block used to build up HTML. Here we create an `Html`
value with no attributes and one child:
hello : Html msg
hello =
div [] [ text "Hello!" ]
-}
type alias Html msg = VirtualDom.Node msg
{-| Set attributes on your `Html`. Learn more in the
[`Html.Attributes`](Html-Attributes) module.
-}
type alias Attribute msg = VirtualDom.Attribute msg
-- PRIMITIVES
{-| General way to create HTML nodes. It is used to define all of the helper
functions in this library.
div : Array (Attribute msg) -> Array (Html msg) -> Html msg
div attributes children =
node "div" attributes children
You can use this to create custom nodes if you need to create something that
is not covered by the helper functions in this library.
-}
node : String -> Array (Attribute msg) -> Array (Html msg) -> Html msg
node =
VirtualDom.node
{-| Just put plain text in the DOM. It will escape the string so that it appears
exactly as you specify.
text "Hello World!"
-}
text : String -> Html msg
text =
VirtualDom.text
-- NESTING VIEWS
{-| Transform the messages produced by some `Html`. In the following example,
we have `viewButton` that produces `()` messages, and we transform those values
into `Msg` values in `view`.
type Msg = Left | Right
view : model -> Html Msg
view model =
div []
[ map (\_ -> Left) (viewButton "Left")
, map (\_ -> Right) (viewButton "Right")
]
viewButton : String -> Html ()
viewButton name =
button [ onClick () ] [ text name ]
If you are growing your project as recommended in [the official
guide](https://guide.elm-lang.org/), this should not come in handy in most
projects. Usually it is easier to just pass things in as arguments.
**Note:** Some folks have tried to use this to make “components” in their
projects, but they run into the fact that components are objects. Both are
local mutable state with methods. Gren is not an object-oriented language, so
you run into all sorts of friction if you try to use it like one. I definitely
recommend against going down that path! Instead, make the simplest function
possible and repeat.
-}
map : (a -> msg) -> Html a -> Html msg
map =
VirtualDom.map
-- SECTIONS
{-| Defines a section in a document.
-}
section : Array (Attribute msg) -> Array (Html msg) -> Html msg
section =
node "section"
{-| Defines a section that contains only navigation links.
-}
nav : Array (Attribute msg) -> Array (Html msg) -> Html msg
nav =
node "nav"
{-| Defines self-contained content that could exist independently of the rest
of the content.
-}
article : Array (Attribute msg) -> Array (Html msg) -> Html msg
article =
node "article"
{-| Defines some content loosely related to the page content. If it is removed,
the remaining content still makes sense.
-}
aside : Array (Attribute msg) -> Array (Html msg) -> Html msg
aside =
node "aside"
{-|-}
h1 : Array (Attribute msg) -> Array (Html msg) -> Html msg
h1 =
node "h1"
{-|-}
h2 : Array (Attribute msg) -> Array (Html msg) -> Html msg
h2 =
node "h2"
{-|-}
h3 : Array (Attribute msg) -> Array (Html msg) -> Html msg
h3 =
node "h3"
{-|-}
h4 : Array (Attribute msg) -> Array (Html msg) -> Html msg
h4 =
node "h4"
{-|-}
h5 : Array (Attribute msg) -> Array (Html msg) -> Html msg
h5 =
node "h5"
{-|-}
h6 : Array (Attribute msg) -> Array (Html msg) -> Html msg
h6 =
node "h6"
{-| Defines the header of a page or section. It often contains a logo, the
title of the web site, and a navigational table of content.
-}
header : Array (Attribute msg) -> Array (Html msg) -> Html msg
header =
node "header"
{-| Defines the footer for a page or section. It often contains a copyright
notice, some links to legal information, or addresses to give feedback.
-}
footer : Array (Attribute msg) -> Array (Html msg) -> Html msg
footer =
node "footer"
{-| Defines a section containing contact information. -}
address : Array (Attribute msg) -> Array (Html msg) -> Html msg
address =
node "address"
{-| Defines the main or important content in the document. There is only one
`main` element in the document.
-}
main_ : Array (Attribute msg) -> Array (Html msg) -> Html msg
main_ =
node "main"
-- GROUPING CONTENT
{-| Defines a portion that should be displayed as a paragraph. -}
p : Array (Attribute msg) -> Array (Html msg) -> Html msg
p =
node "p"
{-| Represents a thematic break between paragraphs of a section or article or
any longer content.
-}
hr : Array (Attribute msg) -> Array (Html msg) -> Html msg
hr =
node "hr"
{-| Indicates that its content is preformatted and that this format must be
preserved.
-}
pre : Array (Attribute msg) -> Array (Html msg) -> Html msg
pre =
node "pre"
{-| Represents a content that is quoted from another source. -}
blockquote : Array (Attribute msg) -> Array (Html msg) -> Html msg
blockquote =
node "blockquote"
{-| Defines an ordered list of items. -}
ol : Array (Attribute msg) -> Array (Html msg) -> Html msg
ol =
node "ol"
{-| Defines an unordered list of items. -}
ul : Array (Attribute msg) -> Array (Html msg) -> Html msg
ul =
node "ul"
{-| Defines a item of an enumeration list. -}
li : Array (Attribute msg) -> Array (Html msg) -> Html msg
li =
node "li"
{-| Defines a definition list, that is, a list of terms and their associated
definitions.
-}
dl : Array (Attribute msg) -> Array (Html msg) -> Html msg
dl =
node "dl"
{-| Represents a term defined by the next `dd`. -}
dt : Array (Attribute msg) -> Array (Html msg) -> Html msg
dt =
node "dt"
{-| Represents the definition of the terms immediately listed before it. -}
dd : Array (Attribute msg) -> Array (Html msg) -> Html msg
dd =
node "dd"
{-| Represents a figure illustrated as part of the document. -}
figure : Array (Attribute msg) -> Array (Html msg) -> Html msg
figure =
node "figure"
{-| Represents the legend of a figure. -}
figcaption : Array (Attribute msg) -> Array (Html msg) -> Html msg
figcaption =
node "figcaption"
{-| Represents a generic container with no special meaning. -}
div : Array (Attribute msg) -> Array (Html msg) -> Html msg
div =
node "div"
-- TEXT LEVEL SEMANTIC
{-| Represents a hyperlink, linking to another resource. -}
a : Array (Attribute msg) -> Array (Html msg) -> Html msg
a =
node "a"
{-| Represents emphasized text, like a stress accent. -}
em : Array (Attribute msg) -> Array (Html msg) -> Html msg
em =
node "em"
{-| Represents especially important text. -}
strong : Array (Attribute msg) -> Array (Html msg) -> Html msg
strong =
node "strong"
{-| Represents a side comment, that is, text like a disclaimer or a
copyright, which is not essential to the comprehension of the document.
-}
small : Array (Attribute msg) -> Array (Html msg) -> Html msg
small =
node "small"
{-| Represents content that is no longer accurate or relevant. -}
s : Array (Attribute msg) -> Array (Html msg) -> Html msg
s =
node "s"
{-| Represents the title of a work. -}
cite : Array (Attribute msg) -> Array (Html msg) -> Html msg
cite =
node "cite"
{-| Represents an inline quotation. -}
q : Array (Attribute msg) -> Array (Html msg) -> Html msg
q =
node "q"
{-| Represents a term whose definition is contained in its nearest ancestor
content.
-}
dfn : Array (Attribute msg) -> Array (Html msg) -> Html msg
dfn =
node "dfn"
{-| Represents an abbreviation or an acronym; the expansion of the
abbreviation can be represented in the title attribute.
-}
abbr : Array (Attribute msg) -> Array (Html msg) -> Html msg
abbr =
node "abbr"
{-| Represents a date and time value; the machine-readable equivalent can be
represented in the datetime attribute.
-}
time : Array (Attribute msg) -> Array (Html msg) -> Html msg
time =
node "time"
{-| Represents computer code. -}
code : Array (Attribute msg) -> Array (Html msg) -> Html msg
code =
node "code"
{-| Represents a variable. Specific cases where it should be used include an
actual mathematical expression or programming context, an identifier
representing a constant, a symbol identifying a physical quantity, a function
parameter, or a mere placeholder in prose.
-}
var : Array (Attribute msg) -> Array (Html msg) -> Html msg
var =
node "var"
{-| Represents the output of a program or a computer. -}
samp : Array (Attribute msg) -> Array (Html msg) -> Html msg
samp =
node "samp"
{-| Represents user input, often from the keyboard, but not necessarily; it
may represent other input, like transcribed voice commands.
-}
kbd : Array (Attribute msg) -> Array (Html msg) -> Html msg
kbd =
node "kbd"
{-| Represent a subscript. -}
sub : Array (Attribute msg) -> Array (Html msg) -> Html msg
sub =
node "sub"
{-| Represent a superscript. -}
sup : Array (Attribute msg) -> Array (Html msg) -> Html msg
sup =
node "sup"
{-| Represents some text in an alternate voice or mood, or at least of
different quality, such as a taxonomic designation, a technical term, an
idiomatic phrase, a thought, or a ship name.
-}
i : Array (Attribute msg) -> Array (Html msg) -> Html msg
i =
node "i"
{-| Represents a text which to which attention is drawn for utilitarian
purposes. It doesn't convey extra importance and doesn't imply an alternate
voice.
-}
b : Array (Attribute msg) -> Array (Html msg) -> Html msg
b =
node "b"
{-| Represents a non-textual annotation for which the conventional
presentation is underlining, such labeling the text as being misspelt or
labeling a proper name in Chinese text.
-}
u : Array (Attribute msg) -> Array (Html msg) -> Html msg
u =
node "u"
{-| Represents text highlighted for reference purposes, that is for its
relevance in another context.
-}
mark : Array (Attribute msg) -> Array (Html msg) -> Html msg
mark =
node "mark"
{-| Represents content to be marked with ruby annotations, short runs of text
presented alongside the text. This is often used in conjunction with East Asian
language where the annotations act as a guide for pronunciation, like the
Japanese furigana.
-}
ruby : Array (Attribute msg) -> Array (Html msg) -> Html msg
ruby =
node "ruby"
{-| Represents the text of a ruby annotation. -}
rt : Array (Attribute msg) -> Array (Html msg) -> Html msg
rt =
node "rt"
{-| Represents parenthesis around a ruby annotation, used to display the
annotation in an alternate way by browsers not supporting the standard display
for annotations.
-}
rp : Array (Attribute msg) -> Array (Html msg) -> Html msg
rp =
node "rp"
{-| Represents text that must be isolated from its surrounding for
bidirectional text formatting. It allows embedding a span of text with a
different, or unknown, directionality.
-}
bdi : Array (Attribute msg) -> Array (Html msg) -> Html msg
bdi =
node "bdi"
{-| Represents the directionality of its children, in order to explicitly
override the Unicode bidirectional algorithm.
-}
bdo : Array (Attribute msg) -> Array (Html msg) -> Html msg
bdo =
node "bdo"
{-| Represents text with no specific meaning. This has to be used when no other
text-semantic element conveys an adequate meaning, which, in this case, is
often brought by global attributes like `class`, `lang`, or `dir`.
-}
span : Array (Attribute msg) -> Array (Html msg) -> Html msg
span =
node "span"
{-| Represents a line break. -}
br : Array (Attribute msg) -> Array (Html msg) -> Html msg
br =
node "br"
{-| Represents a line break opportunity, that is a suggested point for
wrapping text in order to improve readability of text split on several lines.
-}
wbr : Array (Attribute msg) -> Array (Html msg) -> Html msg
wbr =
node "wbr"
-- EDITS
{-| Defines an addition to the document. -}
ins : Array (Attribute msg) -> Array (Html msg) -> Html msg
ins =
node "ins"
{-| Defines a removal from the document. -}
del : Array (Attribute msg) -> Array (Html msg) -> Html msg
del =
node "del"
-- EMBEDDED CONTENT
{-| Represents an image. -}
img : Array (Attribute msg) -> Array (Html msg) -> Html msg
img =
node "img"
{-| Embedded an HTML document. -}
iframe : Array (Attribute msg) -> Array (Html msg) -> Html msg
iframe =
node "iframe"
{-| Represents a integration point for an external, often non-HTML,
application or interactive content.
-}
embed : Array (Attribute msg) -> Array (Html msg) -> Html msg
embed =
node "embed"
{-| Represents an external resource, which is treated as an image, an HTML
sub-document, or an external resource to be processed by a plug-in.
-}
object : Array (Attribute msg) -> Array (Html msg) -> Html msg
object =
node "object"
{-| Defines parameters for use by plug-ins invoked by `object` elements. -}
param : Array (Attribute msg) -> Array (Html msg) -> Html msg
param =
node "param"
{-| Represents a video, the associated audio and captions, and controls. -}
video : Array (Attribute msg) -> Array (Html msg) -> Html msg
video =
node "video"
{-| Represents a sound or audio stream. -}
audio : Array (Attribute msg) -> Array (Html msg) -> Html msg
audio =
node "audio"
{-| Allows authors to specify alternative media resources for media elements
like `video` or `audio`.
-}
source : Array (Attribute msg) -> Array (Html msg) -> Html msg
source =
node "source"
{-| Allows authors to specify timed text track for media elements like `video`
or `audio`.
-}
track : Array (Attribute msg) -> Array (Html msg) -> Html msg
track =
node "track"
{-| Represents a bitmap area for graphics rendering. -}
canvas : Array (Attribute msg) -> Array (Html msg) -> Html msg
canvas =
node "canvas"
{-| Defines a mathematical formula. -}
math : Array (Attribute msg) -> Array (Html msg) -> Html msg
math =
node "math"
-- TABULAR DATA
{-| Represents data with more than one dimension. -}
table : Array (Attribute msg) -> Array (Html msg) -> Html msg
table =
node "table"
{-| Represents the title of a table. -}
caption : Array (Attribute msg) -> Array (Html msg) -> Html msg
caption =
node "caption"
{-| Represents a set of one or more columns of a table. -}
colgroup : Array (Attribute msg) -> Array (Html msg) -> Html msg
colgroup =
node "colgroup"
{-| Represents a column of a table. -}
col : Array (Attribute msg) -> Array (Html msg) -> Html msg
col =
node "col"
{-| Represents the block of rows that describes the concrete data of a table.
-}
tbody : Array (Attribute msg) -> Array (Html msg) -> Html msg
tbody =
node "tbody"
{-| Represents the block of rows that describes the column labels of a table.
-}
thead : Array (Attribute msg) -> Array (Html msg) -> Html msg
thead =
node "thead"
{-| Represents the block of rows that describes the column summaries of a table.
-}
tfoot : Array (Attribute msg) -> Array (Html msg) -> Html msg
tfoot =
node "tfoot"
{-| Represents a row of cells in a table. -}
tr : Array (Attribute msg) -> Array (Html msg) -> Html msg
tr =
node "tr"
{-| Represents a data cell in a table. -}
td : Array (Attribute msg) -> Array (Html msg) -> Html msg
td =
node "td"
{-| Represents a header cell in a table. -}
th : Array (Attribute msg) -> Array (Html msg) -> Html msg
th =
node "th"
-- FORMS
{-| Represents a form, consisting of controls, that can be submitted to a
server for processing.
-}
form : Array (Attribute msg) -> Array (Html msg) -> Html msg
form =
node "form"
{-| Represents a set of controls. -}
fieldset : Array (Attribute msg) -> Array (Html msg) -> Html msg
fieldset =
node "fieldset"
{-| Represents the caption for a `fieldset`. -}
legend : Array (Attribute msg) -> Array (Html msg) -> Html msg
legend =
node "legend"
{-| Represents the caption of a form control. -}
label : Array (Attribute msg) -> Array (Html msg) -> Html msg
label =
node "label"
{-| Represents a typed data field allowing the user to edit the data. -}
input : Array (Attribute msg) -> Array (Html msg) -> Html msg
input =
node "input"
{-| Represents a button. -}
button : Array (Attribute msg) -> Array (Html msg) -> Html msg
button =
node "button"
{-| Represents a control allowing selection among a set of options. -}
select : Array (Attribute msg) -> Array (Html msg) -> Html msg
select =
node "select"
{-| Represents a set of predefined options for other controls. -}
datalist : Array (Attribute msg) -> Array (Html msg) -> Html msg
datalist =
node "datalist"
{-| Represents a set of options, logically grouped. -}
optgroup : Array (Attribute msg) -> Array (Html msg) -> Html msg
optgroup =
node "optgroup"
{-| Represents an option in a `select` element or a suggestion of a `datalist`
element.
-}
option : Array (Attribute msg) -> Array (Html msg) -> Html msg
option =
node "option"
{-| Represents a multiline text edit control. -}
textarea : Array (Attribute msg) -> Array (Html msg) -> Html msg
textarea =
node "textarea"
{-| Represents the result of a calculation. -}
output : Array (Attribute msg) -> Array (Html msg) -> Html msg
output =
node "output"
{-| Represents the completion progress of a task. -}
progress : Array (Attribute msg) -> Array (Html msg) -> Html msg
progress =
node "progress"
{-| Represents a scalar measurement (or a fractional value), within a known
range.
-}
meter : Array (Attribute msg) -> Array (Html msg) -> Html msg
meter =
node "meter"
-- INTERACTIVE ELEMENTS
{-| Represents a widget from which the user can obtain additional information
or controls.
-}
details : Array (Attribute msg) -> Array (Html msg) -> Html msg
details =
node "details"
{-| Represents a summary, caption, or legend for a given `details`. -}
summary : Array (Attribute msg) -> Array (Html msg) -> Html msg
summary =
node "summary"
{-| Represents a command that the user can invoke. -}
menuitem : Array (Attribute msg) -> Array (Html msg) -> Html msg
menuitem =
node "menuitem"
{-| Represents a list of commands. -}
menu : Array (Attribute msg) -> Array (Html msg) -> Html msg
menu =
node "menu"
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1>Bootstrap CSS examnple</h1>
<p>Resize this responsive page to see the effect!</p>
</div>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="assets/icon.png" alt="logo" width="30" height="30">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="design.html">Design</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Play Game</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">Games</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Fortnite</a></li>
<li><a class="dropdown-item" href="#">Ratchet & Clank: Rift Apart</a></li>
<li><a class="dropdown-item" href="#">Splatoon 3</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid mt-3">
<div class="row">
<div class="col-sm-4">
<h3 style="text-align: center;">Fortnite</h3>
<p>Fortnite is a popular online video game developed by Epic Games that combines elements of survival, shooting, and building in a battle royale format.</p>
<p>The latest version of Fortnite is 26.20.0-28096793-Android, which was released on September 26, 2023.</p>
</div>
<div class="col-sm-4">
<h3 style="text-align: center;">Ratchet & Clank: Rift Apart</h3>
<p>Ratchet & Clank is a series of action-adventure platform and third-person shooter video games created and developed by Insomniac Games and published by Sony Interactive Entertainment for PlayStation consoles, such as PlayStation 2, PlayStation 3, PlayStation 4, and PlayStation 5</p>
<p>The latest installment in the series is Ratchet & Clank: Rift Apart, which was released on July 26, 2023</p>
</div>
<div class="col-sm-4">
<h3 style="text-align: center;">Splatoon 3</h3>
<p>Splatoon is a third-person shooter video game franchise created by Hisashi Nogami and Shintaro Sato, and developed and owned by Nintendo.</p>
<p>The latest version of Splatoon is 5.0.0, which was released on August 30, 2023 1. This version includes new gear, titles, and weapons, as well as adjustments to the game's multiplayer modes, including Salmon Run and Story Mode</p>
</div>
</div>
</div>
<!-- Carousel -->
<div id="demo" class="carousel slide" data-bs-ride="carousel">
<!-- Indicators/dots -->
<div class="carousel-indicators">
<button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button>
<button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button>
<button type="button" data-bs-target="#demo" data-bs-slide-to="2"></button>
</div>
<!-- The slideshow/carousel -->
<div class="carousel-inner">
<div class="carousel-item active">
<img src="assets/fortnite.jpg" alt="Fortnite" class="d-block" style="width:100%">
<div class="carousel-caption">
<h3 style="background-color: black;">Fortnite</h3>
<p style="background-color: black;">A game by Epic Games!</p>
</div>
</div>
<div class="carousel-item">
<img src="assets/ratchetandclank.jpg" alt="Ratchet & Clank" class="d-block" style="width:100%">
<div class="carousel-caption">
<h3 style="background-color: black;">Ratchet & Clank: Rift Apart</h3>
<p style="background-color: black;">A game by Insomniac Games!</p>
</div>
</div>
<div class="carousel-item">
<img src="assets/splatoon3.jpg" alt="Splatoon 3" class="d-block" style="width:100%">
<div class="carousel-caption">
<h3 style="background-color: black;">Splatoon 3</h3>
<p style="background-color: black;">A game by Nintendo Entertainment Planning & Development!</p>
</div>
</div>
</div>
<!-- Left and right controls/icons -->
<button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
<span class="carousel-control-prev-icon"></span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
<span class="carousel-control-next-icon"></span>
</button>
</div>
<div class="card" style="width: 300px;">
<img src="assets/icon.jpg" class="card-img-top" alt="...">
<div class="card-body text-center">
<h5 class="card-title">Alan Williams</h5>
<p class="card-text">Alan works at UWS. Specialising in game development; Unity and Unreal Engine along with web technology languages and frameworks.</p>
<a href="#" class="btn btn-primary">View Profile</a>
</div>
</div>
<!-- accordian-->
<div class="accordion" id="accordionExample">
<!-- accordian 1-->
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Fortnite Information #1
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse show" data-bs-parent="#accordionExample">
<div class="accordion-body">
<p>Fortnite is a popular online video game developed by Epic Games. It was initially developed as a survival game, but later evolved into a battle royale game. The game is available on various platforms, including Microsoft Windows, macOS, PlayStation 4, PlayStation 5, Xbox One, Xbox Series X/S, Nintendo Switch, and Android. The game has two main modes: Save the World and Battle Royale. In Save the World mode, players cooperate to defend themselves against zombie-like creatures. In Battle Royale mode, up to 100 players fight to be the last person standing on an island. Players can collect resources and build structures to protect themselves from enemy fire. The game is free-to-play but offers in-game purchases for cosmetic items and other upgrades 1.</p>
</div>
</div>
</div>
<!-- accordian 2-->
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Ratchet and Clank Information #2
</button>
</h2>
<div id="collapseTwo" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
<div class="accordion-body">
<p>Ratchet & Clank is a series of action-adventure platform and third-person shooter video games created and developed by Insomniac Games and published by Sony Interactive Entertainment for PlayStation consoles, such as PlayStation 2, PlayStation 3, PlayStation 4, and PlayStation 51. The series has been highly regarded for its engaging gameplay, humor, and memorable characters. It has gained a large following since its inception.
The latest installment in the series is Ratchet & Clank: Rift Apart, which was released on July 26, 20232. This game is available on Steam and is the first Ratchet & Clank game to be released on PC2. In this interdimensional adventure, players join Ratchet and Clank as they travel between action-packed worlds to take on an evil emperor from another reality2.</p>
</div>
</div>
</div>
<!-- accordian 1-->
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Splatoon Information
</button>
</h2>
<div id="collapseThree" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
<div class="accordion-body">
<p>Splatoon is a third-person shooter video game franchise created by Hisashi Nogami and Shintaro Sato, and developed and owned by Nintendo1. The franchise made its debut with the release of the first game, Splatoon, on May 28, 20151. The game is primarily a team-based third-person shooter that can be played by up to nine players in online four-versus-four matches2. It also features local one-versus-one multiplayer matches and a single-player campaign2.
The latest installment in the series is Splatoon 3, which was released on September 9, 20221. The game is available exclusively on the Nintendo Switch family of systems3. In Splatoon 3, players enter the Splatlands, where they can ink their way to the top in online modes like Turf War and Salmon Run3. The game offers a mix of action, strategy, and teamwork as players compete to cover the most territory with their team’s ink2.</p>
</div>
</div>
</div>
</div>
</body>
</html>
|
import React, { memo, useCallback, useEffect, useState } from 'react';
import Alert from 'react-bootstrap/Alert';
import Form from 'react-bootstrap/Form';
import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { differenceInCalendarDays } from 'date-fns';
import { MAP_INTERACTION_CATEGORY, trackEventFactory } from '../utils/analytics';
import { setTrackLength, setTrackLengthRangeOrigin, TRACK_LENGTH_ORIGINS } from '../ducks/tracks';
import styles from './styles.module.scss';
const mapInteractionTracker = trackEventFactory(MAP_INTERACTION_CATEGORY);
const RANGE_INPUT_ATTRS = { max: 60, min: 1 };
const FREEHAND_INPUT_ATTRS = { max: 365, min: RANGE_INPUT_ATTRS.min };
const TrackLengthControls = () => {
const dispatch = useDispatch();
const { t } = useTranslation('tracks', { keyPrefix: 'trackLengthControls' });
const eventFilterDateRange = useSelector((state) => state.data.eventFilter.filter.date_range);
const trackLength = useSelector((state) => state.view.trackLength);
const [customLengthValid, setCustomLengthValidity] = useState(true);
const [customLengthValue, setCustomLengthValue] = useState(trackLength.length);
const [initialized, setInitState] = useState(false);
const eventFilterDateRangeLength = differenceInCalendarDays(new Date(), eventFilterDateRange.lower);
const focusRange = () => {
if (trackLength.origin !== TRACK_LENGTH_ORIGINS.customLength) {
dispatch(setTrackLengthRangeOrigin(TRACK_LENGTH_ORIGINS.customLength));
}
};
const setTrackLengthToEventDateRange = useCallback(() => {
mapInteractionTracker.debouncedTrack('Set Track Length To Match Report Filter');
dispatch(setTrackLength(eventFilterDateRangeLength));
}, [dispatch, eventFilterDateRangeLength]);
const setTrackLengthToCustomDateRange = useCallback(() => {
const rangeIsValid = (customLengthValue >= FREEHAND_INPUT_ATTRS.min)
&& (customLengthValue <= FREEHAND_INPUT_ATTRS.max);
if (rangeIsValid) {
setCustomLengthValidity(true);
dispatch(setTrackLength(customLengthValue));
mapInteractionTracker.debouncedTrack('Set Track Length To Custom Length', `${customLengthValue} days`);
} else {
setCustomLengthValidity(false);
}
}, [customLengthValue, dispatch]);
useEffect(() => {
if (trackLength.origin === TRACK_LENGTH_ORIGINS.eventFilter) {
setTrackLengthToEventDateRange();
} else if (trackLength.origin === TRACK_LENGTH_ORIGINS.customLength) {
setTrackLengthToCustomDateRange();
}
}, [
eventFilterDateRange,
eventFilterDateRangeLength,
setTrackLengthToCustomDateRange,
setTrackLengthToEventDateRange,
trackLength.origin,
]);
useEffect(() => {
if (!initialized) {
setInitState(true);
}
}, [initialized]);
return <Form className={styles.form} onSubmit={(event) => event.preventDefault()}>
<h6>{t('header')}</h6>
<Form.Label className={styles.label} htmlFor="filter">
<Form.Check
checked={TRACK_LENGTH_ORIGINS.eventFilter === trackLength.origin}
className={styles.radio}
id="filter"
name="track-length-method"
onChange={(event) => dispatch(setTrackLengthRangeOrigin(event.target.value))}
type="radio"
value={TRACK_LENGTH_ORIGINS.eventFilter}
/>
<span>{t('matchReportFilterDateLabel', { reportFilterDateRangeLength: eventFilterDateRangeLength })}</span>
</Form.Label>
<Form.Label className={styles.label} htmlFor="custom-length">
<Form.Check
checked={TRACK_LENGTH_ORIGINS.customLength === trackLength.origin}
className={styles.radio}
id="custom-length"
name="track-length-method"
onChange={(event) => dispatch(setTrackLengthRangeOrigin(event.target.value))}
type="radio"
value={TRACK_LENGTH_ORIGINS.customLength}
/>
<span>{t('customLengthLabel')}</span>
</Form.Label>
<div>
<div className={styles.rangeControls}>
<input
type="range"
{...RANGE_INPUT_ATTRS}
className={`${styles.rangeSlider} ${trackLength.origin !== TRACK_LENGTH_ORIGINS.customLength ? styles.disabled : ''}`}
disabled={trackLength.origin !== TRACK_LENGTH_ORIGINS.customLength}
onChange={(event) => setCustomLengthValue(parseFloat(event.target.value))}
onFocus={focusRange}
onMouseDown={focusRange}
onTouchStart={focusRange}
value={customLengthValue}
/>
<input
autoComplete="off"
{...FREEHAND_INPUT_ATTRS}
className={`${styles.rangeFreeformInput} ${trackLength.origin !== TRACK_LENGTH_ORIGINS.customLength ? styles.disabled : ''}`}
disabled={trackLength.origin !== TRACK_LENGTH_ORIGINS.customLength}
name="range-freeform-input"
onChange={(event) => setCustomLengthValue(parseFloat(event.target.value))}
onFocus={focusRange}
onMouseDown={focusRange}
onTouchStart={focusRange}
type="number"
value={customLengthValue}
/>
</div>
{!customLengthValid && <Alert variant="danger">
{t('invalidCustomLengthAlert', { max: FREEHAND_INPUT_ATTRS.max, min: FREEHAND_INPUT_ATTRS.min })}
</Alert>}
</div>
</Form>;
};
export default memo(TrackLengthControls);
|
import { useCallback, useEffect, useState } from 'react'
import { getLeaderTableData, getWinningStreak } from 'datasource/leaderboard'
import { useWalletConnection } from 'hooks/useWalletConnection'
import { useReactGA4 } from 'GA4/useReactGA4'
const useFetchTableData = (callback) => {
const { connectWallet } = useWalletConnection()
const { gaEvent } = useReactGA4()
const [sortBy, setSort] = useState()
const [leaderTableData, setLeaderTableData] = useState([])
const [error, setError] = useState(null)
const [isPending, setIsPending] = useState(false)
const fetchTableData = useCallback(async () => {
setIsPending(true)
await getLeaderTableData()
.then((res) => {
setLeaderTableData(callback && typeof callback === 'function' ? callback(res) || [] : res || [])
})
.catch((err) => {
//TODO: Toast or other notification on error should be here
if (err.code === 4001) {
connectWallet()
}
setError(err)
})
setIsPending(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
gaEvent('leaderboard_visit', {
pathId: 'dashboard.leaderboard.visit',
source: '',
timeSpent: ''
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
fetchTableData()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sortBy])
return [leaderTableData, setSort, error, isPending]
}
export default useFetchTableData
|
package oop;
// oop = object-oriented programming
// class = template for the object (class Car)
// object = instance of a class (5 objects type Car)
// fields = proprieties = attributes
// variables (The car has: color, brand, price)
// methods = functions in oop
public class BankAccount {
// proprieties
String accountHolder;
String iban;
double sold = 0;
boolean active = false;
private int pin = 7777;
int tries_activate = 0;
// constructors = used to initialize the objects
public BankAccount(String accountHolder, String iban) {
this.accountHolder = accountHolder;
this.iban = iban;
}
// methods
public void describeSold(){
System.out.println(this.accountHolder);
System.out.println(this.iban);
System.out.println(this.sold);
System.out.println(this.active);
System.out.println("Number of wrong tries " + this.tries_activate);
}
public void activateAccount(int pinUser){
// modify to active only if the pin is correct
if (pinUser == this.pin) {
this.active = true;
System.out.println("The card was activated with success");
} else {
System.out.println("The pin is wrong");
this.tries_activate++; // increment tries_activate
}
}
public void topUpCard(double amount_topUp){
// the amount that we have in account + amount_topUp
this.sold = this.sold + amount_topUp;
System.out.println("Top up with success the amount of "+ amount_topUp + " You have in your account the amount of: " + this.sold);
}
public void withdraw(double amount_withdraw){
// we can withdraw only what I have in account
if (amount_withdraw <= this.sold){
this.sold = this.sold - amount_withdraw;
System.out.println("You have in account " + this.sold);
} else {
System.out.println("Insufficient fonds");
}
}
// 4 principles of oop
// inheritance
// polymorphism
// encapsulation
// abstraction
}
|
//
// TestDecodingEventPreview.swift
// BuyTicketsChallengeAppTests
//
// Created by Alexey Lisov on 09/05/2023.
//
import XCTest
@testable import BuyTicketsChallengeApp
class DecodingModelTests: XCTestCase {
override func setUp() {
super.setUp()
}
func testDecodingEventPreview() {
guard let path = Bundle.main.path(forResource: "EventPreviewMock", ofType: "json") else {
fatalError("No file")
}
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) else {
fatalError("No file")
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
guard let eventPreview: EventPreview = try? decoder.decode(EventPreview.self, from: data) else {
fatalError("Can't decode")
}
XCTAssertEqual(eventPreview.price, 50.0)
}
}
|
//1.引入相关包
import org.apache.spark.rdd.RDD
import org.apache.spark.graphx._
//2.获取用作vertexdeRdd
val tweeters = Array((1L, ("Alice", 28)), (2L, ("Bob", 27)), (3L, ("Charlie", 65)), (4L, ("David", 42)), (5L, ("Ed", 55)), (6L, ("Fran", 50)))
val vertexRDD: RDD[(Long, (String, Int))] = spark.sparkContext.parallelize(tweeters)
//3.获取用作Edeg的Rdd
val followRelations = Array(Edge[Int](2L, 1L, 7), Edge[Int](2L, 4L, 2),
Edge[Int](3L, 2L, 4), Edge[Int](3L, 6L, 3), Edge[Int](4L, 1L, 1), Edge[Int](5L, 2L, 2), Edge[Int](5L, 3L, 8), Edge[Int](5L, 6L, 3))
val edgeRDD = spark.sparkContext.parallelize(followRelations)
4.生成Graph
val graph = Graph(vertexRDD,edgeRDD)
常见API
//1.获取graph的vertices
graph.vertices.collect
//2.获取graph的edges
graph.edges.collect
//3.获取graph的triplets(//triplets中有5个属性分别表示(srcId=>前者Id,dstId=>后者Id,srcAttr=>前者属性,dstAttr=>后者属性,attr=>Edge的属性)
graph.triplets.collect
//4。改变vertex的属性(Id无法改变)
val t1_graph=graph.mapVertices{case(id,(name,age))=>(id,name)}.vertices.collect //只能改变属性无法改变ID
val t2_graph=graph.mapVertices{(id,attr)=>(id,attr._1)}.vertices.collect //只能改变属性无法改变ID
val e2_graph=graph.mapEdges(e=>e+1) //只能改变第三个值(第一个和第二个是节点ID不可变)
5。join 和outerjoin
//join & outerJoin
//(id, v, cmpy)中id表示相同的Id;v=>前者attr;cmpy=>后者attr
//join
//批量修改vertices用joinVertices;Id相同则进行变换,Id不同则保留原来的值;
val tweeters_companies = sc.parallelize(Array((1L, "it21 learning"), (2L, "it21 tecth"), (3L, "it21 consulting")))
val t_graph = graph.joinVertices(tweeters_companies)((id, v, cmpy) => (v._1 + " @ " + cmpy, v._2))
t_graph.vertices.collect
//outrtjoin
//批量修改vertices用outerJoinVertices;无论Id是否相同都进行变换(匹配成功则返回Some否则None)
val s_graph = graph.outerJoinVertices(tweeters_companies)((id, v, cmpy) => (v._1 + " @ " + cmpy, v._2))
s_graph.vertices.collect
6。入度和出度
//计算入度和出度并放入vertices的attr中
//inDegrees入度
//outDegrees出度
// ◆ indegree
// ◼ is the in-degree of a vertex
// ◼ Vertices whose indegree is o won’t be included in the result RDD
//◆ outdegree
// ◼ is the out-degree of a vertex
// ◆ degree
// ◼ the sum of inDegree and outDegree
case class User(name:String,age:Int,inDeg:Int,outDeg:Int)
val inUserGraph = graph.mapVertices{case(id,(name,age))=>User(name,age,0,0)}
//inUserGraph.inDegrees.collect //获取入度 Array((4,1), (6,2), (2,2), (1,2), (3,1))
//inUserGraph.outDegrees.collect //获取出度 Array((4,1), (2,2), (3,2), (5,3))
val UserGraph = inUserGraph.outerJoinVertices(inUserGraph.inDegrees){case(id,v,inDeg)=>User(v.name,v.age,inDeg.getOrElse(0),v.outDeg)}
.outerJoinVertices(inUserGraph.outDegrees){case(id,v,outDegrees)=>User(v.name,v.age,v.inDeg,outDegrees.getOrElse(0))}
.vertices.collect
|
<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="template">
<head>
<meta charset="UTF-8">
<title>Update Course</title>
</head>
<body>
<div layout:fragment="content1">
<div class="col-md-6 offset-3 mt-3">
<form class="form-control" method="post" th:action="@{save}" th:object="${course}">
<div class="mb-3 mt-3">
<label class="form-label">Course Name</label>
<input type="text" name="courseName" class="form-control" th:field="${course.courseName}">
</div>
<div class="mb-3 mt-3">
<label class="form-label">Course Duration</label>
<input type="text" name="courseDuration" class="form-control" th:field="${course.courseDuration}" >
</div>
<div class="mb-3 mt-3">
<label class="form-label">Course Description</label>
<input type="text" name="courseDescription" class="form-control" th:field="${course.courseDescription}" >
</div>
<div class="mb-3 mt-3">
<label class="form-label">Instructor</label>
<select th:field="${course.instructor}" name="instructor" class="form-select">
<option th:each="instructor:${listInstructors}"
th:text="${instructor.getFirstName()}+ ' ' +${instructor.getLastName()}"
th:value="${instructor.getInstructorId()}"></option>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div></body>
</html>
|
package org.jbomberman.view;
import javafx.animation.*;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import org.jbomberman.controller.MainController;
import org.jbomberman.utils.*;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.util.Duration;
import java.io.InputStream;
import java.util.*;
public class GameView implements Observer {
private final MainController controller;
public final AnchorPane gameBoard;
public static final int SCALE_FACTOR = 35;
//END GAME PANELS
Pane gameOver;
Pane victory;
//PAUSE PANELS
Pane pause;
Pane options;
//IMAGE VIEWS
ImageView player;
ImageView puBomb;
ImageView puLife;
ImageView puInvincible;
ImageView exit;
//ARRAYS
private final List<ImageView> randomBlocks;
private final List<ImageView> enemies;
private final List<ImageView> coins;
private final List<ImageView> bombExplosion;
//BOTTOM BAR
private final HBox bottomBar = new HBox();
Label livesLabel;
Label pointsLabel;
Label timerLabel;
//IMAGES
private enum BlockImage {
//bomb is the real bomb, fire is the power_up
BEDROCK(BlockImage.class.getResourceAsStream("definitive/static_block.png")),
STONE(BlockImage.class.getResourceAsStream("definitive/random_block.png")),
GRASS(BlockImage.class.getResourceAsStream("definitive/background_green.png")),
STEVE(BlockImage.class.getResourceAsStream("definitive/steve.png")),
DOOR(BlockImage.class.getResourceAsStream("definitive/exit.png")),
BOMB(BlockImage.class.getResourceAsStream("bomb/bomb.gif")),
ENEMY(BlockImage.class.getResourceAsStream("definitive/enemy.png")),
FIRE(BlockImage.class.getResourceAsStream("power_up/bomb.png")),
LIFE(BlockImage.class.getResourceAsStream("power_up/oneup.png")),
INVINCIBLE(BlockImage.class.getResourceAsStream("power_up/resistance.png")),
COIN(BlockImage.class.getResourceAsStream("power_up/coin.gif")),
DESTRUCTION(BlockImage.class.getResourceAsStream("random_blocks/blocks.gif"))
;
private final Image image;
BlockImage(InputStream path) {
this.image = new Image(path);
}
public Image getImage() {
return image;
}
}
//############### CONSTRUCTOR AND INITIALIZE ################//
public GameView() {
controller = MainController.getInstance();
gameBoard = new AnchorPane();
randomBlocks = new ArrayList<>();
enemies = new ArrayList<>();
coins = new ArrayList<>();
bombExplosion = new ArrayList<>();
initialize();
}
public void initialize() {
genInGamePanels();
addBottomBar();
gameBoard.setOnKeyPressed(controller::handleGameKeyEvent);
}
//####################### PANELS #######################//
private void genInGamePanels() {
//################# PAUSE ################//
pause = SceneManager.getP("Pause", true, false);
pause.setVisible(false);
Label pauseResumeButton = SceneManager.getButton("resume", 0, Color.WHITE);
Label pauseOptionsButton = SceneManager.getButton("options", 1, Color.WHITE);
Label pauseRestartButton = SceneManager.getButton("restart", 2, Color.WHITE);
Label pauseExitButton = SceneManager.getButton("menu", 3, Color.WHITE);
pauseResumeButton.setOnMouseClicked(mouseEvent -> controller.resumeController());
pauseOptionsButton.setOnMouseClicked(mouseEvent -> SceneManager.changePane(pause,options));
pauseRestartButton.setOnMouseClicked(mouseEvent -> {
controller.gameButtonPressed();
BackgroundMusic.stopMusic();
});
pauseExitButton.setOnMouseClicked(mouseEvent -> {
controller.quitMatch();
BackgroundMusic.stopMusic();
});
pause.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode().equals(KeyCode.ESCAPE)){
controller.resumeController();
keyEvent.consume();
}
});
pause.getChildren().addAll(pauseResumeButton, pauseOptionsButton, pauseRestartButton, pauseExitButton);
//################# OPTIONS ################//
options = SceneManager.getP("Options", true, false);
options.setVisible(false);
Label optionsBackButton = SceneManager.getButton("back", 2, Color.WHITE);
optionsBackButton.setOnMouseClicked(mouseEvent -> SceneManager.changePane(options, pause));
options.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode().equals(KeyCode.ESCAPE)){
SceneManager.changePane(options,pause);
keyEvent.consume();
}
});
options.getChildren().addAll(optionsBackButton);
//################## GAME OVER #################//
gameOver = SceneManager.getP("Game Over", true,false);
gameOver.setVisible(false);
Label gameOverRestartButton = SceneManager.getButton("restart", 1, Color.WHITE);
Label gameOverExitButton = SceneManager.getButton("menu", 2, Color.WHITE);
gameOverExitButton.setOnMouseClicked(mouseEvent -> controller.quitMatch());
gameOverRestartButton.setOnMouseClicked(mouseEvent -> {
controller.gameButtonPressed();
BackgroundMusic.stopMusic();
});
gameOver.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode().equals(KeyCode.ESCAPE)){
controller.quitMatch();
}
});
gameOver.getChildren().addAll(gameOverRestartButton, gameOverExitButton);
//################## VICTORY ###################//
victory = SceneManager.getP("Victory", true, false);
victory.setVisible(false);
Label victoryNextLevelButton = SceneManager.getButton("nextLevel", 1, Color.WHITE);
Label victoryExitButton = SceneManager.getButton("menu", 3, Color.WHITE);
victoryNextLevelButton.setOnMouseClicked(mouseEvent -> {
//TODO next level
});
victoryExitButton.setOnMouseClicked(mouseEvent -> controller.quitMatch());
victory.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode().equals(KeyCode.ESCAPE)){
controller.quitMatch();
}
});
victory.getChildren().addAll(victoryNextLevelButton, victoryExitButton);
//################## GAMEBOARD ################//
gameBoard.getChildren().addAll(pause, options , gameOver, victory);
}
//#################### BOTTOM BAR ################//
private void addBottomBar() {
// build the bottomBar
bottomBar.setLayoutX(0);
bottomBar.setLayoutY((double)SCALE_FACTOR * 11);
bottomBar.setPrefHeight(SCALE_FACTOR);
bottomBar.setPrefWidth((double)SCALE_FACTOR * 17);
bottomBar.setStyle("-fx-background-color: grey");
// build the label
Font customFontSmall = Font.loadFont(GameView.class.getResourceAsStream("/org/jbomberman/SfComicScriptBold-YXD2.ttf"), 25.0);
livesLabel = new Label("Lives: " + 3);
pointsLabel = new Label("Points: " + 0);
timerLabel = new Label("Tempo: 0");
livesLabel.setFont(customFontSmall);
livesLabel.setTextFill(Color.BLACK);
pointsLabel.setFont(customFontSmall);
pointsLabel.setTextFill(Color.BLACK);
pointsLabel.setLayoutX(200);
//##################### TEST ####################//
//TODO remove after test
Button buttonBlocks = new Button();
buttonBlocks.setOnMouseClicked(mouseEvent -> {
controller.removeBlocks();
mouseEvent.consume();
gameBoard.toFront();
gameBoard.requestFocus();
});
buttonBlocks.setLayoutX(40);
buttonBlocks.setLayoutY(20);
bottomBar.getChildren().addAll(livesLabel, buttonBlocks, pointsLabel);
//###############################################//
gameBoard.getChildren().add(bottomBar);
}
private void updateLife(int index){
livesLabel.setText("Lives: " + index);
}
private void updatePoints(int totalPoints, int currentPoints, Coordinate coordinate){
pointsLabel.setText("Points: " + totalPoints);
Label text = SceneManager.getText(Integer.toString(currentPoints), coordinate, SCALE_FACTOR);
gameBoard.getChildren().add(text);
text.setVisible(true);
text.toFront();
TranslateTransition transition = new TranslateTransition(Duration.millis(700), text);
transition.setByY(-30);
FadeTransition fadeOutTransition = new FadeTransition(Duration.millis(900), text);
fadeOutTransition.setFromValue(1);
fadeOutTransition.setToValue(0);
fadeOutTransition.setOnFinished(actionEvent -> gameBoard.getChildren().remove(text));
ParallelTransition parallelTransition = new ParallelTransition(transition, fadeOutTransition);
parallelTransition.play();
}
//####################### GETTER #######################//
public AnchorPane getGame() {
return gameBoard;
}
public void getFocus() {
gameBoard.setVisible(true);
gameBoard.toFront();
gameBoard.requestFocus();
}
@Override
public void update(Observable ignored, Object arg) {
if (arg instanceof UpdateInfo updateInfo) {
UpdateType updateType = updateInfo.getUpdateType();
switch (updateType) {
case LOAD_MAP -> {
switch (updateInfo.getSubBlock()) {
case GROUND_BLOCKS -> loader(updateInfo.getArray(), BlockImage.GRASS.getImage());
case STATIC_BLOCKS -> loader(updateInfo.getArray(), BlockImage.BEDROCK.getImage());
case RANDOM_BLOCKS -> updateInfo.getArray().forEach(coordinate -> drawImageView(coordinate, BlockImage.STONE.getImage(), randomBlocks));
default -> throw new IllegalStateException("Unexpected value: " + updateInfo.getIndex());
}
}
case LOAD_ENEMIES -> updateInfo.getArray().forEach(coordinate -> drawImageView(coordinate, BlockImage.ENEMY.getImage(), enemies));
case LOAD_COINS -> updateInfo.getArray().forEach(coordinate -> drawImageView(coordinate, BlockImage.COIN.getImage(), coins));
case LOAD_PLAYER -> player = loadItems(updateInfo.getCoordinate(), BlockImage.STEVE.getImage());
case LOAD_EXIT -> exit = loadItems(updateInfo.getCoordinate(), BlockImage.DOOR.getImage());
case LOAD_POWER_UP_LIFE -> puLife = loadItems(updateInfo.getCoordinate(), BlockImage.LIFE.getImage());
case LOAD_POWER_UP_BOMB -> puBomb = loadItems(updateInfo.getCoordinate(), BlockImage.FIRE.getImage());
case LOAD_POWER_UP_INVINCIBLE -> puInvincible = loadItems(updateInfo.getCoordinate(), BlockImage.INVINCIBLE.getImage());
case UPDATE_BLOCK_DESTROYED -> removeImageView(randomBlocks, updateInfo.getIndex());
case UPDATE_ENEMY_DEAD -> removeImageView(enemies, updateInfo.getIndex());
case UPDATE_COINS -> removeImageView(coins, updateInfo.getIndex());
case UPDATE_POSITION -> position(updateInfo.getNewCoord(), updateInfo.getOldCoord(), updateInfo.getIndex());
case UPDATE_RESPAWN -> respawn(updateInfo.getIndex());
case UPDATE_POINTS -> updatePoints(updateInfo.getIndex(), updateInfo.getIndex2(), updateInfo.getCoordinate());
case UPDATE_PU_LIFE -> doLifePowerUp(updateInfo.getIndex());
case UPDATE_PU_BOMB -> doBombPowerUp();
case UPDATE_PU_INVINCIBLE -> doInvinciblePowerUp(updateInfo.getBoo());
case UPDATE_BOMB_RELEASED -> {
BackgroundMusic.playBomb();
drawBomb(updateInfo.getCoordinate(), 1);
}
case UPDATE_EXPLOSION -> drawExplosion(updateInfo.getTriadArrayList(), 1);
case UPDATE_GAME_WIN -> gameWin();
case UPDATE_GAME_OVER -> gameLost(updateInfo.getCoordinate());
default -> throw new IllegalStateException("Unexpected value: " + updateType);
}
}
}
private ImageView loadItems(Coordinate c, Image image) {
ImageView item = createImageView(c, image);
gameBoard.getChildren().add(item);
return item;
}
private void gameLost(Coordinate c) {
BackgroundMusic.stopMusic();
BackgroundMusic.playDeath();
controller.endMatch();
PauseTransition pauseGameOver = new PauseTransition(Duration.millis(400));
gameOverAnimation(c);
pauseGameOver.setOnFinished(event -> {
gameOver.toFront();
gameOver.setVisible(true);
gameOver.requestFocus();
});
pauseGameOver.play();
}
private void gameWin() {
BackgroundMusic.stopMusic();
BackgroundMusic.playSuccess();
controller.endMatch();
PauseTransition pauseGameWin = new PauseTransition(Duration.millis(400));
pauseGameWin.setOnFinished(event -> {
victory.toFront();
victory.setVisible(true);
victory.requestFocus();
});
pauseGameWin.play();
}
//#################### ANIMATION AND MOVEMENT ##################//
private void position(Coordinate newC, Coordinate oldC, int index) {
int oldX = oldC.x() * SCALE_FACTOR;
int oldY = oldC.y() * SCALE_FACTOR;
int newX = newC.x() * SCALE_FACTOR;
int newY = newC.y() * SCALE_FACTOR;
TranslateTransition transition = new TranslateTransition();
if (oldX != newX){
transition.setByX((double)newX-oldX);
}else{
transition.setByY((double)newY-oldY);
}
if (index < 0) {
controller.moving(true);
transition.setDuration(Duration.millis(200));
transition.setOnFinished(event ->
controller.moving(false)
);
transition.setNode(player);
} else {
transition.setDuration(Duration.millis(600));
transition.setNode(enemies.get(index));
}
transition.play();
}
private void respawn(int index) {
controller.moving(true);
PauseTransition pauseRespawn = getPauseTransition();
updateLife(index);
pauseRespawn.play();
}
private PauseTransition getPauseTransition() {
PauseTransition pauseRespawn = new PauseTransition(Duration.millis(200));
pauseRespawn.setOnFinished(event -> {
player.setTranslateX(0);
player.setTranslateY(0);
controller.moving(false);
});
return pauseRespawn;
}
/*
private AnimationTimer animationTimer(){
return new AnimationTimer() {
public void handle(long now) {
// Avvia l'animazione parallela quando la transizione di traslazione inizia
if (translateTransition.getStatus() == Animation.Status.RUNNING) {
parallelTransition.play();
stop(); // Arresta l'AnimationTimer dopo l'avvio dell'animazione parallela
}
}
};
}
*/
private void gameOverAnimation(Coordinate coordinate) {
//TODO
}
//##################### PAUSE ####################//
public void pauseView(){
pause.toFront();
pause.setVisible(true);
pause.requestFocus();
}
public void resumeView() {
SceneManager.changePane(pause,gameBoard);
}
//########################## POWER UPS ########################//
private void doLifePowerUp(int index) {
updateLife(index);
powerUPs(puLife);
}
private void doBombPowerUp(){
powerUPs(puBomb);
}
private void doInvinciblePowerUp(boolean boo) {
if (boo) {
player.setOpacity(0.5);
powerUPs(puInvincible);
}else {
player.setOpacity(1);
}
}
private void powerUPs(ImageView imageView) {
PauseTransition removePU = new PauseTransition(Duration.millis(200));
removePU.setOnFinished(event -> gameBoard.getChildren().remove(imageView));
removePU.play();
imageView.setFitHeight(25);
imageView.setFitWidth(25);
HBox.setMargin(imageView, new Insets(5, 0, 0, 10));
bottomBar.getChildren().add(imageView);
}
//###################### IMAGEVIEW METHODS ######################//
private ImageView createImageView(Coordinate c, Image image) {
ImageView imageView = new ImageView(image);
imageView.setLayoutX((double)c.x() * SCALE_FACTOR);
imageView.setLayoutY((double)c.y() * SCALE_FACTOR);
imageView.setFitHeight(SCALE_FACTOR);
imageView.setFitWidth(SCALE_FACTOR);
return imageView;
}
private void drawImageView(Coordinate coordinate, Image image, List<ImageView> entities) {
ImageView imageView = createImageView(coordinate, image);
entities.add(imageView);
gameBoard.getChildren().add(imageView);
}
private void drawBomb(Coordinate coordinate, int i) {
ImageView tntImage = createImageView(coordinate, new Image(Objects.requireNonNull(GameView.class.getResourceAsStream("bomb/bomb_" + i + ".png"))));
PauseTransition tnt = new PauseTransition(Duration.millis(250));
gameBoard.getChildren().add(tntImage);
player.toFront();
int j = i + 1;
tnt.setOnFinished(actionEvent -> {
gameBoard.getChildren().remove(tntImage);
if (j < 7) {
drawBomb(coordinate, j);
} else {
controller.bombExploded();
}
});
tnt.play();
}
private void removeImageView(List<ImageView> array, int index) {
gameBoard.getChildren().remove(array.get(index));
if (array.equals(randomBlocks)){
ImageView imageView = randomBlocks.get(index);
destroyBlock(new Coordinate((int)imageView.getLayoutX()/SCALE_FACTOR, (int)imageView.getLayoutY()/SCALE_FACTOR), 1);
} else if (array.equals(coins)){
BackgroundMusic.playCoin();
}
array.remove(index);
}
private void destroyBlock(Coordinate c, int i){
ImageView newImageView = createImageView(c, new Image(Objects.requireNonNull(GameView.class.getResourceAsStream( "random_blocks/" + i + ".png"))));
gameBoard.getChildren().add(newImageView);
int j = i + 1;
PauseTransition pauseTransition = new PauseTransition(Duration.millis(160));
pauseTransition.setOnFinished(event -> {
gameBoard.getChildren().remove(newImageView);
if (j < 7) destroyBlock(c, j);
});
pauseTransition.play();
}
private void drawExplosion(ArrayList<Triad> triadArrayList, int i) {
String path = "explosion/" + i;
triadArrayList.forEach(triad -> {
ImageView imageView;
if (triad.getDirection().equals(Direction.CENTER)) {
imageView = createImageView(triad.getCoordinate(), new Image(Objects.requireNonNull(GameView.class.getResourceAsStream( path + "/center.png"))));
} else if (triad.isLast()) {
imageView = createImageView(triad.getCoordinate(), new Image(Objects.requireNonNull(GameView.class.getResourceAsStream(path +"/" + triad.getDirection().getKeyCode() + "_external.png"))));
} else {
imageView = createImageView(triad.getCoordinate(), new Image(Objects.requireNonNull(GameView.class.getResourceAsStream(path +"/" + triad.getDirection().getKeyCode() + ".png"))));
}
bombExplosion.add(imageView);
gameBoard.getChildren().add(imageView);
});
int j = i + 1;
PauseTransition pauseTransition = new PauseTransition(Duration.millis(150));
pauseTransition.setOnFinished(event -> {
removeExplosion();
if (j < 4) drawExplosion(triadArrayList, j);
});
pauseTransition.play();
}
private void removeExplosion() {
bombExplosion.forEach(imageView -> gameBoard.getChildren().remove(imageView));
}
private void loader(ArrayList<Coordinate> array, Image image) {
array.forEach(coordinate -> gameBoard.getChildren().add(createImageView(coordinate, image)));
}
}
|
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/friends', function() {
return response()->json([
'friends' => [
[
'question' => 'Chandlers roomate?',
'answer' => 'Jo'
],
[
'question' => 'Chandlers wife?',
'answer' => 'Monica'
]
]
]);
});
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
|
import java.util.InputMismatchException;
import java.util.Scanner;
public class DigitalBank extends Bank{
public DigitalBank(Scanner sc) {
super(sc);
}
// Method ho tro chuc nang
@Override
public Customer searchCustomerByCCCD(String CCCD) {
return super.searchCustomerByCCCD(CCCD);
}
public boolean withdraw(String customerId, String accountNumber, double amount) {
if (isCustomerExisted(customerId)) {// Neu khach hang ton tai
Customer customer = searchCustomerByCCCD(customerId);
// Casting Customer => DigitalCustomer
if(customer instanceof DigitalCustomer) {
DigitalCustomer digitalCustomer = (DigitalCustomer) customer;
return digitalCustomer.withdraw(accountNumber, amount);
}
}
return false;
}
public void addCustomer(String customerId, String name) {
Customer newCustomer = new DigitalCustomer();
if (!isCustomerExisted(customerId)) {
newCustomer.setCustomerId(customerId);
newCustomer.setName(name);
super.addCustomer(newCustomer);
}
}
public double nhapBalance() {
// Nhap so du
double balance = 0;
do {
try {
System.out.print("Nhap so du: ");
balance = sc.nextDouble();
sc.nextLine();
if (balance < 50000) {
System.out.println("So du tai khoan phai it nhat 50_000 vnd. Vui long nhap lai");
}
} catch (Exception e) {
System.out.println("So du khong hop le. Vui long nhap lai");
sc.next();
}
} while (balance < 50000);
return balance;
}
// Method chuc nang
// Hien thi thong tin khach hang
public void showCustomer() {
Customer customer = this.searchCustomerByCCCD(Asm03.CUSTOMER_ID);
if (customer != null) {
customer.displayInformation();
}
}
public void themTaiKhoanATM() {
SavingsAccount accountATM = new SavingsAccount();
// Nhap so tai khoan
String stk = "";
do {
try {
System.out.print("Nhap ma STK gom 6 chu so: ");
stk = sc.nextLine();
if (stk.equals("No")) {// Thoat nhap
break;
}
if (!accountATM.isValidAccountNumber(stk)) {
System.out.println("So tai khoan khong hop le. Vui long nhap lai hoac nhap 'No' de thoat");
} else {
// Stk chua ton tai
if (!super.isAccountExisted(Asm03.CUSTOMER_ID, stk)) {
double balance = nhapBalance();
// Them so du vao tai khoan
accountATM.setAccountNumber(stk);
accountATM.setBalance(balance);
super.addAccount(Asm03.CUSTOMER_ID, accountATM);
accountATM.setSaving(true); // Luu la tai khoan Savings
// Them giao dich vao lich su
Transaction transaction = new Transaction(stk, balance, Utils.getDateTime(), true);
accountATM.addTransactions(transaction);
System.out.println("Da them tai khoan thanh cong");
break; // Thoat khoi vong lap khi thanh cong
}
else { // So tai khoan da ton tai => Yeu cau nhap lai
System.out.println("So tai khoan da ton tai. Vui long nhap lai hoac nhap 'No' de thoat");
}
}
}
catch (Exception e) {
System.out.println("So tai khoan khong hop le. Vui long nhap lai hoac nhap 'No' de thoat");
sc.next();
}
} while(!accountATM.isValidAccountNumber(stk) || this.isAccountExisted(Asm03.CUSTOMER_ID, stk));
}
public void themTaiKhoanTinDung() {
LoansAccount accountTinDung = new LoansAccount();
// Nhap so tai khoan
String stk = "";
do {
try {
System.out.print("Nhap ma STK gom 6 chu so: ");
stk = sc.nextLine();
if (stk.equals("No")) {// Thoat nhap
break;
}
if (!accountTinDung.isValidAccountNumber(stk)) {
System.out.println("So tai khoan khong hop le. Vui long nhap lai hoac nhap 'No' de thoat");
} else {
// Tai khoan chua ton tai
if (!super.isAccountExisted(Asm03.CUSTOMER_ID, stk)) {
double balance = nhapBalance();
// Them so du vao tai khoan
accountTinDung.setAccountNumber(stk);
accountTinDung.setBalance(balance);
super.addAccount(Asm03.CUSTOMER_ID, accountTinDung);
accountTinDung.setSaving(false); // Danh dau la tai khoang Loans
// Them giao dich vao lich su
Transaction transaction = new Transaction(stk, balance, Utils.getDateTime(), true);
accountTinDung.addTransactions(transaction);
System.out.println("Da them tai khoan thanh cong");
break; // Thoat khoi vong lap khi thanh cong
}
else { // So tai khoan da ton tai => Yeu cau nhap lai
System.out.println("So tai khoan da ton tai. Vui long nhap lai hoac nhap 'No' de thoat");
}
}
}
catch (Exception e) {
System.out.println("So tai khoan khong hop le. Vui long nhap lai hoac nhap 'No' de thoat");
sc.next();
}
} while(!accountTinDung.isValidAccountNumber(stk) || this.isAccountExisted(Asm03.CUSTOMER_ID, stk));
}
public void rutTien() {
Account account = new Account();
boolean flagStk;
String stk;
do{
try {
flagStk = true;
System.out.print("Nhap ma STK gom 6 chu so: ");
stk = sc.nextLine();
if (stk.equals("No")) {// Thoat nhap
break;
}
if (!account.isValidAccountNumber(stk)) {
System.out.println("So tai khoan khong hop le. Vui long nhap lai hoac nhap 'No' de thoat");
flagStk = false;
}
else {
if (this.isAccountExisted(Asm03.CUSTOMER_ID, stk)) {
// Nhap so du
double withdrawAmount;
boolean flagAmount; // Trang thai cua so tien nhap
do {
try {
System.out.print("Nhap so tien ban muon rut: ");
withdrawAmount = sc.nextDouble();
sc.nextLine();
flagAmount = true; // Nhap thanh cong
if (withdrawAmount == -1){// Thoat nhap so tien
break;
}
// So tien khong hop le
if (!withdraw(Asm03.CUSTOMER_ID, stk, withdrawAmount)) {
System.out.println("GIAO DICH THAT BAI");
break;
}
// Luu giao dich rut tien vao lich su
Account transactingAccount = getAccountByAccountNumber(stk);
Transaction transaction = new Transaction(stk, withdrawAmount * -1, Utils.getDateTime(), true);
transactingAccount.addTransactions(transaction);
} catch (InputMismatchException e) {
System.out.println("So tien rut khong hop le. Vui long nhap lai hoac nhap '-1' de thoat");
sc.next();
flagAmount = false;
}
} while(!flagAmount);
}
else { // So tai khoan da ton tai => Yeu cau nhap lai
System.out.println("So tai khoan khong ton tai. Vui long nhap lai hoac nhap 'No' de thoat");
flagStk = false;
}
}
}
catch (InputMismatchException e) {
System.out.println("So tai khoan khong hop le. Vui long nhap lai hoac nhap 'No' de thoat");
flagStk = false;
}
} while(!flagStk);
}
public void lichSuGiaoDich() {
for (Customer customer : getCustomers()) {// Duyet tung khach hang va hien thi thong tin
customer.displayInformation();
for (Account account : customer.getAccounts()) {
// Voi moi account cua tung khach hang in ra lich su giao dich
for (Transaction transaction : account.getTransactions()) {
transaction.displayTransaction();
}
}
}
}
}
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Queue.Test.Models;
namespace Queue.RabbitMQ.Test;
[TestFixture]
public class SetupTests
{
protected IConfiguration Configuration;
protected string QueueConnectionString;
[SetUp]
public void Setup()
{
Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
QueueConnectionString = Configuration.GetConnectionString("MyConnectionString");
}
[Test]
public void ConfigureServices_RegistersMessageHandlers()
{
// Arrange
var services = new ServiceCollection();
// Mock ILogger
var loggerMock = new Mock<ILogger<RabbitMqMessageQueue<MediaMessage>>>();
services.AddSingleton(loggerMock.Object);
// Act
services.ConfigureRabbitMq(QueueConnectionString);
// Build the service provider
var serviceProvider = services.BuildServiceProvider();
// Assert
var handler = serviceProvider.GetService<IMessageHandler<MediaMessage>>();
Assert.That(handler, Is.Not.Null);
var queue = serviceProvider.GetService<IMessageQueue<MediaMessage>>();
Assert.That(queue, Is.Not.Null);
}
[Test]
public void ConfigureServices_RegistersHostedServices()
{
// Arrange
var services = new ServiceCollection();
// Mock ILogger for each type dynamically
services.AddLogging();
// Act
services.ConfigureRabbitMq(QueueConnectionString);
// Build the service provider
var serviceProvider = services.BuildServiceProvider();
// Assert
var hostedServices = serviceProvider.GetServices<IHostedService>();
Assert.That(hostedServices, Is.Not.Empty);
Assert.That(hostedServices.Any(service => service.GetType().Name.Contains("MessageQueueHostedService")), Is.True);
}
}
|
package fhir_r3r4
import "../ResourceBase.wstl"
// Description: Maps the common fields in FHIR STU3 and FHIR R4
//
// Argument(s):
// questionnaire : FHIR Questionnaire resource
//
// Output(s):
// FHIR Questionnaire Resource
//
def QuestionnaireBase(questionnaire) {
resourcebase::ResourceBase(questionnaire)
url: questionnaire.url
identifier: questionnaire.identifier
version: questionnaire.version
name: questionnaire.name
title: questionnaire.title
date: questionnaire.date
publisher: questionnaire.publisher
contact: questionnaire.contact
description: questionnaire.description
useContext: questionnaire.useContext
jurisdiction: questionnaire.jurisdiction
purpose: questionnaire.purpose
copyright: questionnaire.copyright
approvalDate: questionnaire.approvalDate
lastReviewDate: questionnaire.lastReviewDate
effectivePeriod: questionnaire.effectivePeriod
code: questionnaire.code
}
// Description: Converts a FHIR STU3 Questionnaire resource to FHIR R4 Questionnaire resource.
//
// Argument(s):
// questionnaire : FHIR STU3 Questionnaire resource https://www.hl7.org/fhir/stu3/questionnaire.html
//
// Output(s):
// FHIR R4 Questionnaire Resource https://www.hl7.org/fhir/r4/questionnaire.html
//
def R3QuestionnaireToR4(questionnaire) {
QuestionnaireBase(questionnaire)
contained: datatypes::R3ResourceToR4(questionnaire.contained[])
derivedFrom: extension::fetchCanonicalArray("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.derivedFrom", questionnaire.extension)
status: questionnaire.status
experimental: questionnaire.experimental
subjectType: questionnaire.subjectType
item: R3Questionnaire_ItemToR4(questionnaire.item[])
}
// Description: Converts a FHIR R4 Questionnaire resource to FHIR STU3 Questionnaire resource.
//
// Argument(s):
// questionnaire : FHIR R4 Questionnaire resource https://www.hl7.org/fhir/r4/questionnaire.html
//
// Output(s):
// FHIR STU3 Questionnaire Resource https://www.hl7.org/fhir/stu3/questionnaire.html
//
def R4QuestionnaireToR3(questionnaire) {
QuestionnaireBase(questionnaire)
contained: datatypes::R4ResourceToR3(questionnaire.contained[])
status: questionnaire.status
experimental: questionnaire.experimental
subjectType: questionnaire.subjectType
item: R4Questionnaire_ItemToR3(questionnaire.item[])
extension[]: extension::BuildCanonicalExtension("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.derivedFrom", questionnaire.derivedFrom[])
}
// Description: Converts a FHIR STU3 Questionnaire.item to FHIR R4 Questionnaire.item.
//
// Argument(s):
// data : FHIR STU3 Questionnaire.item https://www.hl7.org/fhir/stu3/questionnaire-definitions.html#Questionnaire.item
//
// Output(s):
// FHIR R4 Questionnaire.item https://www.hl7.org/fhir/r4/questionnaire-definitions.html#Questionnaire.item
//
def R3Questionnaire_ItemToR4(required data) {
linkId: data.linkId
definition: data.definition
code: data.code
prefix: data.prefix
text: data.text
type: data.type
enableWhen: R3Questionnaire_Item_EnableWhenToR4(data.enableWhen[])
enableBehavior: extension::fetchCode("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.enableBehavior", data.extension)
'required': data.'required'
repeats: data.repeats
readOnly: data.readOnly
maxLength: data.maxLength
answerValueSet: datatypes::ReferenceToCanonical(data.options)
answerOption: R3Questionnaire_Item_AnswerOptionToR4(data.'option'[])
var initialObject.valueBoolean: data.initialBoolean
var initialObject.valueDecimal: data.initialDecimal
var initialObject.valueInteger: data.initialInteger
var initialObject.valueDate: data.initialDate
var initialObject.valueDateTime: data.initialDateTime
var initialObject.valueTime: data.initialTime
var initialObject.valueString: data.initialString
var initialObject.valueUri: data.initialUri
var initialObject.valueAttachment: data.initialAttachment
var initialObject.valueCoding: data.initialCoding
var initialObject.valueQuantity: data.initialQuantity
var initialObject.valueReference: datatypes::R3ReferenceToR4(data.initialReference)
initial[]: initialObject
item: R3Questionnaire_ItemToR4(data.item[])
}
// Description: Converts a FHIR R4 Questionnaire.item to FHIR STU3 Questionnaire.item.
//
// Argument(s):
// data : FHIR R4 Questionnaire.item https://www.hl7.org/fhir/r4/questionnaire-definitions.html#Questionnaire.item
//
// Output(s):
// FHIR STU3 Questionnaire.item https://www.hl7.org/fhir/stu3/questionnaire-definitions.html#Questionnaire.item
//
def R4Questionnaire_ItemToR3(data) {
linkId: data.linkId
definition: data.definition
code: data.code
prefix: data.prefix
text: data.text
type: data.type
enableWhen: R4Questionnaire_Item_EnableWhenToR3(data.enableWhen[])
'required': data.'required'
repeats: data.repeats
readOnly: data.readOnly
maxLength: data.maxLength
options: datatypes::CanonicalToReference(data.answerValueSet)
'option': R4Questionnaire_Item_AnswerOptionToR3(data.answerOption[])
initialBoolean: data.initial[0].valueBoolean
initialDecimal: data.initial[0].valueDecimal
initialInteger: data.initial[0].valueInteger
initialDate: data.initial[0].valueDate
initialDateTime: data.initial[0].valueDateTime
initialTime: data.initial[0].valueTime
initialString: data.initial[0].valueString
initialUri: data.initial[0].valueUri
initialAttachment: data.initial[0].valueAttachment
initialCoding: data.initial[0].valueCoding
initialQuantity: data.initial[0].valueQuantity
initialReference: datatypes::R4ReferenceToR3(data.initial[0].valueReference)
item: data.item
extension[]: extension::BuildCodeExtension("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.enableBehavior", data.enableBehavior)
}
// Description: Converts a FHIR STU3 Questionnaire.item.enableWhen to FHIR R4 Questionnaire.item.enableWhen.
//
// Argument(s):
// data : FHIR STU3 Questionnaire.item.enableWhen https://www.hl7.org/fhir/stu3/questionnaire-definitions.html#Questionnaire.item.enableWhen
//
// Output(s):
// FHIR R4 Questionnaire.item.enableWhen https://www.hl7.org/fhir/r4/questionnaire-definitions.html#Questionnaire.item.enableWhen
//
def R3Questionnaire_Item_EnableWhenToR4(required data) {
question: data.question
operator: extension::fetchCode("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.enableWhen.operator", data.extension)
operator: utilities::defaultIfNull($this.operator, "exists")
answerBoolean: data.answerBoolean
answerDecimal: data.answerDecimal
answerInteger: data.answerInteger
answerDate: data.answerDate
answerDateTime: data.answerDateTime
answerTime: data.answerTime
answerString: data.answerString
answerCoding: data.answerCoding
answerQuantity: data.answerQuantity
answerReference: datatypes::R3ReferenceToR4(data.answerReference)
// place-holder for 1..1 cardinality
answerString: if !fields($this)[where matchesRegex($, "^answer.*")] then "unknown";
extension[]: extension::BuildBooleanExtension("https://www.hl7.org/fhir/STU3/questionnaire-definitions.html#Questionnaire.item.enableWhen.hasAnswer", data.hasAnswer)
extension[]: extension::BuildUriExtension("https://www.hl7.org/fhir/STU3/questionnaire-definitions.html#Questionnaire.item.enableWhen.answerUri", data.answerUri)
extension[]: extension::BuildAttachmentExtension("https://www.hl7.org/fhir/STU3/questionnaire-definitions.html#Questionnaire.item.enableWhen.answerAttachment", data.answerAttachment)
}
// Description: Converts a FHIR R4 Questionnaire.item.enableWhen to FHIR STU3 Questionnaire.item.enableWhen.
//
// Argument(s):
// data : FHIR R4 Questionnaire.item.enableWhen https://www.hl7.org/fhir/r4/questionnaire-definitions.html#Questionnaire.item.enableWhen
//
// Output(s):
// FHIR STU3 Questionnaire.item.enableWhen https://www.hl7.org/fhir/stu3/questionnaire-definitions.html#Questionnaire.item.enableWhen
//
def R4Questionnaire_Item_EnableWhenToR3(data) {
question: data.question
hasAnswer: extension::fetchBoolean("https://www.hl7.org/fhir/STU3/questionnaire-definitions.html#Questionnaire.item.enableWhen.hasAnswer", data.extension)
answerBoolean: data.answerBoolean
answerDecimal: data.answerDecimal
answerInteger: data.answerInteger
answerDate: data.answerDate
answerDateTime: data.answerDateTime
answerTime: data.answerTime
answerString: data.answerString
answerUri: extension::fetchUri("https://www.hl7.org/fhir/STU3/questionnaire-definitions.html#Questionnaire.item.enableWhen.answerUri", data.extension)
answerAttachment: extension::fetchAttachment("https://www.hl7.org/fhir/STU3/questionnaire-definitions.html#Questionnaire.item.enableWhen.answerAttachment", data.extension)
answerCoding: data.answerCoding
answerQuantity: data.answerQuantity
answerReference: datatypes::R4ReferenceToR3(data.answerReference)
extension[]: extension::BuildCodeExtension("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.enableWhen.operator", data.operator)
}
// Description: Converts a FHIR STU3 Questionnaire.item.answerOption to FHIR R4 Questionnaire.item.answerOption.
//
// Argument(s):
// data : FHIR STU3 Questionnaire.item.answerOption https://www.hl7.org/fhir/stu3/questionnaire-definitions.html#Questionnaire.item.answerOption
//
// Output(s):
// FHIR R4 Questionnaire.item.answerOption https://www.hl7.org/fhir/r4/questionnaire-definitions.html#Questionnaire.item.answerOption
//
def R3Questionnaire_Item_AnswerOptionToR4(data) {
valueInteger: data.valueInteger
valueDate: data.valueDate
valueTime: data.valueTime
valueString: data.valueString
valueCoding: data.valueCoding
valueReference: extension::fetchReference("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.answerOption.valueReference", data.extension)
initialSelected: extension::fetchBoolean("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.answerOption.initialSelected", data.extension)
}
// Description: Converts a FHIR R4 Questionnaire.item.answerOption to FHIR STU3 Questionnaire.item.answerOption.
//
// Argument(s):
// data : FHIR R4 Questionnaire.item.answerOption https://www.hl7.org/fhir/r4/questionnaire-definitions.html#Questionnaire.item.answerOption
//
// Output(s):
// FHIR STU3 Questionnaire.item.answerOption https://www.hl7.org/fhir/stu3/questionnaire-definitions.html#Questionnaire.item.answerOption
//
def R4Questionnaire_Item_AnswerOptionToR3(data) {
valueInteger: data.valueInteger
valueDate: data.valueDate
valueTime: data.valueTime
valueString: data.valueString
valueCoding: data.valueCoding
extension[]: extension::BuildReferenceExtension("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.answerOption.valueReference", data.valueReference)
extension[]: extension::BuildBooleanExtension("https://www.hl7.org/fhir/R4/questionnaire-definitions.html#Questionnaire.item.answerOption.initialSelected", data.initialSelected)
}
|
package main
import (
"fmt"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var titleCaser cases.Caser = cases.Title(language.English)
templ base() {
<html>
<head>
<title>Issue Tracker</title>
<link href="/static/tailwind.css" rel="stylesheet"/>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
</head>
<body>
@header()
<main class="w-1/2 mx-auto">
{ children... }
</main>
</body>
</html>
}
func generateIssueLabelChipStyle(label string) string {
style := "p-1 text-sm rounded-full border"
switch label {
case "improvement":
style = style + " border-teal-600/30 bg-teal-600/15 text-teal-600"
case "bug":
style = style + " border-rose-600/30 bg-rose-600/15 text-rose-600"
}
return style
}
func generateIssueLabelIndicatorStyle(label string) string {
style := "size-4 rounded-full"
switch label {
case "improvement":
style = style + " bg-teal-600/30"
case "bug":
style = style + " bg-rose-600/30"
}
return style
}
templ index(issues []Issue) {
@base() {
<div class="flex justify-between items-center py-2">
<p class="font-bold">Issues</p>
@linkButton("Create Issue", templ.Attributes{"href": "/issue/new"})
</div>
<ul class="bg-slate-300 list-none divide-y">
for i:= len(issues)-1; i >= 0; i-- {
<li class="p-2">
<p>
<span>[ { string(issues[i].Status) } ]</span>
<a href={ templ.URL(fmt.Sprintf("/issue/%s", issues[i].Id)) } class="font-semibold">{ issues[i].Title }</a>
for _, label := range strings.Split(issues[i].Labels, ",") {
<span class={ generateIssueLabelChipStyle(label) }>
{ string(label) }
</span>
}
</p>
<p class="italic">by { issues[i].Creator.Name } - { issues[i].CreatedAt.Format("02/01/2006 15:04") }</p>
</li>
}
</ul>
}
}
templ button(text string, attrs templ.Attributes) {
<button class="px-4 py-2 rounded-md bg-slate-700 hover:bg-slate-600 text-white" { attrs... }>{ text }</button>
}
templ linkButton(text string, attrs templ.Attributes) {
<a class="px-4 py-2 rounded-md bg-slate-700 hover:bg-slate-600 text-white" { attrs... }>{ text }</a>
}
templ header() {
<a href="/">
<header class="bg-slate-700 w-full text-white font-bold py-4 text-center">Issue Tracker</header>
</a>
}
templ AddIssue() {
@base() {
<form hx-post="/api/issue" class="flex flex-col gap-2">
@textInput("title")
@textAreaInput("content")
<div class="flex flex-col">
<legend>Labels</legend>
for _,opt := range issueLabels {
<div class="flex gap-1">
<input type="checkbox" id={ opt } name="labels" value={ opt }/>
<label class="flex items-center gap-1" for={ opt }>
<span class={ generateIssueLabelIndicatorStyle(opt) }></span>
<span>{ titleCaser.String(opt) }</span>
</label>
</div>
}
</div>
@button("Create", templ.Attributes{"type": "submit"})
</form>
}
}
templ IssueDetail(issue Issue) {
@base() {
<div>
<p class="font-bold">{ issue.Title }</p>
<p>{ issue.Content }</p>
if issue.Status != "closed" {
@button("Close", templ.Attributes{"hx-put": "/api/issue", "hx-trigger": "click", "hx-vals": fmt.Sprintf(`{"Id":
"%s", "Status": "closed"}`, issue.Id)})
}
</div>
}
}
templ textInput(name string) {
<div class="flex flex-col">
<label for={ name }>{ titleCaser.String(name) }</label>
<input class="border rounded-md" id={ name } name={ name }/>
</div>
}
templ textAreaInput(name string) {
<div class="flex flex-col">
<label for={ name }>{ titleCaser.String(name) }</label>
<textarea class="border rounded-md" id={ name } name={ name }></textarea>
</div>
}
templ selectInput(name string, opts []string) {
<div class="flex flex-col">
<label for={ name }>{ titleCaser.String(name) }</label>
<select class="border rounded-md" id={ name } name={ name }>
for _,opt := range opts {
<option value={ opt }>{ opt }</option>
}
</select>
</div>
}
|
<h1>Edit <%= resource_name.to_s.humanize %></h1>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= render "devise/shared/error_messages", resource: resource %>
<div class="field mb-3">
<%= f.email_field :email, autofocus: true, autocomplete: "email", class: "form-control", placeholder: "Email"%>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<div class="field mb-3">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, autocomplete: "new-password", class: "form-control", placeholder: "Password" %>
<% if @minimum_password_length %>
<em><%= @minimum_password_length %> characters minimum</em>
<% end %>
</div>
<div class="field mb-3">
<%= f.password_field :password_confirmation, autocomplete: "new-password", class: "form-control", placeholder: "Confirm Password" %>
</div>
<div class="field mb-3">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password, autocomplete: "current-password", class: "form-control", placeholder: "Current Password" %>
</div>
<div class="actions">
<%= f.submit "Update", class: "btn btn-primary" %>
</div>
<% end %>
<br/>
<div class="card">
<div class="card-header">
<h3>Cancel my account</h3>
</div>
<div class="card-body">
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { turbo_method: :delete, turbo_confirm: "Are you sure?" }, class: "btn btn-danger" %></p>
</div>
</div>
<%= link_to "Back", :back %>
|
package com.jd.bluedragon.core.base;
import com.jd.bluedragon.distribution.reverse.domain.LocalClaimInfoRespDTO;
import com.jd.bluedragon.utils.BusinessHelper;
import com.jd.bluedragon.utils.JsonHelper;
import com.jd.uad.api.claim.facade.claim.ClaimListByClueInfoQueryAPI;
import com.jd.uad.api.claim.facade.claim.resp.ClaimInfoRespDTO;
import com.jd.uad.api.core.APIResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
@Service("obcsManager")
public class OBCSManagerImpl implements OBCSManager{
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private ClaimListByClueInfoQueryAPI claimListByClueInfoQueryAPI;
/**
* 获取理赔信息
*
* 整合多个理赔单
*
* 多个理赔单 按完成 > 理赔中 >无理赔 优先整合
理赔金额计算理赔完成状态的理赔单加总
结算主体 和商家事业部ID 均为相同数据 所以默认取一条就可以
* @param clueType 线索类型 1-青龙运单号,2-盘亏单号,3-大件运单号,4- TC转运单(中小件),7- ECLP理赔申请单号
* @param clueValue 线索值
* @return
*/
@Override
public LocalClaimInfoRespDTO getClaimListByClueInfo(int clueType, String clueValue){
LocalClaimInfoRespDTO respDTO = new LocalClaimInfoRespDTO();
try{
APIResultDTO<List<ClaimInfoRespDTO>> apiResultDTO = claimListByClueInfoQueryAPI.getClaimListByClueInfo(clueType,clueValue);
if(log.isInfoEnabled()){
log.info("claimListByClueInfoQueryAPI.getClaimListByClueInfo , req:{},{},resp:{}",clueType,clueValue, JsonHelper.toJson(apiResultDTO));
}
//理赔金额
BigDecimal paymentRealMoney = new BigDecimal(0);
String statusDesc = LocalClaimInfoRespDTO.LP_STATUS_NONE;
//多个理赔单 按完成 > 理赔中 >无理赔 优先整合
//理赔金额计算理赔完成状态的理赔单加总
//结算主体 均为相同数据 所以默认取一条就可以
if(apiResultDTO.isSuccess()){
List<ClaimInfoRespDTO> list = apiResultDTO.getResult();
if(list!=null && list.size()>0){
for(ClaimInfoRespDTO claimInfoRespDTO : list){
String tempStatus = BusinessHelper.getLPStatus(claimInfoRespDTO.getStatus());
if(LocalClaimInfoRespDTO.LP_STATUS_DONE.equals(tempStatus)){
paymentRealMoney = paymentRealMoney.add(claimInfoRespDTO.getPaymentRealMoney());
statusDesc = tempStatus;
//结算主体
respDTO.setSettleSubjectName(claimInfoRespDTO.getSettleSubjectName());
respDTO.setSettleSubjectCode(claimInfoRespDTO.getSettleSubjectCode());
//物权
respDTO.setGoodOwner(claimInfoRespDTO.getGoodOwner());
respDTO.setGoodOwnerName(claimInfoRespDTO.getGoodOwnerName());
}else if(LocalClaimInfoRespDTO.LP_STATUS_DOING.equals(tempStatus)){
if(LocalClaimInfoRespDTO.LP_STATUS_NONE.equals(statusDesc)){
statusDesc = tempStatus;
}
}
}
}
respDTO.setPaymentRealMoney(paymentRealMoney);
respDTO.setStatusDesc(statusDesc);
}else{
log.warn("理赔接口失败 {} 原因:{}",clueValue,apiResultDTO.getMessage());
return null;
}
}catch (Exception e){
log.error("理赔接口异常 {} ",clueValue,e);
return null;
}
return respDTO;
}
}
|
package core
import (
"bytes"
"fmt"
"os"
"path"
"server/global"
"github.com/sirupsen/logrus"
)
const (
red = 31
yellow = 32
blue = 36
gray = 37
)
type LogFormatter struct{}
func (t *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
// 根据level级别展示颜色
var levelColor int
switch entry.Level {
case logrus.DebugLevel, logrus.TraceLevel:
levelColor = gray
case logrus.WarnLevel:
levelColor = yellow
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
levelColor = red
default:
levelColor = blue
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
log := global.Config.Logger
// 自定义日期格式
timestamp := entry.Time.Format("2006-01-02 15:04:05")
// 是否有信息
if entry.HasCaller() {
// 自定义文件路径
funcVal := entry.Caller.Function
fileVal := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)
// 自定义输出格式
fmt.Fprintf(b, "%s[%s] \x1b[%dm[%s]\x1b[0m %s %s %s \n", log.Prefix, timestamp, levelColor, entry.Level, fileVal, funcVal, entry.Message)
} else {
fmt.Fprintf(b, "%s[%s] \x1b[%dm[%s]\x1b[0m %s \n", log.Prefix, timestamp, levelColor, entry.Level, entry.Message)
}
return b.Bytes(), nil
}
func InitLogger() *logrus.Logger {
mLog := logrus.New() //新建实例
mLog.SetOutput(os.Stdout) //输出类型
mLog.SetReportCaller(global.Config.Logger.ShowLine) //是否开启返回函数名和行号
mLog.SetFormatter((&LogFormatter{})) //设置自定义的Formatter
level, err := logrus.ParseLevel(string(global.Config.Logger.Level))
if err != nil {
level = logrus.InfoLevel
}
mLog.SetLevel(level) //设置最低的Level
InitDefaultLogger()
return mLog
}
func InitDefaultLogger() {
// 全局log
logrus.SetOutput(os.Stdout)
logrus.SetReportCaller(global.Config.Logger.ShowLine)
logrus.SetFormatter(&LogFormatter{})
level, err := logrus.ParseLevel(string(global.Config.Logger.Level))
if err != nil {
level = logrus.InfoLevel
}
logrus.SetLevel(level)
}
|
import 'dart:convert';
import 'package:equatable/equatable.dart';
class BlogModel extends Equatable {
final String? id;
final String? title;
final String? cover;
final String? time;
final String? replies;
final String? content;
final String? username;
final String? subject;
final dynamic tags;
const BlogModel({
this.id,
this.title,
this.cover,
this.time,
this.replies,
this.content,
this.username,
this.subject,
this.tags,
});
factory BlogModel.fromMap(Map<String, dynamic> data) => BlogModel(
id: data['id'] as String?,
title: data['title'] as String?,
cover: data['cover'] as String?,
time: data['time'] as String?,
replies: data['replies'] as String?,
content: data['content'] as String?,
username: data['username'] as String?,
subject: data['subject'] as String?,
tags: data['tags'] as dynamic,
);
Map<String, dynamic> toMap() => {
'id': id,
'title': title,
'cover': cover,
'time': time,
'replies': replies,
'content': content,
'username': username,
'subject': subject,
'tags': tags,
};
/// `dart:convert`
///
/// Parses the string and returns the resulting Json object as [BlogModel].
factory BlogModel.fromJson(String data) {
return BlogModel.fromMap(json.decode(data) as Map<String, dynamic>);
}
/// `dart:convert`
///
/// Converts [BlogModel] to a JSON string.
String toJson() => json.encode(toMap());
BlogModel copyWith({
String? id,
String? title,
String? cover,
String? time,
String? replies,
String? content,
String? username,
String? subject,
dynamic tags,
}) {
return BlogModel(
id: id ?? this.id,
title: title ?? this.title,
cover: cover ?? this.cover,
time: time ?? this.time,
replies: replies ?? this.replies,
content: content ?? this.content,
username: username ?? this.username,
subject: subject ?? this.subject,
tags: tags ?? this.tags,
);
}
@override
bool get stringify => true;
@override
List<Object?> get props {
return [
id,
title,
cover,
time,
replies,
content,
username,
subject,
tags,
];
}
}
|
import 'package:flutter_test/flutter_test.dart';
class TestUtils {
/// Writes a [value] to a [TextFormField] and verifies the text has been written
static Future<void> writeTextAndVerify(
{required String value,
required WidgetTester tester,
required Finder textFormField}) async {
await tester.tap(textFormField); // acquire focus
await tester.enterText(textFormField, value); // enter text
await tester.pumpAndSettle();
expect(find.text(value), findsOneWidget); // verify text has been written
}
}
|
# Classifier Chain basado en Label Powerset para la clasificación Multi-Etiqueta
Uno de los métodos más utilizados para abordar la clasificación multi-etiqueta es el
enfoque conocido como "Classifier Chain" o "cadena de clasificadores". Este metodo se
basa en encadenar múltiples clasificadores, donde la salida de un clasificador se utiliza
como entrada para el siguiente, permitiendo así manejar la asignación de múltiples
etiquetas a una instancia. Sin embargo, a pesar de su eficacia, el uso de cadenas de
clasificadores a menudo conlleva un alto coste computacional.
En este trabajo, proponemos una modificación de este enfoque que incorpora el concepto de
"powersets" o conjuntos de potencia. En lugar de construir una cadena de
clasificadores utilizando una sola etiqueta en cada paso, consideramos eslabones más
complejos compuestos por los powersets de un número reducido de etiquetas. Esta
modificación no solo simplifica el número de clasificadores necesarios, sino que
también puede mejorar la eficiencia computacional en problemas con un gran número
de etiquetas.
# Algoritmo implementado.
El proceso comienza con la aplicación del algoritmo de clustering Balanced K-Means a
las etiquetas del conjunto de datos de entrenamiento. Este algoritmo tiene como
objetivo dividir las etiquetas en grupos o clusters de manera equilibrada con el objetivo
de que las etiquetas se agrupen en función de sus características y relaciones,
buscando una mayor eficiencia en la clasificación. El número de clusters se determina
automáticamente, para formar N grupos de 3 miembros como máximo.
_Entrenamiento del modelo_:
Una vez que se ha realizado el clustering, se procede a entrenar la cadena de
clasificadores. Cada cluster de etiquetas se considera un problema de clasificación
independiente, asi que para cada cluster se entrena un clasificador utilizando un
enfoque basado en Label Powerset. El modelo de Label Powerset se utiliza para
transformar el problema de clasificación multi-etiqueta en un problema de clasificación
multi-clase, donde cada combinación única de etiquetas se trata como una clase
separada. Para nuestro caso el clasificador elegido al que aplicarle Label Powerset ha
sido Random Forest.
Cada clasificador de la lista se entrena con el conjunto de datos de características
original, concatenándole a dicho conjunto las predicciones dadas por los clasificadores
anteriores, siguiendo así el concepto principal de Classifier Chain. Esto permite que el
siguiente clasificador en la cadena tenga en cuenta tanto las predicciones previas como
las características originales para mejorar la precisión de la clasificación.
_Fase de predicción_:
Finalmente, cuando se desea hacer predicciones para un nuevo conjunto de datos, el
algoritmo utiliza la cadena completa de clasificadores para generar predicciones multietiqueta. Cada clasificador en la cadena aborda un subconjunto específico de
etiquetas, y las predicciones de todos los clasificadores se combinan para obtener la
etiqueta final para cada instancia de datos.
|
import React, { useState } from "react";
import CardComponent from "../../CardComponent";
import WeeklyScreenModal from "../WeeklyScreen";
import { Data, DataKey, DataValue } from "./styles.js";
const WeeklyCard = () => {
const weeklySummary = {
totalServices: 48,
comparison: "+5%",
busiestDay: "Quinta-feira",
occupancyRate: "85%",
customerSatisfaction: "92%",
};
const [showWeekly, setShowWeekly] = useState(false);
return (
<>
<WeeklyScreenModal
isOpen={showWeekly}
onClose={() => setShowWeekly(false)}
/>
<CardComponent
headerContent="Resumo Semanal"
buttonText="Detalhes"
onButtonClick={() => setShowWeekly(true)}
>
<Data>
<DataKey>Serviços na Semana:</DataKey>
<DataValue>{weeklySummary.totalServices}</DataValue>
</Data>
<Data>
<DataKey>Comparativo Semanal:</DataKey>
<DataValue>{weeklySummary.comparison}</DataValue>
</Data>
<Data>
<DataKey>Dia Mais Movimentado:</DataKey>
<DataValue>{weeklySummary.busiestDay}</DataValue>
</Data>
<Data>
<DataKey>Taxa de Ocupação:</DataKey>
<DataValue>{weeklySummary.occupancyRate}</DataValue>
</Data>
</CardComponent>
</>
);
};
export default WeeklyCard;
|
import user from 'data/user';
import Profile from './Profile/Profile';
import data from 'data/data';
import { Statistics } from './Statistics/Statistics';
import friends from 'data/friends';
import { FriendList } from './FriendList/FriendList';
import transactions from 'data/transactions';
import { TransactionHistory } from './TransactionHistory/TransactionHistory';
export default function App() {
return (
<div>
<Profile
username={user.username}
tag={user.tag}
location={user.location}
avatar={user.avatar}
stats={user.stats}
/>
<Statistics title="Upload stats" stats={data} />
<FriendList friends={friends} />
<TransactionHistory items={transactions} />;
</div>
);
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
public class ReadApi extends Thread {
private String year; // Το έτος για το οποίο θα γίνουν οι κλήσεις
private String API_URL; // Το url στο οποίο θα γίνει η κλήση
private int k; // Ο αριθμός των κλήσεων
private int averageWordsInYear; // Ο μέσος όρος λέξεων που βρέθηκαν, ανα κλήση
private int totalWords = 0; // Το πλήθος των λέξεων που βρέθηκαν
private Map<String, Integer> commonWords = new HashMap<String, Integer>(); // Οι λέξεις που βρέθηκαν
public ReadApi(String year, int k) {
this.year = year;
this.k = k;
API_URL = "http://numbersapi.com/" + year + "/year"; // Δημιουργία του url, με βάση το έτος
}
public Map<String, Integer> getCommonWords() {
return commonWords;
}
public int getAverageWordsInYear() {
return averageWordsInYear;
}
/**
* Εκκίνηση thread
*/
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " started. Επεξεργασία " + k + " κλήσεων");
// Κάνει k κλήσεις και μετράει τις λέξεις για την κάθε μία
for(int i=0;i<k;i++) {
countWords(loadDataFromUrl());
}
// Υπολογισμός του μέσου όρου
calcAverageWordsInYear();
System.out.println(Thread.currentThread().getName() + " finished");
}
/**
* This method loads the data from url
* Source: 1η εργασία ΠΛΗ47 (2021-2022), Θέμα 3
*
* @return the data as String
*/
private String loadDataFromUrl() {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(API_URL);
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
result.append(" ");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
/**
* Παίρνει σε array τις λέξεις που βρίσκονται στο κείμενο
*
* @param text
* @return
*/
private String[] getWordsInText(String text) {
// Χρήση regex, για να σπάσει το κείμενο σε λέξεις
return Pattern.compile("\\b(?:\\w|-)+\\b")
.matcher(text)
.results()
.map(MatchResult::group)
.toArray(String[]::new);
}
/**
* Υπολογισμός μέσου όρου λέξεων στο έτος, για k κλήσεις
*/
private void calcAverageWordsInYear() {
averageWordsInYear = totalWords / k;
}
/**
* Μέτρηση λέξεων (μέχρι τις χαρακτήρες) στο κείμενο και προσθήκη τους σε hashmap
*
* @param text
*/
private void countWords(String text) {
String[] words = getWordsInText(text);
for(String word : words) {
word = word.toLowerCase();
if(word.length()<4) {
// Αν υπάρχει ήδη η λέξη, αυξάνει τον μετρητή της
if(commonWords.containsKey(word)) {
int sum = commonWords.get(word) + 1;
commonWords.put(word, sum);
} else { // Αλλιώς της προσθέτει σαν καινούργια
commonWords.put(word, 1);
}
}
}
// Πρόσθεση του πλήθους λέξεων στο έτος
totalWords += words.length;
}
}
|
/* eslint-disable jsx-a11y/label-has-associated-control */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import triviaLogo from '../trivia.png'
import { IoSettings } from 'react-icons/io5';
import { FaPlay } from 'react-icons/fa';
import { saveToken } from '../localStorage';
import { endGame, loginState } from '../redux/actions';
class Login extends Component {
state = {
email: '',
name: '',
disable: true,
};
componentDidMount() {
const { dispatch } = this.props;
dispatch(endGame());
}
onInputChange = ({ target: { name, value } }) => {
this.setState({ [name]: value }, () => this.validate());
};
validate = () => {
const { email, name } = this.state;
const validateEmail = email.length > 0;
const validateName = name.length > 0;
const validates = validateEmail && validateName;
if (validates) {
return this.setState({ disable: false });
} this.setState({ disable: true });
};
clickSetting = () => {
const { history } = this.props;
history.push('/settings');
};
onClickBtn = async () => {
const { history, dispatch } = this.props;
const url = 'https://opentdb.com/api_token.php?command=request';
const reponse = await fetch(url);
const result = await reponse.json();
saveToken(result.token);
await dispatch(loginState(this.state));
history.push('/game');
};
render() {
const { disable } = this.state;
return (
<div className="Login">
<img src={ triviaLogo } alt='trivia-logo' className="LoginIcon" />
<aside className="LoginAside">
<form className="LoginForms" autoComplete="off">
<label htmlFor="settings" className="LoginSettingsLabel">
<IoSettings className="LoginSettings" />
<button
data-testid="btn-settings"
type="button"
// disabled={ disable }
id="settings"
onClick={ this.clickSetting }
className="LoginButtonSettings"
>
Settings
</button>
</label>
<label htmlFor="email">
<h3>EMAIL</h3>
<input
data-testid="input-gravatar-email"
name="email"
type="text"
id="email"
onChange={ this.onInputChange }
className="LoginInput"
placeholder="test@gmail.com"
/>
</label>
<label htmlFor="name">
<h3>NAME</h3>
<input
data-testid="input-player-name"
name="name"
type="text"
id="name"
onChange={ this.onInputChange }
className="LoginInput"
placeholder="Your name"
/>
</label>
<button
data-testid="btn-play"
type="button"
onClick={ this.onClickBtn }
disabled={ disable }
className="LoginButtonPlay"
>
PLAY
<FaPlay style={ { paddingLeft: '10px' } } />
</button>
</form>
</aside>
</div>
);
}
}
Login.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}),
}.isRequired;
export default connect(null)(Login);
|
package com.example.managproje.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.WindowManager
import android.widget.Toast
import com.example.managproje.R
import com.example.managproje.firebase.FireStoreClass
import com.example.managproje.models.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import kotlinx.android.synthetic.main.activity_sign_up.*
class SignUpActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
setupActionBar()
btn_sign_up.setOnClickListener {
registerUser()
}
}
private fun setupActionBar(){
setSupportActionBar(toolbar_sign_up_activity)
val actionBar = supportActionBar
if(actionBar != null){
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeAsUpIndicator(R.drawable.ic_black_color_back_24dp)
}
toolbar_sign_up_activity.setNavigationOnClickListener {
onBackPressed()
}
}
private fun registerUser(){
val name: String = et_name.text.toString().trim{it <= ' '}
val email: String = et_email.text.toString().trim{it <= ' '}
val password: String = et_password.text.toString().trim{it <= ' '}
if (validateForm(name, email, password)){
showProgressDialog(resources.getString(R.string.please_wait))
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val firebaseUser: FirebaseUser = task.result!!.user!!
val registeredEmail = firebaseUser.email!!
val user = User(firebaseUser.uid,name,registeredEmail)
FireStoreClass().registerUserFireStore(this@SignUpActivity,user)
} else {
Toast.makeText(
this@SignUpActivity,
"Registration Failed", Toast.LENGTH_SHORT).show()
}
}
}
}
private fun validateForm(name: String, email: String, password: String): Boolean{
return when{
TextUtils.isEmpty(name)->{
showErrorSnackBar("Please Enter a Name")
false
}
TextUtils.isEmpty(email)->{
showErrorSnackBar("Please Enter an Email")
false
}
TextUtils.isEmpty(password)->{
showErrorSnackBar("Please Enter the Password")
false
}else ->{
true
}
}
}
fun userRegisteredSuccess(){
Toast.makeText(
this@SignUpActivity,
"You have successfully " +
"registered",
Toast.LENGTH_LONG
).show()
hideProgressDialog()
FirebaseAuth.getInstance().signOut()
finish()
}
}
|
# TIL
> Today I Learned
## CONTENTS
- [Python](#python)
- [FrontEnd](#FrontEnd)
- [Data Science](#data-science)
- [Data Structure & Algorithm](#data-structure--algorithm)
- [SQL](#sql)
- [BootCamp - PlayData](#bootcamp---playdata)
- [Book](#book)
<br>
<hr />
### Python
**Python Code**
- [람다(Lambda) & map, reduce](./Python/PythonCode/%EB%9E%8C%EB%8B%A4(Lambda).md)
- [Asterisk](./Python/PythonCode/Asterisk.md)
- [Collections](./Python/PythonCode/Collections_Study.md)
- [선형 대수 코드화](./Python/PythonCode/Linear%20algebra%20Codes.md)
**도서**
- 코딩 도장
- [(일시중지)~~신비한 파이썬 프로젝트~~](./Python/도서/%EC%8B%A0%EB%B9%84%ED%95%9C%20%ED%8C%8C%EC%9D%B4%EC%8D%AC%20%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8/%EC%8B%A0%EB%B9%84%ED%95%9C%20%ED%8C%8C%EC%9D%B4%EC%8D%AC%20%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8.md)
<br>
[*Back to Contents*](#contents)
<hr />
### FrontEnd
**JavaScript**
- [NomadCoder - TodoApp Mission (GitPage)](https://soulchicken.github.io/todo-app/)
- [NomadCoder - TodoApp Mission (Repo)](https://github.com/soulchicken/todo-app)
<br>
[*Back to Contents*](#contents)
<hr />
### Data Science
- ㅇ
<br>
[*Back to Contents*](#contents)
<hr />
### Data Structure & Algorithm
**JAVA 자료구조, 알고리즘**
- [Java Data Structure](/DataStructureAndAlgorithm/JavaDataStructure/JavaDataStructure.md)
- [Java Algorithm](./DataStructureAndAlgorithm/JavaAlgorithm/JavaAlgorithm.md)
<br>
[*Back to Contents*](#contents)
<hr />
### SQL
**SQL 정리**
- [SQL 내용정리](./SQL/link%20db%20and%20py.md)
- [쿼리문 내용정리](./SQL/database.md)
- [데이터 조회(SELECT)](./SQL/boostcource_SQL/SELECT.md)
- [테이블 결합(JOIN)](./SQL/boostcource_SQL/JOIN.md)
- [서브 쿼리(Sub Query)](./SQL/boostcource_SQL/SubQuery.md)
- [연산자](./SQL/boostcource_SQL/연산자.md)
- [함수](./SQL/boostcource_SQL/함수.md)
- [데이터 마트](./SQL/boostcource_SQL/%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A7%88%ED%8A%B8.md)
- [파이썬에서 쿼리문 사용하기](./SQL/파이썬에서DB사용하기/내용정리.md)
**프로그래머스 문제풀이**
- [LEVEL 1](./SQL/프로그래머스%20문제풀이/Level_1.md)
- [LEVEL 2](./SQL/프로그래머스%20문제풀이/Level_2.md)
- [LEVEL 3](./SQL/프로그래머스%20문제풀이/Level_3.md)
<br>
[*Back to Contents*](#contents)
<hr />
### BootCamp - PlayData
**FrontEnd**
- [부트캠프 수업 정리 흔적 - 프론트엔드](./BootCamp_PlayData/FrontEnd)
- [미니 프로젝트 - Counter 설명서](https://github.com/soulchicken/WEB_collection#readme) : 미니프로젝트 Readme 작성
- [미니 프로젝트 - Counter 링크](https://soulchicken.github.io/WEB_collection/) : 미니 프로젝트. 난잡하게 만드는 것보다 심플하게 만드는 것이 이쁘다.
- [미니 프로젝트 - 파파고 API 활용하기](./BootCamp_PlayData/FrontEnd/PAPAGO_API_STUDY/) : API 사용해보기, Node 서버 사용해보기 등 안해본 것이 많았다.
- [팀 프로젝트 - Movie App](https://github.com/soulchicken/todo-app) : 첫 팀작업. react로 싱글 페이지를 구현했다.
**BackEnd**
- [부트캠프 수업 정리 흔적 - 백엔드](./BootCamp_PlayData/BackEnd)
**알고리즘 스터디**
- [기초 알고리즘 1](./BootCamp_PlayData/AlgorithmStudy/foundation_1/foundation_1.md)
- [기초 알고리즘 2](./BootCamp_PlayData/AlgorithmStudy/foundation_2/foundation_2.md)
- [스택 & 큐](./BootCamp_PlayData/AlgorithmStudy/1week_stack_queue/StackAndQueue.md)
- [완전탐색 & 이분탐색](./BootCamp_PlayData/AlgorithmStudy/2week_bruteforce_binarysearch/BruteForceAndBinarySearch.md)
- [DFS & DFS](./BootCamp_PlayData/AlgorithmStudy/3week_DFS_BFS/DFSandBFS.md)
<br>
[*Back to Contents*](#contents)
<hr />
### BOOK
**책읽기!**
- [클린코드](./Book/클린코드/클린코드.md)
|
function voluntariado() {
contarArquivos();
//ATIVA AS APLICAÇÕES NECESSÁRIAS
let spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); //acessa a planilha ativa
let doc = DocumentApp;
let sheet = spreadsheet.getSheetByName("Termo de Voluntariado");//Acessando a aba Termo Voluntariado
//DADOS VOLUNTARIO(A)
let dadosPessoais = sheet.getRange("F3:F11").getValues();
let dadosEndereco = sheet.getRange("F15:F19").getValues();
Logger.log(dadosPessoais)
//DADOS REPRESENTANTE
let dadosRepresentante = sheet.getRange("C8:C11").getValues();
//DADOS PARA DOCUMENTO
let numTermo = sheet.getRange("C2").getValues();
numTermo = numeroDoTermo(numTermo);
let data = [Utilities.formatDate(new Date(), "America/Sao_Paulo", "dd"),Utilities.formatDate(new Date(), "America/Sao_Paulo", "MM"),Utilities.formatDate(new Date(), "America/Sao_Paulo", "YYYY")]
let mes = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
let dia = ['1º','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'];
let dataHoje = dia[data[0]-1]+" de "+mes[data[1]-1]+" de "+data[2]
//DADOS DE MÁSCARA PARA SUBSTITUIÇÃO
let mascaraVolPes = ["{matricula}","{voluntario}","{curso}","{nacionalidade}","{estado civil}","{profissao}","{CPF}","{RG}","{ps}"];
let mascaraVolEnd = ["{endereco}","{bairro}","{cidade}","{UF}","{CEP}"];
let mascaraRep = ["{cargo-rep}","{nome-rep}","{cpf-rep}","{rg-rep}"];
let mascaraDoc = ["{termo-n}","{data-firmamento}","{ano}"];
//CONFIGURAÇÕES DE DOCUMENTOS
let pasta = DriveApp.getFolderById("url-pasta-destino");
let arquivo_modelo = DriveApp.getFileById("url-arquivo-modelo");
let nome_arquivo = "[Sem assinatura] - Termo de Voluntariado " + numTermo + "/" + data[2] + " - " + dadosPessoais[1];
let nome_arquivo2 = "[Sem assinatura] - Termo de Voluntariado " + numTermo + "/" + data[2] + " - " + dadosPessoais[1]+ ".pdf";
let novo_termo = arquivo_modelo.makeCopy(nome_arquivo, pasta);
let termoVoluntariado = doc.openById(novo_termo.getId());
let body = termoVoluntariado.getBody();
for(i=0; i<mascaraVolPes.length; i++){
body.replaceText(mascaraVolPes[i], dadosPessoais[i]);
}
for(i=0; i<mascaraVolEnd.length; i++){
body.replaceText(mascaraVolEnd[i], dadosEndereco[i]);
}
for(i=0; i<mascaraRep.length; i++){
body.replaceText(mascaraRep[i], dadosRepresentante[i]);
}
body.replaceText(mascaraDoc[0],numTermo);
body.replaceText(mascaraDoc[1],dataHoje); //data manual ex: body.replaceText(mascaraDoc[1],"24/04/2018");
body.replaceText(mascaraDoc[2],data[2]);
termoVoluntariado.saveAndClose();
//Gera o PDF
const termoVoluntariadoPDF = termoVoluntariado.getAs(MimeType.PDF);
pasta.createFile(termoVoluntariadoPDF);
//Apaga o arquivo cópia
pasta.removeFile(novo_termo)
//Limpa os formulários
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Termo de Voluntariado").getRange("C8").setValue("Selecionar");
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Termo de Voluntariado").getRange("C4").setValue("");
//Logger.log(nome_arquivo)
contarArquivos();
let files = DriveApp.getFilesByName(nome_arquivo2);
while (files.hasNext()) {
var file = files.next();
}
let htmlString = '<!DOCTYPE html>'
+ '<html> <head> <base target="_top"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"></head>'
+ '<div class="spinner-border" role="status">'
+ '<span class="visually-hidden"></span>'
+ '</div>'
+ '<script>'
+ 'window.open(##URL## , ##TYPE##, width=0, height=0); google.script.host.close();'
+ '</script>'
+ '</html>';
// Change the parameters inside the window.open method
htmlString = htmlString.replace("##URL##", "'" + file.getUrl() + "'");
htmlString = htmlString.replace("##TYPE##", "'_blank'");
// Create the output window
let html = HtmlService.createHtmlOutput(htmlString)
.setWidth(200)
.setHeight(40);
// Show the Window
SpreadsheetApp.getUi()
.showModalDialog(html,"Carregando...");
//window.open(pdfFile, "_blank", "width=600,height=800");
//return file.getUrl()
limparDados();
}
function numeroDoTermo(numTermo){
if (numTermo < 10) {
numTermo = '000'+numTermo;
}
else if (numTermo < 99 && numTermo >= 10){
numTermo = '00'+numTermo;
}
else{
numTermo = '0'+numTermo;
}
return numTermo
}
function limparDados(){
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Termo de Voluntariado").getRange("C8").setValue("Selecionar");
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Termo de Voluntariado").getRange("C4").setValue("");
}
function contarArquivos() {
let pasta = DriveApp.getFolderById("url-pasta-destino");
let arquivos = pasta.getFiles();
let numeroTermo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Termo de Voluntariado").getRange("C2");
let contador = [];
while (arquivos.hasNext()) {contador.push(arquivos.next());}
numeroTermo.setValue(contador.length+1);
}
// Generate a custom HTML to open the PDF
function showPdfFile(){
let app = SpreadsheetApp;
let spreadsheet = app.getActiveSpreadsheet();
let ui = app.getUi();
let paginaDeVendas = HtmlService.createTemplateFromFile('pag.html').evaluate();
paginaDeVendas.setWidth(400).setHeight(100);
SpreadsheetApp.getUi().showModalDialog(paginaDeVendas,"RH | Sistema de Gestão");
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/
package controller;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.Account;
/**
*
* @author Ngo Tung Son
*/
public abstract class BaseRequiredAuthenticationController extends HttpServlet {
private boolean isAuthenticated(HttpServletRequest request) {
Account account = (Account) request.getSession().getAttribute("account");
if(account ==null)
return false;
else
{
return true;
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(isAuthenticated(request))
{
processGet(request, response);
}
else
{
response.sendRedirect(request.getContextPath() + "/Login");
}
}
protected abstract void processGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
protected abstract void processPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(isAuthenticated(request))
{
processPost(request, response);
}
else
{
response.sendRedirect(request.getContextPath() + "/Login");
}
}
}
|
import Web3 from "web3";
import { useState } from 'react';
const Hello = require("./abi/Hello.json")
function App() {
const [inputMsg, setInputMsg] = useState();
const [outputMsg, setOutPutMsg] = useState();
const ethereum = window.ethereum;
const contractAddress = Hello.networks["5777"].address;
const contractAbi = Hello.abi;
const web3 = new Web3(ethereum);
const myContract = new web3.eth.Contract(contractAbi, contractAddress);
async function enableMetaMask() {
let accounts = await ethereum.request({ method: "eth_requestAccounts" });
console.log(`Connected to ${accounts[0]}!`);
};
function msgHandler(event) {
setInputMsg(event.target.value);
console.log("Input Msg:", event.target.value)
}
async function setValue() {
let accounts = await ethereum.request({ method: "eth_requestAccounts" });
console.log(accounts);
const txValue = await myContract.methods
.setMessage(inputMsg).encodeABI();
await window.ethereum.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: contractAddress,
gas: '0x76c0', // 30400
gasPrice: '0x9184e72a000', // 10000000000000
value: '0x00', // 2441406250
data: txValue,
},
],
})
};
async function getValue() {
const data = await myContract.methods.getMessage().call();
setOutPutMsg(data);
}
return (
<div className="flex flex-col justify-center items-center h-screen text-center">
<p className="font-bold text-2xl py-4" id="greetingTxt">Sample Dapp</p>
<button onClick={enableMetaMask} className="border border-gray-600 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded">
Connect to MetaMask
</button>
<p className="font-bold text-xl py-4" id="greetingTxt">Set Message</p>
<input type="text" onChange={msgHandler} placeholder="Enter Message Value" className="border border-gray-400 py-2 px-6 rounded" /> <br />
<button onClick={setValue} className="border border-gray-600 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded">
Set
</button>
<p className="font-bold text-xl py-4" id="greetingTxt">Get Message</p>
<button onClick={getValue} className="border border-gray-600 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded">
Get
</button>
<p className="font-bold text-m py-4" id="greetingTxt">{outputMsg}</p>
</div>
);
}
export default App;
|
<section class="main-content">
<ul class="breadcrumb breadcrumb-style ">
<li class="breadcrumb-item">
<h5 class="page-title m-b-0">Buttons</h5>
</li>
<li class="breadcrumb-item bcrumb-1">
<a routerLink="/dashboard/main">
<i class="fas fa-home font-17"></i></a>
</li>
<li class="breadcrumb-item">UI</li>
<li class="breadcrumb-item">Buttons</li>
</ul>
<div class="section-body">
<div class="row">
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Basic</h4>
</div>
<div class="card-body">
<p class="text-muted">Use the <code>.btn .btn-#color</code> classes.</p>
<div class="buttons">
<button class="btn btn-primary">Primary</button>
<button class="btn btn-secondary">Secondary</button>
<button class="btn btn-info">Info</button>
<button class="btn btn-warning">Warning</button>
<button class="btn btn-danger">Danger</button>
<button class="btn btn-success">Success</button>
<button class="btn btn-light">Light</button>
<button class="btn btn-dark">Dark</button>
<button class="btn">Link</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Buttons <code>.btn-outline</code></h4>
</div>
<div class="card-body">
<p class="text-muted">Use the <code>.btn .btn-outline-#color</code> classes.</p>
<div class="buttons">
<button class="btn btn-outline-primary">Primary</button>
<button class="btn btn-outline-secondary">Secondary</button>
<button class="btn btn-outline-info">Info</button>
<button class="btn btn-outline-warning">Warning</button>
<button class="btn btn-outline-danger">Danger</button>
<button class="btn btn-outline-success">Success</button>
<button class="btn btn-outline-light">Light</button>
<button class="btn btn-outline-dark">Dark</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Button Sizes</h4>
</div>
<div class="card-body">
<p class="text-muted">Use the <code>.btn-lg</code> or <code>.btn-sm</code> classes.</p>
<div class="buttons">
<button class="btn btn-sm btn-warning">Small</button>
<button class="btn btn-danger">Normal</button>
<button class="btn btn-lg btn-dark">Large</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Button States</h4>
</div>
<div class="card-body">
<p class="text-muted">Use the <code>.disabled</code> or <code>.btn-progress</code> classes.</p>
<div class="buttons">
<button class="btn btn-primary">Normal</button>
<button class="btn disabled btn-primary">Disabled</button>
<button class="btn disabled btn-primary btn-progress">Progress</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Icon Button</h4>
</div>
<div class="card-body">
<p class="text-muted">Use the <code>.btn-icon</code> and <code>.icon-left</code> classes.</p>
<div class="buttons">
<button class="btn btn-icon icon-left"><i class="far fa-user"></i> Default</button>
<button class="btn btn-icon icon-left btn-primary"><i class="far fa-edit"></i> Primary</button>
<button class="btn btn-icon icon-left btn-secondary"><i class="far fa-user"></i> Secondary</button>
<button class="btn btn-icon icon-left btn-info"><i class="fas fa-info-circle"></i> Info</button>
<button class="btn btn-icon icon-left btn-warning"><i class="fas fa-exclamation-triangle"></i>
Warning</button>
<button class="btn btn-icon icon-left btn-danger"><i class="fas fa-times"></i> Danger</button>
<button class="btn btn-icon icon-left btn-success"><i class="fas fa-check"></i> Success</button>
<button class="btn btn-icon icon-left btn-light"><i class="fas fa-star"></i> Light</button>
<button class="btn btn-icon icon-left btn-dark"><i class="far fa-file"></i> Dark</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Only Icon Button</h4>
</div>
<div class="card-body">
<p class="text-muted">Use the <code>.btn-icon</code> class.</p>
<div class="buttons">
<button class="btn btn-icon btn-primary"><i class="far fa-edit"></i></button>
<button class="btn btn-icon btn-secondary"><i class="far fa-user"></i></button>
<button class="btn btn-icon btn-info"><i class="fas fa-info-circle"></i></button>
<button class="btn btn-icon btn-warning"><i class="fas fa-exclamation-triangle"></i></button>
<button class="btn btn-icon btn-danger"><i class="fas fa-times"></i></button>
<button class="btn btn-icon btn-success"><i class="fas fa-check"></i></button>
<button class="btn btn-icon btn-light"><i class="fas fa-star"></i></button>
<button class="btn btn-icon btn-dark"><i class="far fa-file"></i></button>
</div>
<p class="text-muted mt-2">Sizes.</p>
<div class="buttons">
<button class="btn btn-icon btn-sm btn-warning"><i class="fas fa-exclamation-triangle"></i></button>
<button class="btn btn-icon btn-danger"><i class="fas fa-times"></i></button>
<button class="btn btn-icon btn-lg btn-success"><i class="fas fa-check"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Button Group</h4>
</div>
<div class="card-body">
<div class="btn-group mb-3" role="group" aria-label="Basic example">
<button type="button" class="btn btn-info">Left</button>
<button type="button" class="btn btn-info">Middle</button>
<button type="button" class="btn btn-info">Right</button>
</div>
<div class="btn-group mb-3" role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger">Left</button>
<button type="button" class="btn btn-warning">Middle</button>
<button type="button" class="btn btn-success">Right</button>
</div>
<div class="btn-group mb-3 btn-group-sm" role="group" aria-label="Basic example">
<button type="button" class="btn btn-primary">Left</button>
<button type="button" class="btn btn-primary">Middle</button>
<button type="button" class="btn btn-primary">Right</button>
</div>
<div class="clearfix"></div>
<div class="btn-group btn-group-lg" role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger">Left</button>
<button type="button" class="btn btn-danger">Middle</button>
<button type="button" class="btn btn-danger">Right</button>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-6">
<div class="card">
<div class="card-header">
<h4>Vertical Variation</h4>
</div>
<div class="card-body">
<div class="btn-group-vertical" role="group" aria-label="Basic example">
<button type="button" class="btn btn-info">Left</button>
<button type="button" class="btn btn-info">Middle</button>
<button type="button" class="btn btn-info">Right</button>
<button type="button" class="btn btn-info">Justify</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<h4>Ngb-Buttons</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-12 col-md-6 col-lg-6">
<h6>Checkbox buttons</h6>
<div class="btn-group btn-group-toggle">
<label class="btn-raised btn-primary" ngbButtonLabel>
<input type="checkbox" ngbButton [(ngModel)]="model.left"> Left (pre-checked)
</label>
<label class="btn-raised btn-primary" ngbButtonLabel>
<input type="checkbox" ngbButton [(ngModel)]="model.middle"> Middle
</label>
<label class="btn-raised btn-primary" ngbButtonLabel>
<input type="checkbox" ngbButton [(ngModel)]="model.right"> Right
</label>
</div>
<hr>
<pre>{{model | json}}</pre>
</div>
<div class="col-12 col-md-6 col-lg-6">
<h6>Checkbox buttons (Reactive Forms)</h6>
<form [formGroup]="checkboxGroupForm">
<div class="btn-group btn-group-toggle">
<label class="btn-primary" ngbButtonLabel>
<input type="checkbox" formControlName="left" ngbButton> Left (pre-checked)
</label>
<label class="btn-primary" ngbButtonLabel>
<input type="checkbox" formControlName="middle" ngbButton> Middle
</label>
<label class="btn-primary" ngbButtonLabel>
<input type="checkbox" formControlName="right" ngbButton> Right
</label>
</div>
</form>
<hr>
<pre>{{checkboxGroupForm.value | json}}</pre>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 col-lg-6">
<h6>Radio buttons</h6>
<div class="btn-group btn-group-toggle" ngbRadioGroup name="radioBasic" [(ngModel)]="modelRadio">
<label ngbButtonLabel class="btn-raised btn-primary">
<input ngbButton type="radio" [value]="1"> Left (pre-checked)
</label>
<label ngbButtonLabel class="btn-raised btn-primary">
<input ngbButton type="radio" value="2"> Middle
</label>
<label ngbButtonLabel class="btn-raised btn-primary">
<input ngbButton type="radio" [value]="3"> Right
</label>
</div>
<hr>
<p>{{modelRadio}}</p>
</div>
<div class="col-12 col-md-6 col-lg-6">
<h6>Radio buttons (Reactive Forms)</h6>
<form [formGroup]="radioGroupForm">
<div class="btn-group btn-group-toggle" ngbRadioGroup name="radioBasic"
formControlName="modelRadioForm">
<label ngbButtonLabel class="btn-raised btn-primary">
<input ngbButton type="radio" value="Left"> Left (pre-checked)
</label>
<label ngbButtonLabel class="btn-raised btn-primary">
<input ngbButton type="radio" value="Middle"> Middle
</label>
<label ngbButtonLabel class="btn-raised btn-primary">
<input ngbButton type="radio" value="Right"> Right
</label>
</div>
</form>
<hr>
<p>{{radioGroupForm.value['modelRadioForm']}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
|
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Task;
use App\Entity\User;
use App\Form\TaskType;
use Symfony\Component\Security\Core\User\UserInterface;
class TaskController extends AbstractController
{
public function index(ManagerRegistry $doctrine)
{
//Prueba de entidades y relaciones
$em = $doctrine->getManager();
$task_repo = $doctrine->getRepository(Task::class);
$tasks = $task_repo->findBy([], ['id' => 'DESC']);
/*
$user_repo = $doctrine->getManager()->getRepository(User::class);
$users = $user_repo->findAll();
foreach($users as $user){
echo "<h1>{$user->getName()} {$user->getSurname()}</h1>";
foreach ($user->getTasks() as $task) {
echo $task->getTitle()."<br/>";
}
}
*/
return $this->render('task/index.html.twig', [
'tasks' => $tasks
]);
}
public function detail(Task $task) {
if(!$task){
return $this->redirectToRoute('tasks');
}
return $this->render('task/detail.html.twig', [
'task' => $task
]);
}
public function creation(Request $request, UserInterface $user, ManagerRegistry $doctrine) {
$task = new Task();
$form = $this->createForm(TaskType::class, $task);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$task->setCreatedAt(new \DateTime('now'));
$task->setUser($user);
$em = $doctrine->getManager();
$em->persist($task);
$em->flush();
return $this->redirect(
$this->generateUrl('task_detail', ['id' => $task->getId()]));
}
return $this->render('task/creation.html.twig', [
'form' =>$form->createView()
]);
}
public function myTasks(UserInterface $user) {
$tasks = $user->getTasks();
return $this->render('task/my-tasks.html.twig', [
'tasks' => $tasks
]);
}
public function edit(Request $request, Task $task, UserInterface $user, ManagerRegistry $doctrine) {
if(!$user || $user->getId() != $task->getUser()->getId()){
return $this->redirectToRoute('tasks');
}
$form = $this->createForm(TaskType::class, $task);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
//$task->setCreatedAt(new \DateTime('now'));
//$task->setUser($user);
$em = $doctrine->getManager();
$em->persist($task);
$em->flush();
return $this->redirect(
$this->generateUrl('task_detail', ['id' => $task->getId()]));
}
return $this->render('task/creation.html.twig', [
'edit' => true,
'form' => $form->createView()
]);
}
public function delete(Task $task, ManagerRegistry $doctrine, UserInterface $user) {
if(!$user || $user->getId() != $task->getUser()->getId()){
return $this->redirectToRoute('tasks');
}
if(!$task){
return $this->redirectToRoute('tasks');
}
$em = $doctrine->getManager();
$em->remove($task);
$em->flush();
return $this->redirectToRoute('tasks');
}
}
|
% filterbank_FIR_amp_dist.m
%
% Victor Kröger und Lennard Jönsson - WS 23
%
% Entwurf einer Filterbank
%
%
%% Settings
clear
close('all');
format compact
Fs = inputs('Fs_in', 50e3);
% create a frequency vector
freq=(1:999)/2000;
%% Labor 6
L = 2; % Downsampling Faktor
M = 2; % Upsampling Faktor
Fs1 = Fs; % Eingangsfrequenz
Fs2 = Fs1; % Ausgangsfrequenz
Fs3 = Fs1 * L; % Abtastfrequenz auf der das Filter läuft
% stop-band attentuation is in DB, convert to linear for REMEZ
delta_stop_dB = inputs('stop-band attenuation in dB', 40);
delta_stop = dbinv(-delta_stop_dB);
% for pass-band
delta_pass = 1.45e-4;
% edge frequencies
fstop = inputs('fstop', 16100); %(Fs1/2 - f_pass)
fpass = inputs('fpass', 8900);
% determine N_FIR and the coefficients using REMEZ ("normal" FIR filter)
[N_FIR,fo,mo,w] = firpmord( [fpass fstop], [1 0], [delta_pass delta_stop], Fs1);
% for safety reasons, add 2 to N_FIR to achieve the stop-band attenuation for sure
N_FIR = N_FIR + 2; % The number of coefficients must be even!
b_FIR = firpm(N_FIR,fo,mo,w);
% compute the amplitude response using frequency vector
[hz, w] = freqz(b_FIR,1, 2*pi*freq);
fprintf('\n N_FIR = %d\n\n', N_FIR);
% Plot amplitude response
figure(1)
plot(freq*Fs3,db(hz)),grid
legend('FIR\_LP (Fs = 50 kHz)')
xlabel('Frequency in Hz')
ylabel('|H| in dB')
hold on
% Plot phase response
figure(2)
plot(freq*Fs3, w), grid
title('Phase Response of FIR\_LP Filter')
xlabel('Frequency in Hz')
ylabel('Phase in radians')
hold on
% Plot amplitude and phase response using freqz
figure(3)
freqz(b_FIR, 1);
% PPZ coefficients
b_20 = b_FIR(1:2:end);
b_21 = b_FIR(2:2:end);
% PPZ frequency response
hz_20 = freqz(b_20, 1, L*2*pi*freq);
hz_21 = freqz(b_21, 1, L*2*pi*freq);
zhm1 = exp(-1j*2*pi*freq);
% Frequency response from ppz reconstruction
hz_ges = hz_20 + hz_21 .* zhm1;
% Plot amplitude response of ppz reconstruction
figure(4)
plot(freq*Fs3,db(hz_ges)),grid
legend('FIR\_LP PPZ (Fs = 50 kHz)')
xlabel('Frequency in Hz')
ylabel('|H| in dB')
hold on
%% Pol Zeros diagramm
%a = 1;
%b = b_FIR;
%[z,p,k] = tf2zp(b,a);
%fvtool(b,a,'polezero')
%text(real(z)+.1,imag(z),'Zero')
%text(real(p)+.1,imag(p),'Pole')
|
# TikTalk🎃, a MERN Application
TikTalk is a Halloween-themed chat application which allows people to communicate in groups. It is built with React, ExpressJS, NodeJS, and MongoDB (MERN stack). It has been deployed on AWS (EC2 instances) and Netlify.
---
- Production client app: https://www.tiktalkproject.com/
- Production backend service (JSON requests / responses): https://tiktalk-server.codergirlsu.dev
- Staging/Development client app: https://tiktalkdevelopment.netlify.app
- Staging/Development backend service (JSON requests / responses): http://tiktalk-dev-server.codergirlsu.dev
- Client Repo: https://github.com/hunteradams10/TikTalk-Client
- Server Repo: https://github.com/coderGirlSu/TikTalk-server
- Part A Documentation Repo: https://github.com/coderGirlSu/TikTalk-documentation
---
## Installation Guide
The production app can be found at https://www.tiktalkproject.com , where you can make an account, add friends to your group, and get chatting! If you're after a more local experience, please follow the instructions below.
Requirements:
- NodeJS 14.18.0 or later
- MongoDB (be sure to create an account!)
Server-Side:
- Create a new directory and call it whatever you want! We advise `TikTalk`, or something similar 😉
- `cd` into that folder, then create another folder called `tiktalk-server`, or whatever best suits you 😊
- Clone the server repo using the `CLI` from here: `git clone git@github.com:coderGirlSu/TikTalk-server.git`
- `cd` into that folder (you should see `git` initialize), then run `npm install` or `npm i` to download everything you need to get started!
- Open a terminal window, and run `npm start` - make sure you have MongoDB open!
- If all went well, you'll see the server start on port `80` in your terminal!
Client-Side:
- `cd` out of the `server` folder, make a new folder called `tiktalk-client`. `cd` into it, and run `git clone git@github.com:hunteradams10/TikTalk-Client.git`
- Open a terminal, make sure it's in the current directory, and run `npm i` or `npm install` to make sure that all the required files are downloaded into the `package.json`.
- In that terminal, run `npm start` to run the client-side application in a new browser window.
- The server will expect requests from `localhost:3000`, so it should all be good! Happy chatting! 🦇
---
## Libraries and Dependencies
- ` "cors": "^2.8.5"` - The `cors` library allows cross-origin resource sharing. This prevents cors issues when the back-end and front-end are trying to communicate with one-another.
- `"dotenv": "^16.0.3"` `dotenv` is what allows us to load environment variables into the `process.env`, instead of having it in the code body, which is a spooky security risk 👻
- `"express": "^4.18.2",` - `expressjs` is a NodeJs web framework that enabled us to build this application! It helps to manage routes and servers. The force is strong with this one. 💫
- `"firebase": "^9.13.0"` - `Firebase` took care of all our authentication and authorization for the application. It holds the keys to all the doors.
- `"firebase-admin": "^11.2.0"` - Firebase's node SDK allows us to control what environments can access the server (such as development or production), another security step 👮
- `"helmet": "^6.0.0"` - `helmet` allowed us to build safe HTTP headers, to add additional security to the back-end.
- `"mongoose": "^6.7.2"` - `mongoose` allows developers to point to a specific schema in the database. It is an ODM library for MongoDB.
## Dev-Dependencies (Server)
- `"jest": "^29.3.1"` - a Javascript testing framework to make sure all our code is nice and correct and working properly ☑️
- `"nodemon": "^2.0.20"` - `nodemon` will automatically refresh the application when changes are detected in the directory. Very handy and saved a lot of time!
- `"supertest": "^6.3.1"` - `supertest` is a NodeJS testing library that allows us to test our API, the HTTPS servers.
## Dependencies (Client)
- `"react": "^18.2.0"` - `React` is a Javascript front-end framework developed by Facebooks. It helps developers build modular, scalable front-end user interfaces using components.
- `"react-dom": "^18.2.0"` - `react-dom` is a library that binds React to the Document Object Model. It is the reason that React can `render()` browser content.
- `"react-router-dom": "^6.4.3"` - `react-router-dom` allows React applications to be SPA's (or Single Page Applications). It allows us to add extensions to the URL by creating `Routes` that navigate to different "Pages".
- `"react-scripts": "5.0.1"` - `react scripts` enables us to use additional scripts along with those that come with React natively. These can be use to create custom builds, say, for production.
- `"sass": "^1.56.1"` - `SASS` is a CSS-Compiler that allows us to write all of our CSS on one page, with nested descendents inside of ancestors. It also allows us to create custom colour variables! Neat.
- `"moment": "^2.29.4"` - `moment` allows us to show all the dates and times of messages correctly, ensuring that they are readable.
- `"node-sass": "^7.0.3"` - `node-sass` is what allows us to convert the `scss` into `css`. It is a `css` pre-processor.
- `"jwt-decode": "^3.1.2",` - `JWT decode` is a means to decode `jwt` tokens when they are sent from the back-end for authentication.
- `"axios": "^1.1.3"` - `Axios` is a Javascript library that allows us to use the `Promise API` with HTTP requests. It handles all such requests and returns a promise - the result of which can be handled in React.
---
## Environments
In this project we set up two environments. One environment is for development and the other is for production. Each environment is split into two parts. Part one is a front end server running in Netlify. Part two is a backend server running in AWS as an EC2 instance. Each environment also has its own instance of MongoDB and its own instance of firebase configured.
When either the front-end or the back end code starts, it reads environment variables to determine which environment it is running in. Using environment variables such as DB connection string, Firebase private key, API key and port number it can connect to the other related services in the same environment, such as the database or Firebase.
### AWS EC2 instances
In the screenshot below you can see the two EC2 instances running. One instance represents the development backend server and the other the production backend server. The backend servers use the node package `dotenv` to read environment files containing environment variables related to the specific environment they are in.

## Front-End Environments
Here is a screenshot of the two environments running on Netlify. One is a development environment, and the other is the production environment.

Just the front-end development environment, which is set to automatic deploys from Github:

And the development environment, which is set to manual deploys from the `build` folder in React:

---
## API Endpoints
---
| Authentication | Messages | Groups |
| ------------------- | ------------------ | ------------------------------ |
| POST /users/sign-in | POST /messages/ | GET /groups/history?groupId= |
| POST /users/sign-up | | PATCH /groups/leave |
| | | PATCH /groups/add |
| | | POST /groups/create |
| | | GET /groups/ |
---
## Testing
User Manual test logs

### Frontend test coverage

### Backend server test coverage

---
### Postman server testing and error messages
User sign in

Sign in with invalid email

Sign in with invalid password

User sign up

Sign in with wrong password

Sign up with invalid email

Sign up with invalid password

Sign up with registered email address

Create a group

Add user to a group

Add existing user to a group

Get all groups that user is in

Get message history

Leave a group as last user

Leave a group

Send a message with invalid token

Send a message in a group

---
## Application Screenshots
**Register**

**Login**

**Chat**

**Group Chat**

---
## Project Management
All of our project management was done in Trello. Initially, we separated our work into the following columns: `nice to have`, `must to have`, `back-end`, `front-end`, `README2` (for this README!), `doing`, `done`, `check` (for making sure certain things were definitely kept track of), and `ideas` (the initial ideas for the app). We thought of the most basic things we needed to do and made cards in their relevant columns, deciding what was most important all the way through to least important.


We had a meeting and decided upon the initial ideas for the app features, and made cards for them:

We decided that Su would work primarily on the back-end, and Hunter on the front-end, according to our strengths. We added our names to each card that we'd be working on individually, time limits for the most important features, and a number system so that when a pull request was made on github, we could keep track of which number item we were creating the request for and mark it off in Trello.

As the project grew, more cards were added with our names assigned, as well as fixes that needed to be done. Features like making the navbar sticky were added and assigned to the respective developer, and fixes that were being worked on currently were added to the `doing` column. As bugs came up, we added cards for them to keep track of them, and to remind ourselves to work on them.


We decided to try to implement a colour-coding system for which marking criteria each card was for, but this ended up being cumbersome and was abandoned. We began to work on back-end testing.

As we neared our deadline, the `doing` column started to shrink:


There were some small tasks that were added towards the end, once the main project was mostly done:


---
## Commits and PRs
Below is evidence of the client and server side commits and PRs throughout the project. We worked together as a team and used upstream workflows and pull requests to make changes to the main code. We had two seperate repos for the client and server side, as the delegations based on our strengths made this approach more practical.
Client commits (over 130 total)

Client PRs

Server commits

Server PRs

## Reflection
It was a huge joy and a huge challenge to build this application, but Hunter Adams and Su Zhang are very proud of it. We found out that we didn't have enough time to implement every feature that we wanted to (such as a lightmode, drop-down for responsive Chats column), but intend to add these in future. The project-management, although it was a lifesaver, was a little bit cumbersome in its details and the PR card-numbering system was largely abandoned on the front-end, due to the amount of fixes and changes that needed to be made and the time limit in which to make them... and also some forgetfulness. The teamwork and communication, however, was almost flawless. Su and Hunter stayed in constant communication every step of the way. Due to the enormity of the front-end, Su and Hunter decided to work together on it once the back-end was finished, and this contributed enormously to the product being completed by the due date. The developers are enormously proud of their work.
|
import { getUser } from "@/app/api/common";
import * as z from "zod";
import { getErrorMessage } from "../error";
import { TokenPayload } from "../universal/auth";
export type TypedActionResult<T> =
| {
success: true;
data: T;
}
| {
success: false;
error: string;
};
type ValidForm = FormData | Record<string, unknown>;
/**
* Create a Zod-validated server form action.
*/
export async function typedAction<TResponse, TSchema extends z.AnyZodObject>(
schema: TSchema,
form: ValidForm,
callback: (data: z.infer<TSchema>) => Promise<TResponse>
): Promise<TypedActionResult<TResponse>> {
const input =
form instanceof FormData ? Object.fromEntries(form.entries()) : form;
const result = schema.safeParse(input);
if (!result.success) {
return {
success: false,
error: result.error.issues.map((i) => i.message).join("\n"),
};
}
try {
const response = await callback(result.data);
return { success: true, data: response };
} catch (err) {
return { success: false, error: getErrorMessage(err) };
}
}
/**
* Create an authenticated & Zod-validated server form action.
*/
export async function authenticatedAction<
TResponse,
TSchema extends z.AnyZodObject
>(
schema: TSchema,
form: ValidForm,
callback: (data: z.infer<TSchema>, user: TokenPayload) => Promise<TResponse>
): Promise<TypedActionResult<TResponse>> {
const auth = await getUser();
if (auth.success === false) {
return { success: false, error: "Invalid user" };
}
return typedAction(schema, form, (data) => callback(data, auth.user));
}
|
import { applyDecorators } from '@nestjs/common';
import {
ApiBadRequestResponse,
ApiBearerAuth,
ApiBody,
ApiCreatedResponse,
ApiForbiddenResponse,
ApiNotFoundResponse,
ApiOkResponse,
ApiOperation,
} from '@nestjs/swagger';
import { StudentProfileResponse } from '@student/responses';
import { CreateStudentProfileDTO, UpdateStudentProfileDTO } from '@student/dto';
export function StudentFindOneSwaggerDecorator() {
return applyDecorators(
ApiOperation({ summary: "Retrieves student's profile with given userID" }),
ApiOkResponse({ type: StudentProfileResponse }),
ApiNotFoundResponse({ description: 'Profile not found' }),
);
}
export function StudentCreateProfileSwaggerDecorator() {
return applyDecorators(
ApiOperation({ summary: 'Creates profile for authorized student' }),
ApiBody({ type: CreateStudentProfileDTO }),
ApiCreatedResponse({ type: StudentProfileResponse }),
ApiBadRequestResponse({ description: 'This student already has a profile' }),
ApiForbiddenResponse({ description: 'User is not student' }),
ApiNotFoundResponse({ description: 'User not found' }),
ApiBearerAuth('JWT-auth'),
);
}
export function StudentUpdateProfileSwaggerDecorator() {
return applyDecorators(
ApiOperation({ summary: 'Updates profile of authorized student' }),
ApiBody({ type: UpdateStudentProfileDTO }),
ApiOkResponse({ type: StudentProfileResponse }),
ApiBadRequestResponse({ description: 'This user does not have a profile' }),
ApiNotFoundResponse({ description: 'User not found' }),
ApiBearerAuth('JWT-auth'),
);
}
|
import { formatPrice, getAverageRating } from "@/lib/utils";
import { IProduct } from "@/models/product";
import {
Badge,
Flex,
Icon,
Link,
ListItem,
Stat,
StatHelpText,
StatNumber,
Text,
UnorderedList,
useTheme,
} from "@chakra-ui/react";
import React from "react";
import { FiHeart } from "react-icons/fi";
import { Rating } from "react-simple-star-rating";
import NextLink from "next/link";
import { useProductContext } from "@/contexts/ProductContext";
export default function ProductBasicInfo() {
const { product } = useProductContext();
const theme = useTheme();
return (
<Flex direction={"column"} gap={1}>
<Flex justify={"space-between"} align={"center"}>
<Text fontSize={14} color={"gray.400"}>
Nuevo | +5mil vendidos
</Text>
<Icon
as={FiHeart}
boxSize={6}
color={"blue.400"}
cursor={"pointer"}
_hover={{ color: "blue.600" }}
/>
</Flex>
<Text fontWeight={500} fontSize={"2xl"}>
{product?.name}
</Text>
<Flex align={"center"} gap={2} cursor={"pointer"}>
<Rating
onClick={() => {}}
readonly={true}
allowFraction
initialValue={getAverageRating(product!)}
emptyStyle={{ display: "flex" }}
fillStyle={{ display: "-webkit-inline-box" }}
size={24}
fillColor={theme.colors.blue[400]}
/>
<Text fontSize={14} color={"blue.400"}>
({product?.opinions.length})
</Text>
</Flex>
<Badge bgColor={"blue.500"} color={"white"} width={"fit-content"} mt={2}>
Ahora 12
</Badge>
<Stat mt={2}>
<StatNumber fontSize={"4xl"} fontWeight={400}>
$ {formatPrice(product?.price!)}
</StatNumber>
<StatHelpText fontSize={"md"}>
en 12x $ {formatPrice(product?.price! / 12)}
</StatHelpText>
</Stat>
<Link href="/" as={NextLink} color={"blue.300"} fontSize={"sm"}>
Ver los medios de pago
</Link>
<Text fontWeight={500} mt={8} mb={4} fontSize={14}>
Lo que tenés que saber del producto:
</Text>
<UnorderedList fontSize={14} spacing={2} color={"gray.600"}>
{product?.basicFeatures.map((feature, idx) => (
<ListItem key={idx}>{feature}</ListItem>
))}
</UnorderedList>
<Link href="/" as={NextLink} color={"blue.300"} fontSize={"sm"} mt={4}>
Ver más características
</Link>
</Flex>
);
}
|
import { Link,useHistory } from 'react-router-dom'
import styled from 'styled-components'
import React, { useState } from 'react';
import PokemonLogo from '../../img/pokemon-logo.png'
import { getPokemonByName } from '../../Redux/actions';
import { useDispatch, useSelector } from 'react-redux';
const Form=styled.form`
display:flex;
justify-content:center;
align-items:center;
`
const Butt=styled.button`
background-color:rgba(255, 0, 0, 0);
border:none;
cursor:pointer;
transition:0.5s;
&:hover{
transform:scale(1.2);
transition:0.5s;
}
`
const Nav = styled.nav`
display: flex;
justify-content: space-around;
align-items: center;
background-color: red;
border-bottom: .2em solid black;
height: 6em;
`
const IconContainer = styled.div`
display: flex;
flex-direction: row;
align-items: center;
transition: .3s;
&:hover {
cursor: pointer;
transform: scale(1.10);
text-shadow: 3px 5px 8px black;
}
`
const Icon = styled.img`
height: 4em;
width: 4em;
border-radius: 50%;
`
const IconLogo = styled.img`
height:3em;
width:8em;
`
const NavBar = () => {
const [search,setSearch]=useState('');
const dispatch=useDispatch();
let pok=useSelector(state=>state.pokemon);
let history=useHistory();
const onChange=(e)=>{
e.preventDefault();
setSearch(e.target.value);
}
const onSubmit=async (e)=>{
e.preventDefault();
dispatch(getPokemonByName(search)).then((a)=>{
if(a==='success'){
history.push(`/details/${pok[0].id}`)
}
})
}
return (
<>
<Nav>
<Link to='/home' style={{ textDecoration: 'none'}}>
<IconContainer>
<IconLogo src={PokemonLogo}/>
</IconContainer>
</Link>
<Form onSubmit={(e)=>onSubmit(e)}>
<input type="text" value={search} onChange={(e)=>onChange(e)}/>
<Butt type='submit'><Icon src='https://i.imgur.com/EAuw8J0.png'/></Butt>
</Form>
</Nav>
</>
)
}
export default NavBar
|
import os
import cv2
import base64
import json
import pandas as pd
import plotly.express as px
from flask import Flask, render_template, request, jsonify
from roboflow import Roboflow
app = Flask(__name__)
roboflow = Roboflow("username", "api-key", "your-dataset-id")
inference_count = 0
total_images = 0
inference_data = {}
@app.route('/', methods=['GET', 'POST'])
def upload_image():
global inference_count, total_images, inference_data
if request.method == 'POST':
# Get image from POST request
img_base64 = request.form['image'].split(',')[1]
nparr = np.frombuffer(base64.b64decode(img_base64), np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Save image locally for inference
cv2.imwrite('temp.jpg', img_np)
# Perform inference
response = roboflow.detect_image('temp.jpg')
# Process inference results
for result in response['predictions']:
class_name = result['bbox']['class']
if class_name in inference_data:
inference_data[class_name] += 1
else:
inference_data[class_name] = 1
# Extract geotag data
geotag_data = {}
try:
exif_data = piexif.load(img_np)
lat = exif_data['GPS'][piexif.GPSIFD.GPSLatitude]
lon = exif_data['GPS'][piexif.GPSIFD.GPSLongitude]
geotag_data = {"lat": lat, "lon": lon}
except (AttributeError, KeyError, TypeError):
pass
# Increment counters
inference_count += 1
total_images += 1
# Render results page
return render_template('results.html', data=inference_data, count=inference_count, total=total_images, geotag_data=geotag_data)
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)
|
<template>
<Teleport to="body">
<div :class="['tooltip', placement, { center: placement === 'bottom' }]" :style="styling">
<slot></slot>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { TooltipPlacement } from '@/hooks/useTooltip'
const props = withDefaults(
defineProps<{ coords: { x: number; y: number }; placement?: TooltipPlacement }>(),
{
placement: 'bottom'
}
)
const styling = computed(() => {
return { top: props.coords.y + 'px', left: props.coords.x + 'px' }
})
</script>
<style scope lang="scss">
.tooltip {
position: absolute;
background-color: $warn;
padding: 15px 20px;
border-radius: 5px;
color: $white;
transform: translateX(-50%);
z-index: 99;
max-width: 200px;
&:before {
content: '';
display: block;
border: 10px solid transparent;
border-top: 0;
border-bottom: 20px solid $warn;
border-width: 10px;
position: absolute;
top: -10px;
width: 0px;
z-index: 100;
}
&.center {
&::before {
left: 0;
right: 0;
margin: auto;
}
}
&.left {
transform: translate(-100%, -50%);
&:before {
top: 0;
bottom: 0;
height: 0;
right: -9px;
margin: auto;
border: 10px solid transparent;
border-right: 0;
border-left: 20px solid $warn;
border-width: 10px;
}
}
&.right {
transform: translateY(-50%);
&:before {
top: 0;
bottom: 0;
height: 0;
left: -10px;
margin: auto;
border: 10px solid transparent;
border-left: 0;
border-right: 20px solid $warn;
border-width: 10px;
}
}
&.top {
transform: translate(-50%, -100%);
&:before {
left: 0;
right: 0;
height: 0;
bottom: -10px;
top: auto;
margin: 0 auto;
border: 10px solid transparent;
border-bottom: 0;
border-top: 20px solid $warn;
border-width: 10px;
}
}
}
</style>
|
import React, { useState } from 'react'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import Paper from '@mui/material/Paper'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import Grid2 from '@mui/material/Unstable_Grid2/Grid2'
import { usePairminatorContext } from '../context/PairminatorContext'
import { Pair, Pairee } from '../models/interface'
import { PairingState } from '../models/enum'
import LinearProgress from '@mui/material/LinearProgress'
import Snackbar from '@mui/material/Snackbar'
import Alert from '@mui/material/Alert'
export const Pairs = (): JSX.Element => {
const {
project,
activePairees,
lanes,
currentPairs,
togglePaireeAvailability,
assignPairs,
resetCurrentPairs,
recordCurrentPairs
} = usePairminatorContext()
const [recordingPairs, setRecordingPairs] = useState<boolean>(false)
const [pairsRecorded, setPairsRecorded] = useState<boolean>(false)
const record = async () => {
setRecordingPairs(true)
const success = await recordCurrentPairs()
if (success) {
setPairsRecorded(true)
}
setRecordingPairs(false)
}
const availablePairees = activePairees?.filter(p => p.available) || []
const pairingState = project?.pairingStatus
return (
<Paper sx={{ p: 2, display: 'flex', flexDirection: 'column' }}>
<Typography component="h2" variant="h6" color="secondary" gutterBottom>
Current Pairs
</Typography>
{pairingState === PairingState.INITIAL && (
<>
<Typography variant='body1'>
No pairs have been assigned yet.
</Typography>
<Divider sx={{ my: 3 }} />
<Typography component="h2" variant="h6">
Who's available to Pair? (select to toggle)
</Typography>
{activePairees && !!activePairees.length ? (
<Grid2 container px={0} pt={1} spacing={1}>
{activePairees.map((pairee: Pairee) => (
<Grid2 key={pairee.id}>
<Chip
size='medium'
label={pairee.name}
variant={availablePairees.some(p => p.id === pairee.id) ? 'filled' : 'outlined'}
color={availablePairees.some(p => p.id === pairee.id) ? 'info' : 'default'}
onClick={async () => await togglePaireeAvailability(pairee)}
/>
</Grid2>
))}
</Grid2>
) : (
<Typography pt={1} variant='body2' fontStyle='italic'>
Add pairees below
</Typography>
)}
</>
)}
{pairingState === PairingState.ASSIGNING && (
<LinearProgress color='inherit' sx={{ mt: 2 }} />
)}
{pairingState && [PairingState.ASSIGNED, PairingState.RECORDED].includes(pairingState) && currentPairs && (
<Grid2 container px={0} spacing={2}>
{currentPairs
.sort((a: Pair, b: Pair) => {
const laneA = lanes?.find(l => l.id === a.laneId)
const laneB = lanes?.find(l => l.id === b.laneId)
return (laneA && laneB) ? laneA.number - laneB.number : 0
})
.map((pair: Pair, index: number) => {
const lane = lanes?.find(l => l.id === pair.laneId)
const pairee1 = activePairees?.find(p => p.id === pair.pairee1Id)
const pairee2 = pair.pairee2Id ? activePairees?.find(p => p.id === pair.pairee2Id) : null
return lane && pairee1 && (
<Grid2 key={lane.id}>
<Stack direction='column' alignItems='center' spacing={1}
borderRight={index < (currentPairs.length-1) ? '2px dashed grey' : 'none'}
pr={2}
>
<Typography variant='subtitle1'>
{lane.name}
</Typography>
<Chip
size='medium'
label={pairee1.name}
variant='filled'
color={pairingState === PairingState.RECORDED ? 'primary' : 'secondary'}
/>
{pairee2 && (
<Chip
size='medium'
label={pairee2.name}
variant='filled'
color={pairingState === PairingState.RECORDED ? 'primary' : 'secondary'}
/>
)}
</Stack>
</Grid2>
)
}
)}
</Grid2>
)}
<Stack direction="row" pt={3} pb={2} spacing={2}>
{pairingState && [PairingState.INITIAL, PairingState.ASSIGNING].includes(pairingState) && (
<Stack direction='row' alignItems='center' spacing={2}>
<Button
color="info"
variant='contained'
size='large'
disabled={availablePairees.length < 2 || pairingState === PairingState.ASSIGNING}
onClick={assignPairs}
>
Assign
</Button>
{availablePairees.length < 2 && (
<Typography
variant='caption'
color='warning.dark'
>
2 or more pairees must be available to assign pairs.
</Typography>
)}
</Stack>
)}
{pairingState === PairingState.ASSIGNED && (
<Button
color="secondary"
variant='contained'
size='large'
disabled={recordingPairs}
onClick={record}
>
Record
</Button>
)}
{pairingState && [PairingState.ASSIGNED, PairingState.RECORDED].includes(pairingState) && (
<Button
color="inherit"
variant='contained'
size='large'
onClick={resetCurrentPairs}
>
Reset
</Button>
)}
</Stack>
<Snackbar
open={pairsRecorded}
autoHideDuration={3000}
onClose={() => setPairsRecorded(false)}
>
<Alert severity='success'>
Pairs recorded
</Alert>
</Snackbar>
</Paper>
)
}
|
<!--
* @Page:
* @Version: 1.0.0
* @Autor: xumeng
* @Date: 2020-04-26 16:55:07
* @LastEditors: Please set LastEditors
* @LastEditTime: 2020-07-01 15:33:55
-->
<template>
<div class="time-container">
<div :class="themeColor">
<div v-for="(item, index) in testList" @click="handleClick(item, index)" :key="index" :class="`time-line-div ${location}`">
<p>{{item.time}}</p>
<p class="circle"></p>
<p>{{item.text}}</p>
</div>
</div>
</div>
</template>
<script>
export default {
name:'timeline',
props: {
// 参数
testList: {
type: Array,
default: () => []
},
// 布局模式
mode: {
type: String,
default: 'left'
},
// 主题颜色
theme: {
type: String,
default: 'light'
}
},
computed: {
location() {
// 根据传入的mode属性确定不同位置的样式class
if (this.mode == 'left') {
return 'time-line-div-left'
} else if (this.mode == 'right') {
return 'time-line-div-right'
} else if (this.mode == 'alternate') {
return 'time-line-div-alternate'
}
},
themeColor() {
if (this.theme == 'dark') {
return 'time-line-dark'
} else {
return 'time-line-light'
}
},
handleClick(item){
this.$emit('handleClick', item, index)
}
},
};
</script>
<style scoped lang="scss">
$contentColor: #333;
$contentbgColor: linear-gradient(0deg, #eee 0%, rgb(206, 197, 201) 100%);;
$lightContentbgColor:linear-gradient(0deg, pink 0%, rgb(245, 205, 223) 100%);
$timeColor: #333;
$lightTimeColor: rgb(212, 102, 153);
$circleColor: #999;
$lightCircleColor: rgb(180, 223, 152);
.time-container {
width: 100%;
display: flex;
}
.time-line-light {
margin: 20px auto;
color: $lightTimeColor;
// background-color: #eee;
.circle {
margin: 20px;
}
.time-line-div {
display: flex;
min-height: 85px;
margin-bottom: 30px;
p:nth-child(2) {
width: 15px;
height: 15px;
top: 10px;
background: $lightCircleColor;
border-radius: 50%;
z-index: 10;
}
p:nth-child(3) {
width:185px;
word-break:break-all; // 英文换行
white-space:pre-wrap; // 中文换行
padding: 10px;
background: $lightContentbgColor;
font-size: 0.8rem;
text-align: left;
color: #fff;
border-radius: 10px;
cursor: pointer;
}
p:nth-child(3):hover {
color:rgb(212, 143, 143)
}
}
/**
mode: left 样式
*/
.time-line-div-left {
justify-content: start;
}
/**
mode: right 样式
*/
.time-line-div-right {
justify-items: flex-end;
flex-direction: row-reverse;
}
/**
mode: alternate 样式
*/
.time-line-div-alternate {
justify-content: flex-end;
&:nth-child(odd) {
flex-direction: row-reverse;
margin-right: 180px;
}
&:nth-child(even) {
margin-left: 180px;
}
}
}
.time-line-dark {
margin: 20px auto;
color: $timeColor;
// background-color: #eee;
.circle {
margin: 20px;
}
.time-line-div {
display: flex;
min-height: 85px;
margin-bottom: 30px;
p:nth-child(2) {
width: 15px;
height: 15px;
top: 10px;
background: $circleColor;
border-radius: 50%;
z-index: 10;
}
p:nth-child(3) {
width: 165px;
padding: 10px;
text-align: left;
background: $contentbgColor;
font-size: 0.8rem;
color: #666;
border-radius: 10px;
cursor: pointer;
}
p:nth-child(3):hover {
color:#eee;
}
}
/**
mode: left 样式
*/
.time-line-div-left {
justify-content: start;
}
/**
mode: right 样式
*/
.time-line-div-right {
justify-items: flex-end;
flex-direction: row-reverse;
}
/**
mode: alternate 样式
*/
.time-line-div-alternate {
justify-content: flex-end;
&:nth-child(odd) {
flex-direction: row-reverse;
margin-right: 180px;
}
&:nth-child(even) {
margin-left: 180px;
}
}
}
.circle {
animation: circleAnime 1s infinite alternate;
}
@keyframes circleAnime {
from {
transform: translateX(5px);
}
to {
transform: translateX(0);
}
}
</style>
|
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getAllProfiles } from '../../actions/Profile_action';
import Spinner from '../layout/Spinner';
import ProfileItem from './ProfileItem';
const Profiles = ({ getAllProfiles, profile: { profiles, loading } }) => {
useEffect(() => {
getAllProfiles();
}, []);
console.log('getallprofilespage');
return (
<>
{loading ? (
<Spinner />
) : (
<>
<h1 className='large text-primary'>Developers</h1>
<p className='lead'>
<i className='fab fa-connectdevlop'></i>Browse and connect with
developers
</p>
<div className='profiles'>
{profiles.length > 0 ? (
profiles.map((profile) => (
<ProfileItem key={profile._id} profile={profile} />
))
) : (
<h4>No Items FOund</h4>
)}
</div>
</>
)}
</>
);
};
Profiles.propTypes = {
getAllProfiles: PropTypes.func.isRequired,
profile: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
profile: state.profile,
});
export default connect(mapStateToProps, { getAllProfiles })(Profiles);
|
import type { Meta, StoryObj } from "@storybook/react";
import { Header } from "./Header";
const meta = {
title: "Header",
component: Header,
tags: ["autodocs"],
argTypes: {
size: {
options: ["h1", "h2", "h3", "h4", "h5", "h6"],
control: { type: "radio" },
},
},
} satisfies Meta<typeof Header>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {
args: {
size: "h1",
text: "Header for storybook",
},
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table{
margin: 0 auto;
border-collapse: collapse;
width: 800px;
height: 500px;
}
td{
border: 1px solid #ccc;
}
</style>
</head>
<body>
<form action="/" method="post" id="fm" enctype="multipart/form-data">
<table>
<tr>
<td>姓名</td>
<td><input name="name" type="text"></td>
</tr>
<tr>
<td>能力</td>
<td><input name="nengli" type="text"></td>
</tr>
<tr>
<td>集团</td>
<td><input name="jituan" type="text"></td>
</tr>
<tr>
<td>上传图片</td>
<td><input name="img" type="file"></td>
</tr>
<tr>
<td></td>
<td><input value="确认修改" type="button" class="sureBtn"></td>
</tr>
</table>
</form>
</body>
<script>
document.querySelector('.sureBtn').onclick = function(){
//发送AJAX请求
//请求方式是POST
//要将请求的数据放入send方法中(http只支持字符串数据传输)
//服务器需要接收post请求(直接使用formidable就可以了)
//服务器接收数据后,写入json文件,然后返回1或0
//ajax 接收1或0后判断并跳转到首页展示
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
alert(xhr.responseText);
if(xhr.responseText == 1){
location.href = '/';
}
}
};
var fm = document.getElementById('fm');
var fd = new FormData(fm);
xhr.open('post', 'http://127.0.0.1:9000/ajaxAdd');
xhr.send(fd);
}
//该方式不支持文件上传,需要通过FORMDATA
function formidablePost(){
//发送AJAX请求
//请求方式是POST
//要将请求的数据放入send方法中(http只支持字符串数据传输)
//服务器需要接收post请求(直接使用formidable就可以了)
//服务器接收数据后,写入json文件,然后返回1或0
//ajax 接收1或0后判断并跳转到首页展示
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
alert(xhr.responseText);
if(xhr.responseText == 1){
location.href = '/';
}
}
};
//组装send要发送的数据
var inps = document.getElementsByTagName('input');
var inpData = 'name='+inps[0].value+'&nengli='+inps[1].value+'&jituan='+inps[2].value;
// console.log(inpData);
inpData = encodeURI(inpData);
xhr.open('post', 'http://127.0.0.1:9000/ajaxAdd');
//使用formidable需要设置请求头 application/x-www-form-urlencoded意思是URL编码的类型
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(inpData);
}
//原生AJAX请求
function ajaxPost(){
//发送AJAX请求
//请求方式是POST
//要将请求的数据放入send方法中(http只支持字符串数据传输)
//服务器需要接收post请求(直接使用formidable就可以了)
//服务器接收数据后,写入json文件,然后返回1或0
//ajax 接收1或0后判断并跳转到首页展示
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
alert(xhr.responseText);
if(xhr.responseText == 1){
location.href = '/';
}
}
};
//组装send要发送的数据
var inps = document.getElementsByTagName('input');
var inpData = 'name='+inps[0].value+'&nengli='+inps[1].value+'&jituan='+inps[2].value;
xhr.open('post', 'http://127.0.0.1:9000/ajaxAdd');
xhr.send(inpData);
}
</script>
</html>
|
package com.example.amphibians.ui.theme
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.amphibians.R
import com.example.amphibians.model.AmphibianInfo
@Composable
fun HomeScreen(
amphibianUiState: AmphibianUiState,
retryAction: () -> Unit,
modifier: Modifier = Modifier
) {
when (amphibianUiState) {
is AmphibianUiState.Loading -> LoadingScreen(modifier = modifier.fillMaxSize())
is AmphibianUiState.Success -> AmphibianGridScreen(amphibianUiState.info, modifier.fillMaxSize())
is AmphibianUiState.Error -> ErrorScreen(retryAction ,modifier = modifier.fillMaxSize())
}
}
@Composable
fun AmphibianInfoCard(info: AmphibianInfo, modifier: Modifier = Modifier) {
Card(
modifier = modifier,
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "${info.name}(${info.type})",
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(12.dp)
)
AsyncImage(
model = ImageRequest.Builder(context = LocalContext.current)
.data(info.imgSrc)
.crossfade(true)
.build(),
error = painterResource(R.drawable.ic_broken_image),
placeholder = painterResource(R.drawable.loading_img),
contentDescription = stringResource(R.string.amphibian_photo),
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth()
)
Text(
text = info.description,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(12.dp)
)
}
}
}
@Composable
fun AmphibianGridScreen(infos: List<AmphibianInfo>, modifier: Modifier = Modifier) {
LazyColumn(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(24.dp),
contentPadding = PaddingValues(4.dp)
) {
items(items = infos, key = { info -> info.name }) {info ->
AmphibianInfoCard(
info,
modifier = modifier
.fillMaxWidth()
)
}
}
}
@Composable
fun LoadingScreen(modifier: Modifier = Modifier) {
Image(
modifier = modifier.size(200.dp),
painter = painterResource(R.drawable.loading_img),
contentDescription = stringResource(R.string.loading)
)
}
@Composable
fun ErrorScreen(retryAction: () -> Unit, modifier: Modifier = Modifier) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.ic_connection_error), contentDescription = ""
)
Text(text = stringResource(R.string.loading_failed), modifier = Modifier.padding(16.dp))
Button(onClick = retryAction) {
Text(stringResource(R.string.retry))
}
}
}
@Preview(showBackground = true)
@Composable
fun AmphibiansListScreenPreview() {
AmphibiansTheme {
val mockData = List(10) {
AmphibianInfo(
"Lorem Ipsum - $it",
"$it",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do" +
" eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad" +
" minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip" +
" ex ea commodo consequat.",
imgSrc = ""
)
}
AmphibianGridScreen(mockData, Modifier.fillMaxSize())
}
}
|
#include "main.h"
/**
* create_file - creates a file with the given text content
* @filename: the name of the file to create
* @text_content: the text content to write to the file
*
* Return: 1 on success, -1 on failure
*/
int create_file(const char *filename, char *text_content)
{
int fd, bytes_written, length = 0;
if (filename == NULL)
return (-1);
if (text_content != NULL)
{
while (text_content[length] != '\0')
length++;
}
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd == -1)
return (-1);
bytes_written = write(fd, text_content, length);
if (bytes_written == -1 || bytes_written != length)
{
close(fd);
return (-1);
}
close(fd);
return (1);
}
|
class Cake{
public void yummy()
{
System.out.println("Yummy cake");
}
}
class CheeseCake extends Cake{
public void yummy()
{
System.out.println("Yummy Cheese Cake");
}
}
public class YummyCakeOverriding {
public static void main(String[] args)
{
Cake c1 = new CheeseCake(); // 동적바인딩
CheeseCake c2 = new CheeseCake();
c1.yummy();
c2.yummy();
}
}
자바는 동적바인딩이 자동으로 일어난다.
동적바인딩이란 실제 실행을 시켜봐야 알 수 있는 것
정적바인딩이란 컴파일 전에 미리 알 수 있는 것
|
import expect from 'expect.js';
import _ from 'lodash';
import { kibanaToEs, esToKibana } from '../converter';
describe('ingest', () => {
describe('processors', () => {
describe('converters', () => {
describe('set', () => {
describe('kibanaToEs', () => {
let source;
let expected;
beforeEach(function () {
source = {
processor_id: 'foo_processor_id',
target_field: 'foo_target_field',
value: 'foo_value',
failure_action: 'foo_failure_action'
};
expected = {
set: {
tag: 'foo_processor_id',
field: 'foo_target_field',
value: 'foo_value',
failure_action: 'foo_failure_action'
}
};
});
it('should convert from a kibana api object to an elasticsearch object', () => {
const actual = kibanaToEs(source);
expect(_.isEqual(actual, expected)).to.be.ok();
});
it('should ignore additional source fields', () => {
source.foo = 'bar';
source.bar = 'baz';
const actual = kibanaToEs(source);
expect(_.isEqual(actual, expected)).to.be.ok();
});
});
describe('esToKibana', () => {
let source;
let expected;
beforeEach(function () {
source = {
set: {
tag: 'foo_tag',
field: 'foo_field',
value: 'foo_value',
failure_action: 'foo_failure_action'
}
};
expected = {
typeId: 'set',
processor_id: 'foo_tag',
target_field: 'foo_field',
value: 'foo_value',
failure_action: 'foo_failure_action'
};
});
it('should convert from an elasticsearch object to a kibana api object', () => {
const actual = esToKibana(source);
expect(_.isEqual(actual, expected)).to.be.ok();
});
it('should ignore additional source fields', () => {
source.set.foo = 'bar';
source.set.bar = 'baz';
const actual = esToKibana(source);
expect(_.isEqual(actual, expected)).to.be.ok();
});
it('should throw an error if argument does not have an [set] property', () => {
const errorMessage = /elasticsearch processor document missing \[set\] property/i;
source.foo = _.clone(source.set);
delete source.set;
expect(esToKibana).withArgs(source).to.throwException(errorMessage);
expect(esToKibana).withArgs(null).to.throwException(errorMessage);
expect(esToKibana).withArgs(undefined).to.throwException(errorMessage);
expect(esToKibana).withArgs('').to.throwException(errorMessage);
expect(esToKibana).withArgs({}).to.throwException(errorMessage);
});
});
});
});
});
});
|
package ru.apteka.social.data.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import ru.apteka.social.data.repository.IDocsApi
import java.util.concurrent.TimeUnit
import javax.inject.Named
@Module
@InstallIn(SingletonComponent::class)
internal class AppHiltModule {
/**
* Представляет экземпляр [OkHttpClient].
*/
@Named("vk")
@Provides
fun provideVKOkHttpClient(): OkHttpClient = OkHttpClient.Builder().apply {
hostnameVerifier { _, _ -> true }
readTimeout(30, TimeUnit.SECONDS)
connectTimeout(30, TimeUnit.SECONDS)
addInterceptor(Interceptor { chain ->
return@Interceptor chain.proceed(
chain.request().newBuilder().apply {
addHeader(
"Authorization",
"Bearer vk1.a.SLZwPtBAPSy1ATAGR_-z5EKYuYB78jK5WzeDqTUXZdHkkYaoiV0wIay0627f360qd3x3k4l7m12NyHsYB8B6jC44QQj09bw-2eEBWBQdDQGteZ4t0omFQ6jCiG9K4f3_qCH9w786bvaGwyvPeHEvIz-upYLevqEB-6Q0OAQNxi00qauDHWZLD34VDW1ak4WyrQlTwVtZxflgN54_CTwJMg"
)
addHeader("Content-Type", "application/json")
url(
(chain.request().url.toString() + if (chain.request().url.toString()
.contains("?")
) { "&" } else { "?" } + "v=5.131")
).build()
}.build()
)
})
}.build()
/**
* Представляет экземпляр [Retrofit].
*/
@Named("vk")
@Provides
fun provideVKRetrofitClient(
@Named("vk") okHttpClient: OkHttpClient
): Retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://api.vk.com/method/")
.addConverterFactory(GsonConverterFactory.create())
.build()
/**
* Предоставляет экземпляр [IDocsApi].
*/
@Provides
fun provideDocsApi(@Named("vk") retrofitClient: Retrofit): IDocsApi =
retrofitClient.create(IDocsApi::class.java)
}
|
package com.phinion.bloggy.ui.components
import androidx.annotation.RawRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import com.airbnb.lottie.RenderMode
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
@Composable
fun ShowLottieAnimation(
@RawRes
rawRes: Int,
modifier: Modifier
) {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(rawRes))
val progress by animateLottieCompositionAsState(composition)
LottieAnimation(
modifier = modifier,
composition = composition,
progress = { progress },
renderMode = RenderMode.HARDWARE
)
}
|
<script lang="ts">
import {cloneDeep} from 'lodash-es';
import {message,Modal} from 'ant-design-vue'
import {
FilterOutlined,
SearchOutlined,
EyeOutlined,
EyeInvisibleOutlined,
EllipsisOutlined,
DeleteOutlined,
EditOutlined,
CheckOutlined,
CloseCircleOutlined,
ExportOutlined
} from '@ant-design/icons-vue'
;
const editableData = {}
export default {
name: 'Passwords',
components: {
FilterOutlined,ExportOutlined,
SearchOutlined, EyeOutlined, EyeInvisibleOutlined, EllipsisOutlined,
DeleteOutlined, EditOutlined, CheckOutlined, CloseCircleOutlined
},
data() {
return {
columns: [
{
title: '网站',
dataIndex: 'domain',
key: 'domain',
resizable: true,
width: 250,
ellipsis: true,
customFilterDropdown: true,
onFilter: (value, record) =>
record.name.toString().toLowerCase().includes(value.toLowerCase()),
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => {
console.log(this.$refs.searchInput)
this.$refs.searchInput.focus();
}, 100);
}
},
},
{
title: '名称',
dataIndex: 'name',
key: 'name',
filters: [
{text: '未命名', value: 'noname'},
{text: '已命名', value: 'named'},
],
},
{
title: '账号',
dataIndex: 'username',
key: 'username',
},
{
title: '密码',
dataIndex: 'password',
key: 'password',
},
{
title: '',
dataIndex: 'show',
key: 'show',
}, {
title: '',
dataIndex: 'action',
key: 'action'
}
],
passwords: [],
editableData,
filters: {
},
searchText: '',
searchColumn: '',
};
},
computed: {},
async mounted() {
this.passwords = await ipc.invoke('credentialStoreGetCredentials')
this.passwords.forEach(password => {
password.show = false
})
},
methods: {
displayData() {
let result = this.passwords.filter((item) => {
let pass
if (this.filters['name']) {
let matchNameNamed=false
let matchNameNoName=false
let name = item.name || ''
if (this.filters['name'].indexOf('noname') > -1) {
if (name === '') {
matchNameNoName = true
}
}
if (this.filters['name'].indexOf('named') > -1) {
if (name !== '') {
matchNameNamed = true
}
}
pass= matchNameNamed || matchNameNoName
}else{
pass=true
}
if (pass) {
//如果通过了名称筛选,再测试搜索
if (this.searchColumn!=='' && this.searchText !== '') {
console.log('text=',this.searchText,'column=',this.searchColumn)
return item[this.searchColumn].indexOf(this.searchText) > -1
}else{
return true
}
}else{
return false
}
})
return result
},
async delAccount(account) {
Modal.confirm({
content:'确认删除密码?此操作不可还原。',
centered:true,
onOk:async () => {
await ipc.invoke('credentialStoreDeletePassword', {
domain: account.domain,
username: account.username
})
this.passwords.splice(this.passwords.indexOf(account), 1)
}
})
},
edit(domain: string, username: string) {
this.editableData[domain + '_' + username] = cloneDeep(this.passwords.filter(item => (domain === item.domain && username === item.username))[0]);
},
save(domain: string, username: string) {
let oldData = this.passwords.filter(item => (domain === item.domain && username === item.username))[0]
let saveData = this.editableData[domain + '_' + username]
if (saveData.username !== oldData.username) {
//编辑了账号的情况下,要排重
let test = this.passwords.filter(item => (domain === item.domain && item.username === saveData.username)).length >= 1
console.log(saveData, 'savedata')
console.log(test)
if (test) {
message.error('不可设置为已经存在的账号名称。')
return
}
}
//Object.assign(oldData, this.editableData[domain+'_'+username]);
ipc.invoke('credentialStoreSetPassword', {
newUsername: saveData.username,
username: oldData.username,
name: saveData.name,
domain: oldData.domain,
password: saveData.password
})
Object.assign(oldData, this.editableData[domain + '_' + username]);
delete editableData[domain + '_' + username];
},
cancelSave(domain: string, username: string) {
delete editableData[domain + '_' + username];
},
handleTableChange(
pag: { pageSize: number; current: number },
filters: any,
sorter: any,
) {
this.filters = filters
},
handleSearch(selectedKeys, confirm, dataIndex) {
console.log('handleSearch',dataIndex)
this.searchColumn = dataIndex
},
handleReset() {
this.searchText = ''
this.searchColumn=''
},
filterDomain(domain){
this.searchText=domain
this.searchColumn='domain'
}
}
}
</script>
<template>
<div>
<div style="margin-bottom: 10px">
<a-tag v-if="this.searchColumn && this.searchText" :closable='true' @close='()=>{this.searchText="";this.searchColumn=""}'
color="#108ee9">网站:{{this.searchText}}</a-tag>
<span v-if="this.filters['name']">
<a-tag v-for="name in this.filters['name']" @close="()=>{
this.filters['name'].splice(this.filters['name'].indexOf(name),1)
}"
color="#108ee9">{{name==='named'?'已命名':'未命名'}}</a-tag>
</span>
</div>
</div>
<a-table style="user-select: text" @change="handleTableChange" :columns="columns" :data-source="displayData()">
<template #headerCell="{ column }">
<template v-if="column.key === 'name'">
<span>
<smile-outlined/>
名称
</span>
</template>
</template>
<template
#customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
>
<div style="padding: 8px">
<a-input
ref="searchInput"
:placeholder="`搜索 ${column.title}`"
v-model:value="searchText"
style="width: 188px; margin-bottom: 8px; display: block"
@pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
/>
<a-button
type="primary"
size="small"
style="width: 90px; margin-right: 8px"
@click="handleSearch(selectedKeys, confirm, column.dataIndex)"
>
<template #icon>
<SearchOutlined/>
</template>
搜索
</a-button>
<a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
重置
</a-button>
</div>
</template>
<template #customFilterIcon="{ filtered,column }">
<filter-outlined v-if="column.dataIndex==='name'" :style="{ color: filtered ? '#108ee9' : undefined }"/>
<search-outlined v-else :style="{ color: (this.searchText!=='' && this.searchColumn===column.dataIndex) ? '#108ee9' : undefined }"/>
</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'domain'">
<a-dropdown>
<a class="ant-dropdown-link" @click.prevent>
{{ record.domain }}
</a>
<template #overlay>
<a-menu>
<a-menu-item>
<a @click="filterDomain(record.domain)" href="javascript:;"><search-outlined></search-outlined> 只看此网站的账号</a>
</a-menu-item>
<a-menu-item>
<a :href="'http://'+record.domain" target="_blank" href="javascript:;"><export-outlined /> 打开此网站</a>
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
<template v-else-if="column.key === 'name'">
<div v-if="editableData[record.domain+'_'+record.username]" class="editable-cell-input-wrapper">
<a-input v-model:value="editableData[record.domain+'_'+record.username].name"
@pressEnter="save(record.domain,record.username)"/>
</div>
<div v-else class="editable-cell-text-wrapper">
{{ record.name }}
</div>
</template>
<template v-else-if="column.key === 'username'">
<div v-if="editableData[record.domain+'_'+record.username]" class="editable-cell-input-wrapper">
<a-input v-model:value="editableData[record.domain+'_'+record.username].username"
@pressEnter="save(record.domain,record.username)"/>
</div>
<div v-else class="editable-cell-text-wrapper">
{{ record.username }}
</div>
</template>
<template v-if="column.key === 'password'">
<div v-if="editableData[record.domain+'_'+record.username]" class="editable-cell-input-wrapper">
<a-input v-model:value="editableData[record.domain+'_'+record.username].password"
@pressEnter="save(record.domain,record.username)"/>
</div>
<div v-else class="editable-cell-text-wrapper">
<span v-if="record.show">
{{ record.password }}
</span>
<span v-else>
{{ '•••••••••' }}
</span>
</div>
</template>
<template v-else-if="column.key==='show'">
<a-button @click="record.show=!record.show" type="primary" shape="circle" size="small">
<span v-if="!record.show">
<eye-outlined/>
</span>
<span v-else>
<eye-invisible-outlined/>
</span>
</a-button>
</template>
<template v-else-if="column.key === 'tags'">
<span>
<a-tag
v-for="tag in record.tags"
:key="tag"
:color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
>
{{ tag.toUpperCase() }}
</a-tag>
</span>
</template>
<template v-else-if="column.key === 'action'">
<a-dropdown v-if="!editableData[record.domain+'_'+record.username]">
<span class="ant-dropdown-link" @click.prevent>
<ellipsis-outlined style="font-size: 22px"/>
</span>
<template #overlay>
<a-menu>
<a-menu-item>
<a @click="delAccount(record)" href="javascript:;">
<delete-outlined/>
删除</a>
</a-menu-item>
<a-menu-item>
<a @click="edit(record.domain,record.username)">
<edit-outlined/>
编辑</a>
</a-menu-item>
<!-- <a-menu-item>-->
<!-- <a href="javascript:;">2nd menu item</a>-->
<!-- </a-menu-item>-->
<!-- <a-menu-item>-->
<!-- <a href="javascript:;">3rd menu item</a>-->
<!-- </a-menu-item>-->
</a-menu>
</template>
</a-dropdown>
<div style="font-size: 20px" v-else>
<check-outlined class="editable-cell-icon-check" @click="save(record.domain,record.username)"/>
<close-circle-outlined @click="cancelSave(record.domain,record.username)"/>
</div>
</template>
</template>
</a-table>
</template>
<style scoped>
label {
margin: 0 0.5em;
font-weight: bold;
}
code {
background-color: #eee;
padding: 2px 4px;
border-radius: 4px;
color: #304455;
}
</style>
|
package com.lan.website.mbg.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class IpsetExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public IpsetExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andKeyIdIsNull() {
addCriterion("key_id is null");
return (Criteria) this;
}
public Criteria andKeyIdIsNotNull() {
addCriterion("key_id is not null");
return (Criteria) this;
}
public Criteria andKeyIdEqualTo(Integer value) {
addCriterion("key_id =", value, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdNotEqualTo(Integer value) {
addCriterion("key_id <>", value, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdGreaterThan(Integer value) {
addCriterion("key_id >", value, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdGreaterThanOrEqualTo(Integer value) {
addCriterion("key_id >=", value, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdLessThan(Integer value) {
addCriterion("key_id <", value, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdLessThanOrEqualTo(Integer value) {
addCriterion("key_id <=", value, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdIn(List<Integer> values) {
addCriterion("key_id in", values, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdNotIn(List<Integer> values) {
addCriterion("key_id not in", values, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdBetween(Integer value1, Integer value2) {
addCriterion("key_id between", value1, value2, "keyId");
return (Criteria) this;
}
public Criteria andKeyIdNotBetween(Integer value1, Integer value2) {
addCriterion("key_id not between", value1, value2, "keyId");
return (Criteria) this;
}
public Criteria andIpIsNull() {
addCriterion("ip is null");
return (Criteria) this;
}
public Criteria andIpIsNotNull() {
addCriterion("ip is not null");
return (Criteria) this;
}
public Criteria andIpEqualTo(String value) {
addCriterion("ip =", value, "ip");
return (Criteria) this;
}
public Criteria andIpNotEqualTo(String value) {
addCriterion("ip <>", value, "ip");
return (Criteria) this;
}
public Criteria andIpGreaterThan(String value) {
addCriterion("ip >", value, "ip");
return (Criteria) this;
}
public Criteria andIpGreaterThanOrEqualTo(String value) {
addCriterion("ip >=", value, "ip");
return (Criteria) this;
}
public Criteria andIpLessThan(String value) {
addCriterion("ip <", value, "ip");
return (Criteria) this;
}
public Criteria andIpLessThanOrEqualTo(String value) {
addCriterion("ip <=", value, "ip");
return (Criteria) this;
}
public Criteria andIpLike(String value) {
addCriterion("ip like", value, "ip");
return (Criteria) this;
}
public Criteria andIpNotLike(String value) {
addCriterion("ip not like", value, "ip");
return (Criteria) this;
}
public Criteria andIpIn(List<String> values) {
addCriterion("ip in", values, "ip");
return (Criteria) this;
}
public Criteria andIpNotIn(List<String> values) {
addCriterion("ip not in", values, "ip");
return (Criteria) this;
}
public Criteria andIpBetween(String value1, String value2) {
addCriterion("ip between", value1, value2, "ip");
return (Criteria) this;
}
public Criteria andIpNotBetween(String value1, String value2) {
addCriterion("ip not between", value1, value2, "ip");
return (Criteria) this;
}
public Criteria andTypeIsNull() {
addCriterion("type is null");
return (Criteria) this;
}
public Criteria andTypeIsNotNull() {
addCriterion("type is not null");
return (Criteria) this;
}
public Criteria andTypeEqualTo(String value) {
addCriterion("type =", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotEqualTo(String value) {
addCriterion("type <>", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThan(String value) {
addCriterion("type >", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThanOrEqualTo(String value) {
addCriterion("type >=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThan(String value) {
addCriterion("type <", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThanOrEqualTo(String value) {
addCriterion("type <=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLike(String value) {
addCriterion("type like", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotLike(String value) {
addCriterion("type not like", value, "type");
return (Criteria) this;
}
public Criteria andTypeIn(List<String> values) {
addCriterion("type in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<String> values) {
addCriterion("type not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(String value1, String value2) {
addCriterion("type between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(String value1, String value2) {
addCriterion("type not between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andMarkIsNull() {
addCriterion("mark is null");
return (Criteria) this;
}
public Criteria andMarkIsNotNull() {
addCriterion("mark is not null");
return (Criteria) this;
}
public Criteria andMarkEqualTo(String value) {
addCriterion("mark =", value, "mark");
return (Criteria) this;
}
public Criteria andMarkNotEqualTo(String value) {
addCriterion("mark <>", value, "mark");
return (Criteria) this;
}
public Criteria andMarkGreaterThan(String value) {
addCriterion("mark >", value, "mark");
return (Criteria) this;
}
public Criteria andMarkGreaterThanOrEqualTo(String value) {
addCriterion("mark >=", value, "mark");
return (Criteria) this;
}
public Criteria andMarkLessThan(String value) {
addCriterion("mark <", value, "mark");
return (Criteria) this;
}
public Criteria andMarkLessThanOrEqualTo(String value) {
addCriterion("mark <=", value, "mark");
return (Criteria) this;
}
public Criteria andMarkLike(String value) {
addCriterion("mark like", value, "mark");
return (Criteria) this;
}
public Criteria andMarkNotLike(String value) {
addCriterion("mark not like", value, "mark");
return (Criteria) this;
}
public Criteria andMarkIn(List<String> values) {
addCriterion("mark in", values, "mark");
return (Criteria) this;
}
public Criteria andMarkNotIn(List<String> values) {
addCriterion("mark not in", values, "mark");
return (Criteria) this;
}
public Criteria andMarkBetween(String value1, String value2) {
addCriterion("mark between", value1, value2, "mark");
return (Criteria) this;
}
public Criteria andMarkNotBetween(String value1, String value2) {
addCriterion("mark not between", value1, value2, "mark");
return (Criteria) this;
}
public Criteria andFirsttimeIsNull() {
addCriterion("firsttime is null");
return (Criteria) this;
}
public Criteria andFirsttimeIsNotNull() {
addCriterion("firsttime is not null");
return (Criteria) this;
}
public Criteria andFirsttimeEqualTo(Date value) {
addCriterion("firsttime =", value, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeNotEqualTo(Date value) {
addCriterion("firsttime <>", value, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeGreaterThan(Date value) {
addCriterion("firsttime >", value, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeGreaterThanOrEqualTo(Date value) {
addCriterion("firsttime >=", value, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeLessThan(Date value) {
addCriterion("firsttime <", value, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeLessThanOrEqualTo(Date value) {
addCriterion("firsttime <=", value, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeIn(List<Date> values) {
addCriterion("firsttime in", values, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeNotIn(List<Date> values) {
addCriterion("firsttime not in", values, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeBetween(Date value1, Date value2) {
addCriterion("firsttime between", value1, value2, "firsttime");
return (Criteria) this;
}
public Criteria andFirsttimeNotBetween(Date value1, Date value2) {
addCriterion("firsttime not between", value1, value2, "firsttime");
return (Criteria) this;
}
public Criteria andBantimeIsNull() {
addCriterion("bantime is null");
return (Criteria) this;
}
public Criteria andBantimeIsNotNull() {
addCriterion("bantime is not null");
return (Criteria) this;
}
public Criteria andBantimeEqualTo(Date value) {
addCriterion("bantime =", value, "bantime");
return (Criteria) this;
}
public Criteria andBantimeNotEqualTo(Date value) {
addCriterion("bantime <>", value, "bantime");
return (Criteria) this;
}
public Criteria andBantimeGreaterThan(Date value) {
addCriterion("bantime >", value, "bantime");
return (Criteria) this;
}
public Criteria andBantimeGreaterThanOrEqualTo(Date value) {
addCriterion("bantime >=", value, "bantime");
return (Criteria) this;
}
public Criteria andBantimeLessThan(Date value) {
addCriterion("bantime <", value, "bantime");
return (Criteria) this;
}
public Criteria andBantimeLessThanOrEqualTo(Date value) {
addCriterion("bantime <=", value, "bantime");
return (Criteria) this;
}
public Criteria andBantimeIn(List<Date> values) {
addCriterion("bantime in", values, "bantime");
return (Criteria) this;
}
public Criteria andBantimeNotIn(List<Date> values) {
addCriterion("bantime not in", values, "bantime");
return (Criteria) this;
}
public Criteria andBantimeBetween(Date value1, Date value2) {
addCriterion("bantime between", value1, value2, "bantime");
return (Criteria) this;
}
public Criteria andBantimeNotBetween(Date value1, Date value2) {
addCriterion("bantime not between", value1, value2, "bantime");
return (Criteria) this;
}
public Criteria andTotimeIsNull() {
addCriterion("totime is null");
return (Criteria) this;
}
public Criteria andTotimeIsNotNull() {
addCriterion("totime is not null");
return (Criteria) this;
}
public Criteria andTotimeEqualTo(Date value) {
addCriterion("totime =", value, "totime");
return (Criteria) this;
}
public Criteria andTotimeNotEqualTo(Date value) {
addCriterion("totime <>", value, "totime");
return (Criteria) this;
}
public Criteria andTotimeGreaterThan(Date value) {
addCriterion("totime >", value, "totime");
return (Criteria) this;
}
public Criteria andTotimeGreaterThanOrEqualTo(Date value) {
addCriterion("totime >=", value, "totime");
return (Criteria) this;
}
public Criteria andTotimeLessThan(Date value) {
addCriterion("totime <", value, "totime");
return (Criteria) this;
}
public Criteria andTotimeLessThanOrEqualTo(Date value) {
addCriterion("totime <=", value, "totime");
return (Criteria) this;
}
public Criteria andTotimeIn(List<Date> values) {
addCriterion("totime in", values, "totime");
return (Criteria) this;
}
public Criteria andTotimeNotIn(List<Date> values) {
addCriterion("totime not in", values, "totime");
return (Criteria) this;
}
public Criteria andTotimeBetween(Date value1, Date value2) {
addCriterion("totime between", value1, value2, "totime");
return (Criteria) this;
}
public Criteria andTotimeNotBetween(Date value1, Date value2) {
addCriterion("totime not between", value1, value2, "totime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
# `mysql_db` module
Provisions a mysql database using AWS RDS, on a given subnet, along with a security group.
Also creates a policy to interact with the DB and assigns it to the given role.
## Requirements
No requirements.
## Providers
| Name | Version |
| ------------------------------------------------ | ------- |
| <a name="provider_aws"></a> [aws](#provider_aws) | n/a |
## Modules
| Name | Source | Version |
| ----------------------------------------------------------------- | ----------------------------- | ------- |
| <a name="module_rds_policy"></a> [rds_policy](#module_rds_policy) | ../../policies/rds_app_policy | n/a |
## Resources
| Name | Type |
| -------------------------------------------------------------------------------------------------------------------------------- | -------- |
| [aws_db_instance.mysql_db](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/db_instance) | resource |
| [aws_db_subnet_group.db_subnet_grp](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/db_subnet_group) | resource |
| [aws_security_group.mysql_db_sg](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group) | resource |
## Inputs
| Name | Description | Type | Default | Required |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------- | :------: |
| <a name="input_app_role_name"></a> [app_role_name](#input_app_role_name) | Name of the role that will access db. | `string` | n/a | yes |
| <a name="input_context_name"></a> [context_name](#input_context_name) | Name of the current context to create networking resources (eg: an app name) | `string` | n/a | yes |
| <a name="input_credentials"></a> [credentials](#input_credentials) | Username & password pair for db credentials. | <pre>object({<br> username = string<br> password = string<br> })</pre> | n/a | yes |
| <a name="input_db_name"></a> [db_name](#input_db_name) | Name of the db to give access to | `string` | n/a | yes |
| <a name="input_stage"></a> [stage](#input_stage) | Deployment stage name (eg: PRD, STG, SANDBOX, QA, etc) | `string` | n/a | yes |
| <a name="input_subnet_ids"></a> [subnet_ids](#input_subnet_ids) | Subnet ids for the db. | `list(string)` | n/a | yes |
| <a name="input_vpc_id"></a> [vpc_id](#input_vpc_id) | ID of the vpc to bind the db to. | `string` | n/a | yes |
## Outputs
No outputs.
|
const animalArray: string[] = ['Hebbe', 'Zaqi', 'Gizmo', 'Daizy']
const hebbeInfo: string[] = ['Namn: Hebbe', 'Ålder: 13år', 'Ras: Engelsk Cocker Spaniel',
'Älskar att bara ta det lungt men njuter även väldigt mycket av sina promenader']
const zaqiInfo: string[] = ['Namn: Zaqi', 'Ålder: 2år', 'Ras: Blandning mellan Staffe/Boxer',
'Älskar mys i soffan/sängen men blir lätt rastlös utan mycket aktivering och uppmärksamhet']
const gizmoInfo: string[] = ['Namn: Gizmo', 'Ålder: 13år', 'Ras: Staffe/Bullterrier',
'Är världens gullegris som älskar att mysa på soffan och ta lugna promenader']
const daizyInfo: string[] = ['Namn: Daizy', 'Ålder: 3år', 'Ras: Staffe', `Daizy är en 3årig staffe som inte gillar att vara ensam och vill vara med överallt och behöver
mycket aktivering`]
window.addEventListener('load', main)
function main() {
createHeaderElements()
printAnimals()
animalPictures()
informationAboutTheDogs()
}
function createMainContainer() {
let div = document.querySelector('#app')
const mainElement = document.createElement('main')
mainElement.className = 'main'
div!.append(mainElement)
}
function createHeaderElements() {
let div = document.querySelector('#app')
const headerElement = document.createElement('header')
headerElement.className = 'header'
div!.append(headerElement)
let titleName = document.createElement('h1')
titleName.innerText = 'Animal Adoption'
titleName.className = 'title'
headerElement.append(titleName)
}
function printAnimals() {
createMainContainer()
let allAnimals = document.createElement('ul')
allAnimals.innerText = ''
allAnimals.className = 'ulElement'
document.querySelector('main')!.append(allAnimals)
animalArray.forEach((dogs) => {
let listOfDogs = document.createElement('li')
listOfDogs.innerText = dogs
allAnimals.append(listOfDogs)
})
}
function animalPictures() {
let div = document.createElement('div')
div.className = 'Img-container'
let imgHebbe = new Image(300, 500)
imgHebbe.src = './img/Hebbe.jpg'
let imgZaqi = new Image(300, 500)
imgZaqi.src = './img/Zaqi.jpg'
let imgGizmo = new Image(430, 500)
imgGizmo.src = './img/Gizmo&Daizy.jpg'
let imgDaizy = new Image(250, 500)
imgDaizy.src = './img/Daizy.jpg'
document.querySelector('.main')!.append(div)
div.append(imgHebbe, imgZaqi, imgGizmo, imgDaizy)
}
function informationAboutTheDogs() {
let div = document.createElement('div')
div.className = 'div-container'
let hebbeElement = document.createElement('ul')
hebbeInfo.forEach((hebbeDoggo) => {
let dogInfo = document.createElement('li')
dogInfo.innerText = hebbeDoggo
document.querySelector('.main')!.append(div)
hebbeElement.append(dogInfo)
})
let zaqiElement = document.createElement('ul')
zaqiInfo.forEach((zaqiDoggo) => {
let dogInfo = document.createElement('li')
dogInfo.innerText = zaqiDoggo
document.querySelector('.main')!.append(div)
zaqiElement.append(dogInfo)
})
let gizmoElement = document.createElement('ul')
gizmoInfo.forEach((gizmoDoggo) => {
let dogInfo = document.createElement('li')
dogInfo.innerText = gizmoDoggo
document.querySelector('.main')!.append(div)
gizmoElement.append(dogInfo)
})
let daizyElement = document.createElement('ul')
daizyInfo.forEach((daizyDoggo) => {
let dogInfo = document.createElement('li')
dogInfo.innerText = daizyDoggo
document.querySelector('.main')!.append(div)
daizyElement.append(dogInfo)
})
div.append(hebbeElement, zaqiElement, gizmoElement, daizyElement)
}
|
package com.sym.singletonpattern;
/**
* 单例模式-饿汉式变化式
* 可用
* 访问方式:HungrySingleton2 hungrySingleton2 = HungrySingleton2.getHungrySingleton2();
*/
public class HungrySingleton2 {
private static HungrySingleton2 hungrySingleton2 = null;
static {
hungrySingleton2 = new HungrySingleton2();
}
private HungrySingleton2(){}
public static HungrySingleton2 getInstance() {
return hungrySingleton2;
}
}
|
import React from "react";
import { render, screen, act, waitFor } from "@testing-library/react";
import App from "./App";
function MockComponent() {
return <div>mock</div>;
}
jest.mock("./ApiContainer", () => () => <MockComponent />);
test("renders App with a loader until ApiContainer lazy loads", async () => {
render(<App />);
await screen.findByRole("heading", {
name: /search for public apis/i,
});
// assert that accessible loader is rendered
const loader = screen.getByRole("status");
expect(loader.textContent).toMatch(/searching for apis/i);
// wait for lazy loaded component
await screen.findByText(/mock/i);
});
|
<% provide :title, t(".log_in") %>
<h1><%= t ".log_in" %></h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for :session, url: login_path do |f| %>
<div class="form-group">
<%= f.label :email, t(".email") %>
<%= f.email_field :email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :password, t(".password") %>
<%= link_to "(#{t "password_forgot" })", new_password_reset_path %>
<%= f.password_field :password, class: "form-control" %>
</div>
<%= f.label :remember_me, class: "checkbox inline" do %>
<%= f.check_box :remember_me %>
<span><%= t "remember_me" %></span>
<% end %>
<%= f.submit t(".log_in"), class: "btn btn-primary" %>
<% end %>
<p><%= t(".new_user") %> <%= link_to t(".sign_up_now"), signup_path %></p>
</div>
</div>
|
import { Select, Table } from "antd";
import TeacherServices from "api/TeacherServices";
import React, { useEffect, useState } from "react";
import { Link, useParams, useHistory } from "react-router-dom";
import { RouteDefinitons } from "routes/RouteDefinitions";
import Modal from "../../components/common/Modal/Modal";
import CommonButton from "../../components/common/Button/Button";
export const StudentPractice = (props) => {
const [loading, setloading] = useState(false);
const [data, setData] = useState(null);
const [modal, setModal] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const history = useHistory();
const { id } = useParams();
useEffect(() => {
TeacherServices.getClassesById(id).then((res) => {
setData(
res.data.data.studentsList.map((it) => ({ ...it, key: it.student_id }))
);
});
console.log(data);
}, [id]);
const toggleModal = () => {
setModal(!modal);
};
const columns = [
{
title: "Name",
dataIndex: "student_name",
},
{
title: "Mission Points",
dataIndex: "mission_points",
},
{
title: "Revise Points",
dataIndex: "revise_points",
},
{
title: "Recent Mission Date",
dataIndex: "most_recent_mission_date",
render: (text) => text.split("GMT")[0],
},
{
title: "Recent Revise Date",
dataIndex: "most_recent_revise_date",
render: (text) => text.split("GMT")[0],
},
{
title: "Detailed Report",
dataIndex: "most_recent_revise_date",
render: (text, record) => (
<Link
to={RouteDefinitons.ROUTE_STUDENT_PRACTICE_DETAILED_REPORT.replace(
":id",
record.student_id
)}
className="table-btn"
>
{"Click here"}
</Link>
),
},
];
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
setSelectedRowKeys(selectedRowKeys);
console.log(
`selectedRowKeys: ${selectedRowKeys}`,
"selectedRows: ",
selectedRows
);
},
};
return (
<div className="pa-30">
<div className="Monts-Bold fs-24 dark-blue mb-10">Student Practice</div>
<div className="flex-x center mb-20" style={{ gap: "2rem" }}>
<CommonButton
style={{
minWidth: 100,
marginRight: 20,
border: "1px solid #3aa76d",
color: "#3aa76d",
background: "#fff",
}}
text="Summary Report"
width="200"
onClick={() => {
history.push(
RouteDefinitons.ROUTE_TEACHER_SUMMARY_REPORT.replace(":id", id)
);
}}
></CommonButton>
<CommonButton
style={{
minWidth: 100,
marginRight: 20,
border: "1px solid #3aa76d",
color: "#3aa76d",
background: "#fff",
}}
text="All Classes Report"
width="200"
onClick={() => {
history.push(
RouteDefinitons.ROUTE_TEACHER_SUMMARY_REPORT.replace(":id", 0)
);
}}
></CommonButton>
</div>
<Table
bordered
rowSelection={{
type: "checkbox",
...rowSelection,
}}
columns={columns}
dataSource={data}
/>
<CommonButton
text="Message"
onClick={toggleModal}
width={200}
style={{ margin: "auto", display: "block" }}
>
Message
</CommonButton>
<Modal
isOpen={modal}
toggle={toggleModal}
title="Message"
selectedRowKeys={selectedRowKeys}
/>
</div>
);
};
|
<template>
</template>
<script>
import Print from '../mixins/print'
import PDF from '../mixins/pdf'
import Error from '../mixins/errors'
export default {
mixins: [ Print, PDF, Error ],
props: ['columnClass', 'chartType', 'chartTitle', 'dataUrl', 'generalQuery', 'maintainAspectRatio'],
data: function () {
return {
rangeOptions: [
{label: 'Last week', value: '7'},
{label: 'Last 2 weeks', value: '14'},
{label: 'Last month', value: '30'},
{label: 'Last 2 months', value: '60'},
{label: 'Last 6 months', value: '180'},
],
typeOptions: [
{label: 'Bar chart', value: 'bar'},
{label: 'Line chart', value: 'line'},
{label: 'Horizontal bar chart', value: 'horizontalBar'}
],
range: {label: 'Last month', value: '30'},
type: {label: 'Bar chart', value: 'bar'},
data: {},
chart: null,
loading: false,
filtersVisible: false,
chartId: _.uniqueId(['chart_']),
}
},
computed: {
chartTypeComputed: function() {
if(typeof this.chartType !== undefined){
return this.chartType;
} else {
return this.type.value;
}
}
},
watch: {
range: function() {
if(this.chart !== null){
this.chart.destroy();
}
this.getData();
},
type: function() {
this.chartType = this.type.value;
if(this.chart !== null){
this.chart.destroy();
}
this.drawChart();
}
},
created: function () {
},
mounted: function() {
this.getData();
},
methods: {
toggleFilters: function(){
if(this.filtersVisible){
this.filtersVisible = false;
} else {
this.filtersVisible = true;
}
},
/**
* Return a shade of the hex or rba formatted color set in c0 and/or c1 with opacity set in p
*/
shadeColor: function(c0,c1,p) {
var n=p<0?p*-1:p,u=Math.round,w=parseInt;
if(c0.length>7){
var f=c0.split(","),t=(c1?c1:p<0?"rgb(0,0,0)":"rgb(255,255,255)").split(","),R=w(f[0].slice(4)),G=w(f[1]),B=w(f[2]);
return "rgb("+(u((w(t[0].slice(4))-R)*n)+R)+","+(u((w(t[1])-G)*n)+G)+","+(u((w(t[2])-B)*n)+B)+")"
}else{
var f=w(c0.slice(1),16),t=w((c1?c1:p<0?"#000000":"#FFFFFF").slice(1),16),R1=f>>16,G1=f>>8&0x00FF,B1=f&0x0000FF;
return "#"+(0x1000000+(u(((t>>16)-R1)*n)+R1)*0x10000+(u(((t>>8&0x00FF)-G1)*n)+G1)*0x100+(u(((t&0x0000FF)-B1)*n)+B1)).toString(16).slice(1)
}
},
/**
* Transform a hex color to rgba with opacity
*/
hexToRGBA: function(h,p){
h = h.replace('#','');
return 'rgba('+parseInt(h.substring(0,2), 16)+','+parseInt(h.substring(2,4), 16)+','+parseInt(h.substring(4,6), 16)+','+p+')';
}
}
}
</script>
|
/*
* MAX1704X Arduino Library for MAX17043 and MAX17044 Fuel Gauge.
*
* Version 1.0.0
* Copyright © 2018 Daniel Porrey. All Rights Reserved.
* https://github.com/porrey/max1704x
*
* This file is part of the MAX1704X Arduino Library.
*
* The MAX1704X Arduino Library 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.
*
* The MAX1704X Arduino Library is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the MAX1704X Arduino Library. If not,
* see http://www.gnu.org/licenses/.
*/
#include "MAX17043.h"
// ***
// *** Connections:
// *** 1) Conect SDA pin to A4 on Uno
// *** 2) Connect SCL pin to A5 on Uno
// *** 3) Connect the GND pin to ground on the Uno.
// ***
// *** For other devices lookup the correct i2C
// *** (SDA and SCL) pins.
// ***
void setup()
{
// ***
// *** Initialize the serial interface.
// ***
Serial.begin(115200);
// ***
// *** Initialize the fuel gauge.
// ***
FuelGauge.begin();
// ***
// *** Display an initial reading.
// ***
displayReading();
Serial.println();
displayMenu();
}
void loop()
{
Serial.println("Enter an option in the serial input (M for menu):");
while (Serial.available() == 0)
{
delay(25);
}
char c = Serial.read();
Serial.println();
switch (c)
{
case 'M':
displayMenu();
break;
case 'D':
displayReading();
break;
case 'S':
sleepMode();
break;
case 'W':
wakeMode();
break;
case 'Q':
quickStart();
break;
case 'C':
clearAlert();
break;
case 'R':
reset();
break;
case '+':
incrementThreshold();
break;
case '-':
decrementThreshold();
break;
}
Serial.println();
}
void displayMenu()
{
Serial.println("D => Display a reading.");
Serial.println("S => Enter sleep mode.");
Serial.println("W => Wake.");
Serial.println("Q => Quick start.");
Serial.println("C => Clear alert.");
Serial.println("R => Reset.");
Serial.println("+ => Increment threshold.");
Serial.println("- => Decrement threshold.");
}
void displayReading()
{
// ***
// *** Get the voltage, battery percent
// *** and other properties.
// ***
Serial.print("Version: "); Serial.println(FuelGauge.version());
Serial.print("ADC: "); Serial.println(FuelGauge.adc());
Serial.print("Voltage: "); Serial.print(FuelGauge.voltage()); Serial.println(" v");
Serial.print("Percent: "); Serial.print(FuelGauge.percent()); Serial.println("%");
Serial.print("Is Sleeping: "); Serial.println(FuelGauge.isSleeping() ? "Yes" : "No");
Serial.print("Alert: "); Serial.println(FuelGauge.alertIsActive() ? "Yes" : "No");
Serial.print("Threshold: "); Serial.println(FuelGauge.getThreshold());
Serial.print("Compensation: 0x"); Serial.println(FuelGauge.compensation(), HEX);
}
void sleepMode()
{
if (!FuelGauge.isSleeping())
{
FuelGauge.sleep();
if (FuelGauge.isSleeping())
{
Serial.println("Fuel Gauge put in sleep mode.");
}
else
{
Serial.println("Fuel Gauge failed to be put in sleep mode.");
}
}
else
{
Serial.println("Fuel Gauge is already in sleep mode.");
}
}
void wakeMode()
{
if (FuelGauge.isSleeping())
{
FuelGauge.wake();
if (!FuelGauge.isSleeping())
{
Serial.println("Fuel Gauge is now awake.");
}
else
{
Serial.println("Failed to wake Fuel Gauge.");
}
}
else
{
Serial.println("Fuel Gauge is already awake.");
}
}
void reset()
{
FuelGauge.reset();
Serial.println("Fuel Gauge has been reset/rebooted.");
}
void quickStart()
{
FuelGauge.quickstart();
Serial.println("Quick start has been initiated on the Fuel Gauge.");
}
void clearAlert()
{
FuelGauge.clearAlert();
Serial.println("The alert has been cleared on the Fuel Gauge.");
}
void incrementThreshold()
{
uint8_t threshold = FuelGauge.getThreshold();
FuelGauge.setThreshold(++threshold);
Serial.print("The alert threshold has been incremented to "); Serial.print(FuelGauge.getThreshold()); Serial.println(",");
}
void decrementThreshold()
{
uint8_t threshold = FuelGauge.getThreshold();
FuelGauge.setThreshold(--threshold);
Serial.print("The alert threshold has been decremented to "); Serial.print(FuelGauge.getThreshold()); Serial.println(",");
}
|
import { runReaderTask, asksTask } from "../src/ReaderTask"
import * as RT from "fp-ts/ReaderTask"
import * as T from "fp-ts/Task"
import { flow, pipe } from "fp-ts/function"
import fc from "fast-check"
import * as Str from "../src/String"
describe("ReaderTask", () => {
describe("runReaderTask", () => {
it("extracts expected Task from a ReaderTask", async () => {
type Env = { dependency: string }
const env: Env = { dependency: "dependency" }
await fc.assert(
fc.asyncProperty(fc.integer(), async _ => {
const extractedTask = pipe(
RT.of<Env, number>(_),
runReaderTask(env),
)()
await expect(extractedTask).resolves.toBe(_)
}),
)
})
})
describe("asksTask", () => {
it("runs action and lifts to a Reader", () => {
return expect(
asksTask(flow(Str.prepend("foo"), T.of))("bar")(),
).resolves.toBe("foobar")
})
})
})
|
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link href="style.css" type="text/css" rel="stylesheet"/>
<div id="app">
<div class="box" :style="{backgroundColor : color}"></div>
<div class="box" :style="customStyle"></div>
<div class="box" ></div>
<hr>
<input type="text" v-model="color">
<input type="text" v-model="height">
</div>
<script>
new Vue({
el: "#app",
data:{
color:"green",
height:100
},
computed :{
customStyle : function(){
return{
backgroundColor : this.color,
height : this.height + "px"
}
}
}
})
</script>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.