text
stringlengths 184
4.48M
|
|---|
import 'package:battlefield_2042_state/components/basic/constraints_modal_bottom_sheet.dart';
import 'package:battlefield_2042_state/model/player_info_model.dart';
import 'package:battlefield_2042_state/screen/login_screen.dart';
import 'package:battlefield_2042_state/theme/color_schemes.g.dart';
import 'package:battlefield_2042_state/utils/tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(ChangeNotifierProvider(
create: (context) => PlayerInfoModel(),
child: const MyApp(),
));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BF2042State',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a blue toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: lightColorScheme,
// fontFamily: 'HarmonyOS_Sans_SC',
useMaterial3: true,
),
darkTheme: ThemeData(
colorScheme: darkColorScheme,
// fontFamily: 'HarmonyOS_Sans_SC',
useMaterial3: true,
),
themeMode: ThemeMode.system,
home: const MainScreen(),
);
}
}
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
@override
State<StatefulWidget> createState() => MainScreenState();
}
class MainScreenState extends State<MainScreen> with WidgetsBindingObserver {
final SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
systemNavigationBarColor: Colors.transparent,
);
void transparentSystemUi() {
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
}
void forcePortrait() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.resumed) {
transparentSystemUi();
forcePortrait();
}
}
@override
void initState() {
// TODO: implement initState
super.initState();
transparentSystemUi();
forcePortrait();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
actions: [
IconButton(
onPressed: () {
ConstraintsModalBottomSheet.showConstraintsModalBottomSheet(
context, const BottomSheetInfo());
},
icon: const Icon(Icons.menu),
)
],
),
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth < WidthBreakpoints.minS) {
return const LoginScreen(
loginScreenWidthScale: 0.85,
playerInfoCardWidthScale: 0.95,
);
} else if (constraints.maxWidth < WidthBreakpoints.minM) {
return const LoginScreen(
loginScreenWidthScale: 0.6, playerInfoCardWidthScale: 0.6);
} else if (constraints.maxWidth < WidthBreakpoints.minL) {
return const LoginScreen(
loginScreenWidthScale: 0.4, playerInfoCardWidthScale: 0.4);
} else if (constraints.maxWidth < WidthBreakpoints.minXL) {
return const LoginScreen(
loginScreenWidthScale: 0.3, playerInfoCardWidthScale: 0.3);
} else {
return const LoginScreen(
loginScreenWidthScale: 0.2, playerInfoCardWidthScale: 0.2);
}
}));
}
}
class BottomSheetInfo extends StatefulWidget {
const BottomSheetInfo({super.key});
@override
State<StatefulWidget> createState() => _BottomSheetInfoState();
}
class _BottomSheetInfoState extends State<BottomSheetInfo> {
late String version = 'null';
late String buildNumber = '-1';
void getVersion() async {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
setState(() {
version = packageInfo.version;
buildNumber = packageInfo.buildNumber;
});
}
Future<void> urlLauncher(String url) async {
if (!await launchUrl(Uri.parse(url))) {
throw Exception('错误! 无法打开: $url');
}
}
@override
void initState() {
getVersion();
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('战地2042战绩查询助手',
style: Theme.of(context).textTheme.headlineSmall),
const Padding(padding: EdgeInsets.only(top: 8)),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Ver.$version-$buildNumber',
style: TextStyle(
fontSize: Theme.of(context).textTheme.bodySmall?.fontSize,
fontWeight:
Theme.of(context).textTheme.bodySmall?.fontWeight,
color: Theme.of(context).colorScheme.primary,
)),
const Padding(padding: EdgeInsets.only(left: 8)),
Text('by Egg Targaryen',
style: TextStyle(
fontSize: Theme.of(context).textTheme.bodySmall?.fontSize,
fontWeight:
Theme.of(context).textTheme.bodySmall?.fontWeight,
color: Theme.of(context).colorScheme.primary,
)),
],
),
TextButton(
onPressed: () {
urlLauncher('https://github.com/dzxrly/BF2042State2.0');
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const FaIcon(
FontAwesomeIcons.github,
size: 14,
),
const Padding(padding: EdgeInsets.only(left: 4)),
Text('Github',
style: TextStyle(
fontSize:
Theme.of(context).textTheme.bodySmall?.fontSize,
fontWeight:
Theme.of(context).textTheme.bodySmall?.fontWeight,
color: Theme.of(context).colorScheme.primary,
)),
],
)),
const Divider(),
Text(
'本应用由 Egg Targaryen 开发 (橘子ID: x_Reshiram)。'
'玩家数据接口来自 gametools.network,非常感谢其提供的接口。'
'BFBan数据来自 bfban.com,结果仅供参考,'
'本应用及作者不对该结果负责,如有疑问请自行联系BFBan。',
softWrap: true,
style: Theme.of(context).textTheme.bodyMedium,
)
],
),
);
}
}
|
import * as dotenv from 'dotenv';
import inquirer from 'inquirer';
import { PrismaClient } from '@prisma/client';
dotenv.config();
const main = () => {
console.log('Create a new ORCA Organization');
inquirer
.prompt([
{
name: 'orgName',
message: 'What should this org be named?',
default: 'My Organization'
},
{
name: 'orgDescription',
message: 'Provide a short description.',
default: 'A social club for example users'
},
{
name: 'orgDomain',
message: 'What domain will this org access the app on?',
default: 'localhost'
},
{
name: 'orgEmail',
message: 'What email address should this org send messages from?',
default: 'admin@orca.test'
}
])
.then(async (answers) => {
const prisma = new PrismaClient();
console.log(answers);
const newOrg = await prisma.organization.create({
data: {
name: answers.orgName,
description: answers.orgDescription,
domain: answers.orgDomain,
email: answers.orgEmail
}
});
console.log(JSON.stringify(newOrg, null, 4));
});
};
main();
|
package cuit.pymjl.beans.factory.support;
import cuit.pymjl.beans.BeansException;
import cuit.pymjl.beans.factory.config.BeanDefinition;
import java.util.HashMap;
import java.util.Map;
/**
* 这是核心类,它负责管理BeanDefinition
*
* @author Pymjl
* @version 1.0
* @date 2022/6/27 20:38
**/
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry {
private final Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName, beanDefinition);
}
@Override
protected BeanDefinition getBeanDefinition(String name) {
BeanDefinition beanDefinition = beanDefinitionMap.get(name);
if (beanDefinition == null) {
throw new BeansException("No bean named '" + name + "' is defined");
}
return beanDefinition;
}
}
|
import streamlit as st
import base64
import requests
import os
from dotenv import load_dotenv
from openai import OpenAI
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import torch
from transformers import AutoProcessor, Owlv2ForObjectDetection, Owlv2Processor
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
from torchvision.models.detection.faster_rcnn import fasterrcnn_resnet50_fpn, FasterRCNN_ResNet50_FPN_Weights
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import torchvision.transforms as T
import torchvision.transforms.functional as TF
dotenv_path = ".\\dev.env"
load_dotenv(dotenv_path)
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def GPT4(input_image):
base64_image = encode_image(input_image)
client = OpenAI()
payload = {
"model": "gpt-4-turbo",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Do you detect rust on this picture? Or do you see another anomaly?"},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
]
}
],
"max_tokens": 400
}
headers = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
choices = response.json()['choices']
message = choices[0]['message']
content = message['content']
return content
def GPT4o(input_image):
base64_image = encode_image(input_image)
client = OpenAI()
payload = {
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Do you detect rust on this picture? Or do you see another anomaly?"},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
]
}
],
"max_tokens": 400
}
headers = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
st.write(response.json())
#choices = response.json()['choices']
#message = choices[0]['message']
#content = message['content']
#return content
def clip(input_image, sensitivity):
# Use GPU if available
print("clip method called")
if torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("cpu")
input_image = Image.open(input_image)
processor = Owlv2Processor.from_pretrained("google/owlv2-large-patch14-finetuned")
model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-large-patch14-finetuned").to(device)
texts = [["corrosion or rust", "birds nest"]]
inputs = processor(text=texts, images=input_image, return_tensors="pt").to(device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
def get_preprocessed_image(pixel_values):
pixel_values = pixel_values.squeeze().numpy()
unnormalized_image = (pixel_values * np.array(OPENAI_CLIP_STD)[:, None, None]) + np.array(OPENAI_CLIP_MEAN)[:, None, None]
unnormalized_image = (unnormalized_image * 255).astype(np.uint8)
unnormalized_image = np.moveaxis(unnormalized_image, 0, -1)
unnormalized_image = Image.fromarray(unnormalized_image)
return unnormalized_image
unnormalized_image = get_preprocessed_image(inputs.pixel_values.cpu())
target_sizes = torch.Tensor([unnormalized_image.size[::-1]])
# Convert outputs (bounding boxes and class logits) to final bounding boxes and scores
results = processor.post_process_object_detection(
outputs=outputs, threshold=sensitivity, target_sizes=target_sizes
)
i = 0 # Retrieve predictions for the first image for the corresponding text queries
text = texts[i]
boxes, scores, labels = results[i]["boxes"], results[i]["scores"], results[i]["labels"]
draw = ImageDraw.Draw(unnormalized_image)
for box, score, label in zip(boxes, scores, labels):
box = [round(i, 2) for i in box.tolist()]
st.write(f"Detected {text[label]} with confidence {round(score.item(), 3)}")
draw.rectangle(box, outline="red", width=4)
category = 'Cat:' + str(label.item())
font = ImageFont.truetype("arial.ttf", size=15)
text_position = (box[0]+10, box[3]-40)
draw.text(text_position, category, fill="red", font=font)
new_size = (512, 512)
resized_image = unnormalized_image.resize(new_size)
return resized_image
def resnet(input_image, sensitivity_resnet):
model = fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
num_classes = 2
#in_features = model.roi_heads.box_predictor.cls_score.in_features
#model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
model.load_state_dict(torch.load('.\\data5\\patches_faster_rcnn_network\\fasterrcnn_model_weights_20240518'))
# Load the image
img = Image.open(input_image).convert('RGB')
# Convert the PIL Image to a PyTorch Tensor
# Instead of manually converting and normalizing, let's use torchvision transforms
transform = T.Compose([ T.ToTensor() ])
img_tensor = transform(img)
# Add a batch dimension since PyTorch models expect batches
img_tensor = img_tensor.unsqueeze(0)
# Determine the device dynamically
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
img_tensor = img_tensor.to(device) # Move tensor to the appropriate device
# Ensure the model is on the same device and set it to evaluation mode
model = model.to(device)
model.eval()
# Perform the prediction
with torch.no_grad():
prediction = model(img_tensor)
# Process the prediction output as needed
im = TF.to_pil_image(img_tensor.squeeze().cpu())
draw = ImageDraw.Draw(im)
st.write(f"Detected {prediction[0]['scores']}")
for index, box in enumerate(prediction[0]['boxes'].cpu().numpy()):
if prediction[0]['scores'][index] > sensitivity_resnet:
draw.rectangle(box, width=6, outline="red")
text = str(prediction[0]['labels'][index].item())
text = text + ' score: ' + str(round(prediction[0]['scores'][index].item(),2))
font = ImageFont.truetype("arial.ttf", size=10)
text_position = (box[0], box[3])
draw.text(text_position, text, fill="red", font=font)
return im
################################################################
# GUI
################################################################
st.set_page_config(layout="wide")
st.title("High Voltage Tower Monitor")
with st.sidebar:
st.image('.\\elia_logo.jpg')
st.subheader("Upload Image")
image = st.file_uploader('Chose file')
st.subheader("Choose Model")
check1 = st.checkbox('ResNet')
slider1 = st.slider('Resnet Sesitivity:', value=80)
check2 = st.checkbox('CLIP')
slider2 = st.slider('CLIP Sesitivity:', value=8)
check3 = st.checkbox('GPT4-Turbo')
check4 = st.checkbox('GPT4o')
button = st.button("Submit")
if button:
col1 , col2 = st.columns(2)
with col1:
if image:
st.subheader("Original Image")
st.image(image)
image_path = f".\\data5\\testdata\\{image.name}"
with col2:
if check1:
st.subheader("ResNet")
st.image(resnet(image_path, slider1/100))
if check2:
st.subheader("CLIP")
st.image(clip(image_path, slider2/100))
with col1:
if check3:
st.subheader("GPT4-Turbo")
st.write(GPT4(image_path))
if check4:
st.subheader("GPT4o")
st.write(GPT4o(image_path))
|
require("dotenv").config();
const express = require("express");
var cors = require("cors");
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY);
// Create Express server
const app = express();
const PORT = process.env.PORT || 4000;
// Use Middleware cors
const corsOptions = {
origin: "*",
credentials: true, // Access-control-allow-credentials:true
optionSuccessStatus: 200,
};
app.use(cors(corsOptions)); // Use after variable declaration
// Recommended by Stripe documentation
app.use(express.static("public"));
app.use(express.json());
app.post("/checkout", async (req, res) => {
// Initiate session with Stripe
const items = req.body.items;
let lineItems = [];
// Create new array in Stripe-format to process payments
items.forEach((item) => {
lineItems.push({
price: item.id,
quantity: item.quantity,
});
});
const session = await stripe.checkout.sessions.create({
line_items: lineItems,
mode: "payment",
success_url: "https://amazonian.onrender.com/success",
cancel_url: "https://amazonian.onrender.com/store",
});
res.send(
JSON.stringify({
url: session.url,
})
);
});
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
|
import React from "react";
import FullStarDisplay from "./FullStarDisplay";
interface Comment {
postedAt: string;
comment: string;
baseAmenities: number;
baseLogistics: number;
housingOptions: number;
localCommunity: number;
localRecreation: number;
schoolDistrict: number;
}
function CommentCard({
postedAt,
baseAmenities,
baseLogistics,
housingOptions,
localCommunity,
localRecreation,
schoolDistrict,
comment,
}: Comment) {
const createdAt = new Date(postedAt).toLocaleDateString();
return (
<div className="shadow px-5 pb-10 pt-2 w-2xl mb-4 flex flex-col">
<div className="flex justify-center underline text-sm mb-4">
{`Posted: ${createdAt}`}
</div>
<div className="flex justify-around mb-6">
<div className="space-y-5">
<FullStarDisplay
overall="1"
ba={baseAmenities}
bl={baseLogistics}
ho={housingOptions}
lc={localCommunity}
lr={localRecreation}
sd={schoolDistrict}
/>
</div>
</div>
<div>
<p className="underline text-center font-bold">Additional Details:</p>
<p>{comment}</p>
</div>
</div>
);
}
export default CommentCard;
|
<?php
class BookableCell
{
private $booking;
private $currentURL;
public function __construct(Booking $booking)
{
$this->booking = $booking;
$this->currentURL = htmlentities($_SERVER['REQUEST_URI']);
}
public function update(Calendar $cal)
{
if ($this->isDateBooked($cal->getCurrentDate())) {
$cal->cellContent = $this->bookedCell($cal->getCurrentDate());
} else {
$cal->cellContent = $this->openCell($cal->getCurrentDate());
}
}
public function routeActions()
{
if (isset($_POST['delete'])) {
$this->deleteBooking($_POST['id']);
}
if (isset($_POST['add'])) {
if (
isset($_POST['date'], $_POST['time_slot'], $_POST['included'],
$_POST['firstName'], $_POST['lastName'], $_POST['contactNo'], $_POST['email'], $_POST['deposit_amount'], $_POST['balance_amount'], $_POST['amount'])
) {
$this->addBooking(
$_POST['date'], $_POST['time_slot'], $_POST['included'],
$_POST['firstName'], $_POST['lastName'], $_POST['contactNo'],
$_POST['email'], $_POST['deposit_amount'], $_POST['balance_amount'], $_POST['amount']
);
}
}
}
private function openCell($date)
{
return '<div class="open">' . $this->bookingForm($date) . '</div>';
}
private function bookedCell($date)
{
return '<div class="booked">' . $this->deleteForm($this->bookingId($date)) . '</div>';
}
private function isDateBooked($date)
{
return in_array($date, $this->bookedDates());
}
private function bookedDates()
{
return array_map(function ($record) {
return $record['booking_date'];
}, $this->booking->index());
}
private function bookingId($date)
{
$booking = array_filter($this->booking->index(), function ($record) use ($date) {
return $record['booking_date'] === $date;
});
$result = array_shift($booking);
return $result['id'];
}
private function deleteBooking($id)
{
$this->booking->delete($id);
}
private function addBooking($date, $timeSlot, $included, $firstName, $lastName, $contactNo, $email, $deposit_amount, $balance_amount, $amount)
{
// Define time slots and their corresponding start times
$timeSlotStartTimes = [
'8am - 5pm' => '08:00:00',
'12nn - 8pm' => '12:00:00',
'2pm - 10pm' => '14:00:00',
'overnight' => '16:00:00',
'22 hours' => '18:00:00',
];
// Get the start time for the selected time slot
$startTime = $timeSlotStartTimes[$timeSlot] ?? null;
if ($startTime) {
// Combine date and start time to create the booking datetime string
$bookingDateTimeString = $date . ' ' . $startTime;
try {
// Create a DateTimeImmutable object from the booking datetime string
$bookingDateTime = new DateTimeImmutable($bookingDateTimeString);
$amount = 0.00;
if (isset($_POST['date']) && $_POST['date'] === $date && isset($_POST['included'])) {
if ($_POST['included'] === 'LPG gas and Stove') {
$amount = $amount + 300;
}
}
// Calculate the amount based on the selected time slot
switch ($timeSlot) {
case '8am - 5pm':
$amount += 8000;
break;
case '12nn - 8pm':
$amount += 8000;
break;
case '2pm - 10pm':
$amount += 8000;
break;
case 'overnight':
$amount += 9000;
break;
case '22 hours':
$amount += 10000;
break;
default:
$amount = 0;
break;
}
// Calculate deposit and balance amounts
$deposit_amount = 1000;
$balance_amount = $amount - $deposit_amount;
// Add the booking with the constructed DateTimeImmutable object
$this->booking->add($bookingDateTime, $timeSlot, $included, $firstName, $lastName, $contactNo, $email, $deposit_amount, $balance_amount, $amount, "pending");
// Return success message with booking details
} catch (Exception $e) {
// Handle any exceptions, such as invalid date or time formats
return 'Error: ' . $e->getMessage();
}
} else {
return 'Invalid time slot selected.';
}
}
private function bookingForm($date)
{
$amount = 0.00; // Initialize amount
$deposit_amount = 0.00;
$balance_amount = 0.00;
// Check if date matches POST data and calculate amount
if (isset($_POST['date']) && $_POST['date'] === $date && isset($_POST['included'])) {
if ($_POST['included'] === 'LPG gas and Stove') {
$amount = $amount + 300;
}
}
if (isset($_POST['date']) && $_POST['date'] === $date && isset($_POST['time_slot'])) {
if ($_POST['time_slot'] === '8am - 5pm' || $_POST['time_slot'] === '12nn - 8pm' || $_POST['time_slot'] === '2pm - 10pm') {
$amount = $amount + 8000;
} else if ($_POST['time_slot'] === 'overnight') {
$amount = $amount + 9000;
} else if ($_POST['time_slot'] === '22 hours'){
$amount = $amount + 10000;
}
$deposit_amount = 1000;
$balance_amount = $amount - $deposit_amount;
}
// Form HTML
if (isset($_POST['add']) && $_POST['date'] === $date) {
return '
<div class="reservation-box">
<form class="reservation_form" method="post" action="' . $this->currentURL . '">
<button type="button" class="close-btn">X</button>
<input type="hidden" name="add" value="1" />
<input type="hidden" name="date" value="' . $date . '" />
<div class="form-wrapper">
<div class="form-group">
<label for="time_slot">Time Slot:</label>
<select name="time_slot" id="time_slot" required">
<option value="" disabled selected>Select a time slot</option>
<option value="8am - 5pm"' . (isset($_POST['time_slot']) && $_POST['time_slot'] === '8am - 5pm' ? ' selected' : '') . '>8am - 5pm</option>
<option value="12nn - 8pm"' . (isset($_POST['time_slot']) && $_POST['time_slot'] === '12nn - 8pm' ? ' selected' : '') . '>12nn - 8pm</option>
<option value="2pm - 10pm"' . (isset($_POST['time_slot']) && $_POST['time_slot'] === '2pm - 10pm' ? ' selected' : '') . '>2pm - 10pm</option>
<option value="overnight"' . (isset($_POST['time_slot']) && $_POST['time_slot'] === 'overnight' ? ' selected' : '') . '>Overnight</option>
<option value="22 hours"' . (isset($_POST['time_slot']) && $_POST['time_slot'] === '22 hours' ? ' selected' : '') . '>22 hours</option>
</select>
</div>
<div class="form-group">
<label for="included">Include Others:</label>
<select name="included" id="included" required">
<option value="" disabled' . (empty($_POST['included']) ? ' selected' : '') . '>Select an option</option>
<option value="LPG gas and Stove"' . (isset($_POST['included']) && $_POST['included'] === 'LPG gas and Stove' ? ' selected' : '') . '>LPG gas and Stove (+250)</option>
<option value="N/A"' . (isset($_POST['included']) && $_POST['included'] === 'N/A' ? ' selected' : '') . '>N/A</option>
</select>
</div>
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" value="' . ($_POST['firstName'] ?? '') . '" required>
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" value="' . ($_POST['lastName'] ?? '') . '" required>
</div>
<div class="form-group">
<label for="contactNo">Contact No.:</label>
<input type="number" name="contactNo" id="contactNo" value="' . ($_POST['contactNo'] ?? '') . '" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="' . ($_POST['email'] ?? '') . '" required>
</div>
<div class="form-group">
<label for="deposit_amount">Deposit Amount:</label>
<input type="text" name="deposit_amount" id="deposit_amount" value="' . number_format($deposit_amount, 2) . '" readonly>
</div>
<div class="form-group">
<label for="balance_amount">Balance Amount:</label>
<input type="text" name="balance_amount" id="balance_amount" value="' . number_format($balance_amount, 2) . '" readonly>
</div>
<div class="form-group">
<label for="amount">Total Amount:</label>
<input type="text" name="amount" id="amount" value="' . number_format($amount, 2) . '" readonly>
</div>
</div>
<button class="submitReservation" type="submit">Submit</button>
</form>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
const timeSlotSelect = document.getElementById("time_slot");
const includedSelect = document.getElementById("included");
const depositInput = document.getElementById("deposit_amount");
const balanceInput = document.getElementById("balance_amount");
const amountInput = document.getElementById("amount");
const updateAmount = function() {
let newAmount = 0.00;
switch (timeSlotSelect.value) {
case "8am - 5pm":
case "12nn - 8pm":
case "2pm - 10pm":
newAmount += 8000;
break;
case "overnight":
newAmount += 9000;
break;
case "22 hours":
newAmount += 10000;
break;
default:
break;
}
if (includedSelect.value === "LPG gas and Stove") {
newAmount += 300;
}
amountInput.value = newAmount.toFixed(2);
const newDeposit = 1000;
const newBalance = newAmount - newDeposit;
depositInput.value = newDeposit.toFixed(2);
balanceInput.value = newBalance >= 0 ? newBalance.toFixed(2) : "0.00"; // Set balance to 0 if negative
};
timeSlotSelect.addEventListener("change", updateAmount);
includedSelect.addEventListener("change", updateAmount);
updateAmount(); // Initialize amount
const closeBtn = document.querySelector(".close-btn");
closeBtn.addEventListener("click", function() {
// Redirect back to the calendar page
window.location.href = "' . $this->currentURL . '";
});
});
</script>';
} else {
// Display only the "Book" button if it's not clicked
return '
<form method="post" action="' . $this->currentURL . '">
<input type="hidden" name="add" />
<input type="hidden" name="date" value="' . $date . '" />
<input class="submit" id="submit" type="submit" value="Book" />
</form>';
}
}
private function deleteForm($id)
{
return '
<form onsubmit="return confirm(\'Are you sure to cancel?\');" method="post" action="' . $this->currentURL . '">
<input type="hidden" name="delete" />
<input type="hidden" name="id" value="' . $id . '" />
<input class="submit" type="submit" value="Delete" />
</form>';
}
}
?>
|
import { Schema, model, mongoose } from "mongoose";
import mongoosePaginate from "mongoose-paginate-v2";
// import { v4 as uuid } from "uuid";
const userSchema = Schema(
{
firstName: {
type: String,
required: true,
trim: true,
},
lastName: {
type: String,
required: false,
trim: true,
},
email: {
type: String,
required: true,
trim: true,
unique: true,
},
username: {
type: String,
required: true,
trim: true,
unique: true,
},
userType: {
type: String,
enum: ["admin", "readonly", "student"],
},
cart: {
type: Schema.Types.ObjectId,
ref: "Cart",
required: false
},
salt: {
type: String,
required: true,
},
encpy_password: {
type: String,
required: true,
},
},
{ timestamps: true }
);
userSchema.plugin(mongoosePaginate);
const User = model("User", userSchema);
export default User;
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../../core.dart';
class MainNavigationView extends StatefulWidget {
const MainNavigationView({Key? key}) : super(key: key);
Widget build(context, MainNavigationController controller) {
controller.view = this;
return DefaultTabController(
length: 4,
child: Scaffold(
body: Column(
children: [
Container(
color: greenColor,
child: SafeArea(
child: Container(
height: 50,
margin: const EdgeInsets.symmetric(
horizontal: 15.0,
vertical: 10.5,
),
padding: const EdgeInsets.all(5),
decoration: const BoxDecoration(
color: darkGreenColor,
borderRadius: BorderRadius.all(
Radius.circular(30),
),
),
child: TabBar(
indicatorPadding: EdgeInsets.zero,
tabs: [
Tab(
child: Text(
'Beranda',
style: GoogleFonts.lato(fontWeight: semiBold),
),
),
Tab(
child: Text(
'Promo',
style: GoogleFonts.lato(fontWeight: semiBold),
),
),
Tab(
child: Text(
'Pesanan',
style: GoogleFonts.lato(fontWeight: semiBold),
),
),
Tab(
child: Text(
'Chat',
style: GoogleFonts.lato(fontWeight: semiBold),
),
),
],
),
),
),
),
const Expanded(
child: TabBarView(
children: [
DashboardView(),
PromotionView(),
Icon(Icons.shopping_bag),
Icon(Icons.chat),
],
),
),
],
),
),
);
}
@override
State<MainNavigationView> createState() => MainNavigationController();
}
|
//Author - Abhishek
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
int findNthNode(struct node **head, int pos)
{
struct node *n1 = *head;
for(int i = 1; i<pos; i++)
{
//the position was greater than the size of ll
if(n1 == NULL)
return;
n1 = n1->next;
}
return n1->data;
}
void deletingNode(struct node **head, int pos)
{
struct node* prv = NULL;
struct node* tmp = NULL;
prv = *head;
tmp = *head;
for(int i = 0; i < pos; i++)
{
//we want to delete first position
if((i == 0) && (pos == 1))
{
(*head) = (*head)->next;
//either free tmp or prv, basically both are pointing to same memory.
free(prv);
}
else
{
if(i == pos - 1)
{
//what it will do is, it will point to the next to the next element
//and free the memory occupied by that node.
prv->next = tmp->next;
free(tmp);
}
else
{
prv = tmp;
//the position was greater than the size of ll
if(prv == NULL)
return;
tmp = tmp->next;
}
}
}
}
//in this algo we keep on getting the next node of LL in nxt variable and then we point the next to prv variable which will
//be initially NULL and then it will be current node, and then we move the iterator to the next node which is stored in the nxt
//variable.
//At the end we point the *head to prv because it is the current node which is the last node of original linkedlist.
void reverseLinkedList(struct node **head)
{
struct node* prv = NULL;
struct node* curr = *head;
struct node* nxt = NULL;
while(curr != NULL)
{
nxt = curr->next;
curr->next = prv;
prv = curr;
curr = nxt;
}
*head = prv;
}
void pushAfterNode(struct node *head, int data, int after)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp->data = data;
while(head != NULL)
{
if(head->data == after)
{
if(head->next != NULL)
{
temp->next = head->next;
head->next = temp;
break;
}
}
head = head->next;
}
}
void pushAtEnd(struct node *head, int data)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
while(head->next != NULL)
{
head = head->next;
}
head->next = temp;
}
void pushNode(struct node **head, int data)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp->data = data;
temp->next = (*head);
(*head) = temp;
}
void printList(struct node* head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
}
int main()
{
struct node *head = NULL;
pushNode(&head,1);
pushNode(&head,2);
pushNode(&head,3);
pushNode(&head,4);
printList(head);
printf("\n");
pushAfterNode(head, 5, 2);
printList(head);
printf("\n");
pushAtEnd(head, 10);
printList(head);
printf("\n");
reverseLinkedList(&head);
printList(head);
printf("\n");
deletingNode(&head, 6);
printList(head);
printf("\n");
int x = findNthNode(&head, 5);
printf("Nth node is : %d", x);
printf("\n");
}
|
#!/bin/bash
# 1) Обновление системы
apt update && apt upgrade -y
# 2) Установка UFW (Uncomplicated Firewall)
apt install ufw -y
# 3) Создание нового пользователя и добавление его в группу sudo
read -p "Введите имя нового пользователя: " new_user
adduser $new_user
usermod -aG sudo $new_user
# 4) Генерация ключей SSH для нового пользователя и настройка авторизации по ключам
mkdir -p /home/$new_user/.ssh
chmod 700 /home/$new_user/.ssh
ssh-keygen -t rsa -b 2048 -f /home/$new_user/.ssh/id_rsa -N ""
cat /home/$new_user/.ssh/id_rsa.pub >> /home/$new_user/.ssh/authorized_keys
chmod 600 /home/$new_user/.ssh/authorized_keys
chown -R $new_user:$new_user /home/$new_user/.ssh
# 5) Изменение порта SSH, настройка безопасности и запрет аутентификации по паролю
read -p "Введите новый порт SSH: " sshport
sed -i "s/#Port 22/Port $sshport/" /etc/ssh/sshd_config
# Раскомментирование и установка параметра PubkeyAuthentication
sed -i '/^#PubkeyAuthentication yes/ c\PubkeyAuthentication yes' /etc/ssh/sshd_config
# Активация изменений параметров PasswordAuthentication и PermitRootLogin
sed -i '/^#PasswordAuthentication yes/ c\PasswordAuthentication no' /etc/ssh/sshd_config
sed -i '/^PasswordAuthentication yes/ c\PasswordAuthentication no' /etc/ssh/sshd_config
sed -i '/^#PermitRootLogin yes/ c\PermitRootLogin no' /etc/ssh/sshd_config
sed -i '/^PermitRootLogin yes/ c\PermitRootLogin no' /etc/ssh/sshd_config
# Создание файла /etc/ssh/sshd_config.d/50-cloud-init.conf и добавление параметра PasswordAuthentication
echo "PasswordAuthentication no" > /etc/ssh/sshd_config.d/50-cloud-init.conf
# 6) Добавление нового порта в файерволл UFW и активация UFW
ufw allow $sshport/tcp
ufw enable
# 7) Отключение учетной записи root
sed -i 's|^root:x:.*:/bin/bash|root:x:0:0:root:/root:/usr/sbin/nologin|' /etc/passwd
# 8) Перезапуск сервиса SSH для применения изменений
systemctl restart ssh
# 9) Вывод приватного ключа нового пользователя
echo "Приватный ключ нового пользователя:"
cat /home/$new_user/.ssh/id_rsa
echo -e "\nНастройка завершена."
|
package com.example;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;;
public class Sensor {
private String tipoSensor;
private double tiempoEnvio;
private String archivoConfig;
private double probValoresCorrectos;
private double probValoresFueraRango;
private double probValoresIncorrectos;
private double valorMinimo;
private double valorMaximo;
private String tema;
public String getTipoSensor() {
return tipoSensor;
}
public void setTipoSensor(String tipoSensor) {
this.tipoSensor = tipoSensor;
}
public double getTiempoEnvio() {
return tiempoEnvio;
}
public void setTiempoEnvio(double tiempoEnvio) {
this.tiempoEnvio = tiempoEnvio;
}
public String getArchivoConfig() {
return archivoConfig;
}
public void setArchivoConfig(String archivoConfig) {
this.archivoConfig = archivoConfig;
}
public double getProbValoresCorrectos() {
return probValoresCorrectos;
}
public void setProbValoresCorrectos(double probValoresCorrectos) {
this.probValoresCorrectos = probValoresCorrectos;
}
public double getProbValoresFueraRango() {
return probValoresFueraRango;
}
public void setProbValoresFueraRango(double probValoresFueraRango) {
this.probValoresFueraRango = probValoresFueraRango;
}
public double getProbValoresIncorrectos() {
return probValoresIncorrectos;
}
public void setProbValoresIncorrectos(double probValoresIncorrectos) {
this.probValoresIncorrectos = probValoresIncorrectos;
}
public double getValorMinimo() {
return valorMinimo;
}
public void setValorMinimo(double valorMinimo) {
this.valorMinimo = valorMinimo;
}
public double getValorMaximo() {
return valorMaximo;
}
public void setValorMaximo(double valorMaximo) {
this.valorMaximo = valorMaximo;
}
public Sensor() {
}
public Sensor(String tipoSensor, double tiempoEnvio, String archivoConfig) {
this.tipoSensor = tipoSensor;
this.tiempoEnvio = tiempoEnvio;
this.archivoConfig = archivoConfig;
}
public double generarMedida() {
Random random = new Random();
double medida = 0;
double probabilidad = random.nextDouble();
if (probabilidad < probValoresIncorrectos) {
medida = -random.nextDouble();
} else if (probabilidad < probValoresIncorrectos + probValoresCorrectos) {
medida = valorMinimo + random.nextDouble() * (valorMaximo - valorMinimo);
} else {
medida = random.nextDouble() > 0.5 ? valorMaximo + random.nextDouble() * 10
: valorMinimo - random.nextDouble() * 10;
}
return medida;
}
public static void main(String[] args) {
Sensor sensor = validarArgumentos(args);
if (sensor != null) {
String urlSistema="25.5.211.175";
System.out.println("Tipo de Sensor: " + sensor.getTipoSensor());
System.out.println("Tiempo de Envio: " + sensor.getTiempoEnvio());
System.out.println("Archivo de Configuracion: " + sensor.getArchivoConfig());
System.out.println("minimo: " + sensor.getValorMinimo());
System.out.println("Maximo: " + sensor.getValorMaximo());
System.out.println("Tema: "+ sensor.getTema());
ZContext zContext = new ZContext();
ZMQ.Socket socket = zContext.createSocket(SocketType.PUSH);
socket.connect("tcp://"+urlSistema+":5555");
try {
while (!Thread.currentThread().isInterrupted()) {
LocalDateTime horaActual = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String horaFormateada = horaActual.format(formatter);
String mensaje=sensor.getTema()+ " "+horaFormateada+" "+sensor.generarMedida();
socket.send(mensaje);
System.out.println("Medida Enviada: "+ mensaje );
Thread.sleep((long)sensor.getTiempoEnvio()*1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally{
socket.close();
zContext.close();
}
}
}
private static Sensor validarArgumentos(String[] args) {
if (args.length != 3) {
System.err.println(
"Uso incorrecto. Debe proporcionar tres argumentos: Tipo de sensor, tiempo de envio y direccion del archivo de configuracion.");
System.exit(1);
}
String tipoDeSensor = args[0];
String tiempoDeEnvioStr = args[1];
String archivoDeConfiguracion = args[2];
Sensor sensor = new Sensor();
try {
double tiempoDeEnvio = Double.parseDouble(tiempoDeEnvioStr);
if (!ReadConfiguration.validarTipoDeSensor(tipoDeSensor)) {
System.err.println("Tipo de sensor no valido. Debe ser uno de los tipos validos.");
System.exit(1);
}
sensor = new Sensor(tipoDeSensor, tiempoDeEnvio, archivoDeConfiguracion);
ReadConfiguration.leerArchivo("src\\main\\resources\\" + archivoDeConfiguracion + ".json", sensor);
} catch (NumberFormatException e) {
System.err.println("Tiempo de envio no valido. Debe ser un numero entero.");
System.exit(1);
}
return sensor;
}
public String getTema() {
return tema;
}
public void setTema(String tema) {
this.tema = tema;
}
}
|
<template>
<div class="proposal-history-list">
<div class="options-container">
<div class="my-votes">
<div class="value">{{ myVotes | bigNumberFormatter(votesDecimals) }} {{ $t('governance.votes') }}</div>
<div class="text">{{ $t('dao.myVotes') }}</div>
</div>
<div class="button-box">
<van-button class="info" :class="['round', 'middle']" @click="onClickAboutVotesButton">
{{ $t('dao.about') }}
</van-button>
<van-button class="info" :class="['round', 'middle']" @click="onClickDelegateButton">
{{ $t('dao.delegate') }}
</van-button>
</div>
</div>
<div class="proposal-list">
<van-list
v-model="listLoading"
:finished="finishLoadAllProposal"
:loading-text="$t('base.loading')+'...'"
@load="onLoadData"
>
<div class="proposal-item" v-for="(item, index) in proposalList" :key="index" v-if="item"
@click="toVotesPage(item.index)">
<McMProposalCard :state="convertProposalState(item.state)" :index="item.index"
:end-timestamp="item.endTimestamp"
:title="item.description ? item.description.title.slice(0, 50) : ''"
:for-votes="item.for.toNumber()"
:against-votes="item.against.toNumber()"/>
</div>
<template slot="loading">
<McLoadingIcon></McLoadingIcon>
</template>
<div slot='finished'>
<span v-if="hideGOV">{{ $t('base.comingSoon') }}</span>
<McMNoData v-else :label="$t('base.noMore')"></McMNoData>
</div>
</van-list>
</div>
<DelegatePopup :visible.sync="showDelegatePopup"/>
<AboutVotesPopup :visible.sync="showAboutVotesPopup"/>
</div>
</template>
<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator'
import { McMNoData, McMProposalCard } from '@/mobile/components'
import { DaoProposalHistoryMixin, ProposalItem } from '@/template/components/DAO/daoProposalHistoryMixin'
import { ROUTE } from '@/mobile/router'
import DelegatePopup from '../Components/DelegatePopup.vue'
import AboutVotesPopup from '../Components/AboutVotesPopup.vue'
import { DaoProposalState } from '@/type'
import { SUPPORTED_NETWORK_ID, TARGET_NETWORK_ID } from '@/const'
import { McLoadingIcon } from '@/components'
@Component({
components: {
McMProposalCard,
DelegatePopup,
McMNoData,
AboutVotesPopup,
McLoadingIcon,
},
})
export default class ProposalHistoryList extends Mixins(DaoProposalHistoryMixin) {
private hideGOV = TARGET_NETWORK_ID === SUPPORTED_NETWORK_ID.ARB
private showDelegatePopup: boolean = false
private showAboutVotesPopup: boolean = false
private listLoading: boolean = false
get proposalList(): ProposalItem[] {
const result: any[] = []
this.proposals.forEach(item => {
result.push(this.convertProposal(item))
})
return result
}
convertProposalState(state: DaoProposalState): 'success' | 'fail' | 'voting' {
if (state === DaoProposalState.Active) {
return 'voting'
}
if (state === DaoProposalState.Failed || state === DaoProposalState.Defeated) {
return 'fail'
}
if (state === DaoProposalState.Succeeded ||
state === DaoProposalState.Executed ||
state === DaoProposalState.Queued ||
state === DaoProposalState.Expired) {
return 'success'
}
return 'fail'
}
onClickDelegateButton() {
this.showDelegatePopup = true
}
onClickAboutVotesButton() {
this.showAboutVotesPopup = true
}
onClickStakeButton() {
this.$router.push({ name: ROUTE.SATORI_STAKE })
}
toVotesPage(index: string) {
this.$router.push({ name: 'daoProposalVote', params: { index: index } })
}
async onLoadData() {
this.listLoading = true
if (!this.loading && !this.finishLoadAllProposal) {
this.pagination.currentPage += 1
await this.load()
}
this.listLoading = false
}
}
</script>
<style lang="scss" scoped>
.proposal-history-list {
padding-top: 32px;
height: 100%;
.options-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
.value {
font-size: 16px;
line-height: 24px;
}
.text {
font-size: 12px;
line-height: 16px;
color: var(--mc-text-color);
margin-top: 4px;
}
.van-button {
width: 101.5px;
font-size: 16px;
line-height: 22px;
}
.info {
background: var(--mc-background-color);
margin-right: 12px;
&:last-child {
margin-right: 0;
}
}
}
.proposal-list {
height: calc(100% - 68px);
overflow: scroll;
.proposal-item {
margin-bottom: 16px;
}
::v-deep {
.mc-loading-icon {
justify-content: center;
}
.no-data {
margin-top: 170px;
}
}
}
}
</style>
|
import { FormActionTypes, FormActions } from "./actions";
import { IFormState } from "./state";
export const coordinatesFormReducer = (
state: IFormState,
action: FormActions
): IFormState => {
switch (action.type) {
case FormActionTypes.clearPointForm:
return {
...state,
[action.searchInput]: {
...state[action.searchInput],
value: "",
error: "",
suggestions: [],
},
[action.latInput]: {
...state[action.latInput],
value: "",
error: "",
},
[action.lonInput]: {
...state[action.lonInput],
value: "",
error: "",
},
};
case FormActionTypes.setSuggestion:
return {
...state,
[action.searchInputName]: {
...state[action.searchInputName],
suggestions: action.value,
},
};
case FormActionTypes.updateLatAndLon:
return {
...state,
[action.latInput]: { ...state[action.latInput], value: action.lat },
[action.lonInput]: { ...state[action.lonInput], value: action.lon },
};
case FormActionTypes.setIsButtonLoading:
return {
...state,
[action.button]: {
...state[action.button],
isLoading: action.value,
},
};
case FormActionTypes.updateSearchValue:
return {
...state,
[action.searchInputName]: {
...state[action.searchInputName],
value: action.value,
},
};
case FormActionTypes.setInputError:
return {
...state,
[action.inputName]: { ...state[action.inputName], error: action.error },
};
case FormActionTypes.clearErrors:
return {
...state,
lat1: { ...state.lat1, error: "" },
lon1: { ...state.lon1, error: "" },
lat2: { ...state.lat2, error: "" },
lon2: { ...state.lon2, error: "" },
};
case FormActionTypes.changeInputValue:
return {
...state,
[action.inputName]: { ...state[action.inputName], value: action.value },
};
case FormActionTypes.clearError:
return {
...state,
[action.inputName]: { ...state[action.inputName], error: "" },
};
case FormActionTypes.clearSuggestions:
return {
...state,
[action.inputName]: { ...state[action.inputName], suggestions: [] },
};
default:
throw Error(`Unknown action: ${action}`);
}
};
|
jest.mock('../../../../app/storage')
const { getControlFiles } = require('../../../../app/storage')
jest.mock('../../../../app/transfer/outbound/transfer-file')
const { transferFile } = require('../../../../app/transfer/outbound/transfer-file')
const { transferFiles } = require('../../../../app/transfer/outbound/transfer-files')
describe('transfer files', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('should get control files', async () => {
getControlFiles.mockReturnValueOnce([])
await transferFiles()
expect(getControlFiles).toHaveBeenCalledTimes(1)
})
test('should not transfer files if no control files', async () => {
getControlFiles.mockReturnValueOnce([])
await transferFiles()
expect(transferFile).toHaveBeenCalledTimes(0)
})
test('should transfer file for each control file', async () => {
getControlFiles.mockReturnValueOnce([{ filename: 'filename1' }, { filename: 'filename2' }])
await transferFiles()
expect(transferFile).toHaveBeenCalledTimes(2)
})
test('should transfer file for each control file if first file throws error', async () => {
getControlFiles.mockReturnValueOnce([{ filename: 'filename1' }, { filename: 'filename2' }])
transferFile.mockImplementationOnce(() => { throw new Error() })
await transferFiles()
expect(transferFile).toHaveBeenCalledTimes(2)
})
})
|
define({
pageUID: "payment.paymentInitiationSearch",
pageType: "Engine",
dependencies: ["$log", "formHelper", "$state", "$q", "SessionStore", "Utils", "entityManager", "Payment", "LoanBookingCommons", "Queries"],
$pageFn: function($log, formHelper, $state, $q, SessionStore, Utils, entityManager, Payment, LoanBookingCommons, Queries) {
var branch = SessionStore.getBranch();
var centres = SessionStore.getCentres();
var centreId = [];
if (centres && centres.length) {
for (var i = 0; i < centres.length; i++) {
centreId.push(centres[i].centreId);
}
}
return {
"type": "search-list",
"title": "PAYMENT_INITIATION_SEARCH",
"subTitle": "",
initialize: function(model, form, formCtrl) {
model.branch = branch;
model.modeOfPayment = 'Manual';
$log.info("search-list sample got initialized");
var centres = SessionStore.getCentres();
if (_.isArray(centres) && centres.length > 0) {
model.centre = centres[0].centreName;
model.centreCode = centres[0].centreCode;
}
},
definition: {
title: "PAYMENT_INITIATION_SEARCH",
searchForm: [
{
"type": "section",
items: [
{
key: "paymentDate",
title: "PAYMENT_DATE",
type:"date"
},
{
key: "paymentId",
title: "PAYMENT_ID",
},
{
key: "debitAccountName",
title: "DEBIT_ACCOUNT_NAME",
type:"lov",
lovonly:true,
searchHelper: formHelper,
search: function(inputModel, form, model) {
return Queries.getBankAccounts();
},
getListDisplayItem: function(item, index) {
return [
item.bank_name,
item.branch_name,
item.account_number
];
},
onSelect: function(result, model, context) {
model.debitAccountName = result.bank_name
}
},
{
key: "transactionType",
title: "PAYMENT_TYPE",
type:"select",
enumCode:"payment_type"
},
{
key: "modeOfPayment",
title: "PAYMENT_MODE",
type:"select",
enumCode:"mode_of_payment"
},
{
key: "paymentPurpose",
title: "PAYMENT_PURPOSE",
type:"select",
enumCode:"payment_purpose"
},
{
key: "beneficiaryName",
title: "BENEFICIARY_NAME",
},
]
}
],
autoSearch: true,
searchSchema: {
"type": 'object',
"title": 'SearchOptions',
"properties": {
"paymentDate": {
"title": "PAYMENT_DATE",
"type": "string",
},
"paymentId": {
"title": "PAYMENT_ID",
"type": "string"
},
"debitAccountName": {
"title": "DEBIT_ACCOUNT_NAME",
"type": "string"
},
"modeOfPayment": {
"title": "PAYMENT_TYPE",
"type": ["string", "null"]
},
"transactionType": {
"title": "PAYMENT_MODE",
"type": ["string", "null"]
},
"paymentPurpose": {
"title": "PAYMENT_PURPOSE",
"type": ["string", "null"]
},
"beneficiaryName": {
"title": "BENEFICIARY_NAME",
"type": "string"
}
}
},
getSearchFormHelper: function() {
return formHelper;
},
getResultsPromise: function(searchOptions, pageOpts) {
var promise = Payment.search({
'paymentDate': searchOptions.paymentDate,
'paymentId': searchOptions.paymentId,
'debitAccountName': searchOptions.debitAccountName,
'paymentMode': searchOptions.transactionType,
'paymentType': searchOptions.modeOfPayment,
'paymentPurpose': searchOptions.paymentPurpose,
'beneficiaryName': searchOptions.beneficiaryName,
'currentStage':"PaymentInitiation",
'page': pageOpts.pageNo,
'per_page': pageOpts.itemsPerPage
}).$promise;
return promise;
},
paginationOptions: {
"getItemsPerPage": function(response, headers) {
return 100;
},
"getTotalItemsCount": function(response, headers) {
return headers['x-total-count']
}
},
listOptions: {
selectable: true,
expandable: true,
listStyle: "table",
itemCallback: function(item, index) {},
getItems: function(response, headers) {
if (response != null && response.length && response.length != 0) {
return response;
}
return [];
},
getListItem: function(item) {
return [item.id, item.debitAccountName, item.transactionType, item.paymentDate, item.modeOfPayment, item.paymentPurpose, item.beneficiaryName];
},
getTableConfig: function() {
return {
"serverPaginate": true,
"paginate": true,
"pageLength": 10
};
},
getColumns: function() {
return [{
title: 'PAYMENT_ID',
data: 'id'
}, {
title: 'DEBIT_ACCOUNT_NAME',
data: 'debitAccountName'
},{
title: 'PAYMENT_TYPE',
data: 'modeOfPayment'
}, {
title: 'PAYMENT_MODE',
data: 'transactionType'
}, {
title: 'PAYMENT_DATE',
data: 'paymentDate'
}, {
title: 'BENEFICIARY_NAME',
data: 'beneficiaryName'
}, {
title: 'PAYMENT_PURPOSE',
data: 'paymentPurpose'
},];
},
getActions: function() {
return [{
name: "EDIT_PAYMENT_INITIATION",
desc: "",
icon: "fa fa-user",
fn: function(item, index){
$state.go("Page.Engine", {
pageName: "payment.PaymentInitiation",
pageId: item.id,
pageData: item
});
},
isApplicable: function(item, index){
return true;
}
}];
}
}
}
};
}
});
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>实现todolist的删除功能</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<div>
<input v-model="inputValue"/>
<button @click="handleSubmit">提交</button>
</div>
<ul>
<todo-item
v-for="(item, index) of list"
:key="index"
:content="item"
:index="index"
@delete="handleDelete">
</todo-item>
<!--<li v-for="(item, index) of list" :key="index">{{item}}</li>-->
</ul>
</div>
<script>
// 全局组件,在Vue中,每一个组件都是一个实例
Vue.component('todo-item', {
props: ['content', 'index'],
template: '<li @click="handleClick">{{content}}{{index}}</li>',
methods: {
handleClick: function() {
// alert('clicked')
// 向外触发父组件的delete事件
this.$emit('delete', this.index);
}
}
})
// 局部组件
// var todoItem = {
// template: '<li>item</li>'
// }
new Vue({
el: "#root",
// components: {
// 'todo-item': todoItem // 对局部组件进行注册
// },
data: {
inputValue: "",
list:[]
},
// template: '',如果vue的实例中没有定义template,那么vue会使用挂载点的dom作为template
methods: {
handleSubmit: function() {
this.list.push(this.inputValue)
this.inputValue = ''
},
handleDelete: function (index) {
// alert('delete ' + index)
// 删除当前点击的数据
this.list.splice(index, 1)
}
}
});
</script>
</body>
</html>
|
#User function Template for python3
from typing import List
from collections import deque
class Solution:
#Function to return Breadth First Traversal of given graph.
def bfsOfGraph(self, V: int, adj: List[List[int]]) -> List[int]:
# code here
arr=[]
q=deque()
q.append(0)
vis=set()
while q:
node=q.popleft()
if node not in vis:
vis.add(node)
arr.append(node)
for ad in adj[node]:
q.append(ad)
return arr
#{
# Driver Code Starts
if __name__ == '__main__':
T=int(input())
for i in range(T):
V, E = map(int, input().split())
adj = [[] for i in range(V)]
for _ in range(E):
u, v = map(int, input().split())
adj[u].append(v)
ob = Solution()
ans = ob.bfsOfGraph(V, adj)
for i in range(len(ans)):
print(ans[i], end = " ")
print()
# } Driver Code Ends
|
import Flutter
import UIKit
public class SwiftSystemDateTimeFormatPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "system_date_time_format", binaryMessenger: registrar.messenger())
let instance = SwiftSystemDateTimeFormatPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getDateFormat":
result(getDateFormat())
case "getMediumDateFormat":
result(getMediumDateFormat())
case "getLongDateFormat":
result(getLongDateFormat())
case "getTimeFormat":
result(getTimeFormat())
default:
result(FlutterMethodNotImplemented)
}
}
private func getDateFormat() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
return dateFormatter.dateFormat
}
private func getMediumDateFormat() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
return dateFormatter.dateFormat
}
private func getLongDateFormat() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
return dateFormatter.dateFormat
}
private func getTimeFormat() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
return dateFormatter.dateFormat
}
}
|
use crate::tree::{MessageField, WithName};
use std::fmt::{Display, Formatter};
/// A message.
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub struct Message {
name: String,
fields: Vec<MessageField>,
}
impl<S: Into<String>> From<S> for Message {
fn from(name: S) -> Self {
Self {
name: name.into(),
fields: Vec::default(),
}
}
}
impl WithName for Message {
fn name(&self) -> &str {
self.name.as_str()
}
}
impl Message {
//! Fields
/// Gets the fields.
pub fn fields(&self) -> &[MessageField] {
self.fields.as_slice()
}
/// Adds the field.
pub fn with_field<F>(mut self, field: F) -> Self
where
F: Into<MessageField>,
{
self.fields.push(field.into());
self
}
}
impl Display for Message {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "message {} {{\n", self.name)?;
for field in &self.fields {
write!(f, "\t{};\n", field)?;
}
write!(f, "}}\n")
}
}
|
package com.aionemu.gameserver.controllers.observer;
import java.util.concurrent.atomic.AtomicBoolean;
import com.aionemu.gameserver.geoEngine.collision.CollisionResults;
import com.aionemu.gameserver.geoEngine.math.Ray;
import com.aionemu.gameserver.geoEngine.math.Vector3f;
import com.aionemu.gameserver.geoEngine.models.GeoMap;
import com.aionemu.gameserver.geoEngine.scene.Spatial;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldPosition;
import com.aionemu.gameserver.world.geo.GeoService;
/**
* @author MrPoke
* @moved Rolandas
*/
public abstract class AbstractCollisionObserver extends ActionObserver {
protected Creature creature;
protected Vector3f oldPos;
protected Spatial geometry;
protected byte intentions;
private final CheckType checkType;
private AtomicBoolean isRunning = new AtomicBoolean();
public AbstractCollisionObserver(Creature creature, Spatial geometry, byte intentions, CheckType checkType) {
super(ObserverType.MOVE_OR_DIE);
this.creature = creature;
this.geometry = geometry;
WorldPosition lastPos;
if (creature instanceof Player && (lastPos = ((Player) creature).getMoveController().getLastPositionFromClient()) != null)
this.oldPos = new Vector3f(lastPos.getX(), lastPos.getY(), lastPos.getZ());
else
this.oldPos = new Vector3f(creature.getX(), creature.getY(), creature.getZ());
this.intentions = intentions;
this.checkType = checkType;
}
@Override
public void moved() {
if (!isRunning.getAndSet(true)) {
ThreadPoolManager.getInstance().execute(new Runnable() {
@Override
public void run() {
try {
Vector3f pos;
Vector3f dir;
if (checkType == CheckType.TOUCH) { // check if we are standing on the geometry (either top or bottom)
float x = creature.getX();
float y = creature.getY();
float z = creature.getZ();
float zMax = z + 0.05f + creature.getObjectTemplate().getBoundRadius().getUpper();
float zMin = z - 0.11f;
if (creature instanceof Player) {
if (((Player) creature).getMoveController().isJumping() || !((Player) creature).isInGlidingState() && !creature.isFlying()) {
float geoZ = GeoService.getInstance().getZ(creature.getWorldId(), x, y, z, creature.getInstanceId());
if (!Float.isNaN(geoZ)) {
zMin = geoZ - 0.11f;
}
}
}
pos = new Vector3f(x, y, zMax);
dir = new Vector3f(pos.getX(), pos.getY(), zMin);
} else { // check if we passed the geometry (either entering or leaving)
pos = new Vector3f(creature.getX(), creature.getY(), creature.getZ() + GeoMap.COLLISION_CHECK_Z_OFFSET);
dir = oldPos.clone();
dir.setZ(dir.getZ() + GeoMap.COLLISION_CHECK_Z_OFFSET);
}
Float limit = pos.distance(dir);
dir.subtractLocal(pos).normalizeLocal();
Ray r = new Ray(pos, dir);
r.setLimit(limit);
CollisionResults results = new CollisionResults(intentions, creature.getInstanceId(), true);
geometry.collideWith(r, results);
onMoved(results);
oldPos = pos;
} finally {
isRunning.set(false);
}
}
});
}
}
public abstract void onMoved(CollisionResults result);
public enum CheckType {
TOUCH,
PASS
}
}
|
import React, { Suspense } from 'react';
import './scss/app.scss';
import InfoPizza from './PizzaData/Pizza';
import { Routes, Route } from 'react-router-dom';
import Home from './Pages/Home';
import NotFound from './Pages/NotFound';
//import Basket from './Pages/Basket';
import MainLayout from './Iayoats/MainLayout';
const Basket = React.lazy(() => import('./Pages/Basket'));
export interface SearchContext{
search:string
setSearch:(value:string)=>void
}
export const SearchContext = React.createContext<SearchContext |null>(null);
const App:React.FC = () =>{
const [search, setSearch] = React.useState('');
return (
<SearchContext.Provider value={{ search, setSearch }}>
<Suspense fallback={<div>Загрузка...</div>}>
<Routes>
<Route path="/" element={<MainLayout />}>
<Route path="" element={<Home />} />
<Route path="react-pizza/" element={<Home />} />
<Route path="home/" element={<Home />} />
<Route path="home/:id" element={<InfoPizza />} />
<Route path="basket/" element={<Basket />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</Suspense>
</SearchContext.Provider>
);
}
export default App;
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
import "./ERC20.sol";
import "./SafeTransferLib.sol";
/// @title Mantle Token Migrator V2
/// @author Derrick Johnson
/// @notice Token migration contract for the BIT to MNT token migration
contract MantleTokenMigratorV2 {
using SafeTransferLib for ERC20;
/* ========== STATE VARIABLES ========== */
/// @dev The address of the BIT token contract
address public immutable BIT_TOKEN_ADDRESS;
/// @dev The address of the MNT token contract
address public immutable MNT_TOKEN_ADDRESS;
/// @dev The address of the treasury contract that receives defunded tokens
address public treasury;
/// @dev The address of the owner of the contract
/// @notice The owner of the contract is initially the deployer of the contract but will be transferred
/// to a multisig wallet immediately after deployment
address public owner;
/// @dev A mapping of addresses with the ability to approve token migrations
mapping(address => bool) public approvers;
/// @dev A mapping of addresses with the ability blacklist addresses from migration
mapping(address => bool) public blacklisters;
/// @dev A mapping of addresses blacklisted from migration
mapping(address => bool) public blacklistedAddresses;
/// @dev Boolean indicating if this contract is halted
bool public halted;
/* ========== EVENTS ========== */
// TokenSwap Events
/// @dev Emitted when a user swaps BIT for MNT
/// @param to The address of the user that swapped BIT for MNT
/// @param amountSwapped The amount of BIT swapped and MNT received
event TokensMigrated(address indexed to, uint256 amountSwapped);
/// @dev Emitted when a user is approved for token migration
/// @param approver The address of the caller that approved the user for token migration
/// @param user The address of the user that was approved for token migration
/// @param amount The amount of BIT tokens approved for token migration
event TokenMigrationApproved(address indexed approver, address indexed user, uint256 amount);
// Contract State Events
/// @dev Emitted when the owner of the contract is changed
/// @param previousOwner The address of the previous owner of this contract
/// @param newOwner The address of the new owner of this contract
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Emitted when the contract is halted
/// @param halter The address of the caller that halted this contract
event ContractHalted(address indexed halter);
/// @dev Emitted when the contract is unhalted
/// @param halter The address of the caller that unhalted this contract
event ContractUnhalted(address indexed halter);
/// @dev Emitted when the treasury address is changed
/// @param previousTreasury The address of the previous treasury
/// @param newTreasury The address of the new treasury
event TreasuryChanged(address indexed previousTreasury, address indexed newTreasury);
// Admin Events
/// @dev Emitted when non BIT/MNT tokens are swept from the contract by the owner to the recipient address
/// @param token The address of the token contract that was swept
/// @param recipient The address of the recipient of the swept tokens
/// @param amount The amount of tokens swept
event TokensSwept(address indexed token, address indexed recipient, uint256 amount);
/// @dev Emitted when BIT/MNT tokens are defunded from the contract by the owner to the treasury
/// @param defunder The address of the defunder
/// @param token The address of the token contract that was defunded
/// @param amount The amount of tokens defunded
event ContractDefunded(address indexed defunder, address indexed token, uint256 amount);
/// @dev Emitted when the Approver role is given to an address
/// @param approver The address that was given the Approver role
event ApproverRoleAssigned(address indexed approver);
/// @dev Emitted when the Approver role is revoked from an address
/// @param approver The address that had the Approver role revoked
event ApproverRoleRevoked(address indexed approver);
/// @dev Emitted when the Blacklister role is given to an address
/// @param blacklister The address that was given the Blacklister role
event BlacklisterRoleAssigned(address indexed blacklister);
/// @dev Emitted when the Blacklister role is revoked from an address
/// @param blacklister The address that had the Blacklister role revoked
event BlacklisterRoleRevoked(address indexed blacklister);
/// @dev Emitted when an address is blacklisted from migration
/// @param blacklister The address of the caller that blacklisted the address
/// @param blacklistedAddress The address that was blacklisted
event BlacklistModified(
address indexed blacklister, address indexed blacklistedAddress, bool indexed blacklistStatus
);
/// @dev Emitted when an address is removed from the blacklist
/// @param blacklister The address of the caller that removed the address from the blacklist
/// @param blacklistedAddress The address that was removed from the blacklist
event AddressRemovedFromBlacklist(address indexed blacklister, address indexed blacklistedAddress);
/* ========== ERRORS ========== */
/// @notice Thrown when the caller is not the owner and the function being called uses the {onlyOwner} modifier
/// @param caller The address of the caller
error MantleTokenMigrator_OnlyOwner(address caller);
/// @notice Thrown when the caller does not have the Approver role and the function being called uses the {onlyApprover} modifier
/// @param caller The address of the caller
error MantleTokenMigrator_OnlyApprover(address caller);
/// @notice Thrown when the caller does not have the Blacklist role and the function being called uses the {onlyBlacklister} modifier
/// @param caller The address of the caller
error MantleTokenMigrator_OnlyBlacklister(address caller);
/// @notice Thrown when the address being approved for token migration is blacklisted
error MantleTokenMigrator_BlacklistModified(address tokenMigrator);
/// @notice Thrown when the contract is halted and the function being called uses the {onlyWhenNotHalted} modifier
error MantleTokenMigrator_OnlyWhenNotHalted();
/// @notice Thrown when the input passed into the {_migrateTokens} function is zero
error MantleTokenMigrator_ZeroSwap();
/// @notice Thrown when at least one of the inputs passed into the constructor is a zero value
error MantleTokenMigrator_ImproperlyInitialized();
/// @notice Thrown when the {_tokenAddress} passed into the {sweepTokens} function is the BIT or MNT token address
/// @param token The address of the token contract
error MantleTokenMigrator_SweepNotAllowed(address token);
/// @notice Thrown when the {_tokenAddress} passed into the {defundContract} function is NOT the BIT or MNT token address
/// @param token The address of the token contract
error MantleTokenMigrator_InvalidFundingToken(address token);
/// @notice Thrown when the treasury is the zero address
error MantleTokenMigrator_InvalidTreasury(address treasury);
/* ========== MODIFIERS ========== */
/// @notice Modifier that checks that the caller is the owner of the contract
/// @dev Throws {MantleTokenMigrator_OnlyOwner} if the caller is not the owner
modifier onlyOwner() {
if (msg.sender != owner) revert MantleTokenMigrator_OnlyOwner(msg.sender);
_;
}
/// @notice Modifier that checks that the caller has the Approver role
/// @dev Throws {MantleTokenMigrator_OnlyApprover} if the caller does not have the Approver role
modifier onlyApprover() {
if (!approvers[msg.sender]) revert MantleTokenMigrator_OnlyApprover(msg.sender);
_;
}
/// @notice Modifier that checks that the contract is not halted
/// @dev Throws {MantleTokenMigrator_OnlyWhenNotHalted} if the contract is halted
modifier onlyWhenNotHalted() {
if (halted) revert MantleTokenMigrator_OnlyWhenNotHalted();
_;
}
/// @notice Modifier that checks that the caller has the Blacklist role
/// @dev Throws {MantleTokenMigrator_OnlyBlacklister} if the caller does not have the Blacklist role
modifier onlyBlacklister() {
if (!blacklisters[msg.sender]) revert MantleTokenMigrator_OnlyBlacklister(msg.sender);
_;
}
/// @notice Modifier that checks that the address being approved for token migration is not blacklisted
/// @dev Throws {MantleTokenMigrator_BlacklistModified} if the address is blacklisted
/// @param _address The address to check
modifier onlyWhenNotBlacklisted(address _address) {
if (blacklistedAddresses[_address]) revert MantleTokenMigrator_BlacklistModified(_address);
_;
}
/// @notice Initializes the MantleTokenMigrator contract, setting the initial deployer as the contract owner
/// @dev _bitTokenAddress, _mntTokenAddress, _tokenConversionNumerator, and _tokenConversionDenominator are immutable: they can only be set once during construction
/// @dev the contract is initialized in a halted state
/// @dev Requirements:
/// - all parameters must be non-zero
/// - _bitTokenAddress and _mntTokenAddress are assumed to have the same number of decimals
/// @param _bitTokenAddress The address of the BIT token contract
/// @param _mntTokenAddress The address of the MNT token contract
/// @param _treasury The address of the treasury contract that receives defunded tokens
constructor(address _bitTokenAddress, address _mntTokenAddress, address _treasury) {
if (_bitTokenAddress == address(0) || _mntTokenAddress == address(0) || _treasury == address(0)) {
revert MantleTokenMigrator_ImproperlyInitialized();
}
owner = msg.sender;
halted = true;
BIT_TOKEN_ADDRESS = _bitTokenAddress;
MNT_TOKEN_ADDRESS = _mntTokenAddress;
treasury = _treasury;
}
/* ========== TOKEN SWAPPING ========== */
/// @notice Allows an approver to approve a user for token migration and performs the migration on their behalf
/// @dev emits a {TokenMigrationApproved} and {TokensMigrated} event
/// @dev Requirements:
/// - The contract must not be halted
/// - The caller must have the Approver role
/// - The address being approved for token migration must not be blacklisted
function approveMigrationRequest(address _addressToMigrate, uint256 _amount)
external
onlyWhenNotHalted
onlyApprover
onlyWhenNotBlacklisted(_addressToMigrate)
{
emit TokenMigrationApproved(msg.sender, _addressToMigrate, _amount);
_migrateTokens(_addressToMigrate, _amount);
}
/// @notice Internal function that swaps a specified amount of the caller's BIT tokens for MNT tokens
/// @dev emits a {TokensMigrated} event
/// @dev Requirements:
/// - The caller must have approved this contract to spend at least {_amount} of their BIT tokens
/// - The caller must have a balance of at least {_amount} of BIT tokens
/// - {_amount} must be non-zero
/// @param _to The address of the user to swap tokens for
/// @param _amount The amount of BIT tokens to swap
function _migrateTokens(address _to, uint256 _amount) internal {
if (_amount == 0) revert MantleTokenMigrator_ZeroSwap();
// transfer user's BIT tokens to this contract
ERC20(BIT_TOKEN_ADDRESS).safeTransferFrom(_to, address(this), _amount);
// transfer MNT tokens to user, if there are insufficient tokens, in the contract this will revert
ERC20(MNT_TOKEN_ADDRESS).safeTransfer(_to, _amount);
emit TokensMigrated(_to, _amount);
}
/* ========== ADMIN UTILS ========== */
// Ownership Functions
/// @notice Transfers ownership of the contract to a new address
/// @dev emits an {OwnershipTransferred} event
/// @dev Requirements:
/// - The caller must be the contract owner
function transferOwnership(address _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
// Role Assignment Functions
/// @notice Gives the Approver role to an address
/// @dev emits an {ApproverRoleAssigned} event
/// @dev Requirements:
/// - The caller must be the contract owner
/// @param _approver The address to give the Approver role to
function giveApproverRole(address _approver) public onlyOwner {
approvers[_approver] = true;
emit ApproverRoleAssigned(_approver);
}
/// @notice Revokes the Approver role from an address
/// @dev emits an {ApproverRoleRevoked} event
/// @dev Requirements:
/// - The caller must be the contract owner
/// @param _approver The address to revoke the Approver role from
function revokeApproverRole(address _approver) public onlyOwner {
approvers[_approver] = false;
emit ApproverRoleRevoked(_approver);
}
/// @notice Gives the Blacklister role to an address
/// @dev emits an {BlacklisterRoleAssigned} event
/// @dev Requirements:
/// - The caller must be the contract owner
/// @param _blacklister The address to give the Blacklister role to
function giveBlacklisterRole(address _blacklister) public onlyOwner {
blacklisters[_blacklister] = true;
emit BlacklisterRoleAssigned(_blacklister);
}
/// @notice Revokes the Blacklister role from an address
/// @dev emits an {BlacklisterRoleRevoked} event
/// @dev Requirements:
/// - The caller must be the contract owner
/// @param _blacklister The address to revoke the Blacklist role from
function revokeBlacklisterRole(address _blacklister) public onlyOwner {
blacklisters[_blacklister] = false;
emit BlacklisterRoleRevoked(_blacklister);
}
// Contract State Functions
/// @notice Blacklists an address from token migration
/// @dev emits an {BlacklistModified} event
/// @dev Requirements:
/// - The caller must have the Blacklister role
/// @param _address The address to blacklist
function blacklistAddress(address _address) public onlyBlacklister {
blacklistedAddresses[_address] = true;
emit BlacklistModified(msg.sender, _address, true);
}
/// @notice Removes an address from the blacklist
/// @dev emits an {BlacklistModified} event
/// @dev Requirements:
/// - The caller must have the Blacklister role
/// @param _address The address to remove from the blacklist
function removeAddressFromBlacklist(address _address) public onlyBlacklister {
blacklistedAddresses[_address] = false;
emit BlacklistModified(msg.sender, _address, false);
}
/// @notice Halts the contract, preventing token migrations
/// @dev emits a {ContractHalted} event
/// @dev Requirements:
/// - The caller must be the contract owner
function haltContract() public onlyOwner {
halted = true;
emit ContractHalted(msg.sender);
}
/// @notice Unhalts the contract, allowing token migrations
/// @dev emits a {ContractUnhalted} event
/// @dev Requirements:
/// - The caller must be the contract owner
function unhaltContract() public onlyOwner {
halted = false;
emit ContractUnhalted(msg.sender);
}
/// @notice Sets the treasury address
/// @dev emits a {TreasuryChanged} event
/// @dev Requirements:
/// - The caller must be the contract owner
function setTreasury(address _treasury) public onlyOwner {
if (_treasury == address(0)) {
revert MantleTokenMigrator_InvalidTreasury(_treasury);
}
emit TreasuryChanged(treasury, _treasury);
treasury = _treasury;
}
// Token Management Functions
/// @notice Defunds the contract by transferring a specified amount of BIT or MNT tokens to the treasury address
/// @dev emits a {ContractDefunded} event
/// @dev Requirements:
/// - The caller must be the contract owner
/// - {_tokenAddress} must be either the BIT or the MNT token address
/// - The contract must have a balance of at least {_amount} of {_tokenAddress} tokens
/// @param _tokenAddress The address of the token to defund
/// @param _amount The amount of tokens to defund
function defundContract(address _tokenAddress, uint256 _amount) public onlyOwner {
if (_tokenAddress != BIT_TOKEN_ADDRESS && _tokenAddress != MNT_TOKEN_ADDRESS) {
revert MantleTokenMigrator_InvalidFundingToken(_tokenAddress);
}
// we can only defund BIT or MNT into the predefined treasury address
ERC20(_tokenAddress).safeTransfer(treasury, _amount);
emit ContractDefunded(treasury, _tokenAddress, _amount);
}
/// @notice Sweeps a specified amount of tokens to an arbitrary address in case of accidental token transfers
/// @dev emits a {TokensSwept} event
/// @dev Requirements:
/// - The caller must be the contract owner
/// - {_tokenAddress} must not the BIT or the MNT token address
/// - The contract must have a balance of at least {_amount} of {_tokenAddress} tokens
/// @param _tokenAddress The address of the token to sweep
/// @param _recipient The address to sweep the tokens to
/// @param _amount The amount of tokens to sweep
function sweepTokens(address _tokenAddress, address _recipient, uint256 _amount) public onlyOwner {
// we can only sweep tokens that are not BIT or MNT to an arbitrary addres
if ((_tokenAddress == BIT_TOKEN_ADDRESS) || (_tokenAddress == MNT_TOKEN_ADDRESS)) {
revert MantleTokenMigrator_SweepNotAllowed(_tokenAddress);
}
ERC20(_tokenAddress).safeTransfer(_recipient, _amount);
emit TokensSwept(_tokenAddress, _recipient, _amount);
}
}
|
import { ReactNode, FunctionComponent, useEffect } from 'react';
import { LazyMotion, m, domAnimation } from 'framer-motion';
import { Navbar, Footer } from '../components';
import { useThemeStore } from '../store';
type MainLayoutProps = {
children: ReactNode;
location?: string;
};
export const MainLayout: FunctionComponent<MainLayoutProps> = ({
children,
location = '',
}: MainLayoutProps) => {
const theme = useThemeStore((state) => state.theme);
useEffect(() => {
if (theme === 'dark') {
document.body.style.background = '#343A40';
} else {
document.body.style.background = '#ffffff';
}
}, [theme]);
return (
<>
<Navbar
sections={['Blog', 'Projects', 'Skills']}
location={location}
/>
<LazyMotion features={domAnimation}>
<m.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.6 }}
>
{children}
<Footer />
</m.div>
</LazyMotion>
</>
);
};
|
import { createContext, useState, useEffect } from 'react'
import clientAxios from '../helpers/clientAxios'
import useAuthProvider from '../hooks/useAuthProvider'
import { toast } from 'react-toastify';
export const TaskContext = createContext()
const TaskProvider = ({ children }) => {
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [priority, setPriority] = useState('')
const [isOpen, setIsOpen] = useState(false)
const [createMode, setCreateMode] = useState(true)
const [task, setTask] = useState({})
const [tasks, setTasks] = useState([])
const [id, setId] = useState('')
const [status, setStatus] = useState(false)
const [navPriority, setNavPriority] = useState('')
useEffect(() => {
const getTasks = async () => {
try {
const { data } = await clientAxios('/tasks')
setTasks(data)
} catch (error) {
console.log(error)
}
}
getTasks()
}, [])
const createTask = async () => {
//Comprobaciones
if([name, description, priority].includes('')){
toast.error('Fill all the fields')
return
}
if(description.length >= 80){
toast.error('The maxium of caracters is 80')
return
}
if(name.length < 3){
toast.error("The minium of caracters is 3")
return
}
await setCreateMode(true)
try {
const { data } = await clientAxios.post('/tasks', { name, description, priority })
setTasks([...tasks, data])
toast.success("Task created successfully")
setIsOpen(false)
setName('')
setDescription('')
setPriority('')
} catch (error) {
toast.error(error.response?.data?.msg)
}
}
const deleteTask = async (id) => {
try {
const { data } = await clientAxios.delete(`/tasks/${id}`)
const taskUpdated = tasks.filter(taskState => taskState._id !== id)
setTasks(taskUpdated)
setId('')
setIsOpen(false)
setName('')
setDescription('')
setPriority('')
toast.success('Task deleted')
} catch (error) {
toast.error(error.response?.data?.msg)
}
}
const getTask = async (id) => {
setCreateMode(false)
setIsOpen(true)
setId(id)
try {
const task = await clientAxios.get(`/tasks/${id}`)
setName(task.data.task.name)
setDescription(task.data.task.description)
setPriority(task.data.task.priority)
setStatus(task.data.task.status)
} catch (error){
console.log(error)
}
}
const editTask = async () => {
try {
const { data } = await clientAxios.put(`/tasks/${id}`, { name, description, priority, status })
setId('')
setIsOpen(false)
const taskUpdatedState = tasks.map(taskState => taskState._id === data.taskUpdated._id ? data.taskUpdated : taskState)
setTasks(taskUpdatedState)
setName('')
setDescription('')
setPriority('')
setStatus(false)
} catch (error) {
toast.error(error.response?.data?.msg)
}
}
return (
<TaskContext.Provider
value={{
name, setName,
description, setDescription,
priority, setPriority,
createTask,
isOpen, setIsOpen, createMode, setCreateMode,
tasks,
deleteTask, editTask, getTask,
setStatus, status,
setId, id,
setNavPriority, navPriority
}}
>
{children}
</TaskContext.Provider>
)
}
export default TaskProvider
|
package za.ac.cput.domain;
/**
* Using Builder
* Student Number - 206006330
*/
public class City {
private String id;
private String name;
private Country country;
//Private Constructors
private City(Builder builder){
this.id = builder.id;
this.name = builder.name;
this.country = builder.country;
}
//Setters
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setCountry(Country country) {
this.country = country;
}
//Getters
public String getId() {
return id;
}
public String getName() {
return name;
}
public Country getCountry() {
return country;
}
//Builder Class
public static class Builder {
private String id;
private String name;
private Country country;
public Builder(String id) {
this.id = id;
}
public Builder theirName(String name) {
this.name = name;
return this;
}
public Builder theirCountry(Country country) {
this.name = name;
return this;
}
//This is optional
public Builder copy(City city) {
this.id = city.id;
this.name = city.name;
this.country = city.country;
return this;
}
public City build() {
return new City(this);
}
}
@Override
public String toString() {
return "City{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", country=" + country +
'}';
}
}
|
const express = require("express");
const router = express.Router();
const fetchuser = require("../middleware/fetchuser"); //importing fetchuser file
const Notes = require("../models/Notes"); //importing notes schema
const { body, validationResult } = require("express-validator"); //importing express-validator module
//Route :1 Get all notes
router.get("/fetchallnotes", fetchuser, async (req, res) => {
try {
const notes = await Notes.find({ user: req.user.id });
res.json(notes);
} catch (error) {
console.log(error);
res.status(500).send("Internal server error");
}
});
//Route:2 Adding new notes from users : post /api/note/addnotes
router.post(
"/addnotes",
fetchuser,
[
body("title", "Enter a Valid title").isLength({ min: 1 }),
body("description", "Description must be more than 1").isLength({ min: 1 }),
],
async (req, res) => {
try {
//Destructuring the request data
const { title, description, tag } = req.body;
//any errors handle it
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
//create note from note schema
const note = new Notes({
title,
description,
tag,
user: req.user.id,
});
//save the notes into db
const savednote = await note.save();
res.json(savednote);
} catch (error) {
//handle error
console.log(error);
res.status(500).send("Internal server error");
}
}
);
//Route :3 Updating notes using: put /api/note/updatenotes/id
router.put(
"/updatenotes/:id",
fetchuser,
[
body("title", "Enter a Valid title").isLength({ min: 1 }),
body("description", "Description must be more than 1").isLength({ min: 1 }),
],
async (req, res) => {
try {
const { title, description, tag } = req.body;
//Create note
const newNote = {};
//If any updates with other note
if (title) {
newNote.title = title;
}
if (description) {
newNote.description = description;
}
if (tag) {
newNote.tag = tag;
}
//find the note to be updated
let note = await Notes.findById(req.params.id);
if (!note) {
return res.status(404).send("Not Found");
}
//only that user can modify his notes
if (note.user.toString() !== req.user.id) {
return res.status(401).send("Not Allowed");
}
//Update note which is matched
note = await Notes.findByIdAndUpdate(
req.params.id,
{ $set: newNote },
{ new: true }
);
res.json({ note });
} catch (error) {
//handle error
console.log(error);
res.status(500).send("Internal server error");
}
}
);
//Route :4 Deleting note : delete /api/note/deletenote
router.delete(
"/deletenotes/:id",
fetchuser,
[
body("title", "Enter a Valid title").isLength({ min: 3 }),
body("description", "Description must be more than 5").isLength({ min: 5 }),
],
async (req, res) => {
try {
//find the note to be deleted
let note = await Notes.findById(req.params.id);
if (!note) {
return res.status(404).send("Not Found");
}
//only that user can delete his notes
if (note.user.toString() !== req.user.id) {
return res.status(401).send("Not Allowed");
}
//Delete note which is matched
note = await Notes.findByIdAndDelete(req.params.id);
res.json({ Sucess: "the note deleted", note: note });
} catch (error) {
//handle error
console.log(error);
res.status(500).send("Internal server error");
}
}
);
module.exports = router;
|
//! Defines a RequestConfig Enum which represents the data necessary to be passed on for requests
/// An enum that should only contain one item, contains what is required to be
/// sent to the configuration
pub enum RequestConfig {
/// Request Builder for the Solana Configuration
#[cfg(feature = "SOLANA")]
ReqBldr(reqwest::RequestBuilder),
}
impl RequestConfig {
/// Attempts to clone
pub fn try_clone(&self) -> Option<Self> {
match self {
#[cfg(feature = "SOLANA")]
RequestConfig::ReqBldr(req_builder) => {
req_builder.try_clone().map(RequestConfig::ReqBldr)
}
}
}
/// Returns the the value on the inside, consuming the enum
pub fn to_requestbuilder(&self) -> reqwest::RequestBuilder {
match self {
#[cfg(feature = "SOLANA")]
RequestConfig::ReqBldr(reqbldr) => reqbldr.try_clone().unwrap(),
}
}
}
|
package test.DaoTests;
import db_access.*;
import db_access.DaoInterfaces.ContainSubsetDao;
import db_access.DaoInterfaces.ProviderDao;
import model.*;
import static org.junit.Assert.*;
import java.sql.*;
import org.junit.*;
import java.util.List;
public class TestProviderDaoImplementation {
//TODO this class needs to be checked
static ProviderDao providerDao;
static ContainSubsetDao<Provider> providerSubsetDaoPart;
static int generatedId;
static Provider providerToUpdate;
static Provider providerToDelete;
@BeforeClass
public static void setUp() throws SQLException, Exception {
providerDao = DaoFactory.getProviderDao();
providerSubsetDaoPart = (ContainSubsetDao<Provider>) providerDao;
providerToUpdate = ModelFactory.getProviderModel("Michel", "Michel", "Michel", "Michel");
providerDao.createProvider(providerToUpdate);
providerToDelete = ModelFactory.getProviderModel("Michel", "Michel", "Michel", "Michel");
providerDao.createProvider(providerToDelete);
}
@Test
public void testFindProviderByIdWithoutAssociation() throws SQLException, Exception{
Provider result = providerDao.findProviderById(1, false);
assertNotNull("The retrieved object shouldn't be null.", result);
assertNull("The provider PurchaseOrder list shouldn't be set",result.getPurchaseOrders());
}
@Test
public void testFindProviderByIdWithPurchaseOrderAssociation() throws SQLException, Exception{
//Arrange
//Act
Provider result = providerDao.findProviderById(1, true);
//Assert
assertNotNull("The retrieved object shouldn't be null.", result);
assertNotNull("The provider PurchaseOrder list should be set",result.getPurchaseOrders());
}
@Test
public void testFindAllProviderWithoutAssociation() throws SQLException, Exception {
//Arrange
//Act
List<Provider> results = providerDao.findAllProviders(false);
//Assert
assertNotNull("The retrieved object shouldn't be null.", results);
for(Provider provider : results) {
assertNull("The provider PurchaseOrder list shouldn't be set",provider.getPurchaseOrders());
}
}
@Test
public void testFindAllProviderWithPurchaseOrderAssociation() throws SQLException, Exception {
//Arrange
//Act
List<Provider> results = providerDao.findAllProviders(true);
//Assert
assertNotNull("The retrieved object shouldn't be null.", results);
for(Provider provider : results) {
assertNotNull("The provider PurchaseOrder list should be set",provider.getPurchaseOrders());
}
}
@Test
public void testFindProviderByFullNameWithoutAssociation() throws SQLException, Exception{
//Arrange
//Act
Provider result = providerDao.findProviderByFullName("Cassandra Johnson", false);
//Assert
assertNotNull("The retrieved object shouldn't be null.", result);
assertNull("The provider PurchaseOrder list shouldn't be set",result.getPurchaseOrders());
}
@Test
public void testFindProviderByFullNameWithPurchaseOrderAssociation() throws SQLException, Exception{
Provider result = providerDao.findProviderByFullName("Cassandra Johnson", true);
assertNotNull("The retrieved object shouldn't be null.", result);
assertNotNull("The provider PurchaseOrder list should be set",result.getPurchaseOrders());
}
@Test
public void testFindProviderByPartialNameWithoutAssociation() throws SQLException, Exception{
//Arrange
//Act
List<Provider> results = providerDao.findProvidersByName("n", false);
//Assert
assertNotNull("The retrieved object shouldn't be null.", results);
for(Provider provider : results) {
assertNull("The provider PurchaseOrder list should be set",provider.getPurchaseOrders());
}
}
@Test
public void testFindProviderByPartialNameWithPurchaseOrderAssociation() throws SQLException, Exception{
//Arrange
//Act
List<Provider> results = providerDao.findProvidersByName("n", true);
//Assert
assertNotNull("The retrieved object shouldn't be null.", results);
for(Provider provider : results) {
assertNotNull("The provider PurchaseOrder list should be set",provider.getPurchaseOrders());
}
}
@Test
public void testCreateProvider() throws SQLException, Exception {
//Arrange
Provider testProvider = (Provider) ModelFactory.getProviderModel("TestFirstName", "TestLastName", "testCity", "testCountry");
//Act
providerDao.createProvider(testProvider);
generatedId = testProvider.getId();
//Assert
assertNotNull("The retrieved object shouldn't be null.", providerDao.findProviderById(testProvider.getId(), false));
}
@Test
public void testUpdateProvider() throws SQLException, Exception {
//Arrange
providerToUpdate.setFirstName("UpdatedFirstName");
//Act
providerDao.updateProvider(providerToUpdate);
//Assert
assertEquals("Should equal \"UpdatedFirstName\".", "UpdatedFirstName",providerDao.findProviderById(providerToUpdate.getId(), false).getFirstName() );
}
@Test
public void testDeleteProvider() throws SQLException, Exception {
//Arrange
//Act
providerDao.deleteProvider(providerToDelete);
//Assert
assertNull("Should return null.", providerDao.findProviderById(providerToDelete.getId(), false));
}
@Test
public void testFindAllProviderSubset() throws SQLException, Exception{
//Arrange
//Act
List<Provider> providerSubsetList = providerSubsetDaoPart.findAllSubset();
//Assert
assertTrue("Should retrieve a none empty list", providerSubsetList.size()>0);
assertNull("Should retrieve products without selling price", providerSubsetList.get(0).getCountry());
}
@AfterClass
public static void cleanUp() throws SQLException, Exception {
Provider createdProvider = ModelFactory.getProviderModel(generatedId, null, null, null, null);
providerDao.deleteProvider(createdProvider);
providerDao.deleteProvider(providerToUpdate);
}
}
|
import { FC, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faChevronUp } from "@fortawesome/free-solid-svg-icons";
const Dropdown: FC<{ placeholder?: string; options: string[] }> = ({
placeholder,
options,
}) => {
const [isOpen, setIsOpen] = useState(false);
const [selectedOption, setSelectedOption] = useState("");
const toggling = () => setIsOpen(!isOpen);
const onOptionClicked = (value: string) => {
setSelectedOption(value);
setIsOpen(false);
};
return (
<div className="dropdown">
<div className="selected-option" onClick={toggling}>
<span>
{selectedOption
? selectedOption
: placeholder
? placeholder
: options[0]}
</span>
<i
className="arrow"
style={{
transform: `rotate(${isOpen ? "0" : "180deg"}) translateY(${
isOpen ? "-50%" : "50%"
})`,
}}
>
<FontAwesomeIcon icon={faChevronUp} />
</i>
</div>
{isOpen && (
<ul className="list">
{options.map((option) => (
<li
className={`item ${selectedOption === option ? "selected" : ""}`}
onClick={() => onOptionClicked(option)}
key={Math.random()}
>
{option}
</li>
))}
</ul>
)}
</div>
);
};
export default Dropdown;
|
package com.learnreactiveprogramming.service;
import com.learnreactiveprogramming.exception.ReactorException;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import static com.learnreactiveprogramming.util.CommonUtil.delay;
@Slf4j
public class FluxAndMonoGeneratorService {
public Flux<String> namesFlux() {
return Flux.fromIterable(List.of("Mukesh", "Suresh"));
}
public Flux<String> namesFluxMap() {
return Flux.fromIterable(List.of("Mukesh", "Suresh")).map(String::toUpperCase).doOnComplete(() -> System.out.println("hello completed"));
}
public Flux<String> namesFluxImmutability() {
Flux<String> input = Flux.fromIterable(List.of("Mukesh", "Suresh"));
input.map(String::toUpperCase);
return input;
}
public Flux<String> namesFluxFilter(int size) {
Flux<String> input = Flux.fromIterable(List.of("Mukesh", "Suresh"));
return input.map(String::toUpperCase).filter(e -> e.length() > size).map(s -> s.length() + "-" + s).doOnNext(e -> {
System.out.println("Next value is ::: " + e);
}).doOnSubscribe(s -> {
System.out.println("Subscription is :::: " + s);
}).doOnComplete(() -> {
System.out.println("completed Successfully");
}).doFinally(signalType -> {
System.out.println("signalType in side finally " + signalType);
});
}
public Flux<String> namesFlux_Exceptions() {
return Flux.just("Mukesh", "Suresh", "Ramesh").concatWith(Flux.error(new RuntimeException("Exception while Processing flux"))).concatWith(Flux.just("Hello"));
}
public Flux<String> namesFlux_OnErrorReturn() {
return Flux.just("Mukesh", "Suresh", "Ramesh").concatWith(Flux.error(new RuntimeException("Exception while Processing flux"))).onErrorReturn("Hello");
}
public Mono<String> exception_mono_onErrorContinue(String input) {
var monoInput = Mono.just(input);
return monoInput.map(name -> {
if ("abc".equalsIgnoreCase(name)) {
throw new RuntimeException("Exception");
}
return name;
}).onErrorContinue((ex, name) -> {
log.info("Exception is :: " + ex);
log.info("Name is :: " + name);
});
}
public Flux<String> namesFlux_OnErrorResume(Exception e) {
var recoveryFlux = Flux.just("Default Error Message");
return Flux.just("Mukesh", "Suresh", "Ramesh").concatWith(Flux.error(e)).onErrorResume(ex -> {
log.info("Exception is :: " + e);
if (e instanceof IllegalStateException) {
return recoveryFlux;
} else {
return Flux.error(ex);
}
});
}
public Flux<String> namesFlux_OnErrorContinue() {
return Flux.just("Mukesh", "Suresh", "Ramesh").map(name -> {
if ("Suresh".equalsIgnoreCase(name)) {
throw new IllegalStateException("Exception");
}
return name;
}).onErrorContinue((ex, name) -> {
log.info("Exception is :: " + ex);
log.info("Name is :: " + name);
});
}
public Flux<String> namesFlux_OnErrorMap() {
return Flux.just("Mukesh", "Suresh", "Ramesh").map(name -> {
if ("Suresh".equalsIgnoreCase(name)) {
throw new IllegalStateException("Exception");
}
return name;
}).onErrorMap(ex -> {
log.info("Exception is :: " + ex);
return new ReactorException(ex, ex.getMessage());
});
}
public Flux<String> namesFlux_doError() {
return Flux.just("Mukesh", "Suresh", "Ramesh").concatWith(Flux.error(new IllegalStateException("Exception occurred"))).doOnError(ex -> {
log.error("Error e ::: " + ex);
});
}
public Mono<Object> namesMono_ErrorReturn() {
return Mono.just("Mukesh").map(e -> {
throw new RuntimeException("Exception occurred");
}).onErrorReturn("abc");
}
public Flux<String> namesFluxFlatMap() {
Flux<String> input = Flux.fromIterable(List.of("Mukesh"));
return input.flatMap(e -> Flux.fromArray(e.split("")));
}
public Flux<String> namesFluxFlatMap_AsyncDelay() {
Flux<String> input = Flux.fromIterable(List.of("Mukesh"));
var delay = new Random().nextInt(1000);
return input.flatMap(e -> Flux.fromArray(e.split(""))).delayElements(Duration.ofMillis(delay));
}
public Flux<String> namesFluxConcatMapAsyncDelay() {
Flux<String> input = Flux.fromIterable(List.of("Mukesh"));
var delay = 1000;
return input.concatMap(e -> Flux.fromArray(e.split(""))).delayElements(Duration.ofMillis(delay));
}
public Flux<String> namesFluxTransform(int size) {
Function<Flux<String>, Flux<String>> filterMap = name -> name.map(String::toUpperCase).filter(e -> e.length() > size);
Flux<String> input = Flux.fromIterable(List.of("Mukesh"));
return input.transform(filterMap).flatMap(s -> Flux.fromArray(s.split(""))).defaultIfEmpty("default").log();
}
public Flux<String> namesFluxTransform_SwitchIfEmpty(int size) {
Function<Flux<String>, Flux<String>> filterMap = name -> name.map(String::toUpperCase).filter(e -> e.length() > size).flatMap(s -> Flux.fromArray(s.split("")));
Flux<String> input = Flux.fromIterable(List.of("Mukesh"));
Flux<String> aDefault = Flux.just("Default").transform(filterMap);
return input.transform(filterMap).switchIfEmpty(aDefault).log();
}
public Mono<String> namesMono() {
return Mono.just("Tiger");
}
public Flux<String> exploreConcat() {
return Flux.concat(Flux.just("Mukesh"), Flux.just("Mahesh")).log();
}
public Flux<String> exploreConcatDelay() {
return Flux.fromIterable(List.of("Alex", "Bob")).map(String::toUpperCase).filter(s -> s.length() > 3).concatWith(s -> splitString_withDelay(String.valueOf(s)));
}
private Flux<String> splitString_withDelay(String name) {
var delay = new Random().nextInt(1000);
var charArray = name.split("");
return Flux.fromArray(charArray).delayElements(Duration.ofMillis(1000));
}
public Flux<String> exploreConcatWithMono() {
return Mono.just("Mukesh").concatWith(Flux.just("Rasna")).log();
}
public Mono<List<String>> namesMonoFlatMap() {
Mono<String> mono = Mono.just("Tiger").map(String::toUpperCase);
return mono.flatMap(s -> Mono.just(Arrays.asList(s.split(""))));
}
public Flux<String> namesMonoFlatMapMany() {
Mono<String> mono = Mono.just("Tiger").map(String::toUpperCase);
return mono.flatMapMany(s -> Flux.fromArray(s.split(""))).log();
}
public Flux<String> mergeDemo() {
var abcFlux = Flux.just("Mukesh", "Mohan").delayElements(Duration.ofMillis(150));
var defFlux = Flux.just("Roshan", "Sohan").delayElements(Duration.ofMillis(100));
return Flux.merge(abcFlux, defFlux).log();
}
public Flux<String> mergeWithMonoDemo() {
return Flux.merge(Flux.just("Mohan", "Raman").delayElements(Duration.ofMillis(1000)), Flux.just("Roshan", "Data")).delayElements(Duration.ofMillis(1500));
}
public Flux<Integer> explore_Generate() {
return Flux.generate(() -> 1, (state, sink) -> {
sink.next(state * 2);
if (state == 10) {
sink.complete();
}
return state + 1;
});
}
public static List<String> names() {
delay(1000);
return List.of("Alex", "Bob", "Charley");
}
public Flux<String> explore_create() {
return Flux.create(sink -> {
// names().forEach(sink::next);
CompletableFuture
.supplyAsync(() -> names())
.thenAccept(names -> {
names().forEach(sink::next);
})
.thenRun(() -> explore_sendEvents(sink));
});
}
public Mono<String> explore_create_mono() {
return Mono.create(sink -> {
sink.success("Alex");
});
}
public Flux<String> explore_handle() {
return Flux.fromIterable(List.of("Alex", "Bob", "Charley"))
.handle((name, sink) -> {
if (name.length() > 3) {
sink.next(name.toUpperCase());
}
});
}
public void explore_sendEvents(FluxSink<String> fluxSink) {
CompletableFuture
.supplyAsync(() -> names())
.thenAccept(names -> {
names().forEach(fluxSink::next);
}).thenRun(fluxSink::complete);
}
public static void main(String[] args) {
FluxAndMonoGeneratorService service = new FluxAndMonoGeneratorService();
// service.namesFluxMap().subscribe(System.out::println);
// service.namesMono().subscribe(System.out::println);
// service.namesMonoFlatMap().subscribe(System.out::println);
// service.namesFluxTransform_SwitchIfEmpty(6).subscribe(System.out::println);
service.mergeDemo().subscribe(System.out::println);
}
}
|
use std::fmt::{Display, Formatter};
use iso7816_tlv::ber;
use crate::iccoa2::{create_tlv_with_primitive_value, get_tlv_primitive_value, Serde};
use crate::iccoa2::errors::*;
use super::{common, VERSION_TAG};
#[allow(dead_code)]
const SELECT_CLA: u8 = 0x00;
#[allow(dead_code)]
const SELECT_INS: u8 = 0xA4;
#[allow(dead_code)]
const SELECT_P1: u8 = 0x04;
#[allow(dead_code)]
const SELECT_P2: u8 = 0x00;
#[allow(dead_code)]
const SELECT_LE: u8 = 0x00;
#[derive(Debug, PartialOrd, PartialEq)]
pub struct CommandApduSelect {
aid: Vec<u8>,
}
#[allow(dead_code)]
impl CommandApduSelect {
pub fn new(aid: &[u8]) -> Self {
CommandApduSelect {
aid: aid.to_vec(),
}
}
pub fn get_aid(&self) -> &[u8] {
&self.aid
}
pub fn set_aid(&mut self, aid: &[u8]) {
self.aid = aid.to_vec();
}
}
impl Serde for CommandApduSelect {
type Output = Self;
fn serialize(&self) -> Result<Vec<u8>> {
let header = common::CommandApduHeader::new(
SELECT_CLA,
SELECT_INS,
SELECT_P1,
SELECT_P2,
);
let trailer = common::CommandApduTrailer::new(
Some(self.aid.clone()),
Some(SELECT_LE),
);
common::CommandApdu::new(header, Some(trailer)).serialize()
}
fn deserialize(data: &[u8]) -> Result<Self::Output> {
let command_apdu = common::CommandApdu::deserialize(data)?;
let header = command_apdu.get_header();
let trailer = command_apdu.get_trailer().ok_or("deserialize trailer is NULL".to_string())?;
if header.get_cla() != SELECT_CLA ||
header.get_ins() != SELECT_INS ||
header.get_p1() != SELECT_P1 ||
header.get_p2() != SELECT_P2 ||
trailer.get_le().is_none() ||
*trailer.get_le().unwrap() != SELECT_LE {
return Err(ErrorKind::ApduInstructionErr("deserialize SELECT Apdu error".to_string()).into());
}
Ok(CommandApduSelect::new(trailer.get_data().unwrap()))
}
}
impl Display for CommandApduSelect {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:02X?}", self.get_aid())
}
}
#[derive(Debug, PartialOrd, PartialEq)]
pub struct ResponseApduSelect {
version: u16,
status: common::ResponseApduTrailer,
}
#[allow(dead_code)]
impl ResponseApduSelect {
pub fn new(version: u16, status: common::ResponseApduTrailer) -> Self {
ResponseApduSelect {
version,
status,
}
}
pub fn get_version(&self) -> u16 {
self.version
}
pub fn set_version(&mut self, version: u16) {
self.version = version;
}
pub fn get_status(&self) -> &common::ResponseApduTrailer {
&self.status
}
pub fn set_status(&mut self, status: common::ResponseApduTrailer) {
self.status = status;
}
}
impl Serde for ResponseApduSelect {
type Output = Self;
fn serialize(&self) -> Result<Vec<u8>> {
let version_tlv = create_tlv_with_primitive_value(VERSION_TAG, self.get_version().to_be_bytes().as_ref())?;
common::ResponseApdu::new(Some(version_tlv.to_vec()), self.status).serialize()
}
fn deserialize(data: &[u8]) -> Result<Self::Output> {
let response = common::ResponseApdu::deserialize(data)?;
let status = response.get_trailer();
let body = response.get_body().ok_or("deserialize SELECT response version is NULL".to_string())?;
let version_tlv = ber::Tlv::from_bytes(body)
.map_err(|e| ErrorKind::ApduInstructionErr(format!("deserialize version error: {}", e)))?;
let versions = get_tlv_primitive_value(&version_tlv, version_tlv.tag())
.map_err(|e| ErrorKind::ApduInstructionErr(format!("deserialize version value error: {}", e)))?;
let version = u16::from_be_bytes(
(versions[0..2])
.try_into()
.map_err(|e| ErrorKind::ApduInstructionErr(format!("deserialize SELECT version error: {}", e)))?
);
Ok(ResponseApduSelect::new(version, *status))
}
}
impl Display for ResponseApduSelect {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "version: {}, status: {}", self.get_version(), self.get_status())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_select_request() {
let aid = vec![0x10, 0x20, 0x30, 0x40];
let request = CommandApduSelect::new(aid.as_ref());
assert_eq!(request.get_aid(), &aid);
}
#[test]
fn test_update_select_request() {
let aid = vec![0x10, 0x20, 0x30, 0x40];
let mut request = CommandApduSelect::new(aid.as_ref());
let updated_aid = vec![0x11, 0x21, 0x31, 0x41];
request.set_aid(updated_aid.as_ref());
assert_eq!(request.get_aid(), &updated_aid);
}
#[test]
fn test_select_request_serialize() {
let aid = vec![0x10, 0x20, 0x30, 0x40];
let request = CommandApduSelect::new(aid.as_ref());
let serialized_request = request.serialize();
assert!(serialized_request.is_ok());
let serialized_request = serialized_request.unwrap();
assert_eq!(serialized_request, vec![0x00, 0xA4, 0x04, 0x00, 0x04, 0x10, 0x20, 0x30, 0x40, 0x00]);
}
#[test]
fn test_select_request_deserialize() {
let data = vec![0x00, 0xA4, 0x04, 0x00, 0x04, 0x10, 0x20, 0x30, 0x40, 0x00];
let request = CommandApduSelect::deserialize(data.as_ref());
assert!(request.is_ok());
let request = request.unwrap();
assert_eq!(request.get_aid(), &vec![0x10, 0x20, 0x30, 0x40]);
}
#[test]
fn test_create_select_response() {
let version = 0x10;
let sw1 = 0x90;
let sw2 = 0x00;
let status = common::ResponseApduTrailer::new(sw1, sw2);
let response = ResponseApduSelect::new(version, status);
assert_eq!(response.get_version(), version);
assert_eq!(response.get_status(), &status);
assert_eq!(response.get_status().is_success(), true);
}
#[test]
fn test_update_select_response() {
let version = 0x1010;
let sw1 = 0x90;
let sw2 = 0x00;
let status = common::ResponseApduTrailer::new(sw1, sw2);
let mut response = ResponseApduSelect::new(version, status);
let new_version = 0x2020;
let new_sw1 = 0x61;
let new_sw2 = 0x10;
let new_status = common::ResponseApduTrailer::new(new_sw1, new_sw2);
response.set_version(new_version);
response.set_status(new_status);
assert_eq!(response.get_version(), new_version);
assert_eq!(response.get_status(), &new_status);
assert_eq!(response.get_status().is_success(), false);
assert_eq!(response.get_status().has_remain(), true);
assert_eq!(response.get_status().remain_bytes(), new_sw2);
}
#[test]
fn test_select_response_serialize() {
let version = 0x1010;
let sw1 = 0x90;
let sw2 = 0x00;
let status = common::ResponseApduTrailer::new(sw1, sw2);
let response = ResponseApduSelect::new(version, status);
let serialized_response = response.serialize();
assert!(serialized_response.is_ok());
let serialized_response = serialized_response.unwrap();
assert_eq!(
serialized_response,
vec![
0x5A, 0x02,
0x10, 0x10,
0x90, 0x00,
],
);
}
#[test]
fn test_select_response_deserialize() {
let data = vec![
0x5A, 0x02,
0x10, 0x10,
0x90, 0x00,
];
let response = ResponseApduSelect::deserialize(data.as_ref());
assert!(response.is_ok());
let response = response.unwrap();
assert_eq!(response.get_version(), 0x1010);
assert_eq!(response.get_status(), &common::ResponseApduTrailer::new(0x90, 0x00));
assert_eq!(response.get_status().is_success(), true);
}
}
|
export class Customer {
// 使用策略字典, 如果 kinds 需要不断扩展,也可以移出到外部定义,添加时也很方便 kinds[xxx]=function name(params:type) {}
public kinds: Kinds = {
normal: function (amount: number) {
return amount;
},
member: function (amount: number) {
return amount * 0.9;
},
vip: function (amount: number) {
return amount * 0.8;
}
};
pay(amount: number, type: string) {
return this.kinds[type] && this.kinds[type](amount);
}
}
// 索引签名
interface Kinds {
[key: string]: (amount: number) => {};
}
|
<?php
namespace NFePHP\BPe;
/**
* Class responsible for communication with SEFAZ extends
* NFePHP\BPe\Common\Tools
*
* @category NFePHP
* @package NFePHP\BPe\Tools
* @copyright NFePHP Copyright (c) 2008-2017
* @license http://www.gnu.org/licenses/lgpl.txt LGPLv3+
* @license https://opensource.org/licenses/MIT MIT
* @license http://www.gnu.org/licenses/gpl.txt GPLv3+
* @author Roberto L. Machado <linux.rlm at gmail dot com>
* @author Anderson Minuto Consoni Vaz <anderson at wdhouse dot com dot br>
* @link http://github.com/nfephp-org/sped-bpe for the canonical source repository
*/
use NFePHP\Common\Strings;
use NFePHP\Common\Signer;
use NFePHP\Common\UFList;
use NFePHP\BPe\Factories\Events;
use NFePHP\BPe\Common\Tools as ToolsCommon;
use RuntimeException;
use InvalidArgumentException;
class Tools extends ToolsCommon
{
const EVT_CANCELA = '110111';
const EVT_NAOEMBARQUE = '110115';
const EVT_POLTRONA = '110116';
/**
* Check services status SEFAZ
* @param string $uf initials of federation unit
* @param int $tpAmb
* @return string xml soap response
*/
public function sefazStatus($uf = '', $tpAmb = null)
{
if (empty($tpAmb)) {
$tpAmb = $this->tpAmb;
}
if (empty($uf)) {
$uf = $this->config->siglaUF;
}
$servico = 'BPeStatusServico';
$this->servico($servico, $uf, $tpAmb);
$request = "<consStatServBPe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
. "<tpAmb>$tpAmb</tpAmb>"
. "<xServ>STATUS</xServ>"
. "</consStatServBPe>";
$this->isValid($this->urlVersion, $request, 'consStatServBPe');
$this->lastRequest = $request;
$parameters = ['bpeDadosMsg' => $request];
$body = "<bpeDadosMsg xmlns=\"$this->urlNamespace\">$request</bpeDadosMsg>";
$this->lastResponse = $this->sendRequest($body, $parameters);
return $this->lastResponse;
}
/**
* Request authorization to issue BPe in batch with one or more documents
* @param array $aXml array of bpe's xml
* @param string $idLote lote number
* @return string soap response xml
*/
public function sefazEnviaLote(
$aXml,
$idLote = '',
&$xmls = []
) {
if (!is_array($aXml)) {
throw new \InvalidArgumentException('Os XML das BPe devem ser passados em um array.');
}
$servico = 'BPeRecepcao';
$sxml = implode("", $aXml);
$sxml = preg_replace("/<\?xml.*?\?>/", "", $sxml);
$sxml = trim($sxml);
$this->servico(
$servico,
$this->config->siglaUF,
$this->tpAmb
);
$request = $sxml;
$this->lastRequest = $request;
$parameters = ['bpeDadosMsg' => $request];
$request = base64_encode(gzencode($request, 9, FORCE_GZIP));
$body = "<bpeDadosMsg xmlns=\"$this->urlNamespace\">$request</bpeDadosMsg>";
$method = $this->urlMethod;
$this->lastResponse = $this->sendRequest($body, $parameters);
return $this->lastResponse;
}
/**
* Check the BPe status
* @param string $chave
* @param int $tpAmb
* @return string
*/
public function sefazConsultaChave($chave, $tpAmb = null)
{
$uf = UFList::getUFByCode(substr($chave, 0, 2));
if (empty($tpAmb)) {
$tpAmb = $this->tpAmb;
}
$servico = 'BPeConsulta';
$this->servico(
$servico,
$uf,
$tpAmb
);
$request = "<consSitBPe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
. "<tpAmb>$tpAmb</tpAmb>"
. "<xServ>CONSULTAR</xServ>"
. "<chBPe>$chave</chBPe>"
. "</consSitBPe>";
$this->isValid($this->urlVersion, $request, 'consSitBPe');
$this->lastRequest = $request;
$parameters = ['bpeDadosMsg' => $request];
$body = "<bpeDadosMsg xmlns=\"$this->urlNamespace\">$request</bpeDadosMsg>";
$this->lastResponse = $this->sendRequest($body, $parameters);
return $this->lastResponse;
}
/**
* Requires bpe cancellation
* @param string $chave key of CTe
* @param string $xJust justificative 255 characters max
* @param string $nProt protocol number
* @return string
*/
public function sefazCancela($chave, $xJust, $nProt)
{
$uf = $this->validKeyByUF($chave);
$xJust = substr(trim(Strings::replaceUnacceptableCharacters($xJust)), 0, 255);
$tpEvento = self::EVT_CANCELA;
$nSeqEvento = 1;
$tagAdic = "<evCancBPe>"
. "<descEvento>Cancelamento</descEvento>"
. "<nProt>$nProt</nProt>"
. "<xJust>$xJust</xJust>"
. "</evCancBPe>";
return $this->sefazEvento(
$uf,
$chave,
$tpEvento,
$nSeqEvento,
$tagAdic
);
}
/**
* Aleração de poltrona
* @param string $chave
* @param string $nProt
* @param integer $poltrona
* @param integer $nSeqEvento
* @return string
*/
public function sefazPoltrona($chave, $nProt, $poltrona, $nSeqEvento = 1)
{
$uf = $this->validKeyByUF($chave);
$tpEvento = self::EVT_POLTRONA;
$tagAdic = "<evAlteracaoPoltrona>"
. "<descEvento>Alteração de Poltrona</descEvento>"
. "<nProt>$nProt</nProt>"
. "<poltrona>$poltrona</poltrona>"
. "</evAlteracaoPoltrona>";
return $this->sefazEvento(
$uf,
$chave,
$tpEvento,
$nSeqEvento,
$tagAdic
);
}
/**
* Evento de Não Embarque
* @param string $chave
* @param string $xJust
* @param string $nProt
* @param integer $nSeqEvento
* @return string
*/
public function sefazNaoEmbarque($chave, $xJust, $nProt, $nSeqEvento = 1)
{
$uf = $this->validKeyByUF($chave);
$xJust = substr(trim(Strings::replaceUnacceptableCharacters($xJust)), 0, 255);
$tpEvento = self::EVT_NAOEMBARQUE;
$tagAdic = "<evNaoEmbBPe>"
. "<descEvento>Não Embarque</descEvento>"
. "<nProt>$nProt</nProt>"
. "<xJust>$xJust</xJust>"
. "</evNaoEmbBPe>";
return $this->sefazEvento(
$uf,
$chave,
$tpEvento,
$nSeqEvento,
$tagAdic
);
}
/**
* Send event to SEFAZ
* @param string $uf
* @param string $chave
* @param int $tpEvento
* @param int $nSeqEvento
* @param string $tagAdic
* @return string
*/
protected function sefazEvento(
$uf,
$chave,
$tpEvento,
$nSeqEvento = 1,
$tagAdic = ''
) {
$ignore = false;
$servico = 'BPeRecepcaoEvento';
$this->servico(
$servico,
$uf,
$this->tpAmb,
$ignore
);
$cnpj = $this->config->cnpj;
$dt = new \DateTime();
$dhEvento = $dt->format('Y-m-d\TH:i:sP');
$sSeqEvento = str_pad($nSeqEvento, 2, "0", STR_PAD_LEFT);
$eventId = "ID".$tpEvento.$chave.$sSeqEvento;
$cOrgao = UFList::getCodeByUF($uf);
$request = "<eventoBPe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
. "<infEvento Id=\"$eventId\">"
. "<cOrgao>$cOrgao</cOrgao>"
. "<tpAmb>$this->tpAmb</tpAmb>"
. "<CNPJ>$cnpj</CNPJ>"
. "<chBPe>$chave</chBPe>"
. "<dhEvento>$dhEvento</dhEvento>"
. "<tpEvento>$tpEvento</tpEvento>"
. "<nSeqEvento>$nSeqEvento</nSeqEvento>"
. "<detEvento versaoEvento=\"$this->urlVersion\">"
. "$tagAdic"
. "</detEvento>"
. "</infEvento>"
. "</eventoBPe>";
//assinatura dos dados
$request = Signer::sign(
$this->certificate,
$request,
'infEvento',
'Id',
$this->algorithm,
$this->canonical
);
$request = Strings::clearXmlString($request, true);
$this->isValid($this->urlVersion, $request, 'eventoBPe');
$this->lastRequest = $request;
$parameters = ['bpeDadosMsg' => $request];
$body = "<bpeDadosMsg xmlns=\"$this->urlNamespace\">$request</bpeDadosMsg>";
$this->lastResponse = $this->sendRequest($body, $parameters);
return $this->lastResponse;
}
}
|
from typing import Optional
from project.library import Library
from project.user import User
class Registration:
def add_user(self, user: User, library: Library) -> Optional[str]:
if user in library.user_records:
return f"User with id = {user.user_id} already registered in the library!"
library.user_records.append(user)
def remove_user(self, user: User, library: Library) -> Optional[str]:
if user not in library.user_records:
return "We could not find such user to remove!"
library.user_records.remove(user)
def change_username(self, user_id: int, new_username: str, library: Library) -> str:
users = [u for u in library.user_records if u.user_id == user_id]
if not users:
return f"There is no user with id = {user_id}!"
user = users[0]
if user.username == new_username:
return "Please check again the provided username - it should be different than the username used so far!"
user.username = new_username
return f"Username successfully changed to: {new_username} for user id: {user_id}"
|
import React from 'react'
import { StoryFn, Meta } from '@storybook/react'
import ProgressBar, { ProgessBarProps } from '.'
export default {
title: 'ProgressBar',
component: ProgressBar,
args: {
value: 25
}
} as Meta
export const Default: StoryFn<ProgessBarProps> = (args) => (
<ProgressBar {...args} />
)
export const Customized: StoryFn<ProgessBarProps> = (args) => (
<ProgressBar {...args} color="#0064d6" showValue label="My progress bar" />
)
export const Indeterminate: StoryFn<ProgessBarProps> = (args) => (
<ProgressBar indeterminate {...args} label="Loading..." />
)
|
(* ****** ****** *)
(*
Assign1: Onward!
Total: 70 points + 20 bonus points
Except for the basic arithmetic functions
(including those on chars), you may only use
the functions in classlib/OCaml/MyOCaml.ml
*)
(* ****** ****** *)
(*
assign1-1: 10 points
Given a natural number n that is not a multiple
of 10, intrev10(n) is the natural number whose
representation in base 10 reverses that of the
number n.
fun intrev10(n: int): int
For instance, if n = 12345, then intrev10(n) is
54321; if n = 10203, then intrev10(n) is 30201.
Please give a TAIL-RECURSIVE implementation of
intrev10.
*)
let intrev10 n =
let rec helper n acc =
if n = 0 then acc
else helper (n / 10) ((acc * 10) + (n mod 10))
in
helper n 0
(* ****** ****** *)
(*
assign1-2: 10 points
Given two ordered strings cs1 and cs2, please use
string_make_fwork to implement string_merge(cs1, cs2)
which returns the order string obtained from merging
cs1 and cs2.
For instance, if cs1 = "135" and cs2 = "2468", then
string_merge(cs1)(cs2) equals "1234568"
For instance, if cs1 = "abcde" and cs2 = "1234", then
string_merge(cs1)(cs2) equals "1234abcde"
*)
let string_merge cs1 cs2 =
let len1 = String.length cs1 and len2 = String.length cs2 in
let rec merge i j acc =
if i = len1 then acc ^ (String.sub cs2 j (len2 - j))
else if j = len2 then acc ^ (String.sub cs1 i (len1 - i))
else if cs1.[i] <= cs2.[j] then merge (i+1) j (acc ^ (String.make 1 cs1.[i]))
else merge i (j+1) (acc ^ (String.make 1 cs2.[j]))
in
merge 0 0 ""
(* ****** ****** *)
(*
assign1-3: 10 points
A 3-letter sequence abc is 132-like
if a < c < b holds. For instance, 123 is
not 132-like; but 596 is 132-like.
A string is 132-avoid if there is no subsequence
abc in this string that is 132-like. Note that a
subsequence of a string may contain NON-CONSEQUTIVE
letters of the string.
For instance, 123456789 is 132-avoid;
For instance, 987654321 is 132-avoid;
For instance, 123465789 is not 132-avoid since the
subsequence 165 is 132-like.
Please implement a function string_avoid_132 that
checks if a given string is 132-avoid; the function
returns true if and only if the given string is 132-
avoid.
fun string_avoid_132(cs: string): bool
*)
let str_rev s =
let len = String.length s in
String.init len (fun i -> s.[len - i - 1])
let intrep_add ds1 ds2 =
(* Helper function to get a digit from string or 0 if index is out of bounds *)
let get_digit s i =
if i < String.length s then
int_of_char s.[i] - int_of_char '0'
else
0
in
(* Carry out the addition *)
let rec aux ds1 ds2 i carry acc =
if i >= String.length ds1 && i >= String.length ds2 && carry = 0 then
acc
else
let sum = get_digit ds1 i + get_digit ds2 i + carry in
let digit = sum mod 10 in
let next_carry = sum / 10 in
aux ds1 ds2 (i+1) next_carry ((string_of_int digit) ^ acc)
in
(* Remove leading zeros *)
let rec remove_leading_zeros s =
if String.length s = 0 then "0"
else if s.[0] = '0' then remove_leading_zeros (String.sub s 1 ((String.length s) - 1))
else s
in
aux (str_rev ds1) (str_rev ds2) 0 0 ""
|> remove_leading_zeros
;;
(* ****** ****** *)
(*
assign1-5: 20 points
A sequence of chars is ascending if any char in
the sequence is less than or equal to the following
one (when the following one does exist).
Given a string cs, please implement a function
that find the longest ascending subsequence of [cs].
If there are more than one such sequences, the left
most one should be returned.
fun string_longest_ascend(xs: string): string
For instance, given "1324561111", the function
string_longest_ascend returns "13456"
For instance, given "1234561111", the function
string_longest_ascend returns "123456"
For instance, given "1234511111", the function
string_longest_ascend returns "111111".
*)
let string_longest_ascend xs =
let n = String.length xs in
if n = 0 then ""
else
(* Initialize with first char *)
let current_seq_start = ref 0 in
let current_seq_length = ref 1 in
let longest_seq_start = ref 0 in
let longest_seq_length = ref 1 in
for i = 1 to n - 1 do
(* If the current character is greater than or equal to the last character of current sequence *)
if xs.[i] >= xs.[i - 1] then
incr current_seq_length
else
(* Check if the current sequence is longer than the longest sequence *)
if !current_seq_length > !longest_seq_length then begin
longest_seq_length := !current_seq_length;
longest_seq_start := !current_seq_start;
end;
current_seq_length := 1;
current_seq_start := i;
done;
(* Check once more after the loop in case the longest sequence is at the end *)
if !current_seq_length > !longest_seq_length then begin
longest_seq_length := !current_seq_length;
longest_seq_start := !current_seq_start;
end;
String.sub xs !longest_seq_start !longest_seq_length
(* ****** ****** *)
(*
assign1-6: 20 bonus points
A 4-letter sequence abcd is 1324-like
if a < c < b < d holds. For instance, 1234 is
not 132-like; but 2547 is 1324-like.
A string is 1324-avoid if there is no subsequence
abc in this string that is 1324-like. Note that a
subsequence of a string may contain NON-CONSEQUTIVE
letters of the string.
For instance, 123456789 is 1324-avoid;
For instance, 987654321 is 1324-avoid;
For instance, 123465789 is not 132-avoid since the
subsequence 1657 is 1324-like.
Please implement a function string_avoid_1324 that
checks if a given string is 1324-avoid; the function
returns true if and only if the given string is 1324-
avoid.
fun string_avoid_1324(cs: string): bool
*)
let string_avoid_1324 cs =
let n = String.length cs in
let is_1324_like a b c d =
a < c && c < b && b < d
in
let rec check_l i j k =
if k < n then
if is_1324_like (int_of_char cs.[i]) (int_of_char cs.[j]) (int_of_char cs.[k]) (int_of_char cs.[k+1])
then false
else check_l i j (k + 1)
else true
in
let rec check_k i j =
if j < n - 2 then
if not (check_l i j (j + 2))
then false
else check_k i (j + 1)
else true
in
let rec check_j i =
if i < n - 3 then
if not (check_k i (i + 1))
then false
else check_j (i + 1)
else true
in
check_j 0
;;
(* ****** ****** *)
(* end of [CS320-2023-Fall-assigns-assign1.ml] *)
|
import { Inject, Injectable } from '@nestjs/common'
import type { IUserWriterRepository } from '../../../domain/user/repositories/user-writer.repository.interface'
import { EntityManager } from 'typeorm'
import { User } from '../models/user.entity'
import { PointHistory } from '../models/point-history.entity'
import { FailedUserChargePointError } from '../../../domain/user/exceptions/failed-user-charge-point.exception'
import { InValidPointError } from '../../../domain/user/exceptions/invalid-point.exception'
import { v4 as uuidv4 } from 'uuid'
@Injectable()
export class UserWriterRepositoryTypeORM implements IUserWriterRepository {
constructor(@Inject(EntityManager) private readonly entityManager: EntityManager) {}
/**
* Creates a new user with the specified name.
* @param name The name of the user to be created.
* @returns The newly created User entity.
*/
async createUser(name: string): Promise<User> {
const uuid = uuidv4()
return this.entityManager.save(User, { id: uuid, name, point: 0, reservations: [] })
}
/**
* Updates the user's point balance and records the transaction in point history.
* @param user The User entity whose points are to be updated.
* @param amount The amount to add or subtract from the user's points.
* @param reservationId Optional reservation ID if the points are associated with a specific reservation.
* @param queryRunner Optional query runner for transaction management.
* @returns A new PointHistory entry recording the transaction.
* @throws InValidPointError if the transaction would result in a negative point balance.
* @throws FailedUserChargePointError if updating the user's points fails.
*/
async calculatePoint(user: User, amount: number, reason: string, querryRunner?: any) {
const manager = querryRunner ? querryRunner.manager : this.entityManager
if (reason == 'payment' && user.point < Math.abs(amount)) {
throw new InValidPointError('Not enough point')
}
const point = user.point + amount
const result = await manager.createQueryBuilder().update(User).set({ point }).where('id = :id', { id: user.id }).execute()
if (result.affected === 0) throw new FailedUserChargePointError('Failed to charge point')
}
async createPointHistory(user: User, amount: number, reservationId?: string, querryRunner?: any): Promise<PointHistory> {
const reason = reservationId ? 'payment' : 'charge'
const manager = querryRunner ? querryRunner.manager : this.entityManager
const uuid = uuidv4()
return await manager.save(PointHistory, {
id: uuid,
user,
amount: amount,
reason,
reservationId: reason == 'payment' ? reservationId : null,
})
}
}
|
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use matrix_profile::naive::distance_profile;
fn bench_with_history<const HISTORY_LEN: usize>(c: &mut Criterion, normalize: bool) {
let history = Vec::from_iter((0..HISTORY_LEN).map(|v| v as f32));
let mut group = c.benchmark_group(format!(
"distance_profile_{}k_norm_{normalize}",
HISTORY_LEN / 1000
));
for window_size in [16, 32, 64, 128, 256, 512, 1024].iter() {
let window = &history[history.len() - window_size..];
group.throughput(Throughput::Elements(1));
group.bench_with_input(
BenchmarkId::from_parameter(window_size),
window_size,
|b, _| {
b.iter(|| {
let dist = distance_profile(&history, window, 1, normalize);
let _ = black_box(dist);
});
},
);
}
group.finish()
}
fn criterion_benchmark(c: &mut Criterion) {
bench_with_history::<100_000>(c, false);
bench_with_history::<250_000>(c, false);
bench_with_history::<500_000>(c, false);
bench_with_history::<100_000>(c, true);
bench_with_history::<250_000>(c, true);
bench_with_history::<500_000>(c, true);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
/*
* Copyright 2020 Michail Vourlakos <mvourlakos@gmail.com>
*
* This file is part of Latte-Dock
*
* Latte-Dock is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* Latte-Dock is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ABSTRACTWINDOWMANAGER_H
#define ABSTRACTWINDOWMANAGER_H
//Qt
#include <QObject>
#include <QRect>
#include <QVariant>
namespace WM {
struct WMData{
bool filterByActive{false};
bool filterChildren{false};
bool menuAvailable{false};
bool visible{true};
QRect screenGeometry;
QVariant userWindowId{-1};
};
class AbstractWindowManager : public QObject
{
Q_OBJECT
public:
explicit AbstractWindowManager(QObject *parent = nullptr);
~AbstractWindowManager() override;
bool filterByActive() const;
void setFilterByActive(bool active);
bool filterChildren() const;
void setFilterChildren(bool hideChildren);
bool menuAvailable() const;
void setMenuAvailable(bool set);
bool visible() const;
QRect screenGeometry() const;
void setScreenGeometry(QRect geometry);
QVariant winId() const;
void setWinId(const QVariant &id);
WMData data() const;
void setData(const WMData &data);
signals:
void applicationMenuChanged(const QString &serviceName, const QString &menuObjectPath);
void modelNeedsUpdate();
void dataChanged();
void menuAvailableChanged();
void filterByActiveChanged();
void filterChildrenChanged();
void visibleChanged();
void screenGeometryChanged();
void winIdChanged();
protected:
void setVisible(bool visible);
bool hasUserWindowId() const;
protected:
bool m_filterByActive{false};
bool m_filterChildren{false};
bool m_menuAvailable{false};
bool m_visible{true};
QRect m_screenGeometry;
QVariant m_userWindowId{-1};
//! current active window used
QVariant m_currentWindowId{-1};
};
}
#endif
|
// Internal permissions can be defined here.
// They are useful when the underlying database does not have that capability or when the database is not under your control to define api specific roles.
// Permission system is modeled after PostgreSql GRANT + RLS functionality.
// If the permissions array is empty, the internal permission system is disabled and assumes that the underlying database has the
// necessary permissions configured.
export default [
{
table_name: 'Album', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['AlbumId', 'Title', 'ArtistId'],
},
{
table_name: 'Album', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['Title', 'ArtistId'],
},
{
table_name: 'Album', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Artist', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['ArtistId', 'Name'],
},
{
table_name: 'Artist', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['Name'],
},
{
table_name: 'Artist', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Customer', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['CustomerId', 'FirstName', 'LastName', 'Company', 'Address', 'City', 'State', 'Country', 'PostalCode', 'Phone', 'Fax', 'Email', 'SupportRepId'],
},
{
table_name: 'Customer', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['FirstName', 'LastName', 'Company', 'Address', 'City', 'State', 'Country', 'PostalCode', 'Phone', 'Fax', 'Email', 'SupportRepId'],
},
{
table_name: 'Customer', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Employee', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['EmployeeId', 'LastName', 'FirstName', 'Title', 'ReportsTo', 'BirthDate', 'HireDate', 'Address', 'City', 'State', 'Country', 'PostalCode', 'Phone', 'Fax', 'Email'],
},
{
table_name: 'Employee', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['LastName', 'FirstName', 'Title', 'ReportsTo', 'BirthDate', 'HireDate', 'Address', 'City', 'State', 'Country', 'PostalCode', 'Phone', 'Fax', 'Email'],
},
{
table_name: 'Employee', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Genre', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['GenreId', 'Name'],
},
{
table_name: 'Genre', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['Name'],
},
{
table_name: 'Genre', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Invoice', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['InvoiceId', 'CustomerId', 'InvoiceDate', 'BillingAddress', 'BillingCity', 'BillingState', 'BillingCountry', 'BillingPostalCode', 'Total'],
},
{
table_name: 'Invoice', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['CustomerId', 'InvoiceDate', 'BillingAddress', 'BillingCity', 'BillingState', 'BillingCountry', 'BillingPostalCode', 'Total'],
},
{
table_name: 'Invoice', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'InvoiceLine', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['InvoiceLineId', 'InvoiceId', 'TrackId', 'UnitPrice', 'Quantity'],
},
{
table_name: 'InvoiceLine', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['InvoiceId', 'TrackId', 'UnitPrice', 'Quantity'],
},
{
table_name: 'InvoiceLine', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'MediaType', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['MediaTypeId', 'Name'],
},
{
table_name: 'MediaType', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['Name'],
},
{
table_name: 'MediaType', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Playlist', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['PlaylistId', 'Name'],
},
{
table_name: 'Playlist', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['Name'],
},
{
table_name: 'Playlist', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'Track', table_schema: 'public',
role: 'authenticated',
grant: ['select', 'delete'],
columns: ['TrackId', 'Name', 'AlbumId', 'MediaTypeId', 'GenreId', 'Composer', 'Milliseconds', 'Bytes', 'UnitPrice'],
},
{
table_name: 'Track', table_schema: 'public',
role: 'authenticated',
grant: ['insert', 'update'],
columns: ['Name', 'AlbumId', 'MediaTypeId', 'GenreId', 'Composer', 'Milliseconds', 'Bytes', 'UnitPrice'],
},
{
table_name: 'Track', table_schema: 'public',
role: 'authenticated',
policy_for: ['select', 'insert', 'update', 'delete'],
using: [{ "sql": "true" }],
check: [{ "sql": "true" }],
},
{
table_name: 'PlaylistTrack', table_schema: 'public',
role: 'authenticated',
grant: ['all']
},
]
// other examples
// {
// "name": "public can see rows marked as public",
// "table_schema": "public", "table_name": "permissions_check",
// "role": "public",
// "grant": ["select"], "columns": ["id", "value"],
// "policy_for": ["select"],
// "using": [{"column":"public","op":"=","val":"1"}]
// },
// {
// "name": "validation for hidden value",
// "table_schema": "public", "table_name": "permissions_check",
// "role": "public",
// "restrictive": true,
// "check": [{
// "tree":{
// "logic_op":"or",
// "conditions":[
// {"column":"hidden","op":"=","val":"Hidden"},
// {"column":"hidden","op":"=","val":"Hidden changed"}
// ]
// }
// }]
// },
// {
// "name": "admin allow all",
// "table_schema": "public", "table_name": "permissions_check",
// "role": "admin",
// "grant": ["select", "insert", "update", "delete"],
// "policy_for": ["select", "insert", "update", "delete"],
// "using": [{"sql":"true"}],
// "check": [{"sql":"true"}]
// },
// {
// "name": "alice allow owned",
// "table_schema": "public","table_name": "permissions_check",
// "role": "alice",
// "grant": ["all"],
// "policy_for": ["select", "insert", "update", "delete"],
// "using": [{"column":"role","op":"=","env":"request.jwt.claims","env_part":"role"}],
// "check": [{"column":"role","op":"=","env":"request.jwt.claims","env_part":"role"}]
// },
// {
// "name": "bob allow owned",
// "table_schema": "public","table_name": "permissions_check",
// "role": "bob",
// "grant": ["all"],
// "policy_for": ["all"],
// "using": [{"column":"role","op":"=","val":"bob"}],
// "check": [{"column":"role","op":"=","val":"bob"}]
// },
|
import { Component, HostListener, OnInit } from '@angular/core';
import Phaser from 'phaser';
import { combineLatest, map } from 'rxjs';
import { phaserConfig } from 'src/app/config/phaser-config.config';
import { BattleState } from 'src/app/enums/battleState.enum';
import { Region } from 'src/app/enums/region.enum';
import { Message } from 'src/app/interfaces/message.interface';
import { BattleService } from 'src/app/services/battle.service';
import { MoneyService } from 'src/app/services/money.service';
@Component({
selector: 'app-display',
templateUrl: './display.component.html',
styleUrls: ['./display.component.scss'],
})
export class DisplayComponent implements OnInit {
public phaserGame?: Phaser.Game;
public region = Region;
public vm$ = combineLatest({
currentTick: this._battleService.tick$,
isPaused: this._battleService.isPaused$,
money: this._moneyService.totalMoney$,
showBattleIcons: this._battleService.state$.pipe(
map((state) => state !== BattleState.NONE)
),
});
private _broadcastChannel = new BroadcastChannel('control_panel');
constructor(
private _battleService: BattleService,
private _moneyService: MoneyService
) {}
ngOnInit() {
this.phaserGame = new Phaser.Game(phaserConfig);
this._broadcastChannel.onmessage = (msg: MessageEvent<Message>) => {
console.log(msg)
const scene = this.phaserGame?.scene.getAt(0);
this._battleService.addBattles(msg.data.battleData, scene);
};
}
@HostListener('document:keydown', ['$event'])
public updateTimer(event: KeyboardEvent): void {
if (this._battleService.state$.getValue() === BattleState.NONE) {
return;
}
if (event.key === ' ') {
this._battleService.startStopTimer();
} else if (event.key === 'Enter') {
this._battleService.advanceOneTick();
} else {
return;
}
event.stopPropagation();
event.preventDefault();
}
public startStop(): void {
this._battleService.startStopTimer();
}
public advance(): void {
this._battleService.advanceOneTick();
}
}
|
const AppError = require("../misc/AppError");
const commonErrors = require("../misc/commonErrors");
// 미들웨어를 리턴하는 함수
// from은 어떤 값을 "어디"에서 체크해야하는지를 정하는 값
// e.g.
// - 만약 title이라는 값을 req.body에서 체크하고 싶다면 checkCompletePostFrom("body")
// - 만약 title이라는 값을 req.query에서 체크하고 싶다면 checkCompletePostFrom("query")
const checkCompletePostFrom = (from) => (req, res, next) => {
const { title, content, author } = req[from];
// 게시글에 타이틀이 없으면 안된다.
if (title === undefined || title === "") {
next(
new AppError(
commonErrors.requestValidationError,
`${from}: title은 필수값입니다.`,
400
)
);
return;
}
// 게시글에 본문이 없으면 안된다.
if (content === undefined || title === "") {
next(
new AppError(
commonErrors.requestValidationError,
`${from}: content는 필수값입니다.`,
400
)
);
return;
}
// 게시글에 작성자 정보가 없으면 안된다.
if (author === undefined || author === "") {
next(
new AppError(
commonErrors.requestValidationError,
`${from}: author는 필수값입니다.`,
400
)
);
return;
}
next();
};
// 미들웨어를 리턴하는 함수
// from은 어떤 값을 "어디"에서 체크해야하는지를 정하는 값
// e.g.
// - 만약 id이라는 값을 req.body에서 체크하고 싶다면 checkPostIdFrom("body")
// - 만약 id이라는 값을 req.query에서 체크하고 싶다면 checkPostIdFrom("query")
const checkPostIdFrom = (from) => (req, res, next) => {
const { id } = req[from];
// 게시글의 id 정보가 없으면 안된다.
if (id === undefined) {
next(
new AppError(
commonErrors.requestValidationError,
`${from}: id는 필수값입니다.`,
400
)
);
return;
}
next();
};
// 위와 같은 미들웨어를 리턴하는 함수
// 게시글을 수정/삭제할 때 최소한의 조건을 체크해주는 미들웨어이다.
const checkMinPostConditionFrom = (from) => (req, res, next) => {
const { title, content, author } = req[from];
if (title === undefined && content === undefined && author === undefined) {
next(
new AppError(
commonErrors.requestValidationError,
`${from}: title, content, author중 최소 하나는 필요합니다.`,
400
)
);
return;
}
next();
};
module.exports = {
checkCompletePostFrom,
checkPostIdFrom,
checkMinPostConditionFrom,
};
|
import '../../../utils/constants/colors.dart';
import '../../../utils/constants/sizes.dart';
import '../../../utils/helpers/helper_functions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class AppVerticalImageText extends StatelessWidget {
const AppVerticalImageText({
super.key,
required this.image,
required this.title,
this.textColor = Colors.white,
this.backgroundColor,
this.onTap,
});
final String image, title;
final Color? textColor;
final Color? backgroundColor;
final void Function()? onTap;
@override
Widget build(BuildContext context) {
final isDark = AppHelperFuncions.isDarkMode(context);
return GestureDetector(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.only(right: AppSizes.defaultSpace),
child: Column(
children: [
// Circular Icon
Container(
width: 56,
height: 56,
padding: const EdgeInsets.all(AppSizes.sm),
decoration: BoxDecoration(
color: backgroundColor ??
(isDark ? AppColors.black : AppColors.white),
borderRadius: BorderRadius.circular(100)),
child: Center(
// child: Image(
// image: AssetImage(image),
// fit: BoxFit.cover,
// color: (isDark ? AppColors.dark : AppColors.light)),
child: SvgPicture.asset(image,
fit: BoxFit.cover,
height: AppSizes.iconMd,
width: AppSizes.iconMd,
colorFilter: ColorFilter.mode(
isDark ? AppColors.white : AppColors.black,
BlendMode.srcIn)),
)),
// Text
const SizedBox(
height: AppSizes.spaceBetweenItems / 2,
),
SizedBox(
width: 55,
child: Center(
child: Text(
title,
style: Theme.of(context)
.textTheme
.labelMedium!
.apply(color: textColor),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
))
],
),
),
);
}
}
|
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use App\Http\Controllers\Controller;
use App\Models\History;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token) {
$user = User::where('verification_code', $token)->firstOrFail();
return view('auth.passwords.reset', ['token' => $token, 'email' => $user->email]);
}
public function reset(Request $request) {
$request->validate([
'token' => 'required',
'email' => 'required|email',
'password' => 'required|min:6|confirmed'
]);
$user = User::where([['email', $request->email], ['verification_code', $request->token]])->firstOrFail();
$user->password = Hash::make($request->password);
$user->verification_code = "";
$user->save();
History::create(['user_id' => $user->id, 'type_id' => 17]);
if($user->user_type == 'admin') return redirect()->route('admin.login');
else return redirect()->route('login');
}
/**
* Get the response for a successful password reset.
*
* @param \Illuminate\Http\Request $request
* @param string $response
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
/* protected function sendResetResponse(Request $request, $response)
{
if(auth()->user()->user_type == 'admin' || auth()->user()->user_type == 'staff')
{
return redirect()->route('admin.dashboard')
->with('status', trans($response));
}
return redirect()->route('home')
->with('status', trans($response));
}*/
}
|
mostly international and EU law here
# Definition of IP
- Industrial Property -> used by companies
- Copyright -> artistic
- *numerous clausus* of IP laws -> there is a set amount of rules, one cannot make any more intellectual property up
- 40% of EU GDP is IP related
- Trademarks
- Intangible Goods
- Patents
- Information
# Why Protection
- problem: hard to create, easy to copy
- cost of information = cost of copying
- almost 0 with digital goods
- moral rights to be associated to ones creation
- promote creativity
- downside: monopolies can be formed
## Copyright
- aquisition: creation
- only on works, not ideas
- exclusive rights
- 70 years after death of creator
- exception:
- private copy (not selling/passing on)
- sources of copyright
- [[Berne Convention]]
- [[TRIPS]]
- EU Directives (2001/29/EC and 2019/790)
- what is protected? literary, scientific and artistic domain
- what is not protected? news
- creators/authors can only be humans (monkeys do not have copyright)
- also companies cannot create copyright (but they get it anyway through employment contract), but still individual stays the creator
- authorship cannot be given away, just the usage rights/license
- Permitted Acts
- reproduction for private use -> private copy
- accidental copy -> music video running in background of video
- quote -> as long as you quote the source it is fine
-
## Trademarks
- aquisition: registration (with fee)
- examples: Adidas logo, Nike swoosh, Mercedes star
- communication between company and consumer (reputation of manufacture)
- indication of origin/manufacture
- protects the consumer -> being sure of what you are buying
- protects the company -> safeguarding your reputation
- EU trademark laws as well as 27 member state trademark laws
- EU has its trademark office
- Austria has patent office, doing patents and as well trademarks -> confusing
- WIPO Madrid System -> up to 126 countries
- trademarks can last forever (while paying all the fees)
- what is a trademark exactly?
- distinctiveness
- can be put on register
- words, names, letters, numerals, colors, shapes, packaging, sounds
- combinations
- grounds of refusal
- lack of distinctiveness (generic terms, descriptive signs)
- contrary to public policy (nudes)
- functional shapes (LEGO bricks are not trademarked)
- misleading/deceiving character (Hungarian salami made in Austria)
- trademark is only applicable to trade (playing/costumes not affected)
- marking goods and services
- protect against use by others
- opposition by trademark owners
- identical / similar
- likelihood of confusion for public
- earlier trademark has reputation
## Patents
- aquisition: registration
- pro:
- moral -> protecting the creator
- innovation -> better patents, more innovation
- disclosure -> publishing patents leads to disclosure
- cons:
- costs
- unjust enrichment (large companies)
- developing countries -> exploitation of poorest
- EU does not have unified Patent Laws
- European unified patent court exists (not EU)
- what is protected?
- capable of industrial application
- #todo
- requirements
- technical invention -> something new
- novelty -> not part of state of the art
- inventive step -> can it be built
- ownership
- first to register wins
- granted for limited number of years (20 years standard)
- fair protection with pharmaceuticals if bringing drug to market takes time
- employee (transferred to employer through contract)
- can also be transferred to other companies
- licenses need to be handed out if not used
- acts of infringement
- #todo
# Scope of IP right
- exclusive rights
- negative right to defense -> I don't want my book to be translated
- license agreements
- exclusive licenses -> right of free use, not right of ownership
- non-exclusive licenses -> rights granted for special use cases
# International IP law
- [[Hierarchy of Norms]]
- IP is territorial
- Property Rights apply to each country individually
- IP in USA is not valid in China
- WIPO (Word Intellectual Property Organization)
- [[WTO]] (World Trade Organization)
- [[TRIPS]] (Trade-Related aspects of Intellectual Property Rights)
- National Treatment -> if rights granted to nationals, also to other members
- (MFN) Most Favourable Nation treatment -> best case for all members
- gives minimum requirements, more may be added by member state
- no International Trademark
- "international trademark" is actually 126 individual trademarks
- in EU there is union trademark
- in EU there is NO union patent
- [[Principle of First Sale]]
- problems:
- overprotection,
- developing countries not having access to important patents
-
|
<!DOCTYPE html>
<html lang="en">
<head>
<%- include("partials/meta") %>
<title>Inicio</title>
</head>
<body>
<%- include("partials/header") %>
<section id="pantalla-dividida">
<%- include("partials/izquierda") %>
<div class="derecha">
<div class="borde">
<center><h3>Arboles Digitales</h3></center> <!--Ponen el titulo del tema y abajo el contenido-->
<br>
<p>Los árboles digitales son estructuras de datos que se utilizan para almacenar y recuperar datos de manera eficiente. Se llaman "digitales" porque se utilizan a menudo para almacenar datos digitales, como números o caracteres.</p>
<br>
<p>Hay muchos tipos diferentes de árboles digitales, cada uno con sus propias características y usos específicos. Algunos ejemplos comunes de árboles digitales incluyen árboles binarios de búsqueda, árboles de búsqueda rojinegros y árboles Patricia.</p>
<br>
<p>Los árboles digitales son muy útiles porque permiten acceder a los datos de manera rápida y eficiente. Por ejemplo, en un árbol binario de búsqueda, se puede buscar un elemento en el árbol en tiempo logarítmico promedio, lo que significa que el tiempo de búsqueda aumenta de manera relativamente lenta a medida que el árbol crece más grande. Esto es mucho más rápido que la búsqueda secuencial de elementos en una lista simple, donde se debe comparar cada elemento de manera secuencial hasta encontrar el elemento deseado.</p>
<br>
<p>Los árboles digitales también son útiles porque permiten insertar y eliminar elementos de manera eficiente. Por ejemplo, en un árbol binario de búsqueda, se puede insertar un elemento en el árbol en tiempo logarítmico promedio, y se puede eliminar un elemento del árbol en tiempo logarítmico promedio. Esto es mucho más rápido que insertar o eliminar elementos de una lista simple, donde se debe recorrer toda la lista para encontrar la posición adecuada o para eliminar un elemento en particular.</p>
<br>
<center>
<img src="https://opendatastructures.org/ods-cpp/img5694.png" width="550">
</center>
<br>
<h3>Implementacion de un arbol digital</h3>
<br>
<pre>
#include < iostream>
// Un nodo del árbol BST contiene un valor y dos hijos
struct BSTNode {
int value;
BSTNode* left;
BSTNode* right;
};
// La clase BST representa el árbol BST completo
class BST {
public:
BST() : root_(nullptr) {}
// Inserta un elemento en el árbol BST
void insert(int value) {
BSTNode* node = new BSTNode;
node->value = value;
node->left = node->right = nullptr;
if (root_ == nullptr) {
root_ = node;
} else {
BSTNode* current = root_;
while (true) {
if (value < current->value) {
// El valor de inserción es menor que el valor del nodo actual, sigue el camino izquierdo
if (current->left == nullptr) {
current->left = node;
break;
}
current = current->left;
} else {
// El valor de inserción es mayor o igual que el valor del nodo actual, sigue el camino derecho
if (current->right == nullptr) {
current->right = node;
break;
}
current = current->right;
}
}
}
}
// Busca un elemento en el árbol BST
bool search(int value) {
BSTNode* current = root_;
while (current != nullptr) {
if (value == current->value) {
// Se encontró el elemento
return true;
} else if (value < current->value) {
// El valor de búsqueda es menor que el valor del nodo actual, sigue el camino izquierdo
current = current->left;
} else {
// El valor de búsqueda es mayor que el valor del nodo actual, sigue el camino derecho
current = current->right;
}
}
// No se encontró el elemento
return false;
}
private:
BSTNode* root_;
};
int main() {
BST tree;
// Inserta algunos elementos en el árbol
tree.insert(5);
tree.insert(3);
tree.insert(8);
tree.insert(1);
tree.insert(4);
tree.insert(7);
tree.insert(10);
// Busca algunos elementos en el árbol
std::cout << tree.search(5) << std::endl; // imprime 1 (se encontró el elemento)
std::cout << tree.search(6) << std::endl; // imprime 0 (no se encontró el
</pre>
<br>
<p>Link de apoyo</p>
<br>
<li><a href="https://opendatastructures.org/ods-cpp/13_1_digital_search_tree.html">A digital search tree</a></li>
</div>
</div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
</body>
</html>
|
import { IsOptional } from 'class-validator';
import { Transform } from 'class-transformer';
const userSortByValidation = (value: any): string => {
const fields = ['id', 'login', 'email'];
if (!value || typeof value !== 'string') return 'created_at';
if (fields.includes(value.toLowerCase())) return value.toLowerCase();
return 'created_at';
};
const sortDirectionValidation = (value: any): 'ASC' | 'DESC' => {
if (!value || typeof value !== 'string') return 'DESC';
return value.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
};
const searchTermValidation = (value: any): string => {
if (!value || typeof value !== 'string') {
return '%%';
} else {
return `%${value}%`;
}
};
export class DefaultPagination {
@IsOptional()
pageNumber: number = 1;
@IsOptional()
pageSize: number = 10;
@Transform(({ value }) => sortDirectionValidation(value))
@IsOptional()
sortDirection: string = 'DESC';
@IsOptional()
skip(): number {
return (this.pageNumber - 1) * this.pageSize;
}
}
export class UsersPagination extends DefaultPagination {
@Transform(({ value }) => searchTermValidation(value))
@IsOptional()
searchLoginTerm: string = '%';
@Transform(({ value }) => searchTermValidation(value))
@IsOptional()
searchEmailTerm: string = '%';
@Transform(({ value }) => userSortByValidation(value))
@IsOptional()
sortBy: string = 'created_at';
}
|
<template>
<g-pro-layout
v-model:collapsed="baseState.collapsed"
v-model:selectedKeys="baseState.selectedKeys"
v-model:openKeys="baseState.openKeys"
v-bind="state"
:breadcrumb="{ routes: baseState.breadcrumb }"
@reloadPage="handleReloadPage"
@handleCollapse="toggleCollapse"
@menuHeaderClick="menuHeaderClick"
>
<template v-if="store.settings.layout === 'wide'" #menuExtraRender>
<div class="text-center"> 额外元素 </div>
</template>
<ProContent :animate="state.animate" :isRouterAlive="isRouterAlive" />
<setting-drawer :settings="state" @change="handleSettingChange" />
</g-pro-layout>
</template>
<script setup lang="ts">
import { computed, reactive } from 'vue'
import { cloneDeep } from 'lodash-es'
import { useStore } from '@gx-vuex'
import { RouteContextProps, getMenuData, clearMenuItem, SettingDrawer } from '@gx-design/ProLayout'
import config from '/config/config'
import ProContent from './ContentView.vue'
const { animate } = config
const { preset } = animate
const store = useStore()
const router = useRouter()
const isRouterAlive = ref(true)
const routeData: AppRouteModule[] = router.getRoutes() as any
const { menuData } = getMenuData(clearMenuItem(routeData))
const baseState = reactive<Omit<RouteContextProps, 'menuData'>>({
breadcrumb: [],
selectedKeys: [],
openKeys: [],
collapsed: false
})
const state = reactive({
menuData,
logoDirection: 'vertical',
loading: computed(() => store.routes.routerLoading),
layout: computed(() => store.settings.layout),
theme: computed(() => store.settings.theme),
splitMenus: computed(() => store.settings.splitMenus),
primaryColor: computed(() => store.settings.primaryColor),
fixedMultiTab: computed(() => store.settings.fixedMultiTab),
fixedHeader: computed(() => store.settings.fixedHeader),
fixSiderbar: computed(() => store.settings.fixSiderbar),
showTabsBar: computed(() => store.settings.showTabsBar),
autoHideHeader: computed(() => store.settings.autoHideHeader),
showProgressBar: computed(() => store.settings.showProgressBar),
animate: computed(() => store.settings.animate)
})
watch(
() => router.currentRoute,
() => {
const matched = router.currentRoute.value.matched.concat()
const breadcrumb = matched.map((item) => {
return {
path: item.path,
breadcrumbName: item.meta.title || ''
}
})
baseState.breadcrumb = cloneDeep(breadcrumb)
},
{
deep: true,
immediate: true
}
)
watchEffect(() => {
if (router.currentRoute) {
const matched = router.currentRoute.value.matched.concat()
baseState.selectedKeys = matched.filter((r) => r.name !== 'index').map((r) => r.path)
baseState.openKeys = matched
.filter((r) => r.path !== router.currentRoute.value.path)
.map((r) => r.path)
}
})
onMounted(() => {
store.oss.queryOssToken()
})
const handleSettingChange = ({ type, value }) => {
switch (type) {
case 'theme':
store.settings.changeValue('theme', value)
break
case 'primaryColor':
store.settings.changeValue('primaryColor', value)
break
case 'layout':
store.settings.changeValue('layout', value)
if (value === 'mix') {
store.settings.changeValue('splitMenus', true)
store.settings.changeValue('showTabsBar', true)
store.settings.changeValue('fixedHeader', true)
store.settings.changeValue('fixSiderbar', true)
store.settings.changeValue('fixedMultiTab', true)
} else if (value === 'simple') {
store.settings.changeValue('splitMenus', false)
store.settings.changeValue('showTabsBar', false)
store.settings.changeValue('fixedHeader', false)
store.settings.changeValue('fixedMultiTab', false)
} else if (value === 'wide') {
store.settings.changeValue('splitMenus', false)
store.settings.changeValue('fixSiderbar', false)
store.settings.changeValue('showTabsBar', false)
store.settings.changeValue('fixedHeader', true)
store.settings.changeValue('fixedMultiTab', false)
}
break
case 'fixedHeader':
store.settings.changeValue('fixedHeader', value)
if (state.layout === 'side' && !value) store.settings.changeValue('fixedMultiTab', value)
break
case 'fixSiderbar':
store.settings.changeValue('fixSiderbar', value)
break
case 'splitMenus':
store.settings.changeValue('splitMenus', value)
break
case 'showTabsBar':
store.settings.changeValue('showTabsBar', value)
break
case 'fixedMultiTab':
store.settings.changeValue('fixedMultiTab', value)
if (state.layout === 'side' && value) store.settings.changeValue('fixedHeader', value)
break
case 'showProgressBar':
store.settings.changeValue('showProgressBar', value)
break
case 'showAnimate':
store.settings.handleShowAnimate(!value)
break
case 'changeAnimateMode':
store.settings.changeAnimateMode(value)
store.settings.changeAnimateDirections(
preset.find((el: any) => el.name === value)?.directions.includes('default')
? 'default'
: preset.find((el: any) => el.name === value)?.directions[0]
)
break
case 'changeAnimateDirections':
store.settings.changeAnimateDirections(value)
break
}
}
const handleReloadPage = () => {
isRouterAlive.value = false
nextTick(() => {
isRouterAlive.value = true
})
}
const toggleCollapse = () => {
store.settings.toggleCollapse()
}
const menuHeaderClick = () => {
router.push('/')
}
provide('reloadPage', handleReloadPage)
</script>
|
import { Inject, Injectable } from '@nestjs/common';
import { DbqueryService } from 'src/dbquery/dbquery.service';
import {
insertQueryGenerator,
updateQueryGenerator,
} from '../utils/queryGenerator';
@Injectable()
export class TypeDatamapper {
constructor(
@Inject(DbqueryService)
private dbqueryService: DbqueryService,
) {}
async findAll() {
const sql = `
SELECT * FROM type
`;
return this.dbqueryService.sendRawSqlQuery(sql, []);
}
async findByPk(typeId) {
const sql = `
SELECT * FROM type WHERE id = $1
`;
return this.dbqueryService.sendRawSqlQuery(sql, [typeId]);
}
async create(type) {
const [columns, placeHolders, values] = insertQueryGenerator(type);
const sql = `INSERT INTO type
${columns} VALUES
${placeHolders} RETURNING *`;
return this.dbqueryService.sendRawSqlQuery(sql, values);
}
async update(id, type) {
const [setStatement, values] = updateQueryGenerator(type);
const sql = `UPDATE type ${setStatement} WHERE id = $1 RETURNING *`;
return this.dbqueryService.sendRawSqlQuery(sql, [id, ...values]);
}
async delete(id) {
const sql = `
DELETE FROM type WHERE id = $1
`;
return this.dbqueryService.sendRawSqlQuery(sql, [id]);
}
}
|
import java.util.Vector;
public class VectorEx {
public static void main(String[] args) {
add();
// addAll();
// get();
// remove();
// size();
// clear();
}
private static void clear() {
// clear():
Vector<Character> characters = new Vector<>();
characters.add('A');
characters.add('B');
characters.add('C');
characters.clear();
System.out.println("Vector after clearing all elements: " + characters);
}
private static void size() {
// size():
Vector<Double> prices = new Vector<>();
prices.add(19.99);
prices.add(29.99);
prices.add(39.99);
int size = prices.size();
System.out.println("Size of the Vector: " + size);
}
private static void remove() {
// remove(Object o):
Vector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.remove("Banana");
System.out.println("Vector after removing an element: " + fruits);
}
private static void get() {
// get(int index):
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int elementAtIndex1 = numbers.get(1);
System.out.println("Element at index 1: " + elementAtIndex1);
}
private static void addAll() {
// addAll(Collection<? extends E> c):
Vector<String> vector1 = new Vector<>();
vector1.add("Apple");
vector1.add("Banana");
Vector<String> vector2 = new Vector<>();
vector2.add("Orange");
vector2.add("Grapes");
vector1.addAll(vector2);
System.out.println("Vector after adding all elements from another collection: " + vector1);
}
private static void add() {
// add(E element):
Vector<String> vector = new Vector<>();
vector.add("Java");
vector.add("Python");
vector.add("C++");
System.out.println("Vector after adding elements: " + vector);
}
}
|
# https://www.hackerrank.com/challenges/non-divisible-subset/problem?isFullScreen=true
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'nonDivisibleSubset' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY s
#
def nonDivisibleSubset(k, s):
# Write your code here
count = [0] * k
for i in s:
remainder = i % k
count[remainder] +=1
ans = min( count[0] , 1)
if k % 2 == 0:
ans += min(count[k // 2] ,1 )
for i in range(1 , k // 2 + 1):
if i != k - i:
ans += max(count[i] , count[k-i])
return ans
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
k = int(first_multiple_input[1])
s = list(map(int, input().rstrip().split()))
result = nonDivisibleSubset(k, s)
fptr.write(str(result) + '\n')
fptr.close()
|
package DefiningClasses.Exercises.CompanyRoster;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int countOfEmployees = Integer.parseInt(scanner.nextLine());
List<Department> departments = new ArrayList<>();
for (int i = 0; i < countOfEmployees; i++) {
String[] employeeData = scanner.nextLine().split("\\s+");
String name = employeeData[0];
Double salary = Double.parseDouble(employeeData[1]);
String position = employeeData[2];
String employeeDepartment = employeeData[3];
Employee employee = null;
switch (employeeData.length) {
case 4:
employee = new Employee(name, salary, position, employeeDepartment);
break;
case 5:
if (employeeData[4].contains("@")) {
String emplEmail = employeeData[4];
employee = new Employee(name, salary, position, employeeDepartment, emplEmail);
break;
} else {
int age = Integer.parseInt(employeeData[4]);
employee = new Employee(name,salary,position,employeeDepartment,age);
}
break;
case 6:
String email = employeeData[4];
int age = Integer.parseInt(employeeData[5]);
employee = new Employee(name, salary, position, employeeDepartment, email, age);
break;
}
boolean isDepartmentExist = departments
.stream()
.anyMatch(department -> department.getName().equals(employeeDepartment));
if (!isDepartmentExist) {
Department department = new Department(employeeDepartment);
departments.add(department);
}
Department currentDepartment = departments
.stream()
.filter(dep -> dep.getName().equals(employeeDepartment))
.findFirst()
.get();
currentDepartment.getEmployees().add(employee);
}
Department highestPaidDepartment = departments
.stream()
.max(Comparator.comparingDouble(Department::calculateAverageSalary))
.get();
System.out.printf("Highest Average Salary: %s%n", highestPaidDepartment.getName());
highestPaidDepartment.getEmployees()
.stream()
.sorted((first,second)-> Double.compare(second.getSalary(), first.getSalary()))
.forEach(System.out::println);
}
}
|
from azure.cosmos import ConsistencyLevel
from azure.cosmos.aio import CosmosClient, ContainerProxy
from azure.cosmos.exceptions import CosmosHttpResponseError
from contextlib import asynccontextmanager
from helpers.config import CONFIG
from helpers.config_models.database import CosmosDbModel
from helpers.http import azure_transport
from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessStatus
from persistence.icache import ICache
from persistence.istore import IStore
from pydantic import ValidationError
from typing import AsyncGenerator, Optional
from uuid import UUID, uuid4
import asyncio
class CosmosDbStore(IStore):
_client: Optional[CosmosClient] = None
_config: CosmosDbModel
def __init__(self, cache: ICache, config: CosmosDbModel):
super().__init__(cache)
logger.info(f"Using Cosmos DB {config.database}/{config.container}")
self._config = config
async def areadiness(self) -> ReadinessStatus:
"""
Check the readiness of the Cosmos DB service.
This will validate the ACID properties of the database: Create, Read, Update, Delete.
"""
test_id = str(uuid4())
test_partition = "+33612345678"
test_dict = {
"id": test_id, # unique id
"initiate": {
"phone_number": test_partition, # partition key
},
"test": "test",
}
try:
# Test the item does not exist
if await self._item_exists(test_id, test_partition):
return ReadinessStatus.FAIL
async with self._use_client() as db:
# Create a new item
await db.upsert_item(body=test_dict)
# Test the item is the same
read_item = await db.read_item(
item=test_id, partition_key=test_partition
)
assert {
k: v for k, v in read_item.items() if k in test_dict
} == test_dict # Check only the relevant fields, Cosmos DB adds metadata
# Delete the item
await db.delete_item(item=test_id, partition_key=test_partition)
# Test the item does not exist
if await self._item_exists(test_id, test_partition):
return ReadinessStatus.FAIL
return ReadinessStatus.OK
except AssertionError:
logger.error("Readiness test failed", exc_info=True)
except CosmosHttpResponseError as e:
logger.error(f"Error requesting CosmosDB, {e}")
return ReadinessStatus.FAIL
async def _item_exists(self, test_id: str, partition_key: str) -> bool:
exist = False
async with self._use_client() as db:
try:
await db.read_item(item=test_id, partition_key=partition_key)
exist = True
except CosmosHttpResponseError as e:
if e.status_code != 404:
logger.error(f"Error requesting CosmosDB, {e}")
exist = True
return exist
async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
logger.debug(f"Loading call {call_id}")
# Try cache
cache_key = self._cache_key_call_id(call_id)
cached = await self._cache.aget(cache_key)
if cached:
try:
return CallStateModel.model_validate_json(cached)
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
# Try live
call = None
try:
async with self._use_client() as db:
items = db.query_items(
query="SELECT * FROM c WHERE STRINGEQUALS(c.id, @id)",
parameters=[{"name": "@id", "value": str(call_id)}],
)
raw = await anext(items)
try:
call = CallStateModel.model_validate(raw)
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
except StopAsyncIteration:
pass
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB, {e}")
# Update cache
if call:
await self._cache.aset(cache_key, call.model_dump_json())
return call
async def call_aset(self, call: CallStateModel) -> bool:
logger.debug(f"Saving call {call.call_id}")
# Update live
data = call.model_dump(mode="json", exclude_none=True)
data["id"] = str(call.call_id) # CosmosDB requires an id field
logger.debug(f"Saving call {call.call_id}: {data}")
res = False
try:
async with self._use_client() as db:
await db.upsert_item(body=data)
res = True
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB: {e}")
# Update cache
if res:
cache_key_id = self._cache_key_call_id(call.call_id)
await self._cache.aset(
cache_key_id, call.model_dump_json()
) # Update for ID
cache_key_phone_number = self._cache_key_phone_number(
call.initiate.phone_number
)
await self._cache.adel(
cache_key_phone_number
) # Invalidate for phone number because we don't know if it's the same call
return res
async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
logger.debug(f"Loading last call for {phone_number}")
# Try cache
cache_key = self._cache_key_phone_number(phone_number)
cached = await self._cache.aget(cache_key)
if cached:
try:
return CallStateModel.model_validate_json(cached)
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
# Try live
call = None
try:
async with self._use_client() as db:
items = db.query_items(
max_item_count=1,
query=f"SELECT * FROM c WHERE (STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)) AND c.created_at >= DATETIMEADD('hh', -{CONFIG.workflow.conversation_timeout_hour}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
parameters=[
{
"name": "@phone_number",
"value": phone_number,
}
],
)
raw = await anext(items)
try:
call = CallStateModel.model_validate(raw)
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
except StopAsyncIteration:
pass
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB: {e}")
# Update cache
if call:
await self._cache.aset(cache_key, call.model_dump_json())
return call
async def call_asearch_all(
self,
count: int,
phone_number: Optional[str] = None,
) -> tuple[Optional[list[CallStateModel]], int]:
logger.debug(f"Searching calls, for {phone_number} and count {count}")
# TODO: Cache results
calls, total = await asyncio.gather(
self._call_asearch_all_calls_worker(count, phone_number),
self._call_asearch_all_total_worker(phone_number),
)
return calls, total
async def _call_asearch_all_calls_worker(
self,
count: int,
phone_number: Optional[str] = None,
) -> Optional[list[CallStateModel]]:
calls: list[CallStateModel] = []
try:
async with self._use_client() as db:
where_clause = (
"WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)"
if phone_number
else ""
)
items = db.query_items(
query=f"SELECT * FROM c {where_clause} ORDER BY c.created_at DESC OFFSET 0 LIMIT @count",
parameters=[
{
"name": "@phone_number",
"value": phone_number,
},
{
"name": "@count",
"value": count,
},
],
)
async for raw in items:
if not raw:
continue
try:
calls.append(CallStateModel.model_validate(raw))
except ValidationError as e:
logger.debug(f"Parsing error: {e.errors()}")
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB, {e}")
return calls
async def _call_asearch_all_total_worker(
self,
phone_number: Optional[str] = None,
) -> int:
try:
async with self._use_client() as db:
where_clause = (
"WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)"
if phone_number
else ""
)
items = db.query_items(
query=f"SELECT VALUE COUNT(1) FROM c {where_clause}",
parameters=[
{
"name": "@phone_number",
"value": phone_number,
},
],
)
total: int = await anext(items) # type: ignore
except CosmosHttpResponseError as e:
logger.error(f"Error accessing CosmosDB, {e}")
return total if total else 0
@asynccontextmanager
async def _use_client(self) -> AsyncGenerator[ContainerProxy, None]:
"""
Generate the Cosmos DB client and close it after use.
"""
if not self._client:
self._client = CosmosClient(
# Usage
consistency_level=ConsistencyLevel.Eventual,
# Reliability
connection_timeout=10, # 10 seconds
retry_backoff_factor=0.8,
retry_backoff_max=8,
retry_total=3,
# Performance
transport=await azure_transport(),
# Deployment
url=self._config.endpoint,
# Authentication
credential=self._config.access_key.get_secret_value(),
)
async with self._client as client:
database = client.get_database_client(self._config.database)
yield database.get_container_client(self._config.container)
|
import { apiDetails } from "../config/constant";
import callApi from "./callApi.service";
import BigNumber from "bignumber.js";
import { sunDiameter } from "../config/constant";
import { PiDetails } from "../interfaces/PiDetails";
import { ApiResponsePi } from "../interfaces/ApiResponsePi";
import { logging } from "./util.service";
export const generateNewPi = async (): Promise<any> => {
try {
logging(`generateNewPi | Trying to run`);
const calculateLatestResult = await callApi(apiDetails.calculateLatest);
if (!calculateLatestResult[0] && calculateLatestResult[1]) {
throw new Error(calculateLatestResult[1].toString());
}
const calculateLatestSuccessResult = calculateLatestResult[0] as ApiResponsePi;
logging(
`generateNewPi | Get Response : ${calculateLatestSuccessResult.toString()}`
);
return getPiDetails(calculateLatestSuccessResult);
} catch (err: any) {
logging(`generateNewPi | Error : ${err.toString()}`);
return err;
}
};
export const resetPi = async (): Promise<any> => {
try {
logging(`resetPi | Trying to run`);
const resetPiResult = await callApi(apiDetails.resetPi);
if (!resetPiResult[0] && resetPiResult[1]) {
throw new Error(resetPiResult[1].toString());
}
const resetPiSuccessResult = resetPiResult[0] as ApiResponsePi;
logging(`resetPi | Get Response : ${resetPiSuccessResult.toString()}`);
return getPiDetails(resetPiSuccessResult);
} catch (err: any) {
logging(`resetPi | Error : ${err.toString()}`);
return err;
}
};
export const getPiDetails = (apiResponsePi: ApiResponsePi): PiDetails => {
const piDetails: PiDetails = {
pi: apiResponsePi.data.pi,
sunCircumference: calculateSunCircumference(apiResponsePi.data.pi),
};
return piDetails;
};
export const calculateSunCircumference = (pi: string): string => {
const currentPi: BigNumber = new BigNumber(pi);
// Formula = 2πr or πd
let sunCircumference: BigNumber = currentPi.times(sunDiameter);
return sunCircumference.toString();
};
|
//www.elegoo.com
//Custom code modified by Mr. Harms
//05.09.2023
//Line Tracking IO define
#define LT_R !digitalRead(10)
#define LT_M !digitalRead(4)
#define LT_L !digitalRead(2)
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define carSpeed 175
#define turnSpeed 150
void forward(){
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("go forward!");
}
void back(){
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
Serial.println("go back!");
}
void turnRight(){
digitalWrite(ENA,turnSpeed); //enable L298n A channel
digitalWrite(ENB,turnSpeed); //enable L298n B channel
digitalWrite(IN1,HIGH); //set IN1 hight level
digitalWrite(IN2,LOW); //set IN2 low level
digitalWrite(IN3,LOW); //set IN3 low level
digitalWrite(IN4,LOW); //set IN4 low level
Serial.println("Slow right");//send message to serial monitor
}
void turnLeft(){
digitalWrite(ENA,turnSpeed); //enable L298n A channel
digitalWrite(ENB,turnSpeed); //enable L298n B channel
digitalWrite(IN1,LOW); //set IN1 hight level
digitalWrite(IN2,LOW); //set IN2 low level
digitalWrite(IN3,LOW); //set IN3 low level
digitalWrite(IN4,HIGH); //set IN4 low level
Serial.println("Slow left");//send message to serial monitor
}
void spinLeft(){
analogWrite(ENA, 200);
analogWrite(ENB, 200);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("go left!");
}
void spinRight(){
analogWrite(ENA, 200);
analogWrite(ENB, 200);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
Serial.println("go right!");
}
void stop(){
digitalWrite(ENA, LOW);
digitalWrite(ENB, LOW);
Serial.println("Stop!");
}
void setup(){
Serial.begin(9600);
pinMode(LT_R,INPUT);
pinMode(LT_M,INPUT);
pinMode(LT_L,INPUT);
}
void loop() {
if(LT_M){
forward();
}
else if(LT_R) {
turnRight();
while(LT_R);
}
else if(LT_L) {
turnLeft();
while(LT_L);
}
else if (!LT_M && !LT_R && !LT_L){
spinLeft();
while(!LT_M && !LT_R && !LT_L);
}
}
|
/** @file mensaje.hh
@brief Especificación de la clase mensaje
*/
#ifndef _MENSAJE_HH_
#define _MENSAJE_HH_
#include "Calfabetos.hh"
#ifndef NO_DIAGRAM
#include "BinTree.hh"
#include<iostream>
#endif
using namespace std;
class mensaje {
private:
string m, ida;
public:
//Constructoras
/** @brief Constructora de un mensaje.
Se ejecuta automáticamente al declarar un mensaje.
\pre <em> Un string del mensaje m C</em>
\post El resultado es un mensaje de string m.
*/
mensaje(string m, string ida);
//Modificadoras
/** @brief Entra a Calfabetos y le pasa el mensaje a decodificar.
\pre <em>Cert C</em>
\post Entra a codificar del mensaje leido con alfabeto ida.
*/
void Mcs();
/** @brief Lee el número de bloques crea el árbol y codifica el mensaje por permutación.
\pre <em>Cert C</em>
\post Codifica el mensaje m por permutación y lo imprime.
*/
void Mcp();
/** @brief Lee el número de bloques crea el árbol y codifica el mensaje por permutación.
\pre <em>Cert C</em>
\post Decodifica el mensaje m por sustitución y lo imprime.
*/
void Mds();
/** @brief Lee el número de bloques crea el árbol y decodifica el mensaje por permutación.
\pre <em>Cert C</em>
\post Decodifica el mensaje m por permutación y lo imprime.
*/
void Mdp();
};
|
if(description){
script_oid( "1.3.6.1.4.1.25623.1.0.882458" );
script_version( "$Revision: 14058 $" );
script_tag( name: "last_modification", value: "$Date: 2019-03-08 14:25:52 +0100 (Fri, 08 Mar 2019) $" );
script_tag( name: "creation_date", value: "2016-04-14 05:19:02 +0200 (Thu, 14 Apr 2016)" );
script_cve_id( "CVE-2016-2110", "CVE-2016-2111", "CVE-2016-2112", "CVE-2016-2115", "CVE-2016-2118" );
script_tag( name: "cvss_base", value: "6.8" );
script_tag( name: "cvss_base_vector", value: "AV:N/AC:M/Au:N/C:P/I:P/A:P" );
script_tag( name: "qod_type", value: "package" );
script_name( "CentOS Update for libsmbclient CESA-2016:0621 centos5" );
script_tag( name: "summary", value: "Check the version of libsmbclient" );
script_tag( name: "vuldetect", value: "Checks if a vulnerable version is present on the target host." );
script_tag( name: "insight", value: "Samba is an open-source implementation of
the Server Message Block (SMB) protocol and the related Common Internet File
System (CIFS) protocol, which allow PC-compatible machines to share files,
printers, and various information.
Security Fix(es):
* A protocol flaw, publicly referred to as Badlock, was found in the
Security Account Manager Remote Protocol (MS-SAMR) and the Local Security
Authority (Domain Policy) Remote Protocol (MS-LSAD). Any authenticated
DCE/RPC connection that a client initiates against a server could be used
by a man-in-the-middle attacker to impersonate the authenticated user
against the SAMR or LSA service on the server. As a result, the attacker
would be able to get read/write access to the Security Account Manager
database, and use this to reveal all passwords or any other potentially
sensitive information in that database. (CVE-2016-2118)
* Several flaws were found in Samba's implementation of NTLMSSP
authentication. An unauthenticated, man-in-the-middle attacker could use
this flaw to clear the encryption and integrity flags of a connection,
causing data to be transmitted in plain text. The attacker could also force
the client or server into sending data in plain text even if encryption was
explicitly requested for that connection. (CVE-2016-2110)
* It was discovered that Samba configured as a Domain Controller would
establish a secure communication channel with a machine using a spoofed
computer name. A remote attacker able to observe network traffic could use
this flaw to obtain session-related information about the spoofed machine.
(CVE-2016-2111)
* It was found that Samba's LDAP implementation did not enforce integrity
protection for LDAP connections. A man-in-the-middle attacker could use
this flaw to downgrade LDAP connections to use no integrity protection,
allowing them to hijack such connections. (CVE-2016-2112)
* It was found that Samba did not enable integrity protection for IPC
traffic by default. A man-in-the-middle attacker could use this flaw to
view and modify the data sent between a Samba server and a client.
(CVE-2016-2115)
Red Hat would like to thank the Samba project for reporting these issues.
Upstream acknowledges Stefan Metzmacher (SerNet) as the original reporter
of CVE-2016-2118, CVE-2016-2110, CVE-2016-2112, and CVE-2016-2115." );
script_tag( name: "affected", value: "libsmbclient on CentOS 5" );
script_tag( name: "solution", value: "Please Install the Updated Packages." );
script_xref( name: "CESA", value: "2016:0621" );
script_xref( name: "URL", value: "http://lists.centos.org/pipermail/centos-announce/2016-April/021823.html" );
script_tag( name: "solution_type", value: "VendorFix" );
script_category( ACT_GATHER_INFO );
script_copyright( "Copyright (C) 2016 Greenbone Networks GmbH" );
script_family( "CentOS Local Security Checks" );
script_dependencies( "gather-package-list.sc" );
script_mandatory_keys( "ssh/login/centos", "ssh/login/rpms", "ssh/login/release=CentOS5" );
exit( 0 );
}
require("revisions-lib.inc.sc");
require("pkg-lib-rpm.inc.sc");
release = rpm_get_ssh_release();
if(!release){
exit( 0 );
}
res = "";
if(release == "CentOS5"){
if(( res = isrpmvuln( pkg: "libsmbclient", rpm: "libsmbclient~3.0.33~3.41.el5_11", rls: "CentOS5" ) ) != NULL){
security_message( data: res );
exit( 0 );
}
if(( res = isrpmvuln( pkg: "libsmbclient-devel", rpm: "libsmbclient-devel~3.0.33~3.41.el5_11", rls: "CentOS5" ) ) != NULL){
security_message( data: res );
exit( 0 );
}
if(( res = isrpmvuln( pkg: "samba", rpm: "samba~3.0.33~3.41.el5_11", rls: "CentOS5" ) ) != NULL){
security_message( data: res );
exit( 0 );
}
if(( res = isrpmvuln( pkg: "samba-client", rpm: "samba-client~3.0.33~3.41.el5_11", rls: "CentOS5" ) ) != NULL){
security_message( data: res );
exit( 0 );
}
if(( res = isrpmvuln( pkg: "samba-common", rpm: "samba-common~3.0.33~3.41.el5_11", rls: "CentOS5" ) ) != NULL){
security_message( data: res );
exit( 0 );
}
if(( res = isrpmvuln( pkg: "samba-swat", rpm: "samba-swat~3.0.33~3.41.el5_11", rls: "CentOS5" ) ) != NULL){
security_message( data: res );
exit( 0 );
}
if(__pkg_match){
exit( 99 );
}
exit( 0 );
}
|
import math
char_stats = [None] * 3
def main():
print('\nInjustice Basic Damage Gear Calculator')
list_of_gear_tuples = get_gears()
num_gears_to_combine = get_valid_int_input('Enter 1 for single gears, 2 for combinations of 2 gears, or 3 for combinations for 3 gears: ', [1, 2, 3])
list_all_gears = True if get_valid_int_input('Enter 1 to display all combinations, enter 2 to only display the best combination: ', [1, 2]) == 1 else False
num_gears = len(list_of_gear_tuples)
num_combinations = int((math.factorial(num_gears)) / (math.factorial(num_gears - num_gears_to_combine) * math.factorial(num_gears_to_combine)))
get_char_stats()
if num_gears_to_combine == 1:
gear_stats = []
for i, gear in enumerate(list_of_gear_tuples):
gear_stats.append(calculate_expected_damage(gear[0], gear[1], gear[2])[0])
calculated_gears = {k:v for (k,v) in zip(list_of_gear_tuples, gear_stats)}
if not list_all_gears:
best_result_key = max(calculated_gears, key=calculated_gears.get)
print(f'\nBest single gear is: {best_result_key}')
expected_dmg = calculate_expected_damage(best_result_key[0], best_result_key[1], best_result_key[2])
log_final_result(expected_dmg)
else:
sorted_gears = dict(sorted(calculated_gears.items(), key=lambda x: x[1], reverse=True))
print(f'\n{num_combinations} Results, sorted from best to worst:')
gears_iterator = iter(sorted_gears)
for _ in range(len(sorted_gears)):
this_gear = next(gears_iterator)
print(f'\n{this_gear}: ')
expected_dmg = calculate_expected_damage(this_gear[0], this_gear[1], this_gear[2])
log_final_result(expected_dmg)
elif num_gears_to_combine == 2:
gear_pairs = []
for i in range(len(list_of_gear_tuples)):
for j in range(i+1, len(list_of_gear_tuples)):
gear_pairs.append((list_of_gear_tuples[i], list_of_gear_tuples[j]))
gear_combo_stats = []
for gear_pair in gear_pairs:
gear_combo_stats.append(combine_gears(gear_pair[0], gear_pair[1])[0])
calculated_gears = {k:v for (k,v) in zip(gear_pairs, gear_combo_stats)}
if not list_all_gears:
best_result_key = max(calculated_gears, key=calculated_gears.get)
print(f'\nBest gear combo is: {best_result_key}')
expected_dmg = combine_gears(best_result_key[0], best_result_key[1])
log_final_result(expected_dmg)
else:
sorted_gears = dict(sorted(calculated_gears.items(), key=lambda x: x[1], reverse=True))
print(f'\n{num_combinations} Results, sorted from best to worst:')
gears_iterator = iter(sorted_gears)
for _ in range(len(sorted_gears)):
this_gear_pair = next(gears_iterator)
print (f'\n{this_gear_pair}: ')
expected_dmg = combine_gears(this_gear_pair[0], this_gear_pair[1])
log_final_result(expected_dmg)
elif num_gears_to_combine == 3:
gear_triplets = []
for i in range(len(list_of_gear_tuples)):
for j in range(i + 1, len(list_of_gear_tuples)):
for k in range(j + 1, len(list_of_gear_tuples)):
gear_triplets.append((list_of_gear_tuples[i], list_of_gear_tuples[j], list_of_gear_tuples[k]))
gear_combo_stats = []
for gear_triplet in gear_triplets:
gear_combo_stats.append(combine_gears(gear_triplet[0], gear_triplet[1], gear_triplet[2])[0])
calculated_gears = {k:v for (k,v) in zip(gear_triplets, gear_combo_stats)}
if not list_all_gears:
best_result_key = max(calculated_gears, key=calculated_gears.get)
print(f'\nBest gear combo is: {best_result_key}')
expected_dmg = combine_gears(best_result_key[0], best_result_key[1], best_result_key[2])
log_final_result(expected_dmg)
else:
sorted_gears = dict(sorted(calculated_gears.items(), key=lambda x: x[1], reverse=True))
print(f'\n{num_combinations} Results, sorted from best to worst:')
gears_iterator = iter(sorted_gears)
for _ in range(len(sorted_gears)):
this_gear_triplet = next(gears_iterator)
print (f'\n{this_gear_triplet}: ')
expected_dmg = combine_gears(this_gear_triplet[0], this_gear_triplet[1], this_gear_triplet[2])
log_final_result(expected_dmg)
offer_restart()
def get_gears():
while True:
try:
gears_input_string = input('Enter your gears. Separate gear values with commas, and separate different gears with semicolons.\n')
list_of_gear_tuples = [tuple(map(lambda x: float(x) / 100, tpl.split(','))) for tpl in gears_input_string.split(';')]
return list_of_gear_tuples
except:
print('\nInvalid input. Please enter valid numeric values.')
def get_valid_int_input(prompt, valid_options):
while True:
try:
user_input = int(input(prompt))
if user_input in valid_options:
return user_input
else:
print(f'\nInvalid input. Please enter one of these valid options: {valid_options}')
except:
print('\nInvalid input. Please enter a valid integer.')
def combine_gears(gear_1, gear_2, gear_3=[0,0,0]):
gear_dmg = gear_1[0] + gear_2[0] + gear_3[0]
gear_crit_chance = gear_1[1] + gear_2[1] + gear_3[1]
gear_crit_dmg = gear_1[2] + gear_2[2] + gear_3[2]
return calculate_expected_damage(gear_dmg, gear_crit_chance, gear_crit_dmg)
def calculate_expected_damage(gear_dmg, gear_crit_chance, gear_crit_dmg):
total_crit_chance = clamp(char_stats[1] + gear_crit_chance, 0, 1)
total_crit_dmg = char_stats[2] + gear_crit_dmg
total_non_crit_hit_dmg = char_stats[0] * (gear_dmg + 1)
total_crit_hit_dmg = total_non_crit_hit_dmg * total_crit_dmg
return [
(total_crit_chance * total_crit_hit_dmg) + ((1 - total_crit_chance) * total_non_crit_hit_dmg),
total_non_crit_hit_dmg,
total_crit_hit_dmg
]
def get_char_stats():
char_stats[0] = float(''.join(char for char in input('Please enter character base damage: ') if char.isdigit()))
global char_base_dmg
char_base_dmg = char_stats[0]
char_stats[1] = float(''.join(char for char in input('Please enter character crit chance in percentage: ') if char.isdigit())) / 100
char_stats[2] = float(''.join(char for char in input('Please enter character crit damage in percentage (min 150): ') if char.isdigit())) / 100
return char_stats
def log_final_result(expected_damage_values):
print(f'\nAverage expected damage is: {expected_damage_values[0]}')
print(f'Average expected damage multiplier is: {expected_damage_values[0] / char_base_dmg}')
print(f'Non-crit hit damage is: {expected_damage_values[1]}')
print(f'Crit hit damage is: {expected_damage_values[2]}')
def offer_restart():
restart = input('\nRestart? (Y/N) ')
while restart.lower() not in ['y', 'n']:
restart = input('Restart? (Y/N) ')
if restart == 'y':
print('Restarting Application...')
main()
else:
print('Quitting Application...')
quit()
def clamp(num, min_value, max_value):
return max(min(num, max_value), min_value)
if __name__ == '__main__':
main()
|
import {useForm} from 'react-hook-form';
import {useEffect, useRef, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {onToggleEmailModalAction, onToggleLoadingModalAction} from "@action/modal.action.tsx";
import {useAuthMailSendMutation, useNicknameVerifyLazyQuery, useSignUpMutation} from "@graphql/graphql.ts";
import {RootState} from "@reducer/root.reducer.tsx";
import {Link, useNavigate, useSearchParams} from "react-router-dom";
import ValidComponent from "@component/valid.tsx";
import {setEmailAction, setInitialStateAction} from "@action/auth.action.tsx";
import {SignUpFormType} from "@type/auth.type.tsx";
import Swal from 'sweetalert2';
import {useTranslation} from "react-i18next";
import EmailModal from "@container/modal/email.modal.tsx";
import Select from "react-select";
import {countryCodes} from "@helper/country.codes.tsx";
import {selectStyles} from "@container/auth/auth.style.tsx";
const SignupContainer = () => {
const [searchParams] = useSearchParams();
const referralCode = searchParams.get('referralCode');
const selectRef = useRef<any>()
const {t} = useTranslation();
const navigation = useNavigate();
const dispatch = useDispatch();
const [isNicknameValid, setIsNicknameValid] = useState<boolean>(false);
const [isEmailValid, setIsEmailValid] = useState<boolean>(false);
const {register, setValue, watch, handleSubmit, formState: {errors}} = useForm<SignUpFormType>({
mode: 'all'
});
const {emailVerified} = useSelector((root: RootState) => root.AuthReducer)
const [onAuthMailSend] = useAuthMailSendMutation()
const [onNickNameVerify] = useNicknameVerifyLazyQuery();
const [onSinUp] = useSignUpMutation();
const regex = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
const passwordRegex = /^(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;
useEffect(() => {
if (watch("nickname") && watch("nickname").length > 0)
onNickNameVerify({
variables: {
input: {
nickname: watch("nickname")
}
}
}).then(response => {
return setIsNicknameValid(response.data?.nicknameVerify?.success ?? false);
}).catch(e => console.log(e))
else
setIsNicknameValid(false);
}, [watch("nickname")]);
const onChangeAllAccept = (checked: boolean) => {
setValue('allAccept', checked);
setValue('term1Accept', checked);
setValue('term2Accept', checked);
}
const onChangeTerms1 = (checked: boolean) => setValue('term1Accept', checked)
const onChangeTerms2 = (checked: boolean) => setValue('term2Accept', checked)
useEffect(()=> {
(watch('term1Accept') && watch('term2Accept')) ? setValue('allAccept', true) : setValue('allAccept', false)
}, [watch('term1Accept'), watch("term2Accept")])
useEffect(() => {
if (watch('email') && watch('email').length > 0 && regex.test(watch('email')))
setIsEmailValid(false);
else
setIsEmailValid(true);
}, [watch("email")]);
useEffect(() => {
if (navigator.language.includes('ko')) {
selectRef.current.setValue(countryCodes[117]);
setValue('countryCode', countryCodes[117].value)
}
}, []);
// useEffect(() => {
// if (!phoneVerified)
// Swal.fire({
// color: '#000',
// text: 'Proceed to verify your phone.',
// preConfirm: () => {
// navigation("/auth/sms");
// },
// });
// }, [])
useEffect(() => {
window.onpopstate = () => navigation('/auth/login')
}, [])
const onClickSend = () => {
dispatch(onToggleLoadingModalAction(true));
return onAuthMailSend({
variables: {
input: {
email: watch("email")
}
}
}).then(_response => {
dispatch(setEmailAction(watch("email")));
dispatch(onToggleEmailModalAction(true));
return;
}).catch(e => {
Swal.fire({
icon: 'error',
title: t(`auth_signup.email_send_fail`),
text: e.message,
});
return;
}).finally(() => dispatch(onToggleLoadingModalAction(false)))
}
const onSubmit = (data: any) => {
if (!emailVerified)
return Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.err_msg1`),
});
else if (!isNicknameValid)
return Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.nickname_err`),
});
else if (!!errors.confirmPassword)
return Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.pw_multi`),
});
else if (!watch('allAccept'))
return Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.accept_err`),
});
else if (!watch('term1Accept'))
return Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.terms_err`),
});
else if (!watch('term2Accept'))
return Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.terms2_err`),
});
else {
dispatch(onToggleLoadingModalAction(true));
return onSinUp({
variables: {
input: {
email: data.email,
nickname: data.nickname,
password: data.password,
countryCode: data.countryCode,
referralCode: referralCode
}
}
}).then(response => {
if (response.data?.signUp?.id) {
dispatch(setInitialStateAction());
navigation("/auth/complete");
} else if (response.data?.signUp.error) {
if (response.data.signUp.error.code === 'EMAIL_VERIFY')
Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.err_msg1`),
});
else
Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: t(`auth_signup.err_msg2`),
});
return;
}
}).catch(e => {
Swal.fire({
icon: 'error',
title: t(`auth_signup.err_title`),
text: e.message,
})
return;
}).finally(() => dispatch(onToggleLoadingModalAction(false)));
}
}
return (
<>
<div className="authincation section-padding">
<div className="container h-100">
<div className="row justify-content-center h-100 align-items-center">
<div className="col-xl-5 col-md-6">
<div className="mini-logo text-center my-4"><Link to="/"><img src="/images/logo.png"
alt=""/></Link>
<h4 className="card-title mt-5">{t(`auth_signup.title`)}</h4>
</div>
<div className="auth-form card">
<div className="card-body">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col-12 mb-3">
<label className="form-label">{t(`auth_signup.email`)}</label>
<div className="email-area rela">
<input
type={"email"}
className="form-control"
{...register("email", {required: true, pattern: /^\S+@\S+$/i})}
disabled={emailVerified}
/>
<button className="btn btn-primary nowrap"
type={'button'}
disabled={isEmailValid || emailVerified}
onClick={() => onClickSend()}>{t(`auth_signup.email_button`)}</button>
</div>
</div>
<div className="col-12 mb-3 rela">
<label className="form-label">{t(`auth_sms.country_title`)}</label>
<Select ref={selectRef} placeholder={t(`auth_sms.country_select`)} options={countryCodes} styles={selectStyles} onChange={(e: any) => setValue('countryCode', e.value)}/>
</div>
<div className="col-12 mb-3 rela">
<label className="form-label">{t(`auth_signup.nickname`)}</label>
<input
type="text"
className="form-control"
{...register("nickname", {required: true, minLength: 1})}
/>
{
watch('nickname')
? isNicknameValid ? ValidComponent({
valid: isNicknameValid,
text: t(`auth_signup.nickname_confirm`)
}) : ValidComponent({
valid: isNicknameValid,
text: t(`auth_signup.nickname_err`)
})
: <></>
}
</div>
<div className="col-12 mb-3 rela">
<label className="form-label">{t(`auth_signup.pw`)}</label>
<input
type="password"
className="form-control"
{...register('password', {
required: true,
minLength: 8,
maxLength: 20,
pattern: passwordRegex
})}
/>
<small>{t('auth_signup.pw_multi')}</small>
{
errors && watch('password') && watch('password').length > 8
? errors.password
? ValidComponent({
valid: false,
text: t(`auth_signup.pw_multi`)
})
: ValidComponent({
valid: true,
text: t(`auth_signup.pw_confirm`)
})
: <></>
}
</div>
<div className="col-12 mb-3 rela">
<label className="form-label">{t(`auth_signup.confirm_pw`)}</label>
<input
type="password"
className="form-control"
{...register("confirmPassword", {
required: true,
minLength: 8,
maxLength: 20,
validate: (value) => value === watch('password'),
})}
/>
{
errors && watch('confirmPassword') && watch('confirmPassword').length > 0
? errors.confirmPassword ? ValidComponent({
valid: false,
text: t(`auth_signup.confirm_pw_err`)
}) : ValidComponent({
valid: true,
text: t(`auth_signup.confirm_pw_confirm`)
})
: <></>
}
</div>
<div className="col-12">
<div className="form-check check-all">
<input type="checkbox"
id={'allAccept'}
{...register("allAccept", {
required: true,
validate: value => value === true,
onChange: (e) => onChangeAllAccept(e.target.checked)
})}
className="form-check-input "/>
<label className="form-check-label"
htmlFor="allAccept">{t(`auth_signup.accept`)}</label>
</div>
</div>
<div className="col-12">
<div className="form-check">
<input
id={'term1Accept'}
type="checkbox"
className="form-check-input "
// onChange={(e) => onChangeAllAccept(e.target.checked)}
{...register("term1Accept", {
required: true,
validate: value => value === true,
onChange: (e) => onChangeTerms1(e.target.checked)
})}
/>
<label className="form-check-label" htmlFor={'term1Accept'}>
{t(`auth_signup.terms_description1`)}
<Link to={`/terms/${localStorage.getItem('khanway_language') ?? 'en'}/terms-of-service`} target={'_blank'} className="text-primary">{t(`auth_signup.terms_link1`)}</Link>
{t(`auth_signup.terms_description2`)}
<Link to={`/terms/${localStorage.getItem('khanway_language') ?? 'en'}/privacy-policy`} target={'_blank'} className="text-primary">{t(`auth_signup.terms_link2`)}</Link>
{t(`auth_signup.terms_description3`)}
</label>
</div>
</div>
<div className="col-12">
<div className="form-check">
<input
id={'term2Accept'}
type="checkbox"
className="form-check-input "
{...register("term2Accept", {
required: true,
validate: value => value === true,
onChange: (e) => onChangeTerms2(e.target.checked)
})}
/>
<label className="form-check-label" htmlFor={'term2Accept'}>
{t(`auth_signup.terms2_description1`)}
<Link to={`/terms/${localStorage.getItem('khanway_language') ?? 'en'}/terms-of-nfw`} target={'_blank'} className="text-primary">{t(`auth_signup.terms2_link`)}</Link>
{t(`auth_signup.terms2_description2`)}
</label>
</div>
</div>
</div>
<div className="mt-3 d-grid gap-2">
<button type="submit" className="btn btn-primary mr-2"
disabled={!!errors.confirmPassword || !emailVerified || !isNicknameValid || !watch('allAccept')}>{t(`auth_signup.button`)}</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<EmailModal/>
</>
)
}
export default SignupContainer;
|
# Лабораторная работа №3*
«Автоматическая сборка образа с настройкой секретов»
### Команда
* Безкоровайный Павел • K34211
* Долматов Дмитрий • K34212
* Коряков Сергей • K34201
* Кубашин Илья • K34211
## Задание
Сделать красиво работу с секретами. Например, поднять Hashicorp Vault и сделать так, чтобы ci/cd пайплайн ходил туда, брал секрет, использовал его не светя в логах.
## Настройка HashiCorp Vault
Для хранения секретов было решено использовать [HashiCorp Vault](https://www.vaultproject.io/).
> При выполнении работы очень помогла статья из документации:<br/>
> https://developer.hashicorp.com/vault/tutorials/app-integration/github-actions
Скачать бинарник для Vault можно по ссылке: https://developer.hashicorp.com/vault/install.
### Запуск локального Vault сервера
Для запуска сервера используем команду:
```bat
vault server -dev -dev-root-token-id root
```
<img src='./images/Vault_server_start.png' width='600px'/>
Помимо консольной работы, можно взаимодействовать с Vault через графический интерфейс. Для этого нужно открыть запущенный веб-сервер: `http://127.0.0.1:8200/`. Для входа используем токен `root`, указанный во время запуска Vault сервера.
<img src='./images/Vault_web_interface.png' width='360px'/>
> Автор данного отчёта понимает, что нельзя использовать в production _небезопасные_ токены, но в целях изучения Vault был указан стандартный токен `root`
### Создание секретов
Откроем второй терминал. В силу специфики команд был использован bash терминал.
> Также для работы потребовалось скачать `jq` пакет для Windows. [Скачать jq](https://github.com/jqlang/jq/releases/tag/jq-1.7.1).
Используя команды ниже в Vault были добавлены необходимые секреты, настроена политика безопасности для чтения секретов и получен токен для этой политики.
```sh
# set env vars
export VAULT_ADDR=http://127.0.0.1:8200
export VAULT_TOKEN=root
# save secrets
/c/vault/vault kv put secret/docker DOCKERHUB_USERNAME=pashabezk DOCKERHUB_ACCESS_TOKEN=add_your_token_here
# create policy to read secret
/c/vault/vault policy write docker-secret-reader - <<EOF
path "secret/data/docker" {
capabilities = ["read"]
}
EOF
# create env var with policy token
GITHUB_REPO_TOKEN=$(/c/vault/vault token create -policy=docker-secret-reader -format json | /c/vault/jq -r ".auth.client_token")
# test: getting token via policy token
VAULT_TOKEN=$GITHUB_REPO_TOKEN /c/vault/vault kv get secret/docker
```
Также на этом шаге необходимо добавить секрет в GitHub secrets.
Создадим секрет под названием `VAULT_TOKEN` значением которого будет значение переменной `GITHUB_REPO_TOKEN`.
> Чтоб получить значение переменной:
> ```sh
> echo $GITHUB_REPO_TOKEN
> ```
Убедиться, что секреты и политика созданы успешно можно через веб-интерфейс Vault.
<img src='./images/Vault_secrets.png' width='520px'/>
<img src='./images/Vault_policies.png' width='520px'/>
### Создание self-hosted runner
Так как используется локальный Vault сервер, то GH actions необходимо тоже запускать локально. Для этого был создан и настроен self-hosted runner.
<img src='./images/GHRunners.png' width='520px'/>
Вот так выглядит настройка конфигурации раннера локально
<img src='./images/RunnerConfig.png' width='420px'/>
### Настройка workflow
Ниже представлена модификация workflow-файла для работы с Vault. Сам файл: [.github/workflows/lab3_pro_ci_cd.yml](/.github/workflows/lab3_pro_ci_cd.yml).
```yml
name: Publish docker image with Vault
# sets workflow run properties
on:
workflow_dispatch: # to allow run action via github interface
jobs:
build_and_push: # job name
runs-on: self-hosted
defaults:
run:
working-directory: "/Lab3/Base"
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Import Secrets
uses: hashicorp/vault-action@v2.4.0
with:
url: http://127.0.0.1:8200
tlsSkipVerify: true
token: ${{ secrets.VAULT_TOKEN }}
secrets: |
secret/data/docker DOCKERHUB_USERNAME ;
secret/data/docker DOCKERHUB_ACCESS_TOKEN
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ env.DOCKERHUB_USERNAME }}
password: ${{ env.DOCKERHUB_ACCESS_TOKEN }}
- name: Build and push to Docker hub
uses: docker/build-push-action@v5
with:
context: ./Lab3/Base/
push: true
tags: pashabezk/tic-tac-toe-tg-bot:${{ github.run_number }} , pashabezk/tic-tac-toe-tg-bot:latest
```
Рассмотрим изменения более детально.
#### 1. Запуск только по кнопке
В триггерах action был оставлен только ручной запуск, так как для работы этого action нужно, чтобы был локально запущен vault.
#### 2. Импорт секретов
[Vault-action](https://github.com/marketplace/actions/hashicorp-vault) используется для импорта секретов в виде переменных среды.
1. Указываем url, на котором запущен Vault: `http://127.0.0.1:8200`.
2. Указываем токен, сохранённый в GH secrets `secrets.VAULT_TOKEN`.
3. Указываем, что необходимо импортировать секреты `DOCKERHUB_USERNAME` и `DOCKERHUB_ACCESS_TOKEN`.
```yml
- name: Import Secrets
uses: hashicorp/vault-action@v2.4.0
with:
url: http://127.0.0.1:8200
tlsSkipVerify: true
token: ${{ secrets.VAULT_TOKEN }}
secrets: |
secret/data/docker DOCKERHUB_USERNAME ;
secret/data/docker DOCKERHUB_ACCESS_TOKEN
```
#### 3. Авторизация в DockerHub
Скорректируем авторизацию в DockerHub. Теперь секреты берём не из GH Secrets, а из переменных среды, куда они были помещены на предыдущем шаге.
```yml
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ env.DOCKERHUB_USERNAME }}
password: ${{ env.DOCKERHUB_ACCESS_TOKEN }}
```
### Запуск workflow
Для начала необходимо запустить раннер локально. Он будет ждать, пока GH обратится к нему.
На рисунке ниже показан запущенный раннер с успешным завершением workflow.
<img src='./images/RunnerSuccess.png' width='420px'/>
С помощью кнопки в GitHub Actions можно запустить workflow.
На рисунке ниже видно, что после правильной настройки yml-файла workflow успешно отработал.
<img src='./images/GHWorkflows.png' width='520px'/>
## Заключение
С помощью [HashiCorp Vault](https://www.vaultproject.io/) и self-hosted runner было настроено безопасное использование секретов в GitHub Actions
|
package net.liopyu.entityjs.item;
import dev.latvian.mods.kubejs.item.ItemBuilder;
import dev.latvian.mods.kubejs.typings.Info;
import net.liopyu.entityjs.builders.nonliving.vanilla.EyeOfEnderJSBuilder;
import net.liopyu.entityjs.entities.nonliving.vanilla.EyeOfEnderEntityJS;
import net.liopyu.entityjs.util.ContextUtils;
import net.liopyu.entityjs.util.EntityJSHelperClass;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.stats.Stats;
import net.minecraft.tags.StructureTags;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.EnderEyeItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import org.jetbrains.annotations.Nullable;
import java.util.function.Function;
public class EyeOfEnderItemBuilder extends ItemBuilder {
public transient final EyeOfEnderJSBuilder parent;
public transient boolean triggersCriteria;
public transient Player sPlayer;
public transient SoundEvent soundEvent;
public transient SoundSource soundSource;
public transient float soundVolume;
public transient float soundPitch;
public transient boolean overrideSound;
public transient Function<ContextUtils.ItemUseContext, Object> signalTo;
public EyeOfEnderItemBuilder(ResourceLocation i, EyeOfEnderJSBuilder parent) {
super(i);
this.parent = parent;
texture = i.getNamespace() + ":item/" + i.getPath();
this.triggersCriteria = true;
this.overrideSound = false;
}
@Info(value = """
A function to determine where the thrown ender eye item will head towards.
Example usage:
```javascript
builder.signalTo(context => {
const { level, player, hand } = context
return // Some BlockPos for the eye to navigate to when thrown
});
```
""")
public EyeOfEnderItemBuilder signalTo(Function<ContextUtils.ItemUseContext, Object> f) {
this.signalTo = f;
return this;
}
@Info(value = """
Sets the sound to play when the eye item is thrown at the coordinates of the player
@param sPlayer The player to play the sound to, can be null.
@param soundEvent The sound to play when the eye item is thrown
@param soundSource The source of the sound in the mixer.
@param soundVolume The volume of the sound.
@param soundPitch The pitch of the sound.
```javascript
item.playSoundOverride(null,"ambient.basalt_deltas.additions","ambient",1,1)
```
""")
public EyeOfEnderItemBuilder playSoundOverride(@Nullable Player player, SoundEvent soundEvent, SoundSource soundSource, float volume, float pitch) {
this.sPlayer = player;
this.soundEvent = soundEvent;
this.soundSource = soundSource;
this.soundVolume = volume;
this.soundPitch = pitch;
this.overrideSound = true;
return this;
}
@Info(value = "Sets if the eye of ender triggers the USED_ENDER_EYE Criteria")
public EyeOfEnderItemBuilder triggersCriteria(boolean triggersCriteria) {
this.triggersCriteria = triggersCriteria;
return this;
}
@Override
public Item createObject() {
return new EnderEyeItem(createItemProperties()) {
@Override
public InteractionResultHolder<ItemStack> use(Level pLevel, Player pPlayer, InteractionHand pHand) {
ItemStack $$3 = pPlayer.getItemInHand(pHand);
BlockHitResult $$4 = getPlayerPOVHitResult(pLevel, pPlayer, ClipContext.Fluid.NONE);
if ($$4.getType() == HitResult.Type.BLOCK && pLevel.getBlockState($$4.getBlockPos()).is(Blocks.END_PORTAL_FRAME)) {
return InteractionResultHolder.pass($$3);
} else {
pPlayer.startUsingItem(pHand);
if (pLevel instanceof ServerLevel) {
ServerLevel $$5 = (ServerLevel) pLevel;
BlockPos $$6 = $$5.findNearestMapStructure(StructureTags.EYE_OF_ENDER_LOCATED, pPlayer.blockPosition(), 100, false);
if (signalTo != null) {
final ContextUtils.ItemUseContext context = new ContextUtils.ItemUseContext(pLevel, pPlayer, pHand);
Object obj = signalTo.apply(context);
if (obj instanceof BlockPos b) {
EyeOfEnderEntityJS $$7 = new EyeOfEnderEntityJS(parent, pLevel, parent.get(), pPlayer.getX(), pPlayer.getY(0.5), pPlayer.getZ());
$$7.setItem($$3);
$$7.signalTo(b);
pLevel.gameEvent(GameEvent.PROJECTILE_SHOOT, $$7.position(), GameEvent.Context.of(pPlayer));
pLevel.addFreshEntity($$7);
} else {
EntityJSHelperClass.logErrorMessageOnce("[EntityJS]: Invalid return value for signalTo in ender eye item builder: " + obj + ". Must be a BlockPos. Defaulting to null.");
return InteractionResultHolder.consume($$3);
}
if (pPlayer instanceof ServerPlayer) {
if (triggersCriteria) {
CriteriaTriggers.USED_ENDER_EYE.trigger((ServerPlayer) pPlayer, $$6);
}
}
if (overrideSound) {
pLevel.playSound(sPlayer, pPlayer.getX(), pPlayer.getY(), pPlayer.getZ(), soundEvent, soundSource, soundVolume, soundPitch);
} else {
pLevel.playSound((Player) null, pPlayer.getX(), pPlayer.getY(), pPlayer.getZ(), SoundEvents.ENDER_EYE_LAUNCH, SoundSource.NEUTRAL, 0.5F, 0.4F / (pLevel.getRandom().nextFloat() * 0.4F + 0.8F));
}
pLevel.levelEvent((Player) null, 1003, pPlayer.blockPosition(), 0);
if (!pPlayer.getAbilities().instabuild) {
$$3.shrink(1);
}
pPlayer.awardStat(Stats.ITEM_USED.get(this));
pPlayer.swing(pHand, true);
return InteractionResultHolder.success($$3);
} else if ($$6 != null) {
EyeOfEnderEntityJS $$7 = new EyeOfEnderEntityJS(parent, pLevel, parent.get(), pPlayer.getX(), pPlayer.getY(0.5), pPlayer.getZ());
$$7.setItem($$3);
$$7.signalTo($$6);
pLevel.gameEvent(GameEvent.PROJECTILE_SHOOT, $$7.position(), GameEvent.Context.of(pPlayer));
pLevel.addFreshEntity($$7);
if (pPlayer instanceof ServerPlayer) {
if (triggersCriteria) {
CriteriaTriggers.USED_ENDER_EYE.trigger((ServerPlayer) pPlayer, $$6);
}
}
if (overrideSound) {
pLevel.playSound(sPlayer, pPlayer.getX(), pPlayer.getY(), pPlayer.getZ(), soundEvent, soundSource, soundVolume, soundPitch);
} else {
pLevel.playSound((Player) null, pPlayer.getX(), pPlayer.getY(), pPlayer.getZ(), SoundEvents.ENDER_EYE_LAUNCH, SoundSource.NEUTRAL, 0.5F, 0.4F / (pLevel.getRandom().nextFloat() * 0.4F + 0.8F));
}
pLevel.levelEvent((Player) null, 1003, pPlayer.blockPosition(), 0);
if (!pPlayer.getAbilities().instabuild) {
$$3.shrink(1);
}
pPlayer.awardStat(Stats.ITEM_USED.get(this));
pPlayer.swing(pHand, true);
return InteractionResultHolder.success($$3);
}
}
return InteractionResultHolder.consume($$3);
}
}
};
}
}
|
/*
Input Format :-
The first line will have an integer denoting the number of entries in the phone book. Each entry consists of two lines: a name and the corresponding phone number.
After these, there will be some queries. Each query will contain a person's name. Read the queries until end-of-file.
Output Format :-
For each case, print "Not found" if the person has no entry in the phone book. Otherwise, print the person's name and phone number. See sample output for the exact format.
To make the problem easier, we provided a portion of the code in the editor. You can either complete that code or write completely on your own.
*/
// Amswer :-
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
try {
int no_of_entries = 0;
int i = 0;
String name = null;
int number = 0;
String query = null;
HashMap<String, Integer> phoneBook = new HashMap<String, Integer>();
BufferedReader b = new BufferedReader(new InputStreamReader(
System.in));
no_of_entries = Integer.parseInt(b.readLine());
while (i < no_of_entries) {
name = b.readLine();
number = Integer.parseInt(b.readLine());
phoneBook.put(name, number);
i++;
}
while (!(query = b.readLine().trim()).isEmpty()) {
if (phoneBook.containsKey(query))
System.out.println(query + "=" + phoneBook.get(query));
else
System.out.println("Not found");
}
} catch (Exception e) {
}
}
}
|
<?php
namespace App\Services;
use App\Models\Expense;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
class ExpenseService
{
public function index(int $userId): Collection
{
return QueryBuilder::for(Expense::where('user_id', $userId))
->allowedFilters([
AllowedFilter::scope('transacted_after'),
AllowedFilter::scope('transacted_before'),
])
->with(['account', 'category'])
->get();
}
public function store(User $user, array $input): Expense
{
return DB::transaction(
fn () => $user->expenses()->create($input)
);
}
public function update(Expense $expense, array $input): Expense
{
return DB::transaction(
fn () => tap($expense, fn (Expense $expense) => $expense->update($input))
);
}
public function destroy(Expense $expense): Expense
{
return DB::transaction(
fn () => tap($expense, fn (Expense $expense) => $expense->delete())
);
}
}
|
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/username_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="64dp"
app:errorEnabled="true"
app:hintEnabled="true"
app:hintTextAppearance="@style/TextAppearance.MaterialComponents.Caption">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edit_text_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:imeOptions="actionNext"
android:singleLine="true"
android:hint="Username" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/email_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/username_input_layout"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="16dp"
app:errorEnabled="true"
app:hintEnabled="true"
app:hintTextAppearance="@style/TextAppearance.MaterialComponents.Caption">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edit_text_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:maxLines="1"
android:imeOptions="actionNext"
android:singleLine="true"
android:hint="Email" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/password_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/email_input_layout"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="16dp"
app:errorEnabled="true"
app:hintEnabled="true"
app:hintTextAppearance="@style/TextAppearance.MaterialComponents.Caption"
app:endIconMode="password_toggle"
app:endIconTint="@color/black">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edit_text_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:maxLines="1"
android:imeOptions="actionNext"
android:singleLine="true"
android:hint="Password" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/password_confirm_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/password_input_layout"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="16dp"
app:errorEnabled="true"
app:hintEnabled="true"
app:hintTextAppearance="@style/TextAppearance.MaterialComponents.Caption"
app:endIconMode="password_toggle"
app:endIconTint="@color/black">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edit_text_password_confirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:maxLines="1"
android:imeOptions="actionDone"
android:singleLine="true"
android:hint="Confirm Password" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/button_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/password_confirm_input_layout"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="24dp"
android:text="Register" />
<TextView
android:id="@+id/register_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/button_register"
android:text="Already Registered? Login"
android:textSize="14sp"
android:gravity="center"
android:layout_marginTop="16dp"
android:textStyle="bold"
android:textColorLink="@color/primary"
android:autoLink="web"
android:textColor="@color/black"
android:linksClickable="true"
android:onClick="goToLoginPage" />
</RelativeLayout>
|
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
#define ERROR -1
typedef enum {false, true} bool;
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
List MakeEmpty();
Position Find( List L, ElementType X );
bool Insert( List L, ElementType X, Position P );
bool Delete( List L, Position P );
int main()
{
List L;
ElementType X;
Position P;
int N;
L = MakeEmpty();
scanf("%d", &N);
while ( N-- ) {
scanf("%d", &X);
if ( Insert(L, X, 0)==false )
printf(" Insertion Error: %d is not in.\n", X);
}
scanf("%d", &N);
while ( N-- ) {
scanf("%d", &X);
P = Find(L, X);
if ( P == ERROR )
printf("Finding Error: %d is not in.\n", X);
else
printf("%d is at position %d.\n", X, P);
}
scanf("%d", &N);
while ( N-- ) {
scanf("%d", &P);
if ( Delete(L, P)==false )
printf(" Deletion Error.\n");
if ( Insert(L, 0, P)==false )
printf(" Insertion Error: 0 is not in.\n");
}
return 0;
}
/* 你的代码将被嵌在这里 */
List MakeEmpty() {
List L = (List)malloc(sizeof(struct LNode));//sizeof(list)会导致答案错误--++
L->Last = -1;
return L;
}
Position Find( List L, ElementType X )
{
int i = 0;
for(i = 0; i<=L->Last; i++)
{
if(L->Data[i] == X)
return i;
}
return ERROR;
}
bool Insert( List L, ElementType X, Position P )
{
int i = 0;
if(L->Last == MAXSIZE-1)
{
printf("FULL");
return false;
}
if( P > L->Last+1 || P < 0 )
{
printf("ILLEGAL POSITION");
return false;
}
for(i = L->Last+1; i>P; i--)
{
L->Data[i] = L->Data[i-1];
}
L->Data[P] = X;
L->Last++;;
return true;
}
bool Delete( List L, Position P )
{
if( P < 0 || P > L->Last )
{
printf("POSITION %d EMPTY",P);
return false;
}
int i = 0;
for(i = P; i<L->Last; i++)
{
L->Data[i] = L->Data[i+1];
}
L->Last--;
return true;
}
|
import { Button, Card, CardActions, CardContent, Pagination, Typography } from '@mui/material'
import { useState } from 'react';
import SearchBar from './SearchBar';
import config from './data/config.json';
import { useEffect } from 'react';
const gameList = config.Games;
const GameList = ({ perPage=10 }) => {
const [ searchQuery, setSearchQuery ] = useState('');
const [ page, setPage ] = useState(1);
const [ items, setItems ] = useState([]);
useEffect(() => {
setItems(gameList
.filter((game) => {
if (searchQuery.length > 0) {
return game.Title.toLocaleLowerCase().includes(searchQuery.toLocaleLowerCase()) ||
game.Description.toLocaleLowerCase().includes(searchQuery.toLocaleLowerCase())
} else {
return true;
}
}));
}, [ page, perPage, searchQuery ])
const handleChange = (event, value) => {
setPage(value);
}
return (
<>
<SearchBar setSearchQuery={setSearchQuery} />
<Pagination count={Math.ceil(items.length/perPage)} color="primary" onChange={handleChange} />
{
items
.sort((a,b) => {
console.log( a.Updated >= b.Updated);
return a.Updated >= b.Updated;
})
.filter((game,idx) => {
return idx >= (page-1)*perPage && idx < ((page-1)*perPage)+perPage;
})
.map((game) => {
const { Title, Description, Published, Updated, URLId, BrowserPlayable} = game;
return (<Card key={Title} sx={{m: '3px', paddingLeft:'15px', paddingRight:'15px'}}>
<CardContent>
<Typography variant='body1'>{Title}</Typography>
<Typography variant='body1'>{Description}</Typography>
<Typography variant='body2'>Published: {Published === 0 ? '¯\\_(ツ)_/¯' : new Date(Published).toLocaleDateString()}</Typography>
<Typography variant='body2'>Updated: {Updated === 0 ? '¯\\_(ツ)_/¯' : new Date(Updated).toLocaleDateString()}</Typography>
</CardContent>
<CardActions>
<Button variant='outlined' color='secondary' href={`/#/game/${URLId}`}>View</Button>
</CardActions>
</Card>);
})
}
</>
)
}
export default GameList;
|
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5,}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{csquotes}
\MakeOuterQuote{"}
\usepackage{xcolor}
\usepackage{listings}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.98,0.99,0.97}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray},
stringstyle=\color{codepurple},
basicstyle=\ttfamily,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2
}
\lstset{style=mystyle}
\lstset{escapeinside={<@}{@>}}
\title{Verteidigung der Bachelorarbeit}
\subtitle{Ermittlung von Cacheeigenschaften für
ARM-Prozessorkerne}
\author{Felix Müller}
\date{\today}
\usetheme{Boadilla}
\usecolortheme{crane}
\setbeamertemplate{navigation symbols}{}
% Titel
\begin{document}
\begin{frame}
\titlepage
\end{frame}
% TOC
\begin{frame}{Inhaltsübersicht}
\tableofcontents
\end{frame}
\section{Einleitung}
\begin{frame}
Ziel: Ersetzungsstrategie des Level-1-Caches des Arm Cortex A53 experimentell bestimmen
\end{frame}
\begin{frame}
\end{frame}
\section{Grundlagen}
\begin{frame}
\frametitle{Inhaltsübersicht}
\tableofcontents[currentsection]
\end{frame}
\subsection{Caches}
\begin{frame}
\end{frame}
\subsection{WCET-Analyse}
\begin{frame}
\end{frame}
\subsection{Vorarbeiten}
\begin{frame}
\end{frame}
\section{Latenzmessung}
\begin{frame}
\frametitle{Inhaltsübersicht}
\tableofcontents[currentsection]
\end{frame}
\subsection{Cycle Count Register}
\begin{frame}
\frametitle{Cycle Count Register}
\begin{itemize}
\item Performance Monitor Unit bietet Register \texttt{PMCCNTR\_EL0}
\item analog zu \textit{Time Stamp Counter} der \texttt{x86}\,-Familie
\item Zugriff muss aktiviert werden\footnote{\tiny Arm. Arm Cortex -A53 MPCore Processor Technical Reference Manual. 2014. S.71}
\item \texttt{mrs <register>, pmccntr\_el0}
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Code Latenzmessung}
\begin{figure}
\centering
\begin{lstlisting}[language=C]
asm volatile("mrs %0, pmccntr_el0" : "=r"(start));
zu vermessende LOAD-Instruktion
asm volatile("mrs %0, pmccntr_el0" : "=r"(dur));
dur -= start;
\end{lstlisting}
\caption{C-Code zum zweimaligen Auslesen des \textsl{CCR}}
\end{figure}
\end{frame}
\begin{frame}[fragile]
\frametitle{Code Latenzmessung 2}
\begin{figure}
\begin{lstlisting}[language=C]
isb();
asm volatile("mrs %0, pmccntr\el0" : "=r"(start));
zu vermessende LOAD-Instruktion
asm volatile("dmb ld");
asm volatile("mrs %0, pmccntr_el0" : "=r"(dur));
dur -= start;
\end{lstlisting}
\caption{C-Code zum zweimaligen Auslesen des \textsl{CCR}}
\end{figure}
\begin{enumerate}
\item \texttt{isb}
\item \texttt{dmb ld}
\end{enumerate}
\end{frame}
\subsection{Beinflussung der Messung}
\begin{frame}
\frametitle{Beinflussung der Messung}
\begin{columns}[c]
\column {0.5\textwidth}
\begin{itemize}
\item Instruction Reordering
\item Dual Issue Pipeline
\item Unterbrechung
\item nicht-blockierender Cache
\end{itemize}
\column {0.5\textwidth}
\end{columns}
\end{frame}
\begin{frame}
\frametitle{Beinflussung der Messung}
\begin{columns}[c]
\column {0.45\textwidth}
\begin{itemize}
\item Instruction Reordering
\item Dual Issue Pipeline
\item Unterbrechung
\item nicht-blockierender Cache
\end{itemize}
\column {0.55\textwidth}
\begin{itemize}
\item[$\rightarrow$] \textcolor{black!50!green}{In-Order Pipeline}
\item[$\rightarrow$] \textcolor{black!50!green}{Instruction Synchronization Barrier}
\item[$\rightarrow$] \textcolor{black!50!green}{Unterbrechung verhindern}
\item[$\rightarrow$] \textcolor{black!50!green}{Date Memory Barrier}
\end{itemize}
\end{columns}
\end{frame}
\begin{frame}
\frametitle{Beinflussung der Messung: Instruction Synchronization Barrier}
\begin{itemize}
\item \textit{ISB} führt zum Leeren der \textit{Pipeline}
\item dadurch Verhalten bzgl. \textit{Dual-Issue} identisch
\item Messwerte sind vergleichbar und geeignet Cachezustand zu bestimmen
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Beinflussung der Messung: Unterbrechung verhindern}
\begin{itemize}
\item Implementierung als Kernelmodul
\item Spinlock mit Interruptsperre
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Beinflussung der Messung: Data Memory Barrier}
\begin{itemize}
\item Zugriffslatenzen sollen kaschiert werden
\item Abarbeitung von Instruktionen, die semantisch nicht von Daten vorheriger \texttt{load}-Instruktionen abhängen
\item Verhalten des Arm Cortex A53 nicht bekannt
\item \textit{Data Memory Barrier} blockiert Abarbeitung bis Speicheroperartion abgeschlossen
\end{itemize}
\end{frame}
\subsection{Inferenz des Cachszustands}
\begin{frame}
\frametitle{Inferenz des Cachszustands}
\begin{itemize}
\item Messung dauert \textbf{4 Zyklen ohne Zugriff}
\item Zugriffslatenz u.\,d.\,B. Cache-Hit: \textbf{3 Zyklen}\footnote{\tiny Arm. Arm Cortex -A53 MPCore Processor Technical Reference Manual. 2014. S.18.}
\item ab $8$ Zyklen ist von Cache-Miss auszugehen
\item \textbf{Heuristik} $f_{\textrm{Hit}}: \mathbb{N} \rightarrow \mathbb{B}$
\begin{equation}
f_{\textrm{Hit}} (t) =
\begin{cases}
0 & \textrm{wenn } t > 7\\
1 & \textrm{sonst}
\end{cases}
\end{equation}
\end{itemize}
\end{frame}
\section{Bestimmung der Kapazität}
\begin{frame}
\frametitle{Inhaltsübersicht}
\tableofcontents[currentsection]
\end{frame}
\subsection{Idee}
\begin{frame}
\frametitle{Idee zur Bestimmung der Kapazität}
\begin{itemize}
\item Level-1-Datencache kann Werte \textbf{8, 16, 32 oder 64 $\textrm{kiB}$} haben
\item Zugriffssequenz aufsteigender Adressen $M_0 \dots M_a$
\item erstmalige Durchführung: \textbf{Cache wird gefüllt}
\item nochmalige Durchführung mit \textbf{Vermessung}
\end{itemize}
\end{frame}
\subsection{Implementierung}
\begin{frame}
\frametitle{Implementierung}
\begin{itemize}
\item Level-1-Datencache ist \textbf{physisch adressiert}
\item Zugriffe müssen auf physisch aufsteigende Adressen erfolgen
\item außreichende Menge \textbf{physisch zusammenhängender Speicher}
\item \texttt{\_\_get\_free\_pages (gfp\_t gfp\_mask, unsigned int order)} alloziert $2^{\textrm{order}}$ Hauptspeicherseiten (à $4096 \,\textrm{kiB}$)
\item [\textbf{$\rightarrow$}] \textbf{Kernelmodul}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Implementierung 2}
\begin{itemize}
\item Prefetcher erkennt Sequenzen mit Versatz bis $256 \,\textrm{kiB}$
\item Zugriffe des Programms fallen darunter
\item Messung könnte durch Prefetching verfälscht werden
\item automatisches Prefetching deaktivieren\footnote{\tiny Arm. Arm Cortex -A53 MPCore Processor Technical Reference Manual. 2014. S.180.}
\end{itemize}
\end{frame}
\subsection{Ergebnisse}
\begin{frame}
\begin{figure}[h]
\begin{tikzpicture}[scale=0.67]
\pgfplotsset{
width=16cm,
xmin=0.5,
xmax=40.5,
xlabel=angenommene Cachekapazität in $\textrm{kiB}$,
grid style=dashed,
xmajorgrids=true,
xminorgrids=true
}
\begin{axis}[
axis y line*=left,
ymin=0, ymax=0.25,
ylabel=Anzahl Cache-Misses pro Cacheline ,
legend pos=north west,
ymajorgrids=true,
yminorgrids=true
]
\addplot +[thick,mark=none,black!50!red] coordinates {(32, 0) (32, 0.25)};
\addplot[very thick,mark=x,blue,only marks]
coordinates{
(1,0 ) (2,0 ) (3,0 ) (4,0 ) (5,0 ) (6,0 ) (7,0 ) (8,0 ) (9,0 )
(10,0 )(11,0 )(12,0 )(13,0 )(14,0 )(15,0 )(16,0 )
(17,0.0037) (18,0.0069) (19,0.0066)
(20,0.0031) (21,0.0030) (22,0.0057)
(23,0.0082) (24,0.0156) (25,0.0200)
(26,0.0216) (27,0.0255) (28,0.0335)
(29,0.0366) (30,0.0458) (31,0.0403)
(32,0.0469) (33,0.0758) (34,0.1048)
(35,0.1054) (36,0.1406) (37,0.1351)
(38,0.1793) (39,0.2308) (40,0.2438)
};\legend{Cache-Misses pro Cacheline}
\end{axis}
\end{tikzpicture}
\end{figure}
\end{frame}
\section{Bestimmung der Ersetzungsstrategie}
\begin{frame}
\end{frame}
\section{Zusammenfassung \& Ausblick}
\begin{frame}
\end{frame}
\end{document}
|
<?php
/*
* Plugin Name: Contact Management AuthLab
* Description: This is a Contact Management System
* Plugin URI: https://sample.com/contact-management
* Author: Bipul Karmokar
* Author URI: https://bipul.com
* Version: 1.0.0
* Requires at least: 6.3.2
* Requires PHP: 7.4
*/
define("CONTACT_PLUGIN_PATH", plugin_dir_path(__FILE__));
define("CONTACT_PLUGIN_URL", plugin_dir_url(__FILE__));
// Calling action hook to add menu
add_action("admin_menu","cp_add_admin_menu");
//Add Menu
function cp_add_admin_menu()
{
add_menu_page("Contact | Contact Management AuthLab", "Contact", "manage_options",
"contact-management", "contact_manage_system", "dashicons-phone", 23);
//Sub Menus
add_submenu_page("contact-management", "Create Contact", "Create Contact",
"manage_options", "contact-management", "contact_manage_system");
add_submenu_page("contact-management", "Contact List", "Contact List",
"manage_options", "list-contact","list_contact");
}
//Menu Handle Callback
function contact_manage_system()
{
include_once(CONTACT_PLUGIN_PATH."pages/create-contact.php");
}
// Submenu callback function
function list_contact()
{
include_once(CONTACT_PLUGIN_PATH."pages/contact-list.php");
}
register_activation_hook(__FILE__,"ems_create_table");
function ems_create_table()
{
global $wpdb;
$table_prefix=$wpdb->prefix;
$sql="
CREATE TABLE {$table_prefix}ems_form_data (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(120) DEFAULT NULL,
`phoneNo` varchar(50) DEFAULT NULL,
`email` varchar(80) DEFAULT NULL,
`gender` enum('male','female','other','') DEFAULT NULL,
`designation` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
";
include_once ABSPATH. "wp-admin/includes/upgrade.php";
dbDelta($sql);
$pageData = [
"post_title" => "Contact Management System Page",
"post_status" => "publish",
"post_type" => "page",
"post_content" => "This is a sample content",
"post_name" => "contact-management-system-page"
];
wp_insert_post($pageData);
}
register_deactivation_hook(__FILE__,"ems_drop_table");
function ems_drop_table()
{
global $wpdb;
$table_prefix = $wpdb->prefix;
$sql = "DROP TABLE IF EXISTS {$table_prefix}ems_form_data";
$wpdb->query($sql);
// Drop WordPress Page
$pageSlug = "contact-management-system-page";
$pageInfo = get_page_by_path($pageSlug);
if(!empty($pageInfo)){
$pageId = $pageInfo->ID;
wp_delete_post($pageId, true);
}
}
add_action("admin_enqueue_scripts", "ems_add_plugin_assests");
function ems_add_plugin_assests()
{
// CSS
wp_enqueue_style("ems-bootstrap-css", CONTACT_PLUGIN_URL . "css/bootstrap.min.css", array(), "1.0.0", "all");
wp_enqueue_style("ems-datatable-css", CONTACT_PLUGIN_URL . "css/dataTables.dataTables.min.css", array(), "1.0.0", "all");
wp_enqueue_style("ems-custom-css", CONTACT_PLUGIN_URL . "css/custom.css", array(), "1.0.0", "all");
// JS
wp_enqueue_script("ems-bootstrap-js", CONTACT_PLUGIN_URL . "js/bootstrap.min.js", array("jquery"), "1.0.0");
wp_enqueue_script("ems-datatable-js", CONTACT_PLUGIN_URL . "js/dataTables.min.js", array("jquery"), "1.0.0");
wp_enqueue_script("ems-custom-js", CONTACT_PLUGIN_URL . "js/custom.js", array("jquery"), "1.0.0");
// Enqueue wp_remote_get for custom.js
$response = wp_remote_get(CONTACT_PLUGIN_URL . "js/custom.js");
if (!is_wp_error($response)) {
$body = wp_remote_retrieve_body($response);
// Enqueue custom.js content
wp_add_inline_script("ems-custom-js", $body);
} else {
// Handle wp_remote_get error
error_log("Failed to fetch custom.js: " . $response->get_error_message());
}
// Enqueue jQuery Validate
wp_enqueue_script("ems-validate-js", CONTACT_PLUGIN_URL . "js/jquery.validate.min.js", array("jquery"), "1.0.0");
}
|
{% load i18n %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>
{% block head_title %}
{% endblock %}
</title>
{% block extra_head %}
{% endblock %}
{% load static %}
<link rel="stylesheet" href="{% static 'account/auth.css' %}" />
</head>
<body>
{% block body %}
{% if messages %}
<div>
<strong>{% trans 'Messages:' %}</strong>
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<div>
<strong>{% trans 'Menu:' %}</strong>
<ul>
{% if user.is_authenticated %}
<li>
<a href="{% url 'account_email' %}">{% trans 'Change Email' %}</a>
</li>
<li>
<a href="{% url 'account_logout' %}">{% trans 'Sign Out' %}</a>
</li>
{% else %}
<li>
<a href="{% url 'account_login' %}">{% trans 'Sign In' %}</a>
</li>
<li>
<a href="{% url 'account_signup' %}">{% trans 'Sign Up' %}</a>
</li>
{% endif %}
</ul>
</div>
{% block content %}
{% endblock %}
{% endblock %}
{% block extra_body %}
{% endblock %}
</body>
</html>
|
/*📌 Las promesas son estructuras que nosotros vamos a poder definir, para decirle al navegador, que queremos que espere a que nosotros terminemos de hacer una operación y que cuando termine le vamos a dar esos datos. */
const promesa = new Promise((resolve, reject) => {
//Accion que se Realizará.
setTimeout(() => {
const exito = false;
if (exito) {
resolve('La operación tuvo exito');
} else {
reject('La operación no tuvo éxito');
}
}, 4000);
});
//para decirle al navegador que se qude atento a mi respuesta
promesa.then((mensaje) => {
alert(mensaje);
});
//En caso de que haya algún error en la promesa usamos catch
promesa.catch((mensaje) => {
alert(mensaje);
});
|
package cn.edu.pku.treehole.base
import cn.edu.pku.treehole.api.DataState
import cn.edu.pku.treehole.api.HoleApiResponse
import cn.edu.pku.treehole.base.network.ApiException
import cn.edu.pku.treehole.base.network.ResultState
import cn.edu.pku.treehole.base.network.StateLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.*
import timber.log.Timber
import java.io.IOException
import java.net.ConnectException
import java.net.UnknownHostException
/**
*
* @Time: 2021/12/28
* @Desc:
* @Version: 1.0
*/
open class BaseRepository {
/**
* 方式二:结合Flow请求数据。
* 根据Flow的不同请求状态,如onStart、onEmpty、onCompletion等设置baseResp.dataState状态值,
* 最后通过stateLiveData分发给UI层。
*
* @param block api的请求方法
* @param stateLiveData 每个请求传入相应的LiveData,主要负责网络状态的监听
*/
suspend fun <T : Any> executeReqWithFlow(
block: suspend () -> HoleApiResponse<T>,
stateLiveData: StateLiveData<T>
) {
var holeApiResponse = HoleApiResponse<T>()
flow {
val respResult = block.invoke()
holeApiResponse = respResult
Timber.d("executeReqWithFlow: $holeApiResponse")
holeApiResponse.dataState = DataState.STATE_SUCCESS
stateLiveData.postValue(holeApiResponse)
emit(respResult)
}
.flowOn(Dispatchers.IO)
.onStart {
Timber.d("executeReqWithFlow:onStart")
holeApiResponse.dataState = DataState.STATE_LOADING
stateLiveData.postValue(holeApiResponse)
}
.onEmpty {
Timber.d("executeReqWithFlow:onEmpty")
holeApiResponse.dataState = DataState.STATE_EMPTY
stateLiveData.postValue(holeApiResponse)
}
.catch { exception ->
run {
Timber.d("executeReqWithFlow:code ${holeApiResponse.code}")
exception.printStackTrace()
holeApiResponse.dataState = DataState.STATE_ERROR
holeApiResponse.error = exception
stateLiveData.postValue(holeApiResponse)
}
}
.collect {
Timber.d( "executeReqWithFlow: collect")
stateLiveData.postValue(holeApiResponse)
}
}
/**
* 方式一
* repo 请求数据的公共方法,
* 在不同状态下先设置 baseResp.dataState的值,最后将dataState 的状态通知给UI
* @param block api的请求方法
* @param stateLiveData 每个请求传入相应的LiveData,主要负责网络状态的监听
*/
suspend fun <T : Any> executeResp(
block: suspend () -> HoleApiResponse<T>,
stateLiveData: StateLiveData<T>
) : HoleApiResponse<T> {
var holeApiResponse = HoleApiResponse<T>()
try {
holeApiResponse.dataState = DataState.STATE_LOADING
//开始请求数据
val invoke = block.invoke()
//将结果复制给baseResp
holeApiResponse = invoke
if (holeApiResponse.code == 0) {
//请求成功,判断数据是否为空,
//因为数据有多种类型,需要自己设置类型进行判断
if (holeApiResponse.data == null || holeApiResponse.data is List<*> && (holeApiResponse.data as List<*>).size == 0) {
//TODO: 数据为空,结构变化时需要修改判空条件
holeApiResponse.dataState = DataState.STATE_EMPTY
} else {
//请求成功并且数据不为空的情况下,为STATE_SUCCESS
holeApiResponse.dataState = DataState.STATE_SUCCESS
}
} else {
//服务器请求错误,分析不同的情况
holeApiResponse.dataState = DataState.STATE_FAILED
}
} catch (e: Exception) {
//非后台返回错误,捕获到的异常
holeApiResponse.dataState = DataState.STATE_ERROR
holeApiResponse.error = e
} finally {
stateLiveData.postValue(holeApiResponse)
}
return holeApiResponse
}
/**
* @deprecated Use {@link executeResp} instead.
*/
suspend fun <T : Any> executeResp(
resp: HoleApiResponse<T>,
successBlock: (suspend CoroutineScope.() -> Unit)? = null,
errorBlock: (suspend CoroutineScope.() -> Unit)? = null
): ResultState<T> {
return coroutineScope {
if (resp.code == 0) {
successBlock?.let { it() }
ResultState.Success(resp.data!!)
} else {
Timber.d( "executeResp: error")
errorBlock?.let { it() }
ResultState.Error(IOException(resp.msg))
}
}
}
/**
* 带返回值的单个请求
*/
suspend inline fun <reified T: Any> launchRequest(
crossinline block : suspend () -> HoleApiResponse<T?>
): HoleApiResponse<T?> {
return try {
block()
} catch (e: Exception){
if(e.message?.contains("401") == true){
Timber.e("error exception: %s", e.message)
throw ApiException(401, "Unauthorized")
}else{
when(e){
is UnknownHostException -> Timber.e(e)
is ConnectException -> Timber.e(e)
else -> Timber.e(e)
}
throw e
}
}.run {
// if(code == 0){
if(code == 0 || code == 20000){
this
}else{
throw ApiException(code, msg)
}
}
}
/**
* 带返回值的单个请求
*/
suspend inline fun <reified T: Any> launchRequestPic(
crossinline block : suspend () -> HoleApiResponse<T?>
): HoleApiResponse<T?> {
return try {
block()
} catch (e: Exception){
if(e.message?.contains("401") == true){
Timber.e("error exception: %s", e.message)
throw ApiException(401, "Unauthorized")
}else{
when(e){
is UnknownHostException -> Timber.e(e)
is ConnectException -> Timber.e(e)
else -> Timber.e(e)
}
throw e
}
}.run {
// if(code == 0){
if(code == 0 || code == 20000 || code == 40001){
this
}else{
throw ApiException(code, msg)
}
}
}
}
|
//Palindrome Partitioning
//Given a string s, partition s such that every substring of the partition is a palindrome.
//Return all possible palindrome partitioning of s.
//For example, given s = "aab",
//Return
// [
// ["aa","b"],
// ["a","a","b"]
// ]
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
if(s==null) return res;
ArrayList<String> item = new ArrayList<String>();
helper(res,item,0,s);
return res;
}
private boolean isPalindrom(String s){
int p = 0;
int q = s.length()-1;
while(p<q){
if(s.charAt(p)!=s.charAt(q)) return false;
p++;
q--;
}
return true;
}
private void helper(ArrayList<ArrayList<String>> res,ArrayList<String> item,int pos,String s){
if(pos==s.length()){
res.add(new ArrayList<String>(item));
return;
}
for(int i = pos+1;i<=s.length();i++){
String prefix = s.substring(pos,i);
if(!isPalindrom(prefix)){
continue;
}
item.add(prefix);
helper(res,item,i,s);
item.remove(item.size()-1);
}
}
}
|
@use '@angular/material' as mat;
@import './fonts';
$custom-typography: mat.define-typography-config(
$font-family: 'Nunito'
);
// Override typography CSS classes (e.g., mat-h1, mat-display-1, mat-typography, etc.).
@include mat.typography-hierarchy($custom-typography);
// Override typography for a specific Angular Material components.
@include mat.checkbox-typography($custom-typography);
// Override typography for all Angular Material, including mat-base-typography and all components.
@include mat.all-component-typographies($custom-typography);
@include mat.core($custom-typography);
// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue.
$primary: mat.define-palette(mat.$purple-palette);
$accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);
// The warn palette is optional (defaults to red).
$warn: mat.define-palette(mat.$red-palette);
// Create the theme object (a Sass map containing all of the palettes).
$theme: mat.define-light-theme($primary, $accent, $warn);
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include mat.all-component-themes($theme);
|
import type { TodoItem } from "@prisma/client";
import { signIn, signOut, useSession } from "next-auth/react";
import { useState } from "react";
import { trpc } from "../utils/trpc";
const TodosList = () => {
const { data: todos, isLoading } = trpc.todoItem.getAll.useQuery();
if (isLoading) return <div>Fetching todos...</div>;
return (
<div className="flex flex-col gap-4">
{todos?.map((todo, index) => {
return (
<Todo key={index} index={index} todo={todo} />
);
})}
</div>
);
};
const Form = () => {
const [todo, setTodo] = useState("");
const utils = trpc.useContext();
const postTodo = trpc.todoItem.postTodo.useMutation({
onSettled: () => {
utils.todoItem.getAll.invalidate();
},
});
return (
<form
className="flex gap-2"
onSubmit={(event) => {
event.preventDefault();
postTodo.mutate({
name: todo,
});
setTodo("");
}}
>
<input
type="text"
value={todo}
placeholder="Your todo..."
minLength={2}
maxLength={100}
onChange={(event) => setTodo(event.target.value)}
className="rounded-md border-2 border-zinc-800 bg-neutral-900 px-4 py-2 focus:outline-none"
/>
<button
type="submit"
className="rounded-md border-2 border-zinc-800 p-2 focus:outline-none"
>
Submit
</button>
</form>
);
};
const Home = () => {
const { data: session, status } = useSession();
if (status === "loading") {
return <main className="flex flex-col items-center pt-4">Loading...</main>;
}
return (
<main className="flex flex-col items-center">
<h1 className="pt-4 text-3xl">Guestbook</h1>
<p>
Tutorial for <code>create-t3-app</code>
</p>
<div className="pt-10">
<div>
{session ? (
<>
<p>hi {session.user?.name}</p>
<button onClick={() => signOut()}>Logout</button>
<div className="pt-6">
<Form />
</div>
</>
) : (
<button onClick={() => signIn("discord")}>
Login with Discord
</button>
)}
<div className="pt-10">
<TodosList />
</div>
</div>
</div>
</main>
);
};
export default Home;
interface TodoProps {
index: number;
todo: TodoItem;
}
const Todo = ({index, todo}: TodoProps) => {
const [isChecked, setIsChecked] = useState(todo.done);
const utils = trpc.useContext();
const completeTodo = trpc.todoItem.completeTodo.useMutation({
onSettled: () => {
utils.todoItem.getAll.invalidate();
},
});
const deleteTodo = trpc.todoItem.deleteTodo.useMutation({
onSettled: () => {
utils.todoItem.getAll.invalidate();
},
});
return (
<div key={index} className="form-control">
<label className="flex space-x-4 label cursor-pointer">
<input onClick={() => {
setIsChecked(!isChecked);
completeTodo.mutate({ id: todo.id, done: !todo.done });
}}
type="checkbox" checked={isChecked} className="flex-none checkbox checkbox-primary" />
<span className="flex-initial label-text w-64">{todo.name}</span>
<button onClick={() => {
deleteTodo.mutate({id: todo.id});
}}
className="btn btn-square btn-outline h-4 w-12">
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</label>
</div>
);
}
|
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from django.utils.html import format_html
from django.utils.safestring import SafeString
from urllib.parse import urlsplit
from .enums import SocialNetWorkEnum
class SocialNetworkValidator(URLValidator):
DOMAINS: set = SocialNetWorkEnum.get_values()
def __call__(self, value) -> None:
super().__call__(value)
parse = urlsplit(value)
self.message = self._generate_message()
# if domain is invalid or path is empty
if (parse.netloc not in self.DOMAINS) or (
parse.path.replace("/", "").strip() == ""
):
raise ValidationError(self.message, code=self.code, params={"value": value})
def _generate_message(self) -> SafeString:
array_of_networks: list = [net.name for net in SocialNetWorkEnum]
networks: str = ", ".join(array_of_networks)
message: str = f"<p style='background-color: red;'>ENTER URL OF FOLLOWING NETWORKS: {networks}\n</p>"
return format_html(message)
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
request.setAttribute("path",path);
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<nav class="navbar navbar-default navigator">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand logo" href="${path}/home/goHome.shtml"><img src="${path}/static/img/logo_demo.jpg" alt="留学慧"></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav nav-content">
<li><a href="${path}/home/goHome.shtml">首页</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">咨询<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="${path}/jigou/more.shtml?pageNo=1">留学机构</a></li>
<li><a href="${path}/guwen/more.shtml?pageNo=1">留学顾问</a></li>
<li><a href="${path}/wenan/more.shtml?pageNo=1">金牌文案</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">培训<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="${path}/xuexiao/more.shtml?pageNo=1">学校</a></li>
<li><a href="${path}/mingshi/more.shtml?pageNo=1">名师</a></li>
</ul>
</li>
<li><a href="${path}/student/more.shtml?pageNo=1">成功案例</a></li>
<li><a href="${path}/view/zaiXianCePing.jsp">在线测评</a></li>
<li><a href="${path}/kecheng/more.shtml?pageNo=1">特色课程</a></li>
</ul>
<c:if test="${userSession==null}">
<!-- 未登录是显示 -->
<ul class="nav navbar-nav navbar-right">
<a href="${path}/user/loginOrReg.shtml"><button type="button" class="btn btn-success navbar-btn"> 登录 </button></a>
<a href="${path}/user/loginOrReg.shtml"><button type="button" class="btn btn-info navbar-btn"> 注册 </button></a>
</ul>
</c:if>
<c:if test="${userSession!=null}">
<!-- 登录时显示 -->
<ul class="nav navbar-nav navbar-right text-center nav_touxiang">
<li><a href="${path}/member/user.shtml">
<c:if test="${userSession.touxiang!=null}">
<img src="${path}/static/uploadImg/user/${userSession.touxiang}">
</c:if>
<c:if test="${userSession.touxiang==null}">
<img src="${context}/static/img/touxiang.jpg">
</c:if>
${userSession.mobilephone}
</a>
</li>
</ul>
</c:if>
</div>
</div>
</nav>
|
import React, { lazy, Suspense } from 'react';
import { NavLink, Route, Routes } from 'react-router-dom';
import { Loader } from './Loader/Loader';
const Movies = lazy(() => import('../pages/Movies/Movies'));
const Home = lazy(() => import('../pages/Home/Home'));
const MovieDetails = lazy(() => import('../pages/MovieDetails/MovieDetails'));
const Reviews = lazy(() => import('components/Reviews/Reviews'));
const Cast = lazy(() => import('components/Cast/Cast'));
export const App = () => {
return (
<div>
<header className="header">
<nav>
<NavLink className="navlink" to="/">
Home
</NavLink>
<NavLink className="navlink" to="/movies">
Movie
</NavLink>
</nav>
</header>
<Suspense fallback={<Loader />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/movies/:movieId/" element={<MovieDetails />}>
<Route path="cast" element={<Cast />} />
<Route path="reviews" element={<Reviews />} />
</Route>
<Route path="/movies" element={<Movies />} />
<Route path="*" element={<Home />} />
</Routes>
</Suspense>
</div>
);
};
|
import type { NextPage } from "next";
import { trpc } from "../../utils/trpc";
const GetAll: NextPage = () => {
const slugs = trpc.useQuery(["all"], {
refetchOnReconnect: false, // replacement for enable: false which isn't respected.
refetchOnMount: false,
refetchOnWindowFocus: false,
});
if (slugs.isLoading || slugs.isIdle) {
return <h1>Loading...</h1>;
}
if (slugs.error) {
if (slugs.error) {
return <p>{slugs.error.message}</p>;
}
}
return (
<div className="flex flex-col justify-center sm:w-2/3 md:w-1/2 lg:w-1/3">
<table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
<thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
<th scope="col" className="py-3 px-6">
URL
</th>
<th scope="col" className="py-3 px-6">
Shortcut
</th>
<th scope="col" className="py-3 px-6">
Created At
</th>
</tr>
</thead>
<tbody>
{slugs.data.map(slug => {
return (
<tr key={slug.id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<td className="py-4 px-6">{slug.url}</td>
<td className="py-4 px-6 text-blue-600"><a href={`/${slug.slug}`}>{slug.slug}</a> </td>
<td className="py-4 px-6">{new Date(slug.createdAt).toDateString()}</td>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
export default GetAll
|
package br.uel.combustivel;
import java.util.ArrayList;
import java.util.Scanner;
public class Bomba {
private int numeroId;
public ArrayList<Combustivel> getCombustiveis() {
return combustiveis;
}
public void setCombustiveis(ArrayList<Combustivel> combustiveis) {
this.combustiveis = combustiveis;
}
private ArrayList<Combustivel> combustiveis = new ArrayList<>();
public int getNumeroId() {
return numeroId;
}
public void setNumeroId(int numeroId) {
this.numeroId = numeroId;
}
public void addCombustivel(String nome, double preco) {
Combustivel novoCombustivel = new Combustivel(nome, preco);
this.combustiveis.add(novoCombustivel);
}
public void selectCombustivel(String nome, Scanner input) {
int opcao;
double qntLitro;
double qntDinheiro;
int flag = 0;
for(Combustivel combustivel : combustiveis) {
if(nome.equals(combustivel.getNomeCombustivel())) {
flag = 1;
do {
System.out.println("O preço do combustível "+ combustivel.getNomeCombustivel()+ " é "+ combustivel.getPreco());
System.out.println("Escolha uma opção: ");
System.out.println("1) Inserir por litro");
System.out.println("2) Inserir por dinheiro");
System.out.println("3) Sair");
opcao = input.nextInt();
input.nextLine();
switch(opcao) {
case 1:
System.out.println("Insira a quantidade de litros: ");
qntLitro = Double.parseDouble(input.nextLine());
combustivel.absLitro(qntLitro);
System.out.println("Digite (3) para voltar ou (0) para abastecer novamente");
opcao = Integer.parseInt(input.nextLine());
break;
case 2:
System.out.println("Insira a quantidade de dinheiro: ");
qntDinheiro = Double.parseDouble(input.nextLine());
combustivel.absDin(qntDinheiro);
System.out.println("Digite (3) para voltar ou (0) para abastecer novamente");
opcao = Integer.parseInt(input.nextLine());
break;
case 3:
break;
}
} while(opcao != 3);
break;
}
}
if(flag == 0) {
System.out.println("O combustivel " +nome +" não foi encontrada");
}
}
}
|
export interface registrationData {
memberId: string;
memberType: string;
permission: string;
password: string;
contact: string;
landline: string;
email: string;
address: string;
company: string;
}
export interface ProductForm {
productName: string;
productCategory: string;
productSubCategory: string;
officialPrice: number;
vendorSalesName: string;
vendorSalesContact: string;
vendorSalesEmail: string;
comment: string;
}
export interface useInputType {
state: any;
action: any;
}
export interface loginForm {
email: string;
password: string;
}
export interface IRegistrationForm {
id?: string;
username: string;
userFullName: string;
userType: string;
privileges: string[];
password: string;
confirmPassword: string;
email: string;
mobile: string;
phone: string;
addr: string;
addrDetail: string;
zipcode: string;
memberNo: string;
memberName: string;
salesName: string;
admin: string;
activated: string;
regId: string;
regName: string;
regDt: string;
}
export interface ICustomersAddPerForm {
id?: string;
userId: string;
name: string;
dept: string;
email: string;
phoneNo: string;
mobileNo: string;
comment: string;
}
interface ICustomersAddrForm {
id?: string | undefined;
name: string;
zipcode: string;
addr: string;
addrDetail: string;
homepage: string;
}
interface ICustomersCustContactForm {
id?: string;
dept: string;
name: string;
mobileNo: string;
email: string;
comment: string;
}
interface ICustomersSalesForm {
dept: string;
userId: string;
name: string;
phoneNo: string;
email: string;
comment: string;
}
export interface ICustomersForm {
id: string;
memberNo: string;
memberName: string;
regionType: string;
memberType: string;
industry: string;
businessRegNo: string;
custCeo: string;
custPhone: string;
comment: string;
custContact: ICustomersCustContactForm[];
sales: ICustomersSalesForm;
address: ICustomersAddrForm[];
}
|
using System.Diagnostics;
using NiceIO;
using ResetCore.Common;
namespace ReBuildTool.Service.Global;
public class Shell : IDisposable
{
public enum Status
{
Waiting,
Running,
Finished
}
public static Shell Create()
{
return new Shell();
}
private Shell()
{
CurrentStatus = Status.Waiting;
}
public Shell WithProgram(NPath program)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
Program = program;
return this;
}
public Shell WithProgram(string program)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
Program = program;
return this;
}
public Shell WithEnvVars(Dictionary<string, string> envVars)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
EnvVars.AddRange(envVars);
return this;
}
public Shell WithEnvVars(string key, string value)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
EnvVars.Add(key, value);
return this;
}
public Shell WithArguments(IEnumerable<string> arguments)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
Arguments.AddRange(arguments);
return this;
}
public Shell AppendArgument(string argument)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
Arguments.Add(argument);
return this;
}
public Shell AppendArgumentPair(string key, string value)
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
AppendArgument(key);
AppendArgument(value);
return this;
}
public Shell Execute()
{
if (CurrentStatus != Status.Waiting)
{
throw new Exception("Shell is already running or finished.");
}
if (Process != null)
{
Process.Dispose();
Process = null;
}
Process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = Program.ToString();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.CreateNoWindow = true;
startInfo.Arguments = string.Join(' ', Arguments);
foreach (var (key, value) in EnvVars)
{
startInfo.Environment.Add(key, value);
}
Process.StartInfo = startInfo;
Process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
Log.Info(args.Data);
}
};
Process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
Log.Error(args.Data);
}
};
Process.Exited += (sender, args) =>
{
CurrentStatus = Status.Finished;
var result = Process.StandardOutput.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
if (!IsSuccess())
{
Log.Error(result);
}
else
{
Log.Info(result);
}
}
if (!IsSuccess())
{
var errorInfo = Process.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
Log.Error(errorInfo);
}
}
};
Process.Start();
CurrentStatus = Status.Running;
return this;
}
public Shell WaitForEnd()
{
if (CurrentStatus != Status.Running)
{
throw new Exception("Shell is not running.");
}
if (Process != null)
{
Process.WaitForExit();
CurrentStatus = Status.Finished;
}
return this;
}
public bool IsSuccess()
{
if (CurrentStatus != Status.Finished)
{
throw new Exception("Shell is not finished.");
}
if (Process != null)
{
if (!Process.HasExited)
{
return false;
}
return Process.ExitCode == 0;
}
return false;
}
public string Program { get; private set; }
public List<string> Arguments { get; private set; } = new List<string>();
public Process? Process { get; private set; }
public Status CurrentStatus { get; private set; }
public Dictionary<string, string> EnvVars { get; } = new();
public void Dispose()
{
Process?.Dispose();
}
}
|
package org.management_company.db.services;
import jakarta.validation.ConstraintViolationException;
import org.junit.jupiter.api.Test;
import org.management_company.db.TestUtils;
import org.management_company.db.domain.entities.*;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
public class ValidationServiceTest {
@Test
void testValidateAddress_Good() {
Address address = TestUtils.createAddress();
assertDoesNotThrow(() -> ValidationService.validateEntity(address));
}
@Test
void testValidateAddress_Bad() {
Address address = TestUtils.createAddress();
address.setStreet(null);
assertThrows(ConstraintViolationException.class, () -> {
ValidationService.validateEntity(address);
});
}
@Test
void testValidateClient_Good() {
Client client = TestUtils.createClient();
assertDoesNotThrow(() -> ValidationService.validateEntity(client));
}
@Test
void testValidateClient_Bad() {
Client client = TestUtils.createClient();
client.setEmail(null);
assertThrows(ConstraintViolationException.class, () -> {
ValidationService.validateEntity(client);
});
}
@Test
void testValidateRequest_Good() {
Address address = TestUtils.createAddress();
Client client = TestUtils.createClient();
Specialization specialization = TestUtils.createSpecialization();
Staff staff = TestUtils.createStaff(specialization);
Request request = TestUtils.createRequest(client, address, specialization, staff);
assertDoesNotThrow(() -> ValidationService.validateEntity(request));
}
@Test
void testValidateRequest_Bad() {
Request request = TestUtils.createHalfRequest();
assertThrows(ConstraintViolationException.class, () -> {
ValidationService.validateEntity(request);
});
}
@Test
void testValidateReview_Good() {
Review review = TestUtils.createReview();
assertDoesNotThrow(() -> ValidationService.validateEntity(review));
}
@Test
void testValidateReview_Bad() {
Review review = TestUtils.createReview();
review.setScore((short) 7);
assertThrows(ConstraintViolationException.class, () -> {
ValidationService.validateEntity(review);
});
}
@Test
void testValidateSpecialization_Good() {
Specialization specialization = TestUtils.createSpecialization();
assertDoesNotThrow(() -> ValidationService.validateEntity(specialization));
}
@Test
void testValidateSpecialization_Bad() {
Specialization specialization = TestUtils.createSpecialization();
specialization.setName(null);
assertThrows(ConstraintViolationException.class, () -> {
ValidationService.validateEntity(specialization);
});
}
@Test
void testValidateStaff_Good() {
Specialization specialization = TestUtils.createSpecialization();
Staff staff = TestUtils.createStaff(specialization);
assertDoesNotThrow(() -> ValidationService.validateEntity(staff));
}
@Test
void testValidateStaff_Bad() {
Specialization specialization = TestUtils.createSpecialization();
Staff staff = TestUtils.createStaff(specialization);
staff.setEmail(null);
assertThrows(ConstraintViolationException.class, () -> {
ValidationService.validateEntity(staff);
});
}
}
|
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\AppPublisher>
*/
class AppPublisherFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => $this->faker->company,
'url' => $this->faker->url,
'slug' => $this->faker->slug,
'status' => $this->faker->randomElement(['Draft', 'Pending', 'Publish']),
];
}
}
|
<!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" />
<!-- google fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<!-- modern-normalize -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
integrity="sha512-wpPYUAdjBVSE4KJnH1VR1HeZfpl1ub8YT/NKx4PuQ5NmX2tKuGu6U/JRp5y+Y8XG2tV+wKQpNHVUX03MfMFn9Q=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link
href="https://fonts.googleapis.com/css2?family=Raleway:wght@800&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
<!-- CSS STYLE -->
<link rel="stylesheet" href="./css/styles.css" />
<title>WebStudio</title>
</head>
<body>
<!-- HEADER SECTION -->
<header class="header-page">
<div class="container site-nav">
<nav class="header-nav">
<!-- logo -->
<a class="header-nav-logo logo link" href="./index.html"
>Web<span class="header-logo-studio logo">Studio</span></a
>
<ul class="header-nav-menu list">
<!--nav menu -->
<li class="nav-menu">
<a class="header-nav-link active link" href="./index.html"
>Studio</a
>
</li>
<li class="nav-menu">
<a class="header-nav-link link" href="./portfolio.html"
>Portfolio</a
>
</li>
<li class="nav-menu">
<a class="header-nav-link link" href="">Contacts</a>
</li>
</ul>
</nav>
<!-- contacts -->
<address class="header-contacts">
<ul class="header-list list">
<li class="header-contacts-list header-distance">
<a
class="header-contact-link link"
href="mailto:info@devstudio.com"
>info@devstudio.com</a
>
</li>
<li class="header-contacts-list">
<a class="header-contact-link link" href="tel:+110001111111"
>+11 (000) 111-11-11</a
>
</li>
</ul>
</address>
<!-- burgeer menu -->
<button
class=".menu-toggle burger js-open-menu"
aria-expanded="false"
aria-controls="mobile-menu"
type="button"
>
<svg class="svg-menu" width="32" height="22">
<use href="./images/icons.svg#burger-menu"></use>
</svg>
</button>
</div>
</header>
<main>
<!-- HERO SECTION -->
<section class="hero section">
<div class="container">
<h1 class="hero-title">Effective Solutions for Your Business</h1>
<button class="hero-btn" type="button" data-modal-open>
Order Service
</button>
</div>
</section>
<!-- OUR SKILLS SECTION -->
<section class="section">
<div class="container">
<h2 class="section-title visually-hidden">Our strengths</h2>
<ul class="our-strengths list">
<li class="strengths-item">
<div class="benefits-icon">
<svg class="skills-icon" width="64" height="64">
<use href="./images/icons.svg#antenna"></use>
</svg>
</div>
<h3 class="section-subtitle">Strategy</h3>
<p class="section-text">
Our goal is to identify the business problem to walk away with
the perfect and creative solution.
</p>
</li>
<li class="strengths-item">
<div class="benefits-icon">
<svg class="skills-icon" width="64" height="64">
<use href="./images/icons.svg#clock"></use>
</svg>
</div>
<h3 class="section-subtitle">Punctuality</h3>
<p class="section-text">
Bring the key message to the brand's audience for the best price
within the shortest possible time.
</p>
</li>
<li class="strengths-item">
<div class="benefits-icon">
<svg class="skills-icon" width="64" height="64">
<use href="./images/icons.svg#diagram"></use>
</svg>
</div>
<h3 class="section-subtitle">Diligence</h3>
<p class="section-text">
Research and confirm brands that present the strongest digital
growth opportunities and minimize risk.
</p>
</li>
<li class="strengths-item">
<div class="benefits-icon">
<svg class="skills-icon" width="64" height="64">
<use href="./images/icons.svg#astronaut"></use>
</svg>
</div>
<h3 class="section-subtitle">Technologies</h3>
<p class="section-text">
Design practice focused on digital experiences. We bring forth a
deep passion for problem-solving.
</p>
</li>
</ul>
</div>
</section>
<!-- OUR FEATURES SECTION -->
<section class="features-section">
<div class="features-container container">
<h2 class="section-title">What are we doing</h2>
<ul class="features-list list">
<li class="features-item">
<img
src="./images/main-page/section-2/img-1.jpg"
alt="photo-1"
width="360"
height="300"
/>
</li>
<li class="features-item">
<img
src="./images/main-page/section-2/img-2.jpg"
alt="photo-2"
width="360"
height="300"
/>
</li>
<li class="features-item">
<img
src="./images/main-page/section-2/img-3.jpg"
alt="photo-3"
width="360"
height="300"
/>
</li>
</ul>
</div>
</section>
<!-- OUR TEAM SECTION -->
<section class="section-team section">
<div class="container">
<h2 class="section-title">Our Team</h2>
<ul class="team-info list">
<li class="team-list">
<img
class="team-img"
srcset="
./images/main-page/section-3/img-1_team@1x.jpg 1x,
./images/main-page/section-3/img-1_team@2x.jpg 2x
"
src="./images/main-page/section-3/img-1_team@1x.jpg"
alt="team-card-1"
width="264"
height="260"
/>
<div class="text-container">
<h3 class="section-subtitle">Mark Guerrero</h3>
<p class="section-text">Product Designer</p>
<ul class="social-links">
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#instagram"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#twitter"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#facebook"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-list">
<img
class="team-img"
srcset="
./images/main-page/section-3/img-2_team@1x.jpg 1x,
./images/main-page/section-3/img-2_team@2x.jpg 2x
"
src="./images/main-page/section-3/img-2_team@1x.jpg"
alt="team-card-2"
width="264"
height="260"
/>
<div class="text-container">
<h3 class="section-subtitle">Tom Ford</h3>
<p class="section-text">Frontend Developer</p>
<ul class="social-links">
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#instagram"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#twitter"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#facebook"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-list">
<img
class="team-img"
srcset="
./images/main-page/section-3/img-3_team@1x.jpg 1x,
./images/main-page/section-3/img-3_team@2x.jpg 2x
"
src="./images/main-page/section-3/img-3_team@1x.jpg"
alt="team-card-3"
width="264"
height="260"
/>
<div class="text-container">
<h3 class="section-subtitle">Camila Garcia</h3>
<p class="section-text">Marketing</p>
<ul class="social-links">
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#instagram"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#twitter"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#facebook"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-list">
<img
class="team-img"
srcset="
./images/main-page/section-3/img-4_team@1x.jpg 1x,
./images/main-page/section-3/img-4_team@2x.jpg 2x
"
src="./images/main-page/section-3/img-4_team@1x.jpg"
alt="team-card-4"
width="264"
height="260"
/>
<div class="text-container">
<h3 class="section-subtitle">Daniel Wilson</h3>
<p class="section-text">UI Designer</p>
<ul class="social-links">
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#instagram"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#twitter"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#facebook"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="16" height="16">
<use href="./images/icons.svg#linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</section>
<!-- OUR CUSTOMERS -->
<section class="section">
<div class="container">
<h2 class="section-title">Customers</h2>
<ul class="customer-list">
<li class="customer-item">
<a class="customers-link" href="">
<svg class="customers-icon" width="104" height="56">
<use href="./images/icons.svg#client-1"></use>
</svg>
</a>
</li>
<li class="customer-item">
<a class="customers-link" href="">
<svg class="customers-icon" width="104" height="56">
<use href="./images/icons.svg#client-2"></use>
</svg>
</a>
</li>
<li class="customer-item">
<a class="customers-link" href="">
<svg class="customers-icon" width="104" height="56">
<use href="./images/icons.svg#client-3"></use>
</svg>
</a>
</li>
<li class="customer-item">
<a class="customers-link" href="">
<svg class="customers-icon" width="104" height="56">
<use href="./images/icons.svg#client-4"></use>
</svg>
</a>
</li>
<li class="customer-item">
<a class="customers-link" href="">
<svg class="customers-icon" width="104" height="56">
<use href="./images/icons.svg#client-5"></use>
</svg>
</a>
</li>
<li class="customer-item">
<a class="customers-link" href="">
<svg class="customers-icon" width="104" height="56">
<use href="./images/icons.svg#client-6"></use>
</svg>
</a>
</li>
</ul>
</div>
</section>
</main>
<!-- SECTION FOOTER -->
<footer class="footer section">
<div class="container">
<div class="tab-container">
<div class="footer-content">
<div class="footer-container">
<a class="footer-logo link" href="./index.html"
>Web<span class="footer-logo-studio">Studio</span></a
>
<p class="footer-text">
Increase the flow of customers and sales for your business with
digital marketing & growth solutions.
</p>
</div>
<!-- SOCIAL-LINKS -->
<div class="footer-icons-media">
<p class="footer-media-text">Social media</p>
<ul class="footer-social-list">
<li class="footer-social-lists">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#instagram"></use>
</svg>
</a>
</li>
<li class="footer-social-lists">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#twitter"></use>
</svg>
</a>
</li>
<li class="footer-social-lists">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#facebook"></use>
</svg>
</a>
</li>
<li class="footer-social-lists">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
<!-- SUBSCRIBE -->
<div class="subscribe">
<p class="footer-media-text">Subscribe</p>
<form class="footer-forma">
<label class="footer-subscribe-email">
<input
name="email"
class="footer-subscribe-input"
type="email"
placeholder="E-mail"
/>
</label>
<button class="btm-subscribe" type="submit">
<span class="btm-subcribe-title"
>Subscribe
<svg class="footer-subsribe-icon" width="24" height="20">
<use href="./images/icons.svg#footer-subscribe"></use>
</svg>
</span>
</button>
</form>
</div>
</div>
</div>
</div>
</footer>
<!-- /**
| MODAL-WINDOWNDOW
*/ -->
<div class="backdrop is-hidden" data-modal>
<div class="modal">
<button type="button" data-modal-close class="close-icon">
<svg class="modal-close-icon" width="8" height="8">
<use href="./images/icons.svg#close"></use>
</svg>
</button>
<!-- FORM -->
<form class="form">
<p class="form-modal-title">
Leave your contacts and we will call you back
</p>
<div class="form-modal-window">
<!-- NAME -->
<label class="forma-label" for="user-name">Name</label>
<div class="form-field">
<input
class="form-input"
name="user-name"
type="text"
id="user-name"
/>
<svg class="forma-icon" width="18" height="24">
<use href="./images/icons.svg#user-name"></use>
</svg>
</div>
<!-- PHONE -->
<label for="user-phone" class="forma-label">Phone</label>
<div class="form-field">
<input
class="form-input"
name="user-phone"
type="tel"
id="user-phone"
/>
<svg class="forma-icon" width="18" height="24">
<use href="./images/icons.svg#user-phone"></use>
</svg>
</div>
<!-- EMAIL -->
<label for="user-email" class="forma-label">Email</label>
<div class="form-field">
<input
class="form-input"
name="user-email"
type="email"
id="user-email"
/>
<svg class="forma-icon" width="18" height="24">
<use href="./images/icons.svg#user-email"></use>
</svg>
</div>
<!-- COMMENT -->
<label class="forma-label" for="comment">Comment</label>
<div class="form-field">
<textarea
class="forma-comment"
name="comment"
id="comment"
cols="30"
rows="5"
placeholder="Text input"
></textarea>
</div>
</div>
<!-- CHECKBOX -->
<label class="forma-checkbox" for="checkbox">
<input
class="input-checkbox visually-hidden"
type="checkbox"
name="checkbox"
id="checkbox"
/>
<svg class="form-checked" width="16" height="16">
<use class="checked" href="./images/icons.svg#checked"></use>
<use class="unchecked" href="./images/icons.svg#unchecked"></use>
</svg>
<span class="form-agreement">
I accept the terms and conditions of the
<a href="" class="form-agreement-text">Privacy Policy</a>
</span></label
>
<!-- BUTTON "SEND" -->
<button class="forma-btm-send" type="submit">Send</button>
</form>
</div>
</div>
<!-- /**
| burger menu
*/ -->
<div class="menu-container js-menu-container" id="mobile-menu">
<button class="menu-toggle js-close-menu" type="button">
<svg class="svg-menu" fill="#2E2F42" width="8" height="8">
<use href="./images/icons.svg#close"></use>
</svg>
</button>
<ul class="mobile-menu list">
<li class="mobile-list">
<a
class="burger-link link section-subtitle active"
href="./index.html"
>Studio</a
>
</li>
<li class="mobile-list">
<a class="burger-link link section-subtitle" href="./portfolio.html"
>Portfolio</a
>
</li>
<li class="mobile-list">
<a class="burger-link link section-subtitle" href="">Contacts</a>
</li>
</ul>
<ul class="menu-contact menu-contact list">
<li class="burger-contacts">
<a class="burger-tel section-subtitle link" href="tel:+110001111111"
>+11 (000) 111-11-11</a
>
</li>
<li class="burger-contacts">
<a class="burger-post link" href="mailto:info@devstudio.com"
>info@devstudio.com</a
>
</li>
</ul>
<ul class="burger-social-link">
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#instagram"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#twitter"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#facebook"></use>
</svg>
</a>
</li>
<li class="icon-list">
<a class="icon-link" href="">
<svg class="icon" width="24" height="24">
<use href="./images/icons.svg#linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
<!-- Scripts js -->
<script src="./js/modal.js"></script>
<script
defer
src="https://cdnjs.cloudflare.com/ajax/libs/body-scroll-lock/3.1.5/bodyScrollLock.min.js"
integrity="sha512-HowizSDbQl7UPEAsPnvJHlQsnBmU2YMrv7KkTBulTLEGz9chfBoWYyZJL+MUO6p/yBuuMO/8jI7O29YRZ2uBlA=="
crossorigin="anonymous"
></script>
<script defer src="js/mobile-menu.js"></script>
</body>
</html>
|
<html>
<head>
<!--
A canvas example from:
https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/DrawingLinesandShapes/DrawingLinesandShapes.html
Their coding style is different from what we'll be using in class - use our style, not theirs.
-->
<title>Moving curves</title>
<style>
canvas{
background: #ffffff;
cursor: pointer;
margin-left: 10px;
margin-top: 10px;
box-shadow: 3px 3px 6px rgba(0,0,0,0.5);
}
</style>
<script type="text/javascript">
var canvas, ctx;
var ctrlX = 15;
var ctrlY = 155;
var ctrlXa = 51;
var ctrlYa = 310;
var xMod = 1;
var yMod = 1;
function init() {
canvas = document.querySelector("canvas");
ctx = canvas.getContext("2d");
loop();
}
function drawCurves() {
ctx.lineWidth="3";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.quadraticCurveTo(ctrlX, ctrlY, canvas.width, canvas.height);
ctx.stroke();
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(ctrlX, ctrlY, ctrlXa, ctrlYa, canvas.width, canvas.height);
ctx.stroke();
}
function loop(){
requestAnimationFrame(loop);
if(ctrlX >= 100){
xMod = -1;
}
else if(ctrlX <= -100){
xMod = 1;
}
if(ctrlY >= 100){
yMod = -1;
}
else if(ctrlY <= -100){
yMod = 1;
}
ctrlX += xMod;
ctrlY += yMod;
ctx.clearRect(0,0,1200,1200);
drawCurves();
}
</script>
</head>
<body onload="init()" style="background-color:#e0e0e0">
<canvas height="400" width="800">
</canvas>
</body>
</html>
|
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
use std::{
collections::HashMap,
error::Error,
fs::{self, File},
io::{self, ErrorKind, Read, Write},
mem,
path::PathBuf,
process::ExitCode,
str::FromStr,
};
use clap::Parser;
use indexmap::IndexMap;
use pasm::{
Expr, ExprNode, Label, Op, Pos, Reloc, RelocVal, Section, SliceInterner, StrInterner, Sym, Tok,
};
use serde::{de, Deserialize, Deserializer};
use serde_derive::{Deserialize, Serialize};
use tracing::Level;
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Args {
/// Object files
objects: Vec<PathBuf>,
/// Config file
#[arg(short, long)]
config: PathBuf,
/// Output file (default: stdout)
#[arg(short, long)]
output: Option<PathBuf>,
/// Output file for Mesen debug symbols
#[arg(long = "gMLB")]
debug_mesen: Option<PathBuf>,
/// Pre-defined symbols (repeatable)
#[arg(short = 'D', long, value_name="KEY1=val", value_parser = parse_defines::<String, i32>)]
define: Vec<(String, i32)>,
/// One of `TRACE`, `DEBUG`, `INFO`, `WARN`, or `ERROR`
#[arg(short, long, default_value_t = Level::INFO)]
log_level: Level,
}
fn parse_defines<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
where
T: FromStr,
T::Err: Error + Send + Sync + 'static,
U: FromStr,
U::Err: Error + Send + Sync + 'static,
{
let pos = s
.find('=')
.ok_or_else(|| format!("invalid SYMBOL=value: no `=` found in `{s}`"))?;
Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}
fn main() -> ExitCode {
let args = Args::parse();
tracing_subscriber::fmt()
.with_max_level(args.log_level)
.with_writer(io::stderr)
.init();
if let Err(e) = main_real(args) {
tracing::error!("{e}");
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
fn main_real(args: Args) -> Result<(), Box<dyn Error>> {
let mut config = File::open(args.config).map_err(|e| format!("cant open file: {e}"))?;
let mut config_text = String::new();
config.read_to_string(&mut config_text)?;
let config: Script = toml::from_str(&config_text)?;
let mut ld = Ld::new();
let def_file_section = ld.str_int.intern("__DEFINES__");
let def_unit = ld.str_int.intern("__STATIC__");
for (name, val) in &args.define {
let string = ld.str_int.intern(name);
ld.syms.push(Sym::new(
Label::new(None, string),
Expr::Const(*val),
def_unit,
def_file_section,
def_file_section,
Pos(0, 0),
));
}
for (name, mem) in &config.memories {
let name = ld.str_int.intern(&name);
ld.memories.push(Memory::new(name, mem.start, mem.size));
}
for (name, section) in &config.sections {
let name = ld.str_int.intern(&name);
if let Some(memory) = config.memories.get(§ion.load) {
ld.sections.push(Section::new(name));
match memory.ty {
MemoryType::RO => match §ion.ty {
SectionType::RO => {}
_ => {
Err(ld.err(&format!(
"memory \"{}\" is not type-compatible with section \"{name}\"",
section.load
)))?;
}
},
MemoryType::RW => match §ion.ty {
SectionType::RW | SectionType::BSS => {}
_ => {
Err(ld.err(&format!(
"memory \"{}\" is not type-compatible with section \"{name}\"",
section.load
)))?;
}
},
}
} else {
Err(ld.err(&format!(
"memory \"{}\" is not defined in config",
section.load
)))?;
}
}
tracing::trace!("loading objects");
for object in args.objects {
let path = fs::canonicalize(object)?;
let path = path.to_str().unwrap();
let file = File::open(path)?;
ld.load(path, file)?;
}
tracing::trace!("relocating sections");
for (name, section) in &config.sections {
let Ld {
ref mut sections,
ref mut memories,
..
} = ld;
let memory = memories
.iter_mut()
.find(|memory| memory.name == section.load)
.unwrap();
// TODO section alignment?
let section = sections
.iter_mut()
.find(|section| section.name == name)
.unwrap();
// we update the section pc to be its absolute start address in memory
section.pc = memory.pc;
memory.pc += section.data.len() as u32;
// the "end" is actually 1 past the last address in the memory
if memory.pc > memory.end {
Err(io::Error::new(
ErrorKind::InvalidData,
format!(
"no room left in memory \"{}\" for section \"{name}\"",
memory.name
),
))?;
}
}
// TODO as a quick hack we store all symbols for addresses for generating debug
// info later...
let mut debug_addrs = HashMap::new();
for pass in 1..=2 {
tracing::trace!("symbol table pass {pass}");
for i in 0..ld.syms.len() {
let value = match ld.syms[i].value {
Expr::Const(value) => Expr::Const(value),
Expr::Addr(section, pc) => {
let section = ld.sections.iter().find(|sec| sec.name == section).unwrap();
let value = pc + section.pc;
debug_addrs.insert(ld.syms[i].label.to_string(), value);
Expr::Const(value as i32)
}
Expr::List(expr) => {
if let Some(value) = ld.expr_eval(ld.syms[i].unit, expr, &config.sections) {
Expr::Const(value)
} else {
Expr::List(expr)
}
}
};
ld.syms[i].value = value;
}
}
tracing::trace!("symbol table validation");
for sym in &ld.syms {
if let Expr::Const(_) = sym.value {
continue;
}
Err(ld.err_in(
sym.unit,
&format!(
"undefined symbol \"{}\"\n\tdeclared at {}:{}:{}",
sym.label, sym.file, sym.pos.0, sym.pos.1
),
))?;
}
tracing::trace!("linking");
for i in 0..ld.sections.len() {
for j in 0..ld.sections[i].relocs.len() {
let reloc = ld.sections[i].relocs[j];
let value = match reloc.value {
RelocVal::Addr(section, pc) => {
let section = ld.sections.iter().find(|sec| sec.name == section).unwrap();
(pc + section.pc) as i32
}
RelocVal::List(expr) => {
if let Some(value) = ld.expr_eval(reloc.unit, expr, &config.sections) {
value
} else {
Err(ld.err_in(
reloc.unit,
&format!(
"expression cannot be solved\n\tdefined at {}:{}:{}",
reloc.file, reloc.pos.0, reloc.pos.1
),
))?
}
}
};
match reloc.width {
1 => {
if (value as u32) > (u8::MAX as u32) {
Err(ld.err_in(
reloc.unit,
&format!(
"expression >1 byte\n\tdefined at {}:{}:{}",
reloc.file, reloc.pos.0, reloc.pos.1
),
))?;
}
ld.sections[i].data[reloc.offset] = value as u8;
}
2 => {
if (value as u32) > (u16::MAX as u32) {
Err(ld.err_in(
reloc.unit,
&format!(
"expression >2 bytes\n\tdefined at {}:{}:{}",
reloc.file, reloc.pos.0, reloc.pos.1
),
))?;
}
ld.sections[i].data[reloc.offset] = ((value as u32) >> 0) as u8;
ld.sections[i].data[reloc.offset + 1] = ((value as u32) >> 8) as u8;
}
3 => {
if (value as u32) > 0x00FFFFFFu32 {
Err(ld.err_in(
reloc.unit,
&format!(
"expression >3 bytes\n\tdefined at {}:{}:{}",
reloc.file, reloc.pos.0, reloc.pos.1
),
))?;
}
ld.sections[i].data[reloc.offset] = ((value as u32) >> 0) as u8;
ld.sections[i].data[reloc.offset + 1] = ((value as u32) >> 8) as u8;
ld.sections[i].data[reloc.offset + 2] = ((value as u32) >> 16) as u8;
}
_ => unreachable!(),
}
}
}
let mut output: Box<dyn Write> = match args.output {
Some(path) => Box::new(
File::options()
.write(true)
.create(true)
.truncate(true)
.open(path)
.map_err(|e| format!("cant open file: {e}"))?,
),
None => Box::new(io::stdout()),
};
tracing::trace!("writing");
for (mem_name, memory) in &config.memories {
for (sec_name, section) in &config.sections {
if §ion.load != mem_name {
continue;
}
let section = &ld.sections.iter().find(|sec| sec.name == sec_name).unwrap();
tracing::trace!(
"writing {} bytes of section \"{sec_name}\" in memory \"{mem_name}\"",
section.data.len()
);
output.write_all(§ion.data)?;
}
if let Some(value) = memory.fill {
let mem = &ld.memories.iter().find(|mem| mem.name == mem_name).unwrap();
tracing::trace!(
"filling {} bytes of memory \"{mem_name}\" with ${value:02X}",
mem.end - mem.pc,
);
for _ in mem.pc..mem.end {
output.write(&[value])?;
}
}
}
if let Some(path) = args.debug_mesen {
tracing::trace!("writing mesen debug symbols");
let mut file = File::options()
.write(true)
.create(true)
.truncate(true)
.open(path)
.map_err(|e| format!("cant open file: {e}"))?;
for (name, value) in debug_addrs {
writeln!(file, "PRG:{value:X}:{name}")?;
}
}
Ok(())
}
struct Ld<'a> {
str_int: StrInterner<'a>,
expr_int: SliceInterner<ExprNode<'a>>,
sections: Vec<Section<'a>>,
memories: Vec<Memory<'a>>,
syms: Vec<Sym<'a>>,
}
impl<'a> Ld<'a> {
fn new() -> Self {
Self {
str_int: StrInterner::new(),
expr_int: SliceInterner::new(),
sections: Vec::new(),
memories: Vec::new(),
syms: Vec::new(),
}
}
fn err(&self, msg: &str) -> io::Error {
io::Error::new(ErrorKind::InvalidData, msg)
}
fn err_in(&self, file: &str, msg: &str) -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
format!("in file: {file}: {msg}"),
)
}
fn read_int<R: Read, T: FromLeBytes<Buf = [u8; mem::size_of::<T>()]>>(
&self,
reader: &mut R,
) -> io::Result<T>
where
T::Buf: Default,
{
let mut buf = T::Buf::default();
reader.read_exact(&mut buf)?;
Ok(T::from_le_bytes(buf.into()))
}
fn load<R: Read>(&mut self, file: &str, mut reader: R) -> io::Result<()> {
let mut magic = [0u8; 6];
reader.read_exact(&mut magic)?;
if &magic != b"pasm01" {
return Err(self.err_in(file, "bad magic"));
}
// fill up a temporary string table
let mut str_int: StrInterner<'_> = StrInterner::new();
{
let str_len: usize = self.read_int(&mut reader)?;
let mut storage = String::new();
storage.extend((0..str_len).map(|_| ' '));
reader.read_exact(unsafe { storage.as_bytes_mut() })?;
str_int.storages.push(storage);
}
// and a temporary expression table
let mut expr_int: SliceInterner<ExprNode<'_>> = SliceInterner::new();
{
let expr_len: usize = self.read_int(&mut reader)?;
let mut storage = Vec::new();
for _ in 0..expr_len {
let ty: u8 = self.read_int(&mut reader)?;
match ty {
0 => {
let value: i32 = self.read_int(&mut reader)?;
storage.push(ExprNode::Const(value));
}
1 => {
let ty: u8 = self.read_int(&mut reader)?;
match ty {
0 => {
let value: u8 = self.read_int(&mut reader)?;
storage.push(ExprNode::Op(Op::Binary(Tok(value))));
}
1 => {
let value: u8 = self.read_int(&mut reader)?;
storage.push(ExprNode::Op(Op::Unary(Tok(value))));
}
_ => return Err(self.err_in(file, "malformed expression table")),
}
}
2 => {
let ty: u8 = self.read_int(&mut reader)?;
match ty {
0 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let scope = str_int.slice(index..(index + len)).unwrap();
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let string = str_int.slice(index..(index + len)).unwrap();
let scope = self.str_int.intern(scope);
let string = self.str_int.intern(string);
storage.push(ExprNode::Label(Label::new(Some(scope), string)));
}
1 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let string = str_int.slice(index..(index + len)).unwrap();
let string = self.str_int.intern(string);
storage.push(ExprNode::Label(Label::new(None, string)));
}
_ => return Err(self.err_in(file, "malformed expression table")),
}
}
3 => {
let ty: u8 = self.read_int(&mut reader)?;
match ty {
0 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let scope = str_int.slice(index..(index + len)).unwrap();
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let string = str_int.slice(index..(index + len)).unwrap();
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let tag = str_int.slice(index..(index + len)).unwrap();
let scope = self.str_int.intern(scope);
let string = self.str_int.intern(string);
let tag = self.str_int.intern(tag);
storage.push(ExprNode::Tag(Label::new(Some(scope), string), tag));
}
1 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let string = str_int.slice(index..(index + len)).unwrap();
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let tag = str_int.slice(index..(index + len)).unwrap();
let string = self.str_int.intern(string);
let tag = self.str_int.intern(tag);
storage.push(ExprNode::Tag(Label::new(None, string), tag));
}
_ => return Err(self.err_in(file, "malformed expression table")),
}
}
_ => return Err(self.err_in(file, "malformed expression table")),
}
}
expr_int.storages.push(storage);
}
// time to start filling the global symbol table
let syms_len: usize = self.read_int(&mut reader)?;
for _ in 0..syms_len {
let ty: u8 = self.read_int(&mut reader)?;
let label = match ty {
0 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let scope = str_int.slice(index..(index + len)).unwrap();
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let string = str_int.slice(index..(index + len)).unwrap();
let scope = self.str_int.intern(scope);
let string = self.str_int.intern(string);
Label::new(Some(scope), string)
}
1 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let string = str_int.slice(index..(index + len)).unwrap();
let string = self.str_int.intern(string);
Label::new(None, string)
}
_ => return Err(self.err_in(file, "malformed symbol table")),
};
let ty: u8 = self.read_int(&mut reader)?;
let value = match ty {
0 => {
let value: i32 = self.read_int(&mut reader)?;
Expr::Const(value)
}
1 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let expr_section = str_int.slice(index..(index + len)).unwrap();
let pc: u32 = self.read_int(&mut reader)?;
let expr_section = self.str_int.intern(expr_section);
// place the address relative to the start of the section
let pc = if let Some(expr_section) =
self.sections.iter().find(|sec| sec.name == expr_section)
{
pc + expr_section.pc
} else {
return Err(self.err_in(
file,
&format!("section \"{expr_section}\" is not defined in config"),
));
};
Expr::Addr(expr_section, pc)
}
2 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let expr = expr_int.slice(index..(index + len)).unwrap();
let expr = self.expr_int.intern(expr);
Expr::List(expr)
}
_ => return Err(self.err_in(file, "malformed symbol table")),
};
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let unit = str_int.slice(index..(index + len)).unwrap();
// hide static symbols under the object file name
let unit = if unit == "__STATIC__" {
self.str_int.intern(file)
} else {
self.str_int.intern(unit)
};
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let sym_section = str_int.slice(index..(index + len)).unwrap();
let sym_section = self.str_int.intern(sym_section);
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let sym_file = str_int.slice(index..(index + len)).unwrap();
let sym_file = self.str_int.intern(sym_file);
let line: usize = self.read_int(&mut reader)?;
let column: usize = self.read_int(&mut reader)?;
let pos = Pos(line, column);
// duplicate exported symbol?
if let Some(other) = self
.syms
.iter()
.find(|sym| (sym.label == label) && (sym.unit == unit))
{
return Err(self.err_in(file, &format!("duplicate exported symbol \"{label}\" found\n\tdefined at {}:{}:{}\n\tagain at {sym_file}:{line}:{column}", other.file, other.pos.0, other.pos.1)));
}
self.syms
.push(Sym::new(label, value, unit, sym_section, sym_file, pos));
}
// add to sections
let sections_len: usize = self.read_int(&mut reader)?;
for _ in 0..sections_len {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let name = str_int.slice(index..(index + len)).unwrap();
let name = self.str_int.intern(name);
tracing::trace!("loading section \"{name}\"");
let section = if let Some(section) = self.sections.iter().find(|sec| sec.name == name) {
section
} else {
return Err(self.err_in(
file,
&format!("section \"{name}\" is not defined in config"),
));
};
let data_len: usize = self.read_int(&mut reader)?;
let mut data = Vec::new();
data.extend((0..data_len).map(|_| 0));
reader.read_exact(&mut data)?;
// TODO this seems messy,
let mut relocs = Vec::new();
let relocs_len: usize = self.read_int(&mut reader)?;
for _ in 0..relocs_len {
let offset: usize = self.read_int(&mut reader)?;
// place the offset relative to the start of the section
let offset = offset + (section.pc as usize);
let width: u8 = self.read_int(&mut reader)?;
let ty: u8 = self.read_int(&mut reader)?;
let value = match ty {
0 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let reloc_section = str_int.slice(index..(index + len)).unwrap();
let pc: u32 = self.read_int(&mut reader)?;
let reloc_section = self.str_int.intern(reloc_section);
// place the address relative to the start of the section
let pc = if let Some(reloc_section) =
self.sections.iter().find(|sec| sec.name == reloc_section)
{
pc + reloc_section.pc
} else {
return Err(self.err_in(
file,
&format!("section \"{reloc_section}\" is not defined in config"),
));
};
RelocVal::Addr(reloc_section, pc)
}
1 => {
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let expr = expr_int.slice(index..(index + len)).unwrap();
let expr = self.expr_int.intern(expr);
RelocVal::List(expr)
}
_ => return Err(self.err_in(file, "malformed relocation table")),
};
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let unit = str_int.slice(index..(index + len)).unwrap();
let index: usize = self.read_int(&mut reader)?;
let len: usize = self.read_int(&mut reader)?;
let reloc_file = str_int.slice(index..(index + len)).unwrap();
let unit = if unit == "__STATIC__" {
self.str_int.intern(file)
} else {
self.str_int.intern("__EXPORT__")
};
let reloc_file = self.str_int.intern(reloc_file);
let line: usize = self.read_int(&mut reader)?;
let column: usize = self.read_int(&mut reader)?;
let pos = Pos(line, column);
relocs.push(Reloc {
offset,
width,
value,
unit,
file: reloc_file,
pos,
});
}
// extend section
if let Some(section) = self.sections.iter_mut().find(|sec| sec.name == name) {
tracing::trace!("extending section \"{name}\" by {} bytes", data.len());
section.data.extend(&data);
section.relocs.extend(relocs);
section.pc += data.len() as u32;
} else {
return Err(self.err_in(
file,
&format!("section \"{name}\" is not defined in config"),
));
};
}
Ok(())
}
fn expr_eval(
&self,
unit: &'_ str,
expr: &[ExprNode<'_>],
sections: &IndexMap<String, ConfigSection>,
) -> Option<i32> {
let mut scratch = Vec::new();
for node in expr.iter() {
match *node {
ExprNode::Const(value) => scratch.push(value),
ExprNode::Label(label) => {
let sym = self.syms.iter().find(|sym| {
(sym.label == label) && ((sym.unit == unit) || (sym.unit == "__EXPORT__"))
})?;
match sym.value {
Expr::Const(value) => scratch.push(value),
Expr::Addr(section, pc) => {
let section = self
.sections
.iter()
.find(|sec| sec.name == section)
.unwrap();
scratch.push((pc + section.pc) as i32);
}
// expand the sub-expression recursively
Expr::List(expr) => {
scratch.push(self.expr_eval(unit, expr, sections)?);
}
}
}
ExprNode::Tag(label, tag) => {
let sym = self.syms.iter().find(|sym| {
(sym.label == label) && ((sym.unit == unit) || (sym.unit == "__EXPORT__"))
})?;
let tags = sections.get(sym.section).unwrap().tags.as_ref();
let value = tags?.get(tag)?;
scratch.push(*value);
}
ExprNode::Op(op) => {
let rhs = scratch.pop().unwrap();
match op {
Op::Unary(Tok::PLUS) => scratch.push(rhs),
Op::Unary(Tok::MINUS) => scratch.push(-rhs),
Op::Unary(Tok::TILDE) => scratch.push(!rhs),
Op::Unary(Tok::BANG) => scratch.push((rhs == 0) as i32),
Op::Unary(Tok::LT) => scratch.push(((rhs as u32) & 0xFF) as i32),
Op::Unary(Tok::GT) => scratch.push((((rhs as u32) & 0xFF00) >> 8) as i32),
Op::Unary(Tok::CARET) => {
scratch.push((((rhs as u32) & 0xFF0000) >> 16) as i32)
}
Op::Binary(tok) => {
let lhs = scratch.pop().unwrap();
match tok {
Tok::PLUS => scratch.push(lhs.wrapping_add(rhs)),
Tok::MINUS => scratch.push(lhs.wrapping_sub(rhs)),
Tok::STAR => scratch.push(lhs.wrapping_mul(rhs)),
Tok::SOLIDUS => scratch.push(lhs.wrapping_div(rhs)),
Tok::MODULUS => scratch.push(lhs.wrapping_rem(rhs)),
Tok::ASL => scratch.push(lhs.wrapping_shl(rhs as u32)),
Tok::ASR => scratch.push(lhs.wrapping_shr(rhs as u32)),
Tok::LSR => {
scratch.push((lhs as u32).wrapping_shl(rhs as u32) as i32)
}
Tok::LT => scratch.push((lhs < rhs) as i32),
Tok::LTE => scratch.push((lhs <= rhs) as i32),
Tok::GT => scratch.push((lhs > rhs) as i32),
Tok::GTE => scratch.push((lhs >= rhs) as i32),
Tok::EQ => scratch.push((lhs == rhs) as i32),
Tok::NEQ => scratch.push((lhs != rhs) as i32),
Tok::AMP => scratch.push(lhs & rhs),
Tok::PIPE => scratch.push(lhs | rhs),
Tok::CARET => scratch.push(lhs ^ rhs),
Tok::AND => scratch.push(((lhs != 0) && (rhs != 0)) as i32),
Tok::OR => scratch.push(((lhs != 0) || (rhs != 0)) as i32),
_ => unreachable!(),
}
}
_ => unreachable!(),
}
}
}
}
scratch.last().copied()
}
}
struct Memory<'a> {
name: &'a str,
pc: u32,
end: u32,
}
impl<'a> Memory<'a> {
fn new(name: &'a str, pc: u32, len: u32) -> Self {
Self {
name,
pc,
end: pc + len,
}
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum MemoryType {
RO,
RW,
}
#[derive(Serialize, Deserialize)]
struct ConfigMemory {
#[serde(deserialize_with = "deserialize_bases_u32")]
start: u32,
#[serde(deserialize_with = "deserialize_bases_u32")]
size: u32,
#[serde(rename = "type")]
ty: MemoryType,
#[serde(default, deserialize_with = "deserialize_bases_u8")]
fill: Option<u8>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum SectionType {
RO,
RW,
BSS,
}
#[derive(Serialize, Deserialize)]
struct ConfigSection {
load: String,
#[serde(rename = "type")]
ty: SectionType,
#[serde(default, deserialize_with = "deserialize_tags")]
tags: Option<HashMap<String, i32>>,
}
#[derive(Serialize, Deserialize)]
struct Script {
#[serde(rename = "MEMORY")]
memories: IndexMap<String, ConfigMemory>,
#[serde(rename = "SECTIONS")]
sections: IndexMap<String, ConfigSection>,
}
fn deserialize_tags<'de, D>(deserializer: D) -> Result<Option<HashMap<String, i32>>, D::Error>
where
D: Deserializer<'de>,
{
let string_map = Option::<HashMap<String, String>>::deserialize(deserializer)?;
if let Some(string_map) = string_map {
let mut map = HashMap::new();
for (name, buf) in string_map {
let value = if buf.starts_with('$') {
i32::from_str_radix(&buf[1..], 16).map_err(|e| {
de::Error::custom(format!("{buf} is not a valid base 16 value: {e}"))
})?
} else if buf.starts_with('%') {
i32::from_str_radix(&buf[1..], 2).map_err(|e| {
de::Error::custom(format!("{buf} is not a valid base 2 value: {e}"))
})?
} else {
i32::from_str_radix(&buf, 10).map_err(|e| {
de::Error::custom(format!("{buf} is not a valid base 10 value: {e}"))
})?
};
map.insert(name, value);
}
return Ok(Some(map));
}
Ok(None)
}
fn deserialize_bases_u32<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
D: Deserializer<'de>,
{
let buf = String::deserialize(deserializer)?;
if buf.starts_with('$') {
u32::from_str_radix(&buf[1..], 16)
.map_err(|e| de::Error::custom(format!("{buf} is not a valid base 16 address: {e}")))
} else if buf.starts_with('%') {
u32::from_str_radix(&buf[1..], 2)
.map_err(|e| de::Error::custom(format!("{buf} is not a valid base 2 address: {e}")))
} else {
u32::from_str_radix(&buf, 10)
.map_err(|e| de::Error::custom(format!("{buf} is not a valid base 10 address: {e}")))
}
}
fn deserialize_bases_u8<'de, D>(deserializer: D) -> Result<Option<u8>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::deserialize(deserializer)?
.map(|buf| {
if buf.starts_with('$') {
u8::from_str_radix(&buf[1..], 16).map_err(|e| {
de::Error::custom(format!("{buf} is not a valid base 16 value: {e}"))
})
} else if buf.starts_with('%') {
u8::from_str_radix(&buf[1..], 2).map_err(|e| {
de::Error::custom(format!("{buf} is not a valid base 2 value: {e}"))
})
} else {
u8::from_str_radix(&buf, 10).map_err(|e| {
de::Error::custom(format!("{buf} is not a valid base 10 value: {e}"))
})
}
})
.transpose()
}
trait FromLeBytes {
type Buf;
fn from_le_bytes(buf: Self::Buf) -> Self;
}
macro_rules! impl_le_bytes (( $($int:ident),* ) => {
$(
impl FromLeBytes for $int {
type Buf = [u8; mem::size_of::<Self>()];
fn from_le_bytes(buf: Self::Buf) -> Self {
Self::from_le_bytes(buf)
}
}
)*
});
impl_le_bytes!(u8, u32, i32, usize);
|
import React, { useState } from 'react';
import { TextField, Button, Typography, Container, Snackbar } from '@mui/material';
import { useHistory } from 'react-router-dom'
import { UseRegisterMessage } from 'Plugins/UserServersApi/UseRegisterMessage'
export const UserRegisterPage = () => {
const history = useHistory()
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [errorMessage, setErrorMessage] = useState('')
const [snackBarOpen, setSnackBarOpen] = useState(false)
const handleUsernameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setUsername(event.target.value)
}
const handleEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setEmail(event.target.value)
}
const handlePasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value)
}
const handleConfirmPasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setConfirmPassword(event.target.value)
}
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault()
if (password.length < 4 || password.length > 30) {
setErrorMessage('Password length must be between 4 and 30 characters')
setSnackBarOpen(true)
return
}
if (!email.includes('@')) {
setErrorMessage('Please enter a valid email address')
setSnackBarOpen(true)
return
}
if (password !== confirmPassword) {
setErrorMessage('The passwords do not match')
setSnackBarOpen(true)
return
}
new UseRegisterMessage(username, email, password).send(
() => {
history.push('/login')
},
error => {
console.log(error)
setErrorMessage('Registration failed. Please try again later.')
setSnackBarOpen(true)
}
)
}
const handleSnackBarClose = () => {
setSnackBarOpen(false)
}
const handleGotoLogin = () => {
history.push('/login')
}
return (
<Container maxWidth="sm">
<div>
<Typography variant="h4" component="h1" gutterBottom>
Registration
</Typography>
<form onSubmit={handleSubmit}>
<TextField
label="UserName"
value={username}
onChange={handleUsernameChange}
fullWidth
margin="normal"
required
/>
<TextField
label="Email"
type="email"
value={email}
onChange={handleEmailChange}
fullWidth
margin="normal"
required
/>
<TextField
label="Password"
type="password"
value={password}
onChange={handlePasswordChange}
fullWidth
margin="normal"
required
/>
<TextField
label="Confirm Password"
type="password"
value={confirmPassword}
onChange={handleConfirmPasswordChange}
fullWidth
margin="normal"
required
/>
<Button variant="contained" color="primary" type="submit" fullWidth>
Register
</Button>
</form>
<Snackbar
open={snackBarOpen}
onClose={handleSnackBarClose}
message={errorMessage}
autoHideDuration={3000}
anchorOrigin={{
vertical: 'top',
horizontal: 'center',
}}
/>
</div>
<Button variant="outlined" color="primary" onClick={handleGotoLogin} sx={{ marginTop: 2 }}>
Go to Login
</Button>
</Container>
)
}
|
const delay = (ms) => new Promise((res) => setTimeout(res, ms))
export const useUserStore = defineStore("user", () => {
const userData = ref()
const weeks = ref([])
const ghostWeeks = ref([])
const gweeks = ref([])
const tasks = ref([])
const loaded = ref(false)
const runtimeConfig = useRuntimeConfig()
const popupDownload = ref(false)
async function fetch() {
const { data } = await useFetch("/api/auth/user", {
method: "GET",
credentials: "include",
})
await getTasks()
if (data.value) userData.value = data.value
loaded.value = true
}
async function getTasks() {
const { data } = await useFetch("/api/schedule/tasks", {
method: "GET",
})
if (data.value) {
tasks.value = data.value.tasks
}
}
async function regenSecret() {
const { data } = await useFetch("/api/auth/regen-secret", {
method: "POST",
})
if (data.value) {
userData.value = data.value
}
}
function linkAccount(account) {
window.location.href = runtimeConfig.public.API_SERVER + "/inputs/link/" + account
}
async function unlinkAccount(account) {
const { data } = await useFetch("/api/inputs/unlink/" + account, {
method: "POST",
credentials: "include",
})
if (data.value) userData.value = data.value
}
async function login() {
window.location.href = runtimeConfig.public.API_SERVER + "/auth/login/google"
}
async function logout() {
window.location.href = runtimeConfig.public.API_SERVER + "/auth/logout"
}
async function getDailyTaskHoursAll(year, week) {
var dataArrayAll = []
for (var task of tasks.value) {
if (task.name == "Sleep") continue
dataArrayAll.push({
hours: await getDailyTaskHours(year, week, task._id),
task,
})
}
return dataArrayAll
}
async function getDailyTaskHours(year, week, taskId) {
const dataArray = [0, 0, 0, 0, 0, 0, 0]
for (var item of await getItems(year, week)) {
if (item.task._id == taskId) {
for (var weekDay = 0; weekDay <= 6; weekDay++) {
const start = getDate(year, week, weekDay).getTime()
const end = getDate(year, week, weekDay + 1).getTime()
if (item.startTime < end && item.endTime >= start) {
dataArray[weekDay] += (Math.min(end, item.endTime) - Math.max(start, item.startTime)) / 1000 / 60 / 60
}
}
}
}
return dataArray
}
async function getDailySleepHours(year, week) {
const sleepArray = [0, 0, 0, 0, 0, 0, 0]
for (var item of await getItems(year, week)) {
if (item.task._id == "6570999020677f7839f92ffd") {
for (var weekDay = 0; weekDay <= 6; weekDay++) {
const start = getDate(year, week, weekDay).getTime() - 6 * 60 * 60 * 1000
const end = getDate(year, week, weekDay + 1).getTime() - 6 * 60 * 60 * 1000
if (item.startTime > start && item.endTime < end) {
sleepArray[weekDay] += (Math.min(end, item.endTime) - item.startTime) / 1000 / 60 / 60
}
}
}
}
return sleepArray
}
async function getItems(year, week, resetOld) {
const foundWeek = weeks.value.find((i) => i.week == week && i.year == year)
if (foundWeek && foundWeek.items && !resetOld) {
return foundWeek.items
} else if (foundWeek && foundWeek.loading && !resetOld) {
while (true) {
await delay(100)
const foundWeek = weeks.value.find((i) => i.week == week && i.year == year)
if (!foundWeek.loading) return foundWeek.items
}
} else {
var index = weeks.value.length
if (!resetOld)
weeks.value.push({
week,
year,
items: null,
loading: true,
})
const { data } = await useFetch("/api/schedule/items", {
method: "POST",
body: {
year,
week,
timezoneOffset: new Date().getTimezoneOffset(),
},
})
if (data.value) {
if (!resetOld) {
weeks.value[index].items = data.value.sort((a, b) => a.startTime - b.startTime)
weeks.value[index].loading = false
} else {
if (foundWeek) {
foundWeek.items = data.value.sort((a, b) => a.startTime - b.startTime)
} else {
weeks.value.push({
week,
year,
items: data.value.sort((a, b) => a.startTime - b.startTime),
})
}
}
weeks.value = [...weeks.value]
calculateGhostItems(year, week, data.value)
return data.value
}
return []
}
}
function calculateGhostItems(year, week, items) {
var ghostWeekItems = []
for (var { ...loopItem } of [...items]) {
var changed = false
do {
changed = false
const startDay = new Date(loopItem.startTime).getWeekDay()
const startWeek = new Date(loopItem.startTime).getWeekNumber()
const endDay = new Date(loopItem.endTime).getWeekDay()
const endWeek = new Date(loopItem.endTime).getWeekNumber()
if (startDay == endDay) {
if (startWeek == endWeek) ghostWeekItems.push(loopItem)
break
} else {
var loopItem1 = { ...loopItem }
loopItem1.endTime = getDate(year, week, startDay).getTime() + 86400 * 1000
loopItem.startTime = getDate(year, week, endDay).getTime()
if (startWeek == week) ghostWeekItems.push(loopItem1)
changed = true
}
} while (changed)
}
var foundWeek = ghostWeeks.value.find((i) => i.week == week && i.year == year)
if (foundWeek) {
foundWeek.items = ghostWeekItems
ghostWeeks.value = [...ghostWeeks.value]
} else {
ghostWeeks.value.push({
week,
year,
items: ghostWeekItems,
})
}
}
async function getGhostItems(year, week) {
var foundWeek = ghostWeeks.value.find((i) => i.week == week && i.year == year)
if (!foundWeek) {
await getItems(year, week)
foundWeek = ghostWeeks.value.find((i) => i.week == week && i.year == year)
}
return foundWeek.items
}
function getItem(year, week, id) {
const foundWeek = weeks.value.find((i) => i.week == week && i.year == year)
return { ...foundWeek.items.find((i) => i._id == id) }
}
async function createItem(task, startTime, endTime) {
// TODO: MULTIYEAR WEEK SPAN
var startYear = new Date(startTime).getFullYear()
var startWeek = new Date(startTime).getWeekNumber()
var weekSpan = 0
if (startYear == new Date(endTime).getFullYear()) {
weekSpan = new Date(endTime).getWeekNumber() - startWeek + 1
}
const { error } = await useFetch("/api/schedule/items/new", {
method: "POST",
body: {
startTime,
endTime,
task,
week: new Date(startTime).getWeekNumber(),
year: new Date(startTime).getFullYear(),
timezoneOffset: new Date().getTimezoneOffset(),
},
})
if (!error.value) {
for (var weekOffset = 0; weekOffset < weekSpan; weekOffset++) {
await getItems(startYear, startWeek, true)
}
}
}
async function updateItem(id, task, startTime, endTime) {
// TODO: MULTIYEAR WEEK SPAN
var startYear = new Date(startTime).getFullYear()
var startWeek = new Date(startTime).getWeekNumber()
var weekSpan = 0
if (startYear == new Date(endTime).getFullYear()) {
weekSpan = new Date(endTime).getWeekNumber() - startWeek + 1
}
const { error } = await useFetch("/api/schedule/items/update", {
method: "POST",
body: {
_id: id,
task,
startTime,
endTime,
week: startWeek,
year: startYear,
timezoneOffset: new Date().getTimezoneOffset(),
},
})
if (!error.value) {
for (var weekOffset = 0; weekOffset < weekSpan; weekOffset++) {
await getItems(startYear, startWeek, true)
}
}
}
async function deleteItem(item) {
// TODO: MULTIYEAR WEEK SPAN
var startYear = new Date(item.startTime).getFullYear()
var startWeek = new Date(item.startTime).getWeekNumber()
var weekSpan = 0
if (startYear == new Date(item.endTime).getFullYear()) {
weekSpan = new Date(item.endTime).getWeekNumber() - startWeek + 1
}
const { error } = await useFetch("/api/schedule/items/delete", {
method: "POST",
body: {
_id: item._id,
week: startWeek,
year: startYear,
},
})
if (!error.value) {
for (var weekOffset = 0; weekOffset < weekSpan; weekOffset++) {
await getItems(startYear, startWeek, true)
}
}
}
async function getGItems(year, week) {
const foundWeek = gweeks.value.find((i) => i.week == week && i.year == year)
if (foundWeek && foundWeek.items) {
return foundWeek.items
} else if (foundWeek && foundWeek.loading) {
while (true) {
await delay(100)
const foundWeek = gweeks.value.find((i) => i.week == week && i.year == year)
if (!foundWeek.loading) return foundWeek.items
}
} else {
var index = gweeks.value.length
gweeks.value.push({
week,
year,
items: null,
loading: true,
})
const { data } = await useFetch("/api/schedule/gitems", {
method: "POST",
body: {
year,
week,
timezoneOffset: new Date().getTimezoneOffset(),
},
})
if (data.value) {
gweeks.value[index].items = data.value
gweeks.value[index].loading = false
return data.value
}
return []
}
}
function getGItem(year, week, id) {
const foundWeek = gweeks.value.find((i) => i.week == week && i.year == year)
return { ...foundWeek.items.find((i) => i._id == id) }
}
function getWatcher() {
return weeks
}
function getTask(id) {
return { ...tasks.value.find((i) => i._id == id) }
}
async function getEarliestTime(year, week, id, endTime) {
const weekDay = new Date(endTime).getWeekDay()
let time = 0
const items = await getItems(year, week)
for (var i of items) {
if (new Date(i.endTime).getWeekDay() == weekDay && i._id != id) {
if (i.endTime <= endTime) {
if (i.endTime > time) time = i.endTime
}
}
}
return time
}
async function getLatestTime(year, week, id, startTime) {
const weekDay = new Date(startTime).getWeekDay()
let time = getDate(year, week, weekDay).getTime() + 24 * 60 * 60 * 1000
const items = await getItems(year, week)
for (var i of items) {
if (new Date(i.startTime).getWeekDay() == weekDay && i._id != id) {
if (i.startTime >= startTime) {
if (i.startTime < time) time = i.startTime
}
}
}
return time
}
async function setPreference(key, value) {
const { data } = await useFetch("/api/auth/user/setpreference", {
method: "POST",
body: {
key,
value,
},
})
}
function togglePopupDownload() {
popupDownload.value = !popupDownload.value
}
return {
data: userData,
login,
logout,
loaded,
fetch,
getWatcher,
tasks,
getTask,
getEarliestTime,
getLatestTime,
linkAccount,
unlinkAccount,
getItems,
getGhostItems,
getItem,
createItem,
updateItem,
deleteItem,
regenSecret,
togglePopupDownload,
setPreference,
popupDownload,
getGItems,
getGItem,
getDailyTaskHours,
getDailyTaskHoursAll,
getDailySleepHours,
}
})
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/common/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Quản lý loại sản phẩm</title>
</head>
<body>
<main>
<header
class="page-header page-header-dark bg-gradient-primary-to-secondary pb-10">
<div class="container-xl px-4">
<div class="page-header-content pt-4">
<div class="row align-items-center justify-content-between">
<div class="col-auto mt-4">
<h1 class="page-header-title">
<div class="page-header-icon">
<i data-feather="filter"></i>
</div>
Tất cả loại sản phẩm
</h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main page content-->
<div class="container-xl px-4 mt-n10">
<div class="card mb-4">
<div class="card-header d-flex justify-content-between bg-light">
<div class="text-black">kế thừa từ DataTables.net</div>
<div>
<c:if test="${not empty msg}">
<p class="p-3 mb-2 bg-success text-white font-weight-bold">${msg}</p>
</c:if>
</div>
<div>
<a class="btn btn-success btn-sm font-weight-bold"
style="font-size: 14px; font-weight: initial;" href="<%=request.getContextPath()%>/admin/newType"
role="button">Tạo loại sản phảm</a>
</div>
</div>
<div class="card-body">
<c:choose>
<c:when test="${categories != null}">
<table id="datatablesSimple">
<thead>
<tr>
<th>Id</th>
<th>Tên loại</th>
<!-- <th>Salary</th>
<th>Status</th> -->
<th>Chức năng</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Tên loại</th>
<!-- <th>Salary</th>
<th>Status</th> -->
<th>Chức năng</th>
</tr>
</tfoot>
<tbody>
<c:forEach var="category" items="${categories}">
<tr>
<td>${category.id_type}</td>
<td>${category.name_type}</td>
<td>
<a class="btn btn-datatable btn-icon btn-warning me-2"
href="<%=request.getContextPath()%>/admin/editType/${category.id_type}"
> <i style="width: 25px; height: 25px; padding: 5px"
class="bi bi-box-arrow-in-down-left"></i></a>
<a class="btn btn-datatable btn-icon btn-danger"
href="<%=request.getContextPath()%>/admin/deleteType/${category.id_type}"
onclick="return confirm('Do you really want to delete?')"><i
style="width: 25px; height: 25px; padding: 5px"
class="bi bi-trash"></i> </a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:when>
<c:otherwise>
No Categories found in the DB!
</c:otherwise>
</c:choose>
</div>
</div>
</div>
</main>
</body>
</html>
|
import 'dart:io';
void main(){
// 1 gram = 1000 Milligrams
print("Enter the Number of gram");
double? gram= double.parse(stdin.readLineSync()!);
if(gram >=0){
double milligrams=gram*1000;
print("$gram g ====> $milligrams mg");
}
else{
print("You cant take grams in negative values");
}
}
// Explanation:
// The main() function serves as the entry point of the Dart program.
// The program prompts the user to input the number of grams.
// It then checks if the entered value is greater than or equal to 0.
// If the input is not negative, the program proceeds to convert grams to milligrams.
// It performs the conversion by multiplying the number of grams by 1000 (since 1 gram = 1000 milligrams).
// The program prints the converted value in milligrams using string interpolation.
// If the entered value is negative, the program prints an error message indicating that grams can't be negative.
// Import statement for 'dart:io' is used to enable interaction with input/output streams.
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021-2022 Hewlett Packard Enterprise, Inc. All rights reserved.
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
---
module: ilo_firmware
short_description: Performs Firmware related operations on iLO using Redfish APIs
version_added: 4.2.0
description:
- Builds Redfish URIs locally and sends them to iLO to
perform SNMP related operations.
- For use with HPE iLO SNMP operations that require Redfish OEM extensions.
options:
category:
required: true
description:
- List of categories to execute on iLO.
type: list
elements: str
command:
required: true
description:
- List of commands to execute on iLO.
type: list
elements: str
baseuri:
required: true
description:
- Base URI of iLO.
type: str
username:
description:
- User for authentication with iLO.
type: str
password:
description:
- Password for authentication with iLO.
type: str
auth_token:
description:
- Security token for authentication with iLO.
type: str
version_added: 2.3.0
timeout:
description:
- Timeout in seconds for URL requests to iLO.
default: 60
type: int
cert_file:
description:
- Absolute path to the server cert file
type: str
key_file:
description:
- Absolute path to the server key file
type: str
file_name:
description:
- Component filename when uploading it to iLO repository
type: str
image_uri:
description:
- Webserver path where the firmware component is located.
type: str
install_set_attributes:
description:
- Name,description and sequence of the install set to be created
type: dict
maintenance_window_details:
description:
- Name,description,start and end time of maintenance window to be created
type: dict
author:
- Gayathiri Devi Ramasamy (@Gayathirideviramasamy)
- T S Kushal (@TSKushal)
- Varni H P (@varini-hp)
- Prativa Nayak (@prativa-n)
- Nagendra M (@nagendram399)
"""
EXAMPLES = """
- name: Perform firmware upgrade on the server using image uri
ilo_firmware:
category: UpdateService
command: UpdateFirmwareWithUpload
baseuri: "{{ baseuri }}"
username: "{{ username }}"
password: "{{ password }}"
image_uri: "http://***.***.***.***:8088/ilo5_278.fwpkg"
file_name: "Sample filename"
- name: Perform firmware upgrade on the server using install set without maintenance window
ilo_firmware:
category: UpdateService
command: UpdateFirmwareThroughInstallSet
baseuri: "{{ baseuri }}"
username: "{{ username }}"
password: "{{ password }}"
install_set_attributes:
Name: "Install set name"
Description: "Install set description"
Install_set_sequence: [
{
"Name": "ilo",
"Filename": "ilo6_110.fwpkg",
"UpdatableBy": ["Bmc","Uefi","RuntimeAgent"]
},
{
"Name": "OCP adapter",
"Filename": "OCPAdapterfile"
}]
- name: Perform firmware upgrade on the server using install set with maintenance window
ilo_firmware:
category: UpdateService
command: UpdateFirmwareThroughInstallSet
baseuri: "{{ baseuri }}"
username: "{{ username }}"
password: "{{ password }}"
install_set_attributes:
Name: "Install set name"
Description: "Install set description"
Install_set_sequence: [
{
"Name": "ilo",
"Filename": "ilo6_110.fwpkg",
"UpdatableBy": ["Bmc","Uefi","RuntimeAgent"]
},
{
"Name": "OCP adapter",
"Filename": "OCPAdapterfile"
}]
maintenance_window_details: {
"Description": "Sample description of maintenance window",
"Name": "Maintenance window name",
"StartAfter": "2023-01-19T18:35:00Z",
"Expire": "2023-01-19T19:30:00Z"
}
- name: Perform firmware upload to ilo repository
ilo_firmware:
category: UpdateService
command: FirmwareUpload
baseuri: "{{ baseuri }}"
username: "{{ username }}"
password: "{{ password }}"
image_uri: "http://***.***.***.***:8088/ilo5_278.fwpkg"
file_name: "Sample filename"
- name: Get firmware upgrade/upload status
ilo_firmware:
category: TaskService
command: GetFirmwareStatus
baseuri: "{{ baseuri }}"
username: "{{ username }}"
password: "{{ password }}"
"""
RETURN = """
ilo_firmware:
description: Returns the status of the operation performed on the iLO.
type: dict
contains:
command:
description: Returns the output msg and whether the function executed successfully.
type: dict
contains:
ret:
description: Return True/False based on whether the operation was performed succesfully.
type: bool
msg:
description: Status of the operation performed on the iLO.
type: dict
returned: always
"""
CATEGORY_COMMANDS_ALL = {"UpdateService": ["UpdateFirmwareWithUpload", "UpdateFirmwareThroughInstallSet", "FirmwareUpload"],
"TaskService": ["GetFirmwareStatus"]}
CATEGORY_COMMANDS_DEFAULT = {"UpdateService": "FirmwareUpload",
"TaskService": "GetFirmwareStatus"}
HAS_OEM_REDFISH = True
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
try:
from ansible_collections.hpe.ilo.plugins.module_utils.ilo_oem_utils import iLOOemUtils, ilo_certificate_login
except ImportError:
OEM_REDFISH_IMP_ERR = traceback.format_exc()
HAS_OEM_REDFISH = False
def main():
result = {}
category_list = []
module = AnsibleModule(
argument_spec=dict(
category=dict(required=True, type="list", elements="str"),
command=dict(required=True, type="list", elements="str"),
baseuri=dict(required=True),
username=dict(),
password=dict(no_log=True),
auth_token=dict(no_log=True),
timeout=dict(type="int", default=60),
cert_file=dict(type="str"),
key_file=dict(type="str"),
image_uri=dict(required=False, type="str"),
task_ids=dict(required=False, type="list"),
file_name=dict(required=False, type="str"),
install_set_attributes=dict(required=False, type="dict"),
maintenance_window_details=dict(required=False, type="dict"),
max_time=dict(required=False, type="int"),
polling_interval=dict(required=False, type="int")
),
required_together=[
("username", "password"),
("cert_file", "key_file")
],
required_one_of=[
("username", "auth_token", "cert_file"),
],
mutually_exclusive=[
("username", 'auth_token', 'cert_file'),
],
supports_check_mode=True
)
creds = {
"user": module.params["username"],
"pswd": module.params["password"],
"token": module.params["auth_token"],
}
if not HAS_OEM_REDFISH:
module.fail_json(msg="missing required fucntions in ilo_oem_utils.py")
timeout = module.params["timeout"]
root_uri = "https://" + module.params["baseuri"]
if module.params["cert_file"]:
creds["token"] = ilo_certificate_login(root_uri, module, module.params["cert_file"], module.params["key_file"])
rf_utils = iLOOemUtils(creds, root_uri, timeout, module)
# Build Category list
if "all" in module.params["category"]:
for entry in CATEGORY_COMMANDS_ALL:
category_list.append(entry)
else:
# one or more categories specified
category_list = module.params["category"]
for category in category_list:
command_list = []
# Build Command list for each Category
if category in CATEGORY_COMMANDS_ALL:
if not module.params["command"]:
# True if we don't specify a command --> use default
command_list.append(CATEGORY_COMMANDS_DEFAULT[category])
elif "all" in module.params["command"]:
for entry in CATEGORY_COMMANDS_ALL[category]:
command_list.append(entry)
# one or more commands
else:
command_list = module.params["command"]
# Verify that all commands are valid
for cmd in command_list:
# Fail if even one command given is invalid
if cmd not in CATEGORY_COMMANDS_ALL[category]:
module.fail_json(msg="Invalid Command: %s" % cmd)
else:
# Fail if even one category given is invalid
module.fail_json(msg="Invalid Category: %s" % category)
# Organize by Categories / Commands
if category == "UpdateService":
for command in command_list:
result[command] = {}
if command == "FirmwareUpload":
if not module.params.get("image_uri"):
result[command]['ret'] = False
result[command]['msg'] = "Image uri params is required"
module.fail_json(result)
result[command] = rf_utils.firmware_upgrade_with_upload(module.params["image_uri"], module.params["file_name"], False)
elif command == "UpdateFirmwareWithUpload":
if not module.params.get("image_uri"):
result[command]['ret'] = False
result[command]['msg'] = "Image uri params is required"
module.fail_json(result)
result[command] = rf_utils.firmware_upgrade_with_upload(module.params["image_uri"], module.params["file_name"])
elif command == "UpdateFirmwareThroughInstallSet":
if not module.params.get("install_set_attributes"):
result[command]['ret'] = False
result[command]['msg'] = "Install set params is required"
module.fail_json(result)
install_set_attributes = module.params["install_set_attributes"]
maintenance_window_details = module.params["maintenance_window_details"]
result[command] = rf_utils.firmware_upgrade_through_install_set(install_set_attributes, maintenance_window_details)
elif category == "TaskService":
for command in command_list:
result[command] = {}
if command == "GetFirmwareStatus":
result[command] = rf_utils.get_firmware_status()
if not result[command]['ret']:
module.fail_json(msg=to_native(result))
module.exit_json(ilo_firmware=result)
if __name__ == "__main__":
main()
|
<?php
namespace App\Entity;
use App\Repository\TagRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\String\UnicodeString;
/**
* @ORM\Entity(repositoryClass=TagRepository::class)
*/
class Tag
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private int $id;
/**
* @ORM\Column(type="string", length=50)
*/
private string $name;
/**
* @ORM\ManyToMany(targetEntity=Drink::class, mappedBy="tag")
* @ORM\OrderBy({"id" = "DESC"})
*/
private Collection $drinks;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="tags")
* @ORM\JoinColumn(nullable=false)
*/
private User $user;
public function __construct()
{
$this->drinks = new ArrayCollection();
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = (new UnicodeString($name))->upper()->toString();
return $this;
}
/**
* @return Collection|Drink[]
*/
public function getDrinks(): Collection
{
return $this->drinks;
}
public function addDrink(Drink $drink): self
{
if (!$this->drinks->contains($drink)) {
$this->drinks[] = $drink;
$drink->addTag($this);
}
return $this;
}
public function removeDrink(Drink $drink): self
{
if ($this->drinks->removeElement($drink)) {
$drink->removeTag($this);
}
return $this;
}
public function getUser(): User
{
return $this->user;
}
public function setUser(User $user): self
{
$this->user = $user;
return $this;
}
}
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract TetherUSD is ERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor() ERC20("Tether USD", "USDT") {
_mint(msg.sender, 500_000_000 * 10 ** decimals());
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function decimals() public pure override returns (uint8) {
return 6;
}
}
contract BUSD is ERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor() ERC20("BUSD", "BUSD") {
_mint(msg.sender, 500_000_000 * 10 ** decimals());
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
}
contract USDC is ERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor() ERC20("USDC", "USDC") {
_mint(msg.sender, 500_000_000 * 10 ** decimals());
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function decimals() public pure override returns (uint8) {
return 6;
}
}
|
<?php
namespace App\Services;
use App\Models\StudentDemographicInfo;
use Exception;
use Illuminate\Support\Facades\Http;
class StudentDemographicsManager
{
/** @var object */
private $api_data_response;
/** @var StudentDemographicInfo */
private $student_demographic_info;
/** @var string */
private static $route = 'https://api.data.gov/ed/collegescorecard/v1/schools.json';
/** @var bool */
public $is_error;
/** @var string */
public $error_message;
public function __construct()
{
$this->student_demographic_info = new StudentDemographicInfo();
$this->is_error = false;
}
public function import(): void
{
try {
//extract from api
$this->api_request();
//transform json to eloquent model
$this->marshal_data();
//load model into db and log
$this->insert_into_db();
} catch (Exception $e) {
$this->is_error = true;
$this->error_message = $e->getMessage();
}
}
private function api_request(): void
{
$response = Http::get($this::$route, [
'school.name' => 'Salisbury',
'api_key' => env('DoE_API_KEY'),
]);
$body = json_decode($response->body());
$this->api_data_response = $body->results[0]->latest;
}
private function insert_into_db(): void
{
$this->student_demographic_info->save();
}
private function marshal_data(): void
{
//ethnicity
$ethnicity_object = $this->api_data_response->student->demographics->race_ethnicity;
$this->student_demographic_info->native_american_pct = $this->format_percentage($ethnicity_object->aian);
$this->student_demographic_info->pacific_islander_pct = $this->format_percentage($ethnicity_object->nhpi);
$this->student_demographic_info->asian_pct = $this->format_percentage($ethnicity_object->asian);
$this->student_demographic_info->black_pct = $this->format_percentage($ethnicity_object->black);
$this->student_demographic_info->white_pct = $this->format_percentage($ethnicity_object->white);
$this->student_demographic_info->hispanic_pct = $this->format_percentage($ethnicity_object->hispanic);
$this->student_demographic_info->two_or_more_races_pct = $this->format_percentage($ethnicity_object->two_or_more);
$this->student_demographic_info->unknow_race_pct = $this->format_percentage($ethnicity_object->unknown);
//gender
$gender_object = $this->api_data_response->student->demographics;
$this->student_demographic_info->male_pct = $this->format_percentage($gender_object->men);
$this->student_demographic_info->non_male_pct = $this->format_percentage($gender_object->women);
//parental education
$education_object = $this->api_data_response->student->share_firstgeneration_parents;
$first_gen_percentage = $this->api_data_response->student->demographics->first_generation;
$this->student_demographic_info->middle_school_pct = $this->format_percentage($first_gen_percentage * $education_object->middleschool);
$this->student_demographic_info->high_school_pct = $this->format_percentage($first_gen_percentage * $education_object->highschool);
$this->student_demographic_info->some_college_pct = $this->format_percentage($first_gen_percentage * $education_object->somecollege);
$this->student_demographic_info->college_degree_pct = $this->format_percentage(1 - $first_gen_percentage);
//student type
$enrollment_object = $this->api_data_response->student->enrollment;
$this->student_demographic_info->undergraduate_count = $enrollment_object->undergrad_12_month;
$this->student_demographic_info->graduate_count = $enrollment_object->grad_12_month;
//parental income
$income_object = $this->api_data_response->student;
$this->student_demographic_info->pct_0_30000 = $this->format_percentage($income_object->share_lowincome->{'0_30000'});
$this->student_demographic_info->pct_30001_48000 = $this->format_percentage($income_object->share_middleincome->{'30001_48000'});
$this->student_demographic_info->pct_48001_75000 = $this->format_percentage($income_object->share_middleincome->{'48001_75000'});
$this->student_demographic_info->pct_75001_110000 = $this->format_percentage($income_object->share_highincome->{'75001_110000'});
$this->student_demographic_info->pct_110001_greater = $this->format_percentage($income_object->share_highincome->{'110001plus'});
}
private function format_percentage(float $number): float
{
return round(($number * 100), 1);
}
}
|
```bash
$ npm init -y
```
```bash
$ npm i parcel -D
```
`package.json`
```javascript
"scripts": {
"dev": "parcel ./index.html",
"build": "parcel build ./index.html"
},
```
`index.html` 생성
```HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module" defer src="./src/main.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
```
src 폴더 생성<br/>
src 폴더안에 main.js 파일 생성
`main.js`
```javascript
import App from './App';
const root = document.querySelector('#root');
root.append(new App().el);
```
src 폴더안에 App.js 파일 생성
`App.js`
```javascript
export default class App {
constructor() {
this.el = document.querySelector('div');
this.el.textContent = 'Hello, World';
}
}
```
src폴더안에 core라는 폴더를 만들고<br/>
그안에 ho.js 만든다
`jo,js`
```javascript
///// Component /////
export class Component {
constructor(payload = {}) {
const { tagName = 'div' } = payload;
this.el = document.createElement(tagName);
this.render();
}
render() {
// ...
}
}
```
`App.js`
```javascript
import { Component } from './core/jo';
export default class App extends Component {
// constructor() {
// super({
// tagName: 'h1'
// });
// }
render() {
this.el.textContent = 'Hello world';
}
}
```
|
<template>
<div class="course">
<div class="container">
<div style="padding: 20px;">
<h1><strong>TEMARIO</strong></h1>
</div>
<div style="padding: 20px;">
<b-row class="animated fadeInLeft">
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #1</strong> <br><br>
<p>
<strong>
La Bolsa Mexicana de Valores. Sus participantes; nuestro papel como inversionistas; Inflación; índice
</strong>
</p>
</b-col>
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #2</strong> <br><br>
<p>
<strong>
Casa de Bolsa. Abre tu cuenta; Enlazar tus cuentas; realizar tu primer depósito; Estado de Cuenta; Retiros a tu cuenta.
</strong>
</p>
</b-col>
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #3</strong> <br><br>
<p>
<strong>
Índices, Sectores y ETF.
</strong>
</p>
</b-col>
</b-row>
<hr>
<b-row class="animated fadeInRight">
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #4</strong> <br><br>
<p>
<strong>
Plan Financiero. Identificar el Capital para invertir; Rastrear ETF; Ventanas de Oportunidad; Duración; Riesgo; y Recompensas.
</strong>
</p>
</b-col>
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #5</strong> <br><br>
<p>
<strong>
<code>Primer Acto</code>: <br> La Compra. Orden; precio, títulos, tiempo, registro
</strong>
</p>
</b-col>
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #6</strong> <br><br>
<p>
<strong>
<code>Segundo Acto</code>: <br> La Espera. Seguimiento del plan, registro de dividendos, Splits, Fuentes de noticias.
</strong>
</p>
</b-col>
</b-row>
<hr>
<b-row class="animated fadeInLeft">
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #7</strong> <br><br>
<p>
<strong>
<code>Tercer Acto</code>: <br> La Venta. Revisar plan, Stop Loss, Take Profit, Registro Final
</strong>
</p>
</b-col>
<b-col class="border rounded squareSeq shadow">
<strong class="title">Módulo #8</strong> <br><br>
<p>
<strong>
<code>Kaizen</code>: <br> Registro de Avance, Análisis.
</strong>
</p>
</b-col>
</b-row>
<div style="padding-top: 23px;">
<b-button class="inscribete rounded-pill" variant="primary" size="lg" @click="showModal()">
<strong>
¡ INSCRÍBETE <br> AQUÍ !
</strong>
</b-button>
</div>
<div v-if="modalSh" class="floatModals">
<register v-bind:modal="modalSh" />
</div>
</div>
</div>
</div>
</template>
<script>
import register from '../components/register.vue'
export default {
name: 'course',
data: function () {
return {
modalSh: false
}
},
methods: {
async showModal () {
if (!this.modalSh) {
this.modalSh = true
} else {
this.modalSh = await false
this.modalSh = await true
}
},
async hideModal () {
this.modalSh = false
}
},
components: {
register
}
}
</script>
<style scoped>
@media (max-width:850px) and (orientation : landscape) {
.course {
padding-top: 100px !important;
width: 850px !important;
}
.course .inscribete {
width: 90% !important;
}
.container, .container-fluid, .container-sm, .container-md, .container-lg, .container-xl {
padding-right: 35px;
}
}
@media (max-width:768px) and (orientation : portrait) {
.course {
padding-top: 100px !important;
width: 440px !important;
}
.course .inscribete {
width: 90% !important;
}
.container, .container-fluid, .container-sm, .container-md, .container-lg, .container-xl {
padding-right: 35px;
}
}
.course {
padding-top: 140px;
padding-bottom: 40px;
}
.course .title {
font-size: 20px;
color: rgb(0, 156, 164);
font-weight: bolder;
}
.course .squareSeq {
margin: 10px;
text-align: center;
padding-top: 13px;
padding-bottom: 13px;;
}
.course .inscribete {
width: 30%;
font-size: 23px;
padding: 30px;
margin-top: 23px;
}
.course .btn-primary {
color: #fff;
background-color: #0ba3ad;
border-color: #0ba3ad;
}
.course .shadow {
box-shadow: cadetblue;
}
</style>
|
//---------------------------------------------------------------------
// Arquivo : Sort.cpp
// Conteudo : implementacao da classe Sort
// -implementacao dos métodos de ordenação
// Autor : Igor Rahzel Colares Galdino (igorrahzel@ufmg.br)
//---------------------------------------------------------------------
#include "Sort.h"
#include <cstring>
/*aloca um vetor 'array'
com tamanho de size*/
Sort::Sort(int size){
this->size = size -1;
array = new Word[size];
}
Word Sort::GetWord(int pos){
return array[pos];
}
void Sort::SetOrder(string ord){
for (long unsigned int i = 0; i < ord.length(); i++){
ord[i] = tolower(ord[i]);
}
strcpy(order, ord.c_str());
}
void Sort::SetWord(Word p, int pos){
array[pos] = p;
}
/*Ordena através de insercao
uma particao do vetor*/
void Sort::Insertion(int L,int R){
int i,j;
Word aux;
for (i = L; i <= R; i++) {
aux = array[i];
j = i - 1;
while (( j >= 0 ) && (AllowSwap(array[j].getWord(),aux.getWord()))) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = aux;
}
}
/*Ordena por insercao o vetor
usado para obter a mediana de m */
void Sort::Insertion(Word *&median,int m) {
int i,j;
Word aux;
for (i = 0; i < m; i++) {
aux = median[i];
j = i - 1;
while (( j >= 0 ) && (AllowSwap(median[j].getWord(),aux.getWord()))) {
median[j + 1] = median[j];
j--;
}
median[j + 1] = aux;
}
}
/*Ordena uma particao do vetor */
void Sort::Partition(int L, int R,int *i, int *j,int m){
Word x, v;
*i = L; *j = R;
/*Escolhendo pivô pela mediana de 'm'*/
if(m > 1){
Word *median = new Word[m];
for(int c = L; c < L+m; c++){
median[c-L] = array[c];
}
Insertion(median,m);
int p = m/2;
x = median[p];
delete []median;
}
/*Escolhendo elemento do meio da particao como pivô*/
else{
x = array[(*i + *j)/2];
}
do
{
while (AllowSwap(x.getWord(),array[*i].getWord())) (*i)++;
while (AllowSwap(array[*j].getWord(),x.getWord())) (*j)--;
if (*i <= *j)
{
v = array[*i]; array[*i] = array[*j]; array[*j] = v;
(*i)++; (*j)--;
}
} while (*i <= *j);
}
/* parte recursiva do quicksort */
void Sort::sort(int L, int R,int s,int m){
int i;
int j;
int subArray_size = R - L + 1;
/*Condicoes para realizar particao*/
if((subArray_size <= s && s>1) || (subArray_size < m && subArray_size > s)){
Insertion(L,R);
}
/*chamadas recursivas do método sort*/
else{
Partition(L, R, &i, &j, m);
if (L < j) sort(L, j,s,m);
if (i < R) sort(i, R,s,m);
}
}
void Sort::QuickSort(int n,int s = 0,int m = 0){
sort(0, n-1,s,m);
}
/*Método análogo ao operador '>'
baseado na nova ordem lexicográfica*/
bool Sort::AllowSwap(string w1, string w2){
int min; /*tamanho da menor palavra*/
int index1; /*posição de uma letra de 'w1' em relação a nova ordem*/
int index2; /*posição de uma letra de 'w2' em relação a nova ordem*/
int n1 = w1.length();
int n2 = w2.length();
char a1[n1 +1];
char a2[n2 +1];
strcpy(a1, w1.c_str()); /*transformar 'w1' em char array*/
strcpy(a2, w2.c_str()); /*transformar 'w2' em char array*/
bool contains = false; /*verificar se palavra está contida em outra*/
bool found1; /*verificar se caracter de 'w1' nao esta no alfabeto */
bool found2; /*verificar se caracter de 'w2' nao esta no alfabeto */
string shortest; /*identifica qual é a menor palavra */
/*encontrar menor palavra */
if(w1.length() > w2.length()){
min = w2.length();
shortest = w2;
}
else{
min = w1.length();
shortest = w1;
}
/*loop para verificar qual palavra é maior*/
for (int i = 0; i < min; i++){
found1 = false;
found2 = false;
for (int j = 0; j < 26; j++){
if(a1[i] == order[j]){
index1 = j;
found1 = true;
break;
}
/*caso caracter da palavra 'w1' nao pertenca ao alfabeto*/
else if(found1 == false && j == 25){
index1 = a1[i];
index2 = a2[i];
break;
}
}
if(found1 == true){
for (int j = 0; j < 26; j++){
if(a2[i] == order[j]){
index2 = j;
break;
}
/*caso caracter da palavra 'w2' nao pertenca ao alfabeto*/
else if((found2 == false && j == 25)){
index2 = a2[i];
index1 = a1[i];
break;
}
}
}
if(index1 != index2){
break;
}
/*caso uma palavra esteja contida na outra, e.g 'ver' e 'verde'*/
if(i == min-1 && index1==index2 && w1.compare(w2)!=0){
contains = true;
}
}
if(contains == false){
if(index1 > index2){
return true;
}
else{
return false;
}
}
else{
if(shortest.compare(w2)==0)
return true;
else
return false;
}
}
|
import { useEffect } from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { Helmet } from 'react-helmet';
import axios from 'axios';
import * as Yup from 'yup';
import { Formik } from 'formik';
import {
Box,
Button,
Container,
Link,
TextField,
Typography
} from '@material-ui/core';
const Register = () => {
const navigate = useNavigate();
useEffect(() => {
axios.get('http://localhost:5000/api/user/find', {
headers: {
'Access-Control-Allow-Origin': true,
'x-access-token': localStorage.getItem('token')
},
params: {
userId: localStorage.getItem('userId'),
loginWithFB: localStorage.getItem('loginWithFB')
}
}).then((res) => {
console.log(res.data);
navigate('/app/dashboard', { replace: true });
}).catch((err) => { console.log(err); console.log('User not logged in'); });
}, []);
return (
<>
<Helmet>
<title>Register | Material Kit</title>
</Helmet>
<Box
sx={{
backgroundColor: 'background.default',
display: 'flex',
flexDirection: 'column',
height: 'fit-content',
justifyContent: 'center'
}}
>
<Container maxWidth="sm">
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
password: '',
password2: ''
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email('Must be a valid email')
.max(255)
.required('Email is required'),
firstName: Yup.string()
.max(255)
.required('First name is required'),
lastName: Yup.string()
.max(255)
.required('Last name is required'),
password: Yup.string()
.max(255)
.min(8)
.required('password is required'),
password2: Yup.string()
.max(255)
.min(8)
.required('password is required')
.length(8)
})}
onSubmit={(e) => {
console.log(e);
axios
.post('http://localhost:5000/api/user/register', {
firstName: e.firstName,
lastName: e.lastName,
email: e.email,
password: e.password,
password2: e.password2
}, {
headers: {
'Access-Control-Allow-Origin': true,
}
})
.then((res) => {
console.log(res.data);
// eslint-disable-next-line no-alert
alert('Account created.');
navigate('/login', { replace: true });
})
.catch((err) => {
console.log(err);
});
}}
>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
touched,
values
}) => (
<form onSubmit={handleSubmit}>
<Box sx={{ mb: 3 }}>
<Typography color="textPrimary" variant="h2" marginTop="20px" textAlign="center">
Create new account
</Typography>
<Typography
color="textSecondary"
gutterBottom
variant="body2"
textAlign="center"
>
Use your email to create new account
</Typography>
</Box>
<TextField
error={Boolean(touched.firstName && errors.firstName)}
fullWidth
helperText={touched.firstName && errors.firstName}
label="First name"
margin="normal"
name="firstName"
onBlur={handleBlur}
onChange={handleChange}
value={values.firstName}
variant="outlined"
/>
<TextField
error={Boolean(touched.lastName && errors.lastName)}
fullWidth
helperText={touched.lastName && errors.lastName}
label="Last name"
margin="normal"
name="lastName"
onBlur={handleBlur}
onChange={handleChange}
value={values.lastName}
variant="outlined"
/>
<TextField
error={Boolean(touched.email && errors.email)}
fullWidth
helperText={touched.email && errors.email}
label="Email Address"
margin="normal"
name="email"
type="email"
onBlur={handleBlur}
onChange={handleChange}
value={values.email}
variant="outlined"
/>
<TextField
error={Boolean(touched.password && errors.password)}
fullWidth
helperText={touched.password && errors.password}
label="Password"
margin="normal"
name="password"
type="password"
onBlur={handleBlur}
onChange={handleChange}
value={values.password}
variant="outlined"
/>
<TextField
error={Boolean(touched.password2 && errors.password2)}
fullWidth
helperText={touched.password2 && errors.password2}
label="Confirm Password"
margin="normal"
name="password2"
type="password"
onBlur={handleChange}
onChange={handleChange}
value={values.password2}
variant="outlined"
/>
{/* <Typography color="red" size="large" textAlign="center" display={wrong ? 'block' : 'none'}>Email or password is wrong</Typography> */}
<Box sx={{ py: 2 }}>
<Button
color="primary"
disabled={isSubmitting}
fullWidth
size="large"
type="submit"
variant="contained"
>
Sign up now
</Button>
</Box>
<Typography color="textSecondary" variant="body1" marginBottom="20px">
Have an account?
{' '}
<Link component={RouterLink} to="/login" variant="h6">
Sign in
</Link>
</Typography>
</form>
)}
</Formik>
</Container>
</Box>
</>
);
};
export default Register;
|
Сначала нам нужно создать папку с проектом
project
- file1.txt
- file2.txt
Далее открываем консоль в этой папке и выполняем команду
npm init.
> npm init
Вывод
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (project)
В процессе инициализации, npm задаст несколько вопросов на тему того как должен
называться проект, какая у него должна быть версия, описание и тому подобное.
Все эти вопросы можно смело пропускать, у вас всегда будет возможность поменять
ответы.
В конце npm спросит все ли правильно и покажет содержимое файла package.json,
который и станет основой нового проекта. После ответа yes этот файл запишется на
диск и проект будет считаться готовым к работе.
См. пример в файле ../files/package-example.json
После завершения процесса инициализации, можно приступать к самому главному —
написанию кода. По умолчанию код создается внутри файла index.js, лежащего
в корне проекта (там, где создан файл package.json). Это не значит, что весь
пакет состоит из одного файла. Файлов с кодом можно создавать сколько угодно,
главное, при этом, что основная работа происходит внутри index.js, куда
импортируется код из остальных файлов.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.