text
stringlengths 184
4.48M
|
|---|
import React, { useContext } from 'react';
import { AuthContext } from '../../../providers/AuthProvider';
import Swal from 'sweetalert2/dist/sweetalert2.all.js';
const AddToy = () => {
const { user } = useContext(AuthContext)
const handleAddToy = event => {
event.preventDefault();
const form = event.target;
const picture = form.photo.value;
const name = form.name.value;
const sellerName = form.seller.value;
const email = user?.email;
const subCategory = form.category.value;
const price = form.price.value;
const rating = form.rating.value;
const description = form.details.value;
const quantity = form.quantity.value;
const addToy = { picture, sellerName, name, email, subCategory, price, rating, description, quantity }
console.log(addToy);
// send data to the server
fetch('https://toy-marketplace-server-three-alpha.vercel.app/addToy', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(addToy)
})
.then(res => res.json())
.then(data => {
console.log(data);
if (data.insertedId) {
Swal.fire(
'Post successfully',
)
form.reset();
}
})
}
return (
<div className="bg-slate-300 p-24 mb-20 mt-10 rounded-lg">
<h2 className="text-4xl text-center font-extrabold">Add a Toy</h2>
<form onSubmit={handleAddToy}>
{/* form name and price row */}
<div className="md:flex mb-8">
<div className="form-control md:w-1/2">
<label className="label">
<span className="label-text">Name</span>
</label>
<label className="input-group">
<input type="text" name="name" placeholder="Name" className="input input-bordered w-full" />
</label>
</div>
<div className="form-control md:w-1/2 ml-4">
<label className="label">
<span className="label-text">Price</span>
</label>
<label className="input-group">
<input type="text" name="price" placeholder="Price" className="input input-bordered w-full" />
</label>
</div>
</div>
{/* form seller row */}
<div className="md:flex mb-8">
<div className="form-control md:w-1/2">
<label className="label">
<span className="label-text">Seller Name</span>
</label>
<label className="input-group">
<input type="text" name="seller" defaultValue={user?.displayName} placeholder="Seller Name" className="input input-bordered w-full" />
</label>
</div>
<div className="form-control md:w-1/2 ml-4">
<label className="label">
<span className="label-text">Email</span>
</label>
<label className="input-group">
<input readOnly type="text" name="email" placeholder="Email" className="input input-bordered w-full" defaultValue={user?.email} />
</label>
</div>
</div>
{/* form sub category and rating row */}
<div className="md:flex mb-8">
<div className="form-control md:w-1/2">
<label className="label">
<span className="label-text">Sub-category</span>
</label>
<label className="input-group">
<input type="text" name="category" placeholder="Sub-category" className="input input-bordered w-full" />
</label>
</div>
<div className="form-control md:w-1/2 ml-4">
<label className="label">
<span className="label-text">Rating</span>
</label>
<label className="input-group">
<input type="text" name="rating" placeholder="Rating" className="input input-bordered w-full" />
</label>
</div>
</div>
{/* form available quantity and details row */}
<div className="md:flex mb-8">
<div className="form-control md:w-1/2">
<label className="label">
<span className="label-text">Available Quantity</span>
</label>
<label className="input-group">
<input type="text" name="quantity" placeholder="Available Quantity" className="input input-bordered w-full" />
</label>
</div>
<div className="form-control md:w-1/2 ml-4">
<label className="label">
<span className="label-text">Detail description</span>
</label>
<label className="input-group">
<input type="text" name="details" placeholder="Detail description" className="input input-bordered w-full" />
</label>
</div>
</div>
{/* form Photo url row */}
<div className="mb-8">
<div className="form-control w-full">
<label className="label">
<span className="label-text">Photo URL</span>
</label>
<label className="input-group">
<input type="text" name="photo" placeholder="Photo URL" className="input input-bordered w-full" />
</label>
</div>
</div>
<input type="submit" value="Add Toy" className="bg-[#38797B] btn btn-neutral glass text-[white] py-3 rounded-xl cursor-pointer btn-block" />
</form>
</div>
);
};
export default AddToy;
|
import React from 'react'
import {withTheme} from 'styled-components'
import {Box, Card, Half} from './Box.jsx'
import {Text} from './Text.jsx'
const Swatch = ({color, width, height, m, theme}) => {
const footerHeight = height - 75
return (
<Card width={width} m={m} bg='white' style={{height, border: 'solid 1px rgba(205, 207, 214, 0.66)'}}>
<div>
<Half bg={color} style={{height: footerHeight}} />
<Half bg={`${color}-muted`} style={{height: footerHeight}} />
</div>
<Box align='left' px={3} pt={3} pb={2}>
<Text display='block' pb={2} color='charcoal-muted' textTransform='capitalize' fontWeight={500}>
{color}
</Text>
<Half>
<Text fontSize={1} color='charcoal-muted' textTransform='uppercase' fontWeight={500} title={color}>
{theme.colors[color]}
</Text>
</Half>
<Half fontSize={1} align='right' fontWeight={500}>
<Text color='gray' title={`${color}-muted`} textTransform='uppercase'>
{theme.colors[`${color}-muted`]}
</Text>
</Half>
</Box>
</Card>
)
}
Swatch.defaultProps = {
width: 233,
height: 160,
m: 3
}
export default withTheme(Swatch)
|
import * as dotenv from 'dotenv';
import jwt from 'jsonwebtoken';
import { IUser } from '../../models/User';
import { Token } from '../../models/Token';
import { ACCESS_TOKEN_MAX_AGE, REFRESH_TOKEN_MAX_AGE } from '../../const';
import { ErrorService } from '../ErrorService';
import { userService } from '../UserService/UserService';
dotenv.config();
const { ACCESS_TOKEN_SECRET, REFRESH_TOKEN_SECRET } = process.env;
class TokensService {
generateTokens(payload: Pick<IUser, '_id' | 'userName' | 'userEmail'>) {
const accessToken = jwt.sign(payload, ACCESS_TOKEN_SECRET!, {
expiresIn: ACCESS_TOKEN_MAX_AGE / 1000,
});
const refreshToken = jwt.sign(payload, REFRESH_TOKEN_SECRET!, {
expiresIn: REFRESH_TOKEN_MAX_AGE / 1000,
});
return {
accessToken,
refreshToken,
};
}
validateAccessToken(token: string) {
try {
const userData = jwt.verify(token, ACCESS_TOKEN_SECRET!);
return userData as IUser | null;
} catch (e) {
return null;
}
}
validateRefreshToken(token: string) {
try {
const userData = jwt.verify(token, REFRESH_TOKEN_SECRET!);
return userData as IUser | null;
} catch (e) {
return null;
}
}
async saveToken(userId: string, refreshToken: string) {
const tokenData = await Token.findOne({ userId: userId });
if (tokenData) {
tokenData.refreshToken = refreshToken;
return tokenData.save();
}
const token = await Token.create({ userId: userId, refreshToken });
return token;
}
async removeToken(refreshToken: string) {
const tokenData = await Token.deleteOne({ refreshToken });
return tokenData;
}
async findToken(refreshToken: string) {
const tokenData = await Token.findOne({
refreshToken: refreshToken,
});
return tokenData;
}
async refreshToken(refreshToken: string) {
if (!refreshToken) {
throw ErrorService.UnauthorizedError();
}
const userData = this.validateRefreshToken(refreshToken);
const tokenFromDb = await this.findToken(refreshToken);
if (!userData || !tokenFromDb) {
throw ErrorService.UnauthorizedError();
} else {
const user = await userService.getUserById(userData._id);
if (user) {
const tokens = this.generateTokens({
_id: user._id,
userName: user.userName,
userEmail: user.userEmail,
});
await this.saveToken(user._id, tokens.refreshToken);
return { ...tokens, userData: user };
} else {
throw ErrorService.UnauthorizedError(`User doesn't exist`, [`User doesn't exist`]);
}
}
}
}
export const tokensService = new TokensService();
|
// Read ADC value for battery voltage and charge.
// Read SHTC3 for temperature and humidity inside enclosure
uint16_t batteryVoltage;
uint8_t batteryCharge;
uint16_t insideTemperature;
uint8_t insideHumidity;
#define PIN_VBAT WB_A0
uint32_t vbat_pin = PIN_VBAT;
#define VBAT_MV_PER_LSB (0.73242188F) // 3.0V ADC range and 12 - bit ADC resolution = 3000mV / 4096
#define VBAT_DIVIDER_COMP (1.73) // Compensation factor for the VBAT divider, depend on the board
#define REAL_VBAT_MV_PER_LSB (VBAT_DIVIDER_COMP * VBAT_MV_PER_LSB)
// Get RAW Battery Voltage
uint16_t readVBAT(void)
{
float raw;
// Get the raw 12-bit, 0..3000mV ADC value
raw = analogRead(vbat_pin);
return (uint16_t) raw * REAL_VBAT_MV_PER_LSB;
}
// Convert from raw mv to percentage
uint8_t mvToPercent(float mvolts)
{
if (mvolts < 3300) return 0;
if (mvolts < 3600)
{
mvolts -= 3300;
return mvolts / 30;
}
mvolts -= 3600;
return 10 + (mvolts * 0.15F); // thats mvolts /6.66666666
}
void init_adc(void)
{
// Set the analog reference to 3.0V (default = 3.6V)
analogReference(AR_INTERNAL_3_0);
// Set the resolution to 12-bit (0..4095)
analogReadResolution(12); // Can be 8, 10, 12 or 14
// Let the ADC settle
delay(1);
// Get a single ADC sample and throw it away
readVBAT();
}
void get_battery_voltage(void)
{
// Get a raw ADC reading
uint16_t vbat_mv = readVBAT();
// Convert from raw mv to percentage (based on LIPO chemistry)
uint8_t vbat_per = mvToPercent(vbat_mv);
// Display the results
#ifndef MAX_SAVE
Serial.printf("LiPo Voltage = %d mV\n", vbat_mv);
Serial.printf("LiPo Charge = %d %%\n", vbat_per);
#endif
batteryVoltage = vbat_mv;
batteryCharge = vbat_per;
}
// SHTC3
void shtc3_read_data(void)
{
float Temperature = 0;
float Humidity = 0;
g_shtc3.update();
if (g_shtc3.lastStatus == SHTC3_Status_Nominal) // You can also assess the status of the last command by checking the ".lastStatus" member of the object
{
Temperature = g_shtc3.toDegC(); // Packing LoRa data
Humidity = g_shtc3.toPercent();
// Display the results
#ifndef MAX_SAVE
Serial.printf("Temperature = %4.1f °C\n", Temperature);
Serial.printf("Humidity = %3.0f %% rH\n", Humidity);
#endif
insideTemperature = (uint16_t) (Temperature * 10 + .5);
insideHumidity = (uint8_t) (Humidity + .5);
}
}
|
package org.example.composites;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
public class VirtualDirectory extends VirtualUnit {
@Getter
private List<VirtualUnit> units;
public VirtualDirectory(String name) {
super(name);
units = new ArrayList<>();
}
@Override
public void printUnit(int depth, StringBuilder sb) {
for (int i = 0; i < depth; i++) {
sb.append("\t");
}
sb.append(name).append("/").append("\n");
units.forEach(unit -> unit.printUnit(depth + 1, sb));
}
public void addUnit(VirtualUnit unit) {
units.add(unit);
}
}
|
#include <stdio.h>
#include <string.h>
#define MAX_CONTACTS 100
struct Contact {
char name[50];
char address[100];
char phone[15];
};
struct Contact contacts[MAX_CONTACTS];
int contactCount = 0;
void addContact() {
if (contactCount < MAX_CONTACTS) {
struct Contact newContact;
printf("Enter Name: ");
scanf("%s", newContact.name);
printf("Enter Address: ");
scanf("%s", newContact.address);
printf("Enter Phone Number: ");
scanf("%s", newContact.phone);
contacts[contactCount++] = newContact;
printf("Contact added successfully!\n");
} else {
printf("Contact storage is full.\n");
}
}
void displayContacts() {
printf("Contacts:\n");
for (int i = 0; i < contactCount; i++) {
printf("Contact %d:\n", i + 1);
printf("Name: %s\n", contacts[i].name);
printf("Address: %s\n", contacts[i].address);
printf("Phone: %s\n", contacts[i].phone);
}
}
void updateContact() {
int contactIndex;
printf("Enter the index of the contact you want to update: ");
scanf("%d", &contactIndex);
if (contactIndex >= 1 && contactIndex <= contactCount) {
struct Contact updatedContact;
printf("Enter Name: ");
scanf("%s", updatedContact.name);
printf("Enter Address: ");
scanf("%s", updatedContact.address);
printf("Enter Phone Number: ");
scanf("%s", updatedContact.phone);
contacts[contactIndex - 1] = updatedContact;
printf("Contact updated successfully!\n");
} else {
printf("Invalid contact index.\n");
}
}
void removeContact() {
int contactIndex;
printf("Enter the index of the contact you want to remove: ");
scanf("%d", &contactIndex);
if (contactIndex >= 1 && contactIndex <= contactCount) {
for (int i = contactIndex - 1; i < contactCount - 1; i++) {
contacts[i] = contacts[i + 1];
}
contactCount--;
printf("Contact removed successfully!\n");
} else {
printf("Invalid contact index.\n");
}
}
int main() {
int choice;
while (1) {
printf("\nContact Logger Menu:\n");
printf("1. Add Contact\n");
printf("2. Display Contacts\n");
printf("3. Update Contact\n");
printf("4. Remove Contact\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addContact();
break;
case 2:
displayContacts();
break;
case 3:
updateContact();
break;
case 4:
removeContact();
break;
case 5:
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
|
import 'package:flutter/material.dart';
import '../../../app_core/services/size_config.dart';
import '../../models/special_offer.dart';
class SpecialOffers extends StatefulWidget {
const SpecialOffers({
super.key,
});
@override
State<SpecialOffers> createState() => _SpecialOffersState();
}
class _SpecialOffersState extends State<SpecialOffers> {
late final List<SpecialOffer> specials = homeSpecialOffers;
int selectIndex = 0;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(15),
vertical: getProportionateScreenWidth(15),
),
child: Stack(children: [
Container(
height: getProportionateScreenWidth(150),
decoration: BoxDecoration(
color: const Color(0xFFE7E7E7),
borderRadius: BorderRadius.circular(20),
),
child: PageView.builder(
itemBuilder: (context, index) {
final data = specials[index];
return SpecialOfferWidget(context, data: data, index: index);
},
itemCount: specials.length,
allowImplicitScrolling: true,
onPageChanged: (value) {
setState(() => selectIndex = value);
},
),
),
_buildPageIndicator()
]),
);
}
Widget _buildPageIndicator() {
List<Widget> list = [];
for (int i = 0; i < specials.length; i++) {
list.add(i == selectIndex ? _indicator(true) : _indicator(false));
}
return Container(
height: 140,
alignment: Alignment.bottomCenter,
padding: const EdgeInsets.only(bottom: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: list,
),
);
}
Widget _indicator(bool isActive) {
return SizedBox(
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
margin: const EdgeInsets.symmetric(horizontal: 5.0),
height: 4.0,
width: isActive ? 16 : 4.0,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(2)),
color: isActive ? const Color(0XFF101010) : const Color(0xFFBDBDBD),
),
),
);
}
}
class SpecialOfferWidget extends StatelessWidget {
const SpecialOfferWidget(
this.context, {
Key? key,
required this.data,
required this.index,
}) : super(key: key);
final SpecialOffer data;
final BuildContext context;
final int index;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
data.discount,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: getProportionateScreenWidth(26)),
),
const SizedBox(height: 6),
Text(
data.title,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: getProportionateScreenWidth(16)),
),
const SizedBox(height: 6),
Text(
data.detail,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: getProportionateScreenWidth(12)),
),
],
),
),
),
AspectRatio(
aspectRatio: 0.7,
child: Image.asset(
data.icon,
),
),
],
);
}
}
|
export const hexToRgba = (hex: string): string => {
let r: number = 0,
g: number = 0,
b: number = 0;
// Dealing with a three-digit hexadecimal color (short form)
if (hex.length === 4) {
r = parseInt(hex[1] + hex[1], 16);
g = parseInt(hex[2] + hex[2], 16);
b = parseInt(hex[3] + hex[3], 16);
// Dealing with a six-digit hexadecimal color (long form)
} else if (hex.length === 7) {
r = parseInt(hex[1] + hex[2], 16);
g = parseInt(hex[3] + hex[4], 16);
b = parseInt(hex[5] + hex[6], 16);
}
// If the color wasn't three or six digits long, return an error.
if (!(hex.length === 4 || hex.length === 7))
throw new Error('Invalid HEX color.');
// Make sure r, g, and b are in the set {0, 1, ..., 255}
if (r > 255 || g > 255 || b > 255) throw new Error('Invalid HEX color.');
// Return as rgba
return `rgba(${r},${g},${b},0.5)`;
};
|
<template>
<svg
v-if="(hasSegments && numSegments > 1)"
:key="node.id"
@click="onClick"
>
<defs>
<filter :id="`${node.id}-path-shadow`" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="10" dy="10" />
<feColorMatrix result="matrixOut" in="offOut" type="matrix"
values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0" />
<feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<circle
:key="`double_circle_path_${node.id}_a`"
class="clickable"
fill="white"
:cx="circleData.x"
:cy="circleData.y"
:r="circleData.radius"
:stroke="getHexColour(this.segments[0].colour)"
:stroke-width="1"
:filter="`url(#${node.id}-path-shadow)`"
></circle>
<circle
:key="`double_circle_path_${node.id}_b`"
class="clickable"
fill="white"
:cx="circleData.x"
:cy="circleData.y"
:r="circleData.radius / 3"
:stroke="getHexColour(this.typeColour)"
:stroke-width="2"
></circle>
<path
v-for="(segment, loopIndex) in segments"
:key="`path_${node.id}_${loopIndex}`"
fill="white"
:stroke="getHexColour(segment.colour)"
:stroke-width="(strokeWidth + (segment.count * 3))"
:d="describeArc(circleData.x, circleData.y, circleData.radius, arcPoints[loopIndex][0], arcPoints[loopIndex][1])"
></path>
</svg>
<svg
v-else-if="(hasSegments && numSegments == 1)"
:key="node.id"
@click="onClick"
>
<defs>
<filter :id="`${node.id}-shadow`" x="-35%" y="-35%" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="5" dy="7" />
<feColorMatrix result="matrixOut" in="offOut" type="matrix"
values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.5 0" />
<feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<circle
:key="`double_circle_${node.id}_a`"
class="clickable"
fill="white"
:cx="circleData.x"
:cy="circleData.y"
:r="circleData.radius / 3"
:stroke="getHexColour(this.typeColour)"
:stroke-width="2"
></circle>
<circle
:key="`double_circle_${node.id}_b`"
class="clickable"
fill="white"
:cx="circleData.x"
:cy="circleData.y"
:r="circleData.radius"
:stroke="getHexColour(this.segments[0].colour)"
:stroke-width="strokeWidth"
:filter="`url(#${node.id}-shadow)`"
></circle>
</svg>
<svg
v-else
:key="node.id"
@click="onClick"
>
<defs>
<filter :id="`${node.id}-shadow`" x="-35%" y="-35%" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="5" dy="7" />
<feColorMatrix result="matrixOut" in="offOut" type="matrix"
values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.5 0" />
<feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<circle
:key="`single_circle_${node.id}`"
class="clickable"
fill="white"
:cx="circleData.x"
:cy="circleData.y"
:r="circleData.radius"
:stroke="getHexColour(this.typeColour)"
:stroke-width="strokeWidth"
:filter="`url(#${node.id}-shadow)`"
></circle>
</svg>
</template>
<script lang="ts">
import Vue from 'vue'
const colourMap: any = {
'light-green darken-1': '#7CB342',
'green darken-1': '#43A047',
'light-blue darken-1': '#039BE5',
'blue darken-1': '#1E88E5',
'indigo darken-1': '#3949AB',
'deep-purple darken-1': '#5E35B1',
'amber darken-1': '#FFB300',
'orange darken-1': '#FB8C00',
'red darken-1': '#E53935',
'light-green darken-3': '#558B2F',
'green darken-3': '#2E7D32',
'blue darken-3': '#2979FF',
'indigo darken-3': '#283593',
'deep-purple darken-3': '#4527A0',
'amber darken-3': '#FF8F00',
'orange darken-3': '#EF6C00',
'red darken-3': '#C62828',
}
export default Vue.extend({
name: 'DonutChart',
props: ['index', 'node', 'segments', 'typeColour', 'circleData'],
data() {
return {
numSegments: this.segments.length,
strokeWidth: 15 as number,
}
},
computed: {
hasSegments(): boolean {
return this.segments !== undefined && this.segments.length > 0
},
// svgSize(): number {
// const circleData = this.circleData as CircleData
// return circleData.x * 2
// },
arcSize(): number {
const size = 360 / this.segments.length
return size
},
arcPoints(): [number, number][] {
let arcs = [] as [number, number][];
for (let i = 0; i < this.segments.length; i++) {
const start = i * this.arcSize
arcs.push([start, start + this.arcSize])
}
return arcs
}
},
methods: {
onClick(event: any) {
this.$store.commit('nodes/set', this.node)
this.$store.commit('display/setDisplayBeliefDetails', true)
},
getHexColour(name: string) {
return colourMap[name]
// switch (name) {
// case 'light-green darken-1':
// return '#7CB342'
// case 'green darken-1':
// return '#43A047'
// case 'light-blue darken-1':
// return '#039BE5'
// case 'blue darken-1':
// return '#1E88E5'
// case 'indigo darken-1':
// return '#3949AB'
// case 'deep-purple darken-1':
// return '#5E35B1'
// case 'amber darken-1':
// return '#FFB300'
// case 'orange darken-1':
// return '##FB8C00'
// case 'red darken-1':
// return '#E53935'
// case 'light-green darken-3':
// return '#558B2F'
// case 'green darken-3':
// return '#2E7D32'
// case 'blue darken-3':
// return '#2979FF'
// case 'indigo darken-3':
// return '#283593'
// case 'deep-purple darken-3':
// return '#4527A0'
// case 'amber darken-3':
// return '#FF8F00'
// case 'orange darken-3':
// return '#EF6C00'
// case 'red darken-3':
// return '#C62828'
// default:
// return '#FFFFFF'
// }
},
// CODE TAKEN FROM https://stackoverflow.com/questions/5736398/how-to-calculate-the-svg-path-for-an-arc-of-a-circle
describeArc(x: number , y: number , radius: number , startAngle: number , endAngle: number) {
const start = this.polarToCartesian(x, y, radius, endAngle);
const end = this.polarToCartesian(x, y, radius, startAngle);
const largeArcFlag = (endAngle - startAngle <= 180) ? "0" : "1";
const d = [
"M", start.x, start.y,
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");
return d;
},
polarToCartesian(centerX: number, centerY: number, radius: number, angleInDegrees: number) {
const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
},
// END OF TAKEN CODE
},
})
</script>
<style lang="scss">
.clickable:hover {
cursor: pointer;
}
</style>
|
<!DOCTYPE html>
<html lang="en" ng-app="app" ng-controller="registerCtrl">
<head>
<meta charset="UTF-8">
<title>TrackR | Register</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/customcss/custom.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/angular/angular.js"></script>
<script src="/controllers/register.controller.js"></script>
</head>
<body>
<ng-include src="'/includes/header.html'"></ng-include>
<div class="container bg-overlay">
<div class="row">
<div class="container container-table">
<div class="row vertical-center-row">
<div class="text-center col-md-4 col-md-offset-4 form-body-register">
<form name="registerForm">
<h1>TrackR Register</h1>
<div class="form-group">
<label for="name">Full name</label>
<input type="text" class="form-control" ng-model="user.name" placeholder="Enter your name" name="name" required>
<span ng-show="registerForm.name.$dirty && registerForm.name.$error.required" style="color:red">Your name is required</span>
</div>
<div class="form-group ">
<label for="username">Username</label>
<input type="text" class="form-control" ng-model="user.username" placeholder="Enter a username" name="username" ng-minLength="6" required>
<span ng-show="registerForm.username.$dirty && registerForm.username.$error.required" style="color:red">A username is required</span>
<span ng-show="registerForm.username.$dirty && registerForm.username.$error.minlength" style="color:red">Username must be six characters</span>
</div>
<div class="form-group ">
<label for="email">Email address</label>
<input type="email" class="form-control" ng-model="user.email" placeholder="Enter email" name="email" required>
<span ng-show="registerForm.email.$dirty && registerForm.email.$error.required" style="color:red">An email is required</span>
<span ng-show="registerForm.email.$dirty && registerForm.email.$error.email" style="color:red">Must be a valid email</span>
</div>
<div class="form-group ">
<label for="password">Password</label>
<input type="password" class="form-control" ng-model="user.password" placeholder="Password" name="password" ng-minLength="6" required>
<span ng-show="registerForm.password.$dirty && registerForm.password.$error.required" style="color:red">A password is required</span>
<span ng-show="registerForm.password.$dirty && registerForm.password.$error.minlength" style="color:red">Password must be six characters</span>
</div>
<input ng-disabled="registerForm.$invalid" type="submit" class="btn btn-default" ng-click="registerUser(user)" value="Register" />
</form>
<p ng-show="registerSuccess" style="color:green">Register Successful</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|
package com.example.liuxiaoming.upwork.test;
import android.text.TextUtils;
import android.util.Log;
import com.example.liuxiaoming.testthread.MainActivity;
import com.example.liuxiaoming.upwork.UpWorker;
import com.example.liuxiaoming.upwork.Utils;
import com.orhanobut.logger.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
public class TestWork2 extends UpWorker<TestWork2.Builder> {
private String tag = "TestWork2";
public TestWork2(TestWork2.Builder builder) {
super(builder);
}
@Override
public Observable doWork() {
final String count = (String) inputData.getKeyValueMap().get(MainActivity.COUNT);
Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> e) throws Exception {
Log.d(tag,"编号:"+count+" 发送大便~~"+" thread-->"+Utils.getThreadSignature()+" 时间:"+new SimpleDateFormat("hh:mm:ss:SSS").format(new Date()));
e.onNext( "编号:"+count+" 发送大便~~"+" thread-->"+Utils.getThreadSignature()+" 时间:"+new SimpleDateFormat("hh:mm:ss:SSS").format(new Date()));
}
}).doOnNext(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
Utils.sleepForInSecs(2);
Log.d(tag,"编号:"+count+" 大便传送中。。。"+" thread-->"+Utils.getThreadSignature()+" 时间:"+new SimpleDateFormat("hh:mm:ss:SSS").format(new Date()));
}
});
return observable;
}
public static final class Builder extends UpWorker.Builder<Builder> {
@Override
public TestWork2 build() {
return new TestWork2(this);
}
@Override
public TestWork2.Builder getThis() {
return this;
}
}
}
|
import { isValidENSAddress } from '../../../src/api/utils/isValidENSAddress';
describe('isValidENSAddress', () => {
describe('should return true for', () => {
it('a valid .eth name', () => {
expect(isValidENSAddress('myens.eth')).toBe(true);
expect(isValidENSAddress('ensdomain.eth')).toBe(true);
});
it('a valid .xyz name', () => {
expect(isValidENSAddress('example.xyz')).toBe(true);
expect(isValidENSAddress('myname.xyz')).toBe(true);
});
it('valid emoji names', () => {
expect(isValidENSAddress('🐉🐉🐉🐉🐉🐉🐉🐉🐉🐉🐉🐉🐉.eth')).toBe(true);
expect(isValidENSAddress('🚀.xyz')).toBe(true);
expect(isValidENSAddress('somewordsbefore🚀.eth')).toBe(true);
});
it('valid label.address.eth names', () => {
expect(isValidENSAddress('mylabel.address.eth')).toBe(true);
expect(isValidENSAddress('💫.address.eth')).toBe(true);
});
it('255 character .eth names', () => {
const ensName = 'a'.repeat(250) + '.eth';
expect(isValidENSAddress(ensName)).toBe(true);
});
it('unicode .eth names', () => {
expect(isValidENSAddress('大木888.eth')).toBe(true);
});
it('special characters', () => {
expect(isValidENSAddress('$$$.eth')).toBe(true);
});
});
describe('should return false for', () => {
it('an invalid .abc name', () => {
expect(isValidENSAddress('invalid.abc')).toBe(false);
});
it('just ".eth"', () => {
expect(isValidENSAddress('.eth')).toBe(false);
});
it('an empty string', () => {
expect(isValidENSAddress('')).toBe(false);
});
});
});
|
import {Component, ViewContainerRef,ViewChild} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Device, DeviceVariable} from './models.ts';
import {Subscription} from 'rxjs/Subscription';
import {MapToIterable} from './pipes';
import {VariableComponent} from './variable.component';
import {IotService} from './iot.service';
@Component({
selector: '[variable]',
template: `
<div class="iot-resource">
<b>{{name}}</b>
<div class="iot-device-raw-value">{{rawValue}}</div>
<mdl-switch [(ngModel)]="value" (change)="onChange($event)" [disabled]="isReadOnly()" ></mdl-switch>
</div>`
})
export class VariableBinnaryComponent extends VariableComponent {
rawValue : string;
value : number = 0;
max : number;
min : number;
sub;
@ViewChild('slider') slider;
constructor(private iot : IotService) {
super();
}
ngAfterViewInit(){
this.iot.onConnected(() => {
this.sub = this.iot.subscribe("EventValueUpdate", { di: this.di, resource: this.resource }, (data) => {
this.value = data.value["value"];
this.rawValue = JSON.stringify(data.value);
});
});
}
init(di, name, variable) {
super.init(di, name, variable);
setTimeout(()=>{
this.value = variable.values["value"];
this.rawValue = JSON.stringify(variable.values);
}, 10);
}
onChange(e){
this.updateValue(e);
}
updateValue(value){
let obj = {
"value": value
};
this.iot.setValue(this.di, this.resource, obj);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/jQuery.min.js"></script>
</head>
<style>
div {
width: 200px;
height: 200px;
background-color: antiquewhite;
}
</style>
<body>
<video src="mov.mp4"></video>
<div></div>
<script>
//JavaScript库:即仓库,是一个封装好的特定集合;js文件,对原生代码进行封装,比如jquery就是为了快速方便的仓做dom,里面基本上都是函数(方法)
//常见的js库,jQuery,prototype,Yui,Dojo,extjs 移动端zepto,内部都是用js实现,主要学习jQuery
//jQuery是一个快速,简洁的js库
//一。页面加载 $(function() {})
//$('div').hide();
//1.等着页面dom加载完毕再去执行js代码
/* $(document).ready(function() {
$('div').hide();
})*/
//2.等着页面dom加载完毕再去执行js代码
/*$(function() {
$('div').hide();
})
二。$是什么
//$是jQuery的别称(另外的名字)
$(function() {
alert(11);
})
$(function() {
jQuery('div').hide();
})
//2.$同时也是jQuery的顶级对象
//三。jQuery有自己的方法,不能乱用
//1.dom对象,用原生js获取过来的对象就是dom对象
var myDiv = document.querySelector('div'); //myDiv是dom对象
console.log(myDiv);
//2.jquery对象 :用jquery方式获取过来的对象是jQuery,本质:通过$把dom元素进行封装
$('div');
console.log($('div')); //有一个jQuery对象
//3.jquery对象只能使用jQuery方法,dom对象使用原生JavaScript属性和方法
myDiv.style.display = 'none';
//myDiv.hide();//报错
$('div').style.display = 'none'; //报错
*/
//四。dom和jQuery对象的互相转换
//1.dom对象转jQuery对象
//1).直接获取视频,得到的激素jQuery
$('video');
console.log($('video'));
//2).已经使用原生dom获取获取过来dom对象
var myVideo = document.querySelector('video');
//$(myVideo);
//$(myVideo).play(); //jquery里面无play这个方法
//2.jquery对象转换为dom对象
//myVideo.play();
$('div')[0].play();
$('div').get[0].play();
</script>
</body>
</html>
|
<ng-container *ngIf="basket$ | async">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="border-0 bg-light" scope="col">
<div class="p-2 px-3 text-uppercase">Product</div>
</th>
<th class="border-0 bg-light" scope="col">
<div class="p-2 px-3 text-uppercase">Price</div>
</th>
<th class="border-0 bg-light" scope="col">
<div class="p-2 px-3 text-uppercase">Quantity</div>
</th>
<th class="border-0 bg-light" scope="col">
<div class="p-2 px-3 text-uppercase">Total</div>
</th>
<th *ngIf="isBasket" class="border-0 bg-light" scope="col">
<div class="p-2 px-3 text-uppercase">Remove</div>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of (basket$|async)!.basketItem">
<th scope="row">
<div class="p-2">
<img src="{{item.picUrl}}" alt="{{item.productName}}
" class="img-fluid" style="max-height: 50px;">
<div class="ml-3 d-inline-block align-middle">
<h5 class="mb-0">
<a routerLink="/shop/{{item.productId}}" class="text-dark">{{item.productName}}</a>
</h5>
<span class="text-muted font-weight-normal d-block">Category: {{item.category}}</span>
</div>
</div>
</th>
<td class="align-middle">
<strong>
{{item.price |currency:'BDT '}}
</strong>
</td>
<td class="align-middle">
<div class="d-flex align-items-center">
<i *ngIf="isBasket" (click)="decrementItemQuantity(item)" class="fa fa-minus-circle text-warning mr-2"
style="cursor: pointer; font-size: 2em;"></i>
<span class="font-weight-bold" style="font-size: 1.5em;">
{{item.quantity}}
</span>
<i *ngIf="isBasket" (click)="incrementItemQuantity(item)" class="fa fa-plus-circle text-warning mx-2"
style="cursor: pointer; font-size: 2em;"></i>
</div>
</td>
<td class="align-middle">
<strong>
{{item.price * item.quantity | currency:'BDT '}}
</strong>
</td>
<td class="align-middle text-center">
<a class="text-danger">
<i *ngIf="isBasket" (click)="removeBasketItem(item)" class="fa fa-trash" style="font-size: 3em;"></i>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</ng-container>
|
import { useContext } from "react";
import { Avatar, Badge, Button, Layout, Grid } from "antd";
import { Link, useNavigate } from "react-router-dom";
import { AuthContext } from "../context/auth.context";
import Logo from "../assets/tutti-cake-logo.png";
import { ShoppingCartOutlined, UserOutlined } from "@ant-design/icons";
function Navbar() {
const { Header } = Layout;
const navigate = useNavigate();
const { isLoggedIn, logOutUser, cartItemCount, user } = useContext(AuthContext);
const screens = Grid.useBreakpoint();
const handleLogout = () => {
logOutUser();
navigate("/");
};
return (
<Header
style={{
display: "flex",
alignItems: "center",
background: "#FFF",
borderBottom: "1px solid rgba(5, 5, 5, 0.06)",
padding: screens.lg ? '' : 0,
}}
>
<nav className="nav-container">
<Link to="/" className="logo-container">
<img src={Logo} alt="TuttiCake Logo" height={screens.lg ? 48 : 24} width={screens.lg ? 48 : 24} />
TuttiCake
</Link>
<ul className="nav-items-container">
<li>
<Link to="/cakes">
<Button type="link">Cakes</Button>
</Link>
</li>
{isLoggedIn ? (
<>
<li style={{ marginRight: 12 }}>
<Link to={"/order/cart"}>
<Badge count={cartItemCount} showZero>
<Button
disabled={cartItemCount < 1}
shape="circle"
icon={<ShoppingCartOutlined />}
/>
</Badge>
</Link>
</li>
<li>
{
user && (
<Link to="/my-account">
<Button
icon={
user.imageUrl ? (
<Avatar shape="circle" size='small' src={user.imageUrl} />
) : (
<UserOutlined />
)
}
style={{
paddingLeft: 4
}}
>{user.name}</Button>
</Link>
)
}
</li>
<li>
<Button type="primary" onClick={handleLogout}>
Logout
</Button>
</li>
</>
) : (
<>
<li>
<Link to="/sign-up">
<Button>Sign Up</Button>
</Link>
</li>
<li>
<Link to="/login">
<Button type="primary">Login</Button>
</Link>
</li>
</>
)}
</ul>
</nav>
</Header>
);
}
export default Navbar;
|
<?php
namespace App\Http\Controllers\vendor;
use App\Http\Controllers\Controller;
use App\Models\communities;
use App\Models\community_order_from_shop;
use App\Models\order;
use App\Models\Order_product;
use App\Models\shop_info;
use App\Models\User;
use App\Models\vendor_community_list;
use Barryvdh\DomPDF\Facade\Pdf;
use http\Exception\BadConversionException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class orderController extends Controller
{
public function __construct()
{
try {
$this->middleware(function ($request,$next){
$this->user_info = Auth::user();
$shop_info = shop_info::where('owner_id',$this->user_info->id)->first();
if ($shop_info)
{
if ($shop_info->status != 1)
{
return redirect(route('my.shop'));
}
return $next($request);
}
else {
return redirect(route('create.shop'));
}
});
}catch (\Throwable $exception)
{
return back();
}
}
public function primaryOrder ()
{
try {
$headerData = ['app'=>str_replace('_',' ',config('app.name')),'role'=>Auth::user()->roles()->first()->display_name,'title'=>'New Order List'];
$me = Auth::user();
$primaryOrders = Order_product::leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->select('u.name as customer_name','o.invoice_id','p.p_name','p.p_image','p.p_quantity','Order_products.*')
->where('Order_products.order_status',1)->where('order_products.vendor_id',$me->id)->get();
return view('back-end.vendor.orders.primary.order-list',compact('headerData','primaryOrders'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function acceptedOrder (Request $request)
{
try {
if ($request->isMethod('put'))
{
return $this->acceptedOrderSubmit($request);
}
$headerData = ['app'=>str_replace('_',' ',config('app.name')),'role'=>Auth::user()->roles()->first()->display_name,'title'=>'New Order List'];
$me = Auth::user();
$primaryOrders = Order_product::leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->select('u.name as customer_name','o.invoice_id','p.p_name','p.p_image','p.p_quantity','Order_products.*')->where('order_products.vendor_id',$me->id)->where(function ($query){
$query->where('Order_products.order_status',2);
$query->orWhere('Order_products.order_status',9);
$query->orWhere('Order_products.order_status',11);
})->get();
return view('back-end.vendor.orders.accepted.order-list',compact('headerData','primaryOrders'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
private function acceptedOrderSubmit(Request $request)
{
try {
$request->validate([
'product_id' => ['required', 'string'],
]);
extract($request->post());
$oID = decrypt($product_id); //oID = order_product table primary key (id)
$user = Auth::user();
$userOrder = Order_product::where('order_status',1)->where('id',$oID)->where('vendor_id',$user->id)->first();
Order_product::where('order_status',1)->where('id',$oID)->where('vendor_id',$user->id)->update([
'order_status' => 2,
'updated_by' => $user->id,
'number_of_updated' => ($userOrder->number_of_updated + 1),
]);
return back()->with('success','Order accept successfully');
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function sendingAdminOrder (Request $request)
{
try {
if ($request->isMethod('put'))
{
return $this->acceptedOrderSubmit($request);
}
$headerData = ['app'=>str_replace('_',' ',config('app.name')),'role'=>Auth::user()->roles()->first()->display_name,'title'=>'New Order List'];
$me = Auth::user();
$primaryOrders = Order_product::leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->leftJoin('order_statuses as os','order_products.order_status','os.status_value')
->select('u.name as customer_name','o.invoice_id','p.p_name','p.p_image','p.p_quantity','Order_products.*','os.status_name','os.status_value','os.title','os.badge')->where('order_products.vendor_id',$me->id)->where(function ($query){
$query->where('Order_products.order_status',9);
$query->orWhere('Order_products.order_status',10);
})->get();
// dd($primaryOrders);
return view('back-end.vendor.orders.sending.order-list',compact('headerData','primaryOrders'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function submitAdmin(Request $request)
{
try {
$request->validate([
'order_id' => ['required', 'string'],
]);
extract($request->post());
// dd($order_id);
$oID = decrypt($order_id); //oID = order_product table primary key (id)
$user = Auth::user();
Order_product::where('order_status',2)->where('id',$oID)->where('vendor_id',$user->id)->update([
'order_status' => 9,
]);
return back()->with('success','Order accept successfully');
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function sendingCommunityOrder (Request $request)
{
try {
if ($request->isMethod('put'))
{
return $this->acceptedOrderSubmit($request);
}
$headerData = ['app'=>str_replace('_',' ',config('app.name')),'role'=>Auth::user()->roles()->first()->display_name,'title'=>'New Order List'];
$me = Auth::user();
$primaryOrders = Order_product::leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->leftJoin('order_statuses as os','Order_products.order_status','os.status_value')
->select('u.name as customer_name','o.invoice_id','p.p_name','p.p_image','p.p_quantity','Order_products.*','os.status_name','os.status_value','os.title','os.badge')->where('order_products.vendor_id',$me->id)->where(function ($query){
$query->where('Order_products.order_status',11);
$query->orWhere('Order_products.order_status',12);
})->get();
return view('back-end.vendor.orders.sending.order-list',compact('headerData','primaryOrders'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function submitOrderCommunity(Request $request)
{
try {
$request->validate([
'order_id' => ['required','string'],
'community' => ['required','string'],
]);
extract($request->post());
$oID = decrypt($order_id);
$cID = decrypt($community);
$user = Auth::user();
$userOrder = Order_product::where('vendor_id',$user->id)->where('id',$oID)->first();
if (!($userOrder))
{
return back()->with('error','Access denied! Invalid order id');
}
$userCommunity = vendor_community_list::where('vendor_id',$user->id)->where('id',$cID)->where('status',1)->first();
if (!($userCommunity))
{
return back()->with('error','Access denied! Invalid community id');
}
$community = communities::where('id',$userCommunity->community_id)->where('status',1)->first();
$shop = shop_info::where('owner_id',$user->id)->where('status',1)->first();
if (community_order_from_shop::where('order_id',$userOrder->id)->where('status',1)->first())
{
return back()->with('error','Data already exist in database!');
}
community_order_from_shop::create([
'order_id' => $userOrder->id,
'shop_id' => $shop->id,
'community_id' => $community->id,// communities table id is here
'status' => 1,//1= Shop request to community
]);
Order_product::where('vendor_id',$user->id)->where('id',$oID)->where('order_status',2)->update([
'order_status' => 11,// Vendor request to community
'updated_by' => $user->id,
'number_of_updated' => ($userOrder->number_of_updated + 1),
]);
return back()->with('success', "Request send successfully");
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function viewOrder($orderID)
{
try {
$headerData = ['app'=>str_replace("_"," ",config("app.name")) ,'role'=>'User','title'=>'My Order view'];
$cID = Auth::user()->id;
$oID = decrypt($orderID); //oID = order_product table primary key (id)
$order_product = Order_product::leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->leftJoin('order_statuses as os','order_products.order_status','os.status_value')
->where('order_products.id',$oID)->where('order_products.vendor_id',$cID)->select('p.p_name as product_name','order_products.*','o.invoice_id','u.name as customer_name','os.status_name','os.status_value','os.title','os.badge')->first();
$vendorCommunities = vendor_community_list::leftJoin('communities as c','c.id','vendor_community_lists.community_id')->where('vendor_community_lists.vendor_id',$cID)->where('vendor_community_lists.status',1)->select('c.community_name as community','c.community_type','c.village','c.home','c.word','c.union','c.upazila','c.district','c.division','c.country','vendor_community_lists.*')->get();
// dd($vendorCommunities);
return view("back-end/vendor/orders/order-single-view",compact('order_product','headerData','vendorCommunities'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function InvoicePDF($orderID)
{
try {
$cID = Auth::user()->id;
$oID = decrypt($orderID); //oID = order_product table primary key (id)
$order_product = Order_product::leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->where('order_products.id',$oID)->where('order_products.vendor_id',$cID)->select('p.p_name as product_name','order_products.*','o.invoice_id','u.name as customer_name')->first();
// dd($order_product->product_name);
// return view("back-end/vendor/invoice_print_product_wise",compact("order_product"));
$pdf = PDF::loadView('back-end/vendor/invoice_print_product_wise',compact('order_product'));
$output = $pdf->output();
return new Response($output, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline',
'filename'=>"$oID'_invoice.pdf'"]);
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function viewInvoice($invoiceID)
{
try {
$invoice = decrypt($invoiceID);
$user = Auth::user();
$order = order::leftJoin('order_products as op','op.order_id','orders.order_id')->where('orders.invoice_id',$invoice)->where('op.vendor_id',$user->id)->first();
$order_products = Order_product::leftJoin('orders as o','o.order_id','order_products.order_id')
->leftJoin('products as p','p.id','order_products.product_id')
->where('o.invoice_id',$invoice)->where('order_products.vendor_id',$user->id)->select('p.p_name as product_name','order_products.*')->get();
return view("back-end/vendor/orders/order-invoice-view",compact('order','order_products'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function viewInvoicePdf($invoiceID)
{
try {
$invoice = decrypt($invoiceID);
$user = Auth::user();
$order = order::leftJoin('order_products as op','op.order_id','orders.order_id')->where('orders.invoice_id',$invoice)->where('op.vendor_id',$user->id)->first();
$order_products = Order_product::leftJoin('orders as o','o.order_id','order_products.order_id')
->leftJoin('products as p','p.id','order_products.product_id')
->where('o.invoice_id',$invoice)->where('order_products.vendor_id',$user->id)->select('p.p_name as product_name','order_products.*')->get();
// return view('back-end/vendor/invoice_print_invoice_wise',compact('order_products','order'));
$pdf = PDF::loadView('back-end/vendor/invoice_print_invoice_wise',compact('order_products','order'));
$output = $pdf->output();
return new Response($output, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline',
'filename'=>"$invoice'_invoice.pdf'"]);
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function canceledOrder()
{
try {
$headerData = ['app'=>str_replace('_',' ',config('app.name')),'role'=>Auth::user()->roles()->first()->display_name,'title'=>'New Order List'];
$me = Auth::user();
$primaryOrders = Order_product::leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->select('u.name as customer_name','o.invoice_id','p.p_name','p.p_image','p.p_quantity','Order_products.*')
->where('Order_products.order_status',0)->where('order_products.vendor_id',$me->id)->get();
return view('back-end.vendor.orders.canceled.order-list',compact('headerData','primaryOrders'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function completeOrderList()
{
try {
$headerData = ['app'=>str_replace('_',' ',config('app.name')),'role'=>Auth::user()->roles()->first()->display_name,'title'=>'New Order List'];
$me = Auth::user();
$primaryOrders = Order_product::leftJoin('users as u','u.id','Order_products.customer_id')
->leftJoin("products as p",'p.id','order_products.product_id')
->leftJoin('orders as o','o.order_id','order_products.order_id')
->select('u.name as customer_name','o.invoice_id','p.p_name','p.p_image','p.p_quantity','Order_products.*')
->where('Order_products.order_status',3)->where('order_products.vendor_id',$me->id)->get();
return view('back-end.vendor.orders.completed.order-list',compact('headerData','primaryOrders'));
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
public function destroy(Request $request)
{
try {
$request->validate([
'product_id' => ['required', 'string'],
]);
extract($request->post());
$oID = decrypt($product_id); //oID = order_product table primary key (id)
$user = Auth::user();
Order_product::where('order_status',1)->where('id',$oID)->where('vendor_id',$user->id)->update([
'order_status' => 0,
]);
return back()->with('success','Order cancel successfully');
}catch (\Throwable $exception)
{
return back()->with('error',$exception->getMessage());
}
}
}
|
import React from 'react';
import styled, {css} from "styled-components";
// Type (TS) FC
type PropsType = {
backgroundActive?: string
backgroundHover?: string
itemText?: string
itemColor?: string
itemActiveColor?: string
fullMode?: boolean
isActive?: boolean
}
// FC
const FirstNavItem: React.FC<PropsType> = (props) => {
return (
<StyledNavItem itemColor={props.itemColor} itemActiveColor={props.itemActiveColor}
backgroundHover={props.backgroundHover} backgroundActive={props.backgroundActive}
isActive={props.isActive} fullMode={props.fullMode}
>
<StyledNavItemIcon>
{props.children}
</StyledNavItemIcon>
<StyledNavItemText fullMode={props.fullMode} itemColor={props.itemColor}>
{props.itemText}
</StyledNavItemText>
</StyledNavItem>
);
}
export default FirstNavItem;
// Styled
const StyledNavItem = styled.button<PropsType>`
display: flex;
align-items: center;
margin-bottom: 4px;
padding-top: 10px;
padding-bottom: 10px;
width: 100%;
border-radius: 6px;
border-width: 0;
background-color: transparent;
cursor: pointer;
@media (max-width: 767px) {
margin-bottom: 0;
padding-left: 12px;
padding-right: 12px;
}
& path {
fill: ${props => props.itemColor};
}
;
${props => props.isActive && css<PropsType>`
background-color: ${props => props.backgroundActive};
& path {
fill: ${props => props.itemActiveColor};
}
;
& span {
color: ${props => props.itemActiveColor};
}
;
`};
${props => !props.isActive && css<PropsType>`
&:hover {
background-color: ${props => props.backgroundHover};
}
;
&:hover path {
fill: ${props => props.itemActiveColor};
}
;
&:hover span {
color: ${props => props.itemActiveColor};
}
;
`};
${props => !props.fullMode && css`
justify-content: center;
& div {
margin-left: 0;
}
;
`};
`
const StyledNavItemIcon = styled.div`
margin-left: 12px;
transform: translateY(2px);
`
const StyledNavItemText = styled.span<PropsType>`
display: block;
margin-left: 18px;
color: ${props => props.itemColor};
${props => !props.fullMode && css`
position: absolute;
visibility: hidden;
`}
`
|
*DECK EDIRAT
SUBROUTINE EDIRAT(IOPERA,NREGIO,NBMIX,MATCOD,FLXINT,AFLUX,RATES,
> SIGMAX,IMERGE,NMERGE)
*
*-----------------------------------------------------------------------
*
*Purpose:
* evaluate reaction rates from cross sections.
*
*Copyright:
* Copyright (C) 2002 Ecole Polytechnique de Montreal
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version
*
*Author(s): G. Marleau
*
*Parameters: input
* IOPERA type of action taken:
* = 2 add cross section (no flux);
* = 1 add reaction rates;
* = 0 evaluate integrated flux;
* =-1 subtract reaction rates.
* NREGIO number of regions.
* NBMIX number of mixtures.
* MATCOD material per region.
* FLXINT integrated fluxes.
* AFLUX adjoint fluxes.
* SIGMAX cross section array.
* IMERGE region merging matrix.
* NMERGE number of merged regions.
*
*Parameters: input/output
* RATES initial and final reaction rates.
*
*-----------------------------------------------------------------------
*
*----
* SUBROUTINE ARGUMENTS
*----
INTEGER IOPERA,NREGIO,NBMIX,MATCOD(NREGIO),IMERGE(NREGIO),
> NMERGE
REAL FLXINT(NREGIO),AFLUX(NREGIO),RATES(NMERGE),
> SIGMAX(0:NBMIX)
DOUBLE PRECISION, ALLOCATABLE, DIMENSION(:) :: DBRAT
*----
* SCRATCH STORAGE ALLOCATION
* DBRAT double-precision reaction rates.
*----
ALLOCATE(DBRAT(0:NMERGE))
*----
* INITIALIZE DOUBLE PRECISION REACTION RATES
*----
DO 90 IREG=0,NMERGE
DBRAT(IREG)=0.0D0
90 CONTINUE
IF(IOPERA.EQ.0) THEN
*----
* INTEGRATED FLUXES
*----
DO 100 IREG=1,NREGIO
IRATME=IMERGE(IREG)
DBRAT(IRATME)=DBRAT(IRATME)+DBLE(FLXINT(IREG))
100 CONTINUE
ELSE IF(IOPERA.EQ.1) THEN
*----
* SUM REACTION RATES
*----
DO 110 IREG=1,NREGIO
IRATME=IMERGE(IREG)
MATNUM=MATCOD(IREG)
DBRAT(IRATME)=DBRAT(IRATME)+DBLE(FLXINT(IREG))
> *DBLE(SIGMAX(MATNUM))
110 CONTINUE
ELSE IF(IOPERA.EQ.-1) THEN
*----
* SUBSTRACT REACTION RATES
*----
DO 120 IREG=1,NREGIO
IRATME=IMERGE(IREG)
MATNUM=MATCOD(IREG)
DBRAT(IRATME)=DBRAT(IRATME)-DBLE(FLXINT(IREG))
> *DBLE(SIGMAX(MATNUM))
120 CONTINUE
ELSE IF(IOPERA.EQ.2) THEN
*----
* ADD CROSS SECTIONS
*----
DO 130 IREG=1,NREGIO
IRATME=IMERGE(IREG)
MATNUM=MATCOD(IREG)
DBRAT(IRATME)=DBRAT(IRATME)+DBLE(SIGMAX(MATNUM))
130 CONTINUE
ELSE IF(IOPERA.EQ.10) THEN
*----
* INTEGRATED ADJOINT FLUXES
*----
DO 140 IREG=1,NREGIO
IRATME=IMERGE(IREG)
DBRAT(IRATME)=DBRAT(IRATME)+DBLE(FLXINT(IREG))
> *DBLE(AFLUX(IREG))
140 CONTINUE
ELSE IF(IOPERA.EQ.11) THEN
*----
* SUM ADJOINT-WEIGHTED REACTION RATES
*----
DO 150 IREG=1,NREGIO
IRATME=IMERGE(IREG)
MATNUM=MATCOD(IREG)
DBRAT(IRATME)=DBRAT(IRATME)+DBLE(FLXINT(IREG))
> *DBLE(AFLUX(IREG))*DBLE(SIGMAX(MATNUM))
150 CONTINUE
ELSE IF(IOPERA.EQ.-11) THEN
*----
* SUBSTRACT ADJOINT-WEIGHTED REACTION RATES
*----
DO 160 IREG=1,NREGIO
IRATME=IMERGE(IREG)
MATNUM=MATCOD(IREG)
DBRAT(IRATME)=DBRAT(IRATME)-DBLE(FLXINT(IREG))
> *DBLE(AFLUX(IREG))*DBLE(SIGMAX(MATNUM))
160 CONTINUE
ENDIF
*----
* STORE DOUBLE PRECISION REACTION RATES IN SINGLE PRECISION VECTOR
*----
DO 170 IREG=1,NMERGE
RATES(IREG)=RATES(IREG)+REAL(DBRAT(IREG))
170 CONTINUE
*----
* SCRATCH STORAGE DEALLOCATION
*----
DEALLOCATE(DBRAT)
RETURN
END
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
abstract class StreamingSocket {
Stream<int> getCounterStream(int startnum, bool status);
}
// ignore: camel_case_types
class counterSocket implements StreamingSocket {
@override
Stream<int> getCounterStream(startnum, status) async*{
int i = startnum;
while (status) {
yield i--;
await Future.delayed(const Duration(milliseconds: 1000));
if (i<0){
break;
}
}
}
}
final startNumProvider = StateProvider((ref) => 20);
final streamCountProvider = Provider<StreamingSocket>((ref) => counterSocket());
final streamCountProvider1 = Provider<StreamingSocket>((ref) => counterSocket());
final statusProvider = StateProvider((ref) => true);
final counterProvider = StateProvider<Stream>((ref) {
final socket = ref.watch(streamCountProvider);
return socket.getCounterStream(ref.watch(startNumProvider), ref.watch(statusProvider));
});
final counterProvider1 = StreamProvider<int>((ref) {
final socket = ref.watch(streamCountProvider1);
return socket.getCounterStream(30, true);
});
|
"use client";
import React, { useState } from "react";
import { enableMapSet, produce } from "immer";
import { NormalisedData, NormalisedMap, TreeListPorps } from "./types";
import { TreeListHelper } from "./helper";
import { Group, Icon, Tree, TreeItem, TreeItemLabel } from "./tree-list-styles";
import Checkbox from "../../checkbox/checkbox";
/**
* Learning purpose
* Reference from one talented developer
*/
enableMapSet();
const TreeList = ({ data }: TreeListPorps) => {
// CONST, STATE, REF
const [selectedKeyPaths, setSelectedKeyPaths] = useState<string[][]>([["A"]]);
const [list, setList] = useState<NormalisedMap>(
TreeListHelper.buildSelectionState(TreeListHelper.normaliseData(data), selectedKeyPaths)
);
// EVENT HANDLERS
const handleOnClick = (event: React.MouseEvent<HTMLLIElement>) => {
event.stopPropagation();
// toggle expended
};
// RENDER FUNCTION
const renderItem = (item: NormalisedData) => {
const { key, keyPath, checked, selected, expanded, indeterminate, label, children } = item;
return (
<TreeItem
role="leaf"
key={key}
aria-selected={selected}
aria-expanded={!!children ? expanded : undefined}
onClick={handleOnClick}
>
<TreeItemLabel $focued={false} $selected={selected}>
{children && <Icon aria-hidden />}
<Checkbox tabIndex={-1} checked={checked} indeterminate={indeterminate} />
{label}
</TreeItemLabel>
{children && expanded && (
<Group role="group">
{Array.from(children.values()).map((child) => renderItem(child))}
</Group>
)}
</TreeItem>
);
};
return <Tree role="tree">{Array.from(list.values()).map((item) => renderItem(item))}</Tree>;
};
export default TreeList;
|
pub struct BitifyFlags(u8);
impl BitifyFlags {
pub const ESCAPING: u8 = 0;
pub const START: u8 = 1;
pub const END: u8 = 2;
pub const fn new() -> Self {
Self(0b0000_0000)
}
pub const fn mask(&self, index: u8) -> u8 {
1 << index
}
pub const fn set_on(self, index: u8) -> Self {
let flags = self.0 | self.mask(index);
Self(flags)
}
pub const fn toggle(self, index: u8) -> Self {
let flags = self.0 ^ self.mask(index);
Self(flags)
}
pub const fn is_on(&self, index: u8) -> bool {
self.0 & self.mask(index) != 0
}
pub const fn is_off(&self, index: u8) -> bool {
!self.is_on(index)
}
}
|
//
// ProductsTableViewCell.swift
// DigioTest
//
// Created by Vitor Mendes on 01/08/23.
//
import UIKit
class ProductsTableViewCell: UITableViewCell {
let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.boldSystemFont(ofSize: 18)
titleLabel.text = "Produtos"
return titleLabel
}()
var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
return collectionView
}()
var products: [Product] = []
var openDetail: ((Product) -> Void)?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCollection()
setupViews()
}
func setupCollection() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(ProductsCollectionViewCell.self,
forCellWithReuseIdentifier: ProductsCollectionViewCell.description())
}
func setupViews() {
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(titleLabel)
contentView.addSubview(collectionView)
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: Spacing.normalSpacing),
titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor,
constant: -Spacing.normalSpacing),
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,
constant: Spacing.normalSpacing)
])
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor),
collectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
collectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
collectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
collectionView.heightAnchor.constraint(equalToConstant: Size.cardSize)
])
}
func setup(products: [Product], openDetail: @escaping (Product) -> Void) {
self.products = products
self.openDetail = openDetail
collectionView.reloadData()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ProductsTableViewCell: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ProductsCollectionViewCell.description(),
for: indexPath) as! ProductsCollectionViewCell
cell.setupCell(image: products[indexPath.row].imageURL)
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: Size.productCollectionSize, height: Size.productCollectionSize)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
openDetail?(self.products[indexPath.item])
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: Spacing.mediumSpacing)
}
}
|
/******************************************************************
imu driver instance for WIT brand
Features:
- imu operation logic for onboard hardware
- xxx
Prerequisites:
- sudo apt install ros-<ros distro>-serial
Written by Xinjue Zou, xinjue.zou@outlook.com
GNU General Public License, check LICENSE for more information.
All text above must be included in any redistribution.
Changelog:
2022-04-04: Initial version
2022-xx-xx: xxx
******************************************************************/
#pragma once
#include "imu_base.h"
#include <serial/serial.h>
#include <vector>
class ImuWit : public ImuBase
{
public:
ImuWit() = delete;
ImuWit(std::shared_ptr<ros::NodeHandle>& NodeHandle, const std::string& Module,
const std::string& SerPort, unsigned int Baudrate, unsigned int PackLength,
const std::shared_ptr<std::vector<int>> ResetYaw, const std::shared_ptr<std::vector<int>> Unlock = nullptr, int InstructionMinSpan = 5,
bool WithMagnetic = true, bool WithTemperature = false);
~ImuWit() override;
public:
// override
void setPublishParams(const std::string& FrameId, const std::string& DataTopic,
const std::string& MagTopic, const std::string& TempTopic) override;
bool init(bool ResetAtInitial = false) override;
void read2Publish() override;
bool reset() override;
protected:
void reconfigPub();
void extract2Array(const std::string& Str, std::vector<std::string>& Array, const char Sep = '*');
void convert2Hex(std::vector<std::string>& Array, std::vector<uint8_t>& HexArray);
void fetchData(unsigned char* Data, size_t Length);
protected:
struct Time
{
int year;
int month;
int day;
int hour;
int min;
int sec;
time_t utc;
};
struct Triple
{
double x;
double y;
double z;
};
struct Angle
{
double r;
double p;
double y;
};
struct Quat
{
double x;
double y;
double z;
double w;
};
protected:
std::string module_;
std::string serial_port_;
unsigned int baudrate_{ 9600 };
size_t pack_length_{ 11 };
std::vector<uint8_t> unlock_;
std::vector<uint8_t> reset_yaw_;
int instruction_min_span_{ 5 };
std::unique_ptr<serial::Serial> serial_inst_{ nullptr };
Time time_;
Triple acc_;
Triple gyro_;
Angle angle_;
Triple magnetic_;
Quat quaternion_;
bool with_magnetic_{ true };
bool with_temperature_{ true };
protected:
static const double CONSTANT;
static const double CONSTANT_ACC;
static const double CONSTANT_GYRO;
static const double CONSTANT_ANGLE;
static const double CONSTANT_QUATERNION;
};
|
import React, { useEffect, useState } from "react";
export default function MainText() {
const [value, setValue] = useState("");
const [show, setShow] = useState<Boolean>(false);
// 데이터 가져오기
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const myText = urlParams.get("t");
if (myText != null) {
const tempText = JSON.parse(decodeURIComponent(escape(atob(myText))));
setValue(tempText);
console.log(tempText);
}
}, []);
let save;
return (
<div className="w-100">
<label
htmlFor="message"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Your Text
</label>
<textarea
id="message"
rows={4}
value={value}
onChange={(e) => {
setValue(e.target.value);
save = btoa(
unescape(encodeURIComponent(JSON.stringify(e.target.value)))
);
window.history.pushState({}, "", "?t=" + save);
}}
className="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Write your thoughts here..."
></textarea>
<button
type="button"
onClick={() => {
navigator.clipboard.writeText(window.location.href);
setShow(true);
setTimeout(() => {
setShow(false);
}, 2000);
}}
className="text-white m-3 bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-5 py-2.5 text-center mr-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
>
Share
</button>
{/* alert */}
<div
className={
"transition-opacity duration-300 flex items-center p-4 mb-4 text-sm text-blue-800 rounded-lg bg-blue-50 dark:bg-gray-800 dark:text-blue-400 " +
(show ? "opacity-100" : "opacity-0")
}
role="alert"
>
<svg
className="flex-shrink-0 inline w-4 h-4 mr-3"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
viewBox="0 0 20 20"
>
<path d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" />
</svg>
<span className="sr-only">Info</span>
<div>
<span className="font-medium">success!</span> url has been copied to
your clipboard.
</div>
</div>
</div>
);
}
|
<?php
namespace App\Repositories;
use App\Http\Controllers\BaseController;
use App\Http\Resources\ProductVariantResource\ProductVariantShowAllResource;
use App\Interfaces\ProductVariantInterface;
use App\Models\Product_variant;
use App\PipelineFilters\ProductVariantPipeline\GetByKey;
use App\PipelineFilters\ProductVariantPipeline\GetByWord;
use App\PipelineFilters\ProductVariantPipeline\UseSort;
use Illuminate\Pipeline\Pipeline;
class ProductVariantRepository extends BaseController implements ProductVariantInterface
{
public function show($request,$getOnlyColumn) {
try {
$getData = app(Pipeline::class)
->send(Product_variant::query())
->through([
GetByKey::class,
GetByWord::class,
UseSort::class,
])
->thenReturn()
->select($getOnlyColumn);
if(request()->get('paginate') == true)
{
$outputData = $getData->paginate(request()->get('per_page') ,$getOnlyColumn,'page',request()->get('page'));
$getCollection = $outputData->getCollection();
}
else
{
$getCollection = $getData->limit(250)->get();
}
$itemsTransformed = $getCollection
->map(function($item) {
return $this->resourceFormat('show_all',$item);
});
if(count($getCollection) > 1 || request()->get('paginate') == true)
{
$itemsTransformed = $itemsTransformed->toArray();
}
else
{
$itemsTransformed = $itemsTransformed->first();
}
if(request()->get('paginate') == true)
{
$outputData = new \Illuminate\Pagination\LengthAwarePaginator(
$itemsTransformed,
$outputData->total(),
$outputData->perPage(),
$outputData->currentPage(), [
'path' => \Request::url(),
'query' =>request()->all()
]
);
$message = 'get product variant with paginate success';
}
else {
$outputData = $itemsTransformed;
if(count($getCollection) > 1 )
{
$message = 'get product variant data success without pagination max 250 data';
}
else
{
$message = 'get product variant data success';
}
}
return $this->handleQueryArrayResponse($outputData,$message);
} catch (\Exception $e) {
return $this->handleQueryErrorArrayResponse($e->getMessage(),'error when get product variant');
}
}
public function upsert($data) {
try {
foreach($data['data'] as $datas ) {
if($datas['id'] !== null) {
$upsertData = Product_variant::find($datas['id']);
if($upsertData) {
$upsertData->update($datas);
}
else {
$upsertData = Product_variant::create($datas);
}
}
else {
$upsertData = Product_variant::create($datas);
}
}
$message = 'upsert success';
$outputData = count($data['data']);
return $this->handleQueryArrayResponse($outputData,$message);
} catch (\Exception $e) {
return $this->handleQueryErrorArrayResponse($e->getMessage(),'error when insert / update product variant');
}
}
public function destroy($data){
try {
if(isset($data['by_id']))
{
$remove = Product_variant::where('id',$data['by_id'])->delete();
}
if(isset($data['by_product_id']))
{
$remove = Product_variant::where('fk_product_id',$data['by_product_id'])->delete();
}
if($remove == true)
{
return $this->handleQueryArrayResponse($remove,'destroy product variant success');
}
else
{
return $this->handleQueryErrorArrayResponse($remove,'destroy product variant fail');
}
}
catch (\Exception $e) {
return $this->handleQueryErrorArrayResponse($e->getMessage(),'error when destory product variant');
}
}
private function resourceFormat($returnCollection,$data) {
if($returnCollection == 'show_all') //faq service & experience
{
return new ProductVariantShowAllResource([
'data' => $data,
'status' => true
]);
}
}
}
|
/*
Copyright 2019 Bill Nixon
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package onedrive
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"log"
"os"
"golang.org/x/oauth2"
)
// randomBytesBase64 returns n bytes encoded in URL friendly base64.
func randomBytesBase64(n int) string {
// buffer to store n bytes
b := make([]byte, n)
// get b random bytes
_, err := rand.Read(b)
if err != nil {
log.Panic(err)
}
// convert to URL friendly base64
return base64.URLEncoding.EncodeToString(b)
}
// readTokenFromFile reads the json encoded token from a file.
func readTokenFromFile(filename string) (*oauth2.Token, error) {
// open file
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
// read json encoded token
token := &oauth2.Token{}
err = json.NewDecoder(file).Decode(token)
return token, err
}
// writeTokenToFile writes a josn encoded token to a file.
// If file already exists, it is replaced.
func writeTokenToFile(fileName string, token *oauth2.Token) {
// create file
file, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// write access token string
json.NewEncoder(file).Encode(token)
return
}
|
package handler
import (
"github.com/esmailemami/chess/game/internal/app/chess"
"github.com/esmailemami/chess/game/internal/app/models"
"github.com/esmailemami/chess/game/internal/app/service"
"github.com/esmailemami/chess/shared/errs"
"github.com/esmailemami/chess/shared/handler"
"github.com/esmailemami/chess/shared/logging"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type ChessHandler struct {
handler.Handler
chessService *service.ChessService
}
func NewChessHandler(chessService *service.ChessService) *ChessHandler {
return &ChessHandler{
chessService: chessService,
}
}
// JoinGame godoc
// @Tags chess
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path string true "id"
// @Success 200 {object} handler.JSONResponse[bool]
// @Failure 400 {object} errs.Error
// @Failure 422 {object} errs.ValidationError
// @Router /chess/join/{id} [post]
func (g *ChessHandler) JoinGame(ctx *gin.Context, id uuid.UUID) (handler.Response, error) {
currentUser := g.GetUser(ctx)
if currentUser == nil {
return nil, errs.UnAuthorizedErr()
}
err := g.chessService.JoinGame(ctx, currentUser, id)
if err != nil {
return nil, err
}
if err := chess.Join(ctx, currentUser.ID, id); err != nil {
logging.WarnE("failed to join chess in websocket", err)
}
return handler.OKBool(), nil
}
// WatchGame godoc
// @Tags chess
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path string true "id"
// @Success 200 {object} handler.JSONResponse[bool]
// @Failure 400 {object} errs.Error
// @Failure 422 {object} errs.ValidationError
// @Router /chess/watch/{id} [post]
func (g *ChessHandler) WatchGame(ctx *gin.Context, id uuid.UUID) (handler.Response, error) {
currentUser := g.GetUser(ctx)
if currentUser == nil {
return nil, errs.UnAuthorizedErr()
}
if err := chess.Watch(ctx, currentUser.ID, id); err != nil {
return nil, err
}
return handler.OKBool(), nil
}
// NewChess godoc
// @Tags chess
// @Accept json
// @Produce json
// @Security Bearer
// @Param input body models.CreateChessInputModel true "input model"
// @Success 200 {object} handler.JSONResponse[bool]
// @Failure 400 {object} errs.Error
// @Failure 422 {object} errs.ValidationError
// @Router /chess [post]
func (g *ChessHandler) NewChess(ctx *gin.Context, req models.CreateChessInputModel) (handler.Response, error) {
currentUser := g.GetUser(ctx)
if currentUser == nil {
return nil, errs.UnAuthorizedErr()
}
dbChess, err := g.chessService.NewChess(ctx, currentUser, &req)
if err != nil {
return nil, err
}
// send the new chess to the websocket to show users games
if err := chess.New(ctx, currentUser.ID, dbChess.ID); err != nil {
logging.WarnE("failed to create chess in websocket", err)
}
return handler.OKBool(), nil
}
|
import React, { Suspense, lazy, useEffect } from 'react';
import { Switch } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import routes from './routes';
import Loader from 'react-loader-spinner';
import Layout from './components/Layout/Layout';
import authOperations from './redux/auth/auth-operations';
import PrivateRoute from './components/PrivateRoute';
import PublicRoute from './components/PublicRoute';
// import { Home } from '@material-ui/icons';
const HomePage = lazy(() =>
import('./pages/HomePage/HomePage.js' /* webpackChunkName: "home-page" */),
);
const RegisterPage = lazy(() =>
import(
'./pages/RegisterPage/RegisterPage.js' /* webpackChunkName: "register-page" */
),
);
const LoginPage = lazy(() =>
import('./pages/LoginPage/LoginPage.js' /* webpackChunkName: "login-page" */),
);
const ContactsPage = lazy(() =>
import(
'./pages/ContactsPage/ContactsPage.js' /* webpackChunkName: "contacts-page" */
),
);
export default function App() {
const dispatch = useDispatch();
useEffect(() => dispatch(authOperations.getCurrentUser()), [dispatch]);
return (
<Layout>
<Suspense
fallback={
<Loader
type="BallTriangle"
color="#e1e2ed"
height={60}
width={60}
className="loader"
/>
}
>
<Switch>
<PublicRoute exact path={routes.home}>
<HomePage />
</PublicRoute>
<PublicRoute
path={routes.register}
restricted
redirectTo={routes.contacts}
>
<RegisterPage />
</PublicRoute>
<PublicRoute
path={routes.login}
restricted
LoginPage
redirectTo={routes.contacts}
>
<LoginPage />
</PublicRoute>
<PrivateRoute path={routes.contacts} redirectTo={routes.login}>
<ContactsPage />
</PrivateRoute>
<PublicRoute>
<HomePage />
</PublicRoute>
</Switch>
</Suspense>
</Layout>
);
}
|
package com.example.myfirstapp.pictures.data
import android.util.Log
import com.example.myfirstapp.core.Result
import com.example.myfirstapp.core.TAG
import com.example.myfirstapp.core.data.remote.Api
import com.example.myfirstapp.pictures.data.local.ItemDao
import com.example.myfirstapp.pictures.data.remote.ItemEvent
import com.example.myfirstapp.pictures.data.remote.ItemService
import com.example.myfirstapp.pictures.data.remote.ItemWsClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.withContext
class ItemRepository(private val itemService: ItemService,
private val itemWsClient: ItemWsClient,
private val itemDao: ItemDao) {
val picturesStream by lazy { itemDao.getAll() }
init {
Log.d(TAG, "init")
}
suspend fun refresh() {
Log.d(TAG, "refresh started")
try {
val pictures = itemService.find(authorization = getBearerToken())
itemDao.deleteAll()
pictures.forEach{ itemDao.insert(it) }
Log.d(TAG, "refresh succeeded")
} catch (e: Exception) {
Log.w(TAG, "refresh failed", e)
}
}
suspend fun openWsClient() {
Log.d(TAG, "openWsClient")
withContext(Dispatchers.IO) {
getItemEvents().collect {
Log.d(TAG, "Item event collected $it")
if (it is Result.Success) {
val itemEvent = it.data;
when (itemEvent.event) {
"created" -> handleItemCreated(itemEvent.payload.updatedPicture)
"updated" -> handleItemUpdated(itemEvent.payload.updatedPicture)
"deleted" -> handleItemDeleted(itemEvent.payload.updatedPicture)
}
}
}
}
}
suspend fun closeWsClient() {
Log.d(TAG, "closeWsClient")
withContext(Dispatchers.IO) {
itemWsClient.closeSocket()
}
}
suspend fun getItemEvents(): Flow<Result<ItemEvent>> = callbackFlow {
Log.d(TAG, "getItemEvents started")
itemWsClient.openSocket(
onEvent = {
Log.d(TAG, "onEvent $it")
if (it != null) {
Log.d(TAG, "onEvent trySend $it")
trySend(Result.Success(it))
}
},
onClosed = { close() },
onFailure = { close() });
awaitClose { itemWsClient.closeSocket() }
}
suspend fun update(picture: Picture): Picture {
Log.d(TAG, "update $picture...")
picture.isSaved = true
val updatedItem = itemService.update(authorization = getBearerToken(), picture._id, picture)
Log.d(TAG, "update $picture succeeded")
handleItemUpdated(updatedItem)
return updatedItem
}
suspend fun save(picture: Picture): Picture {
Log.d(TAG, "save $picture...")
picture.isSaved = true
val createdItem = itemService.create(authorization = getBearerToken(), picture)
Log.d(TAG, "save $picture succeeded")
Log.d(TAG, "handle created $createdItem")
handleItemCreated(createdItem)
deletePicture(createdItem.title, false)
return createdItem
}
suspend fun addLocally(picture: Picture){
itemDao.insert(picture);
}
suspend fun deleteLocally(){
itemDao.getLocalPictures(isSaved = false)
}
suspend fun getLocallySaved(): List<Picture>{
return itemDao.getLocalPictures(isSaved = false)
}
suspend fun updateLocally(picture: Picture){
Log.d(TAG, "Updating picture locally: ${picture}")
itemDao.update(picture)
}
private suspend fun handleItemDeleted(picture: Picture) {
Log.d(TAG, "handleItemDeleted - todo $picture")
}
private suspend fun handleItemUpdated(picture: Picture) {
Log.d(TAG, "handleItemUpdated...: $picture")
itemDao.update(picture)
}
private suspend fun handleItemCreated(picture: Picture) {
Log.d(TAG, "handleItemCreated...: $picture")
itemDao.insert(picture)
}
suspend fun deleteAll(){
itemDao.deleteAll()
}
suspend fun deletePicture(title: String, isSaved: Boolean) {
Log.d(TAG, "deleting not saved: ${title}, ${isSaved}")
itemDao.deletePictureNotSaved(title, isSaved)
}
suspend fun getNrUnsaved(): Int{
return itemDao.getNotSaved(false)
}
fun setToken(token: String) {
itemWsClient.authorize(token)
}
private fun getBearerToken() = "Bearer ${Api.tokenInterceptor.token}"
}
|
import React, { useState, useEffect, useContext } from 'react'
import { useHistory, useParams } from 'react-router-dom'
import { PlayerContext } from '../contexts/PlayerContext'
import '../styles/PlayerInformation.css'
import previous from "../assets/svgFiles/backward-solid.svg";
import play from "../assets/svgFiles/play-solid.svg";
import pause from "../assets/svgFiles/pause-solid.svg";
import next from "../assets/svgFiles/forward-solid.svg";
import share from "../assets/svgFiles/share-svgrepo-com.svg";
import mute from "../assets/svgFiles/mute.svg";
import unmute from "../assets/svgFiles/unmute.svg";
import SearchField from "./SearchField";
function PlayerApi({ playlistIndex, setPlaylistIndex }) {
const [context, updateContext, setContext] = useContext(PlayerContext)
const url = 'https://yt-music-api.herokuapp.com/api/yt/song/'
const videoId = context
const [player, setPlayer] = useState()
const [progress, setProgress] = useState(0)
const [volume, setVolume] = useState(100)
const [copyUrl, setCopyUrl] = useState(false)
const [playlistSongs, setPlaylistSongs] = useState([])
const [playlistArtist, setPlaylistArtist] = useState([])
const [userNotificationBottom, setuserNotificationBottom] = useState(false)
const [userNotificationTop, setuserNotificationTop] = useState(false)
const [playlist, setPlaylist] = useState([])
const history = useHistory()
useEffect(() => {
loadPlayer()
context.videoId
fetch(url + videoId)
}, [])
useEffect(() => {
setProgress(0)
var interval = setInterval(() => {
if (!context.player) return
let currentTime = context.player.getCurrentTime()
let duration = context.player.getDuration()
let playedPercent = (currentTime / duration) * 100
setProgress(playedPercent)
if (currentTime / duration == 1) {
pauseSong
clearInterval(interval)
nextSong()
playPauseImage.src = pause;
}
}, 100);
}, [playlistIndex, context.player])
useEffect(() => {
setTimeout(() => { playSong() }, 100);
}, [context])
function changeVolume(e) {
setVolume(e.target.value)
player.setVolume(volume - 2)
}
function changeSongPosition(e) {
setProgress(e.target.value)
let newPosition = (context.player.getDuration() * (e.target.value / 100))
context.player.seekTo(newPosition, true)
}
function loadPlayer() {
let ytPlayer = new YT.Player('yt-player', {
height: '0',
width: '0',
events: {
'onStateChange': onPlayerStateChange
}
});
setPlayer(ytPlayer)
updateContext({
player: ytPlayer
})
}
function playSong() {
player.loadVideoById(context.videoId);
setPlaylistIndex(context.queue.length - 1)
document.getElementById("playPauseButton").src = pause;
}
function pauseSong() {
player.pauseVideo();
}
function resumeSong() {
window.onload = playSong
player.playVideo();
}
function previousSong() {
if (playlistIndex === 1) {
setPlaylistIndex(context.queue.length - 1)
player.loadVideoById(context.queue[playlistIndex].videoId)
setuserNotificationBottom(true)
setTimeout(() => {
setuserNotificationBottom(false)
}, 1500);
return
}
player.loadVideoById(context.queue[(playlistIndex - 1)])
setPlaylistIndex((playlistIndex - 1))
}
function fetchPlaylist() {
/*
fetch(urlArtist + context.artistId)
.then(res => res.json())
.then(data => setPlaylistArtist({
artistSongs: data.products.songs.content
}))
.then(data => setPlaylistSongs(playlistArtist.artistSongs))
if (playlist.length <= 5) {
playlistSongs.map(song => (
playlist.push(song)
))
}*/
return
}
function nextSong() {
if (playlistIndex === context.queue.length - 1) {
setuserNotificationTop(true)
setPlaylistIndex(0)
setTimeout(() => {
setuserNotificationTop(false)
}, 2000);
return
}
player.loadVideoById(context.queue[(playlistIndex + 1)])
setPlaylistIndex((playlistIndex + 1))
}
function playPause() {
let playPauseImage = document.getElementById("playPauseButton");
if (playPauseImage.getAttribute('src') == play) {
resumeSong();
playPauseImage.src = pause;
} else {
pauseSong();
playPauseImage.src = play;
}
}
function muteUnmute() {
let muteUnmuteImage = document.getElementById("muteUnmuteButton");
if (muteUnmuteImage.getAttribute('src') == unmute) {
player.mute()
muteUnmuteImage.src = mute;
} else {
player.unMute()
muteUnmuteImage.src = unmute;
}
}
function shareSong() {
try {
const href = window.location.href;
navigator.clipboard.writeText(href);
setCopyUrl(true)
} catch {
}
setTimeout(() => {
setCopyUrl(false)
}, 2000);
}
function onPlayerStateChange(event) {
if (event.data != YT.PlayerState.PLAYING) return
}
return (
<div className="information">
<div className="artistText"> {context.queue[playlistIndex].song}</div>
<div className="artistText">{context.queue[playlistIndex].artist} </div>
<div id="yt-player"></div>
{copyUrl ? <div className="copyClipboard"> Copied to clipboard. </div> : null}
{userNotificationTop ? <div className="copyClipboard"> add more by playing more songs! </div> : null}
{userNotificationBottom ? <div className="copyClipboard"> No more songs at the bottom </div> : null}
<input type="range"
value={progress}
onChange={changeSongPosition}
className="slider"
style={{ width: '90%' }}
id="myRange"
/>
<div className="controllers">
<div></div>
<div className="controlButton"><img src={previous} id="previousButton" onClick={previousSong} /></div>
<div className="controlButton"><img src={play} id="playPauseButton" onClick={playPause} /></div>
<div className="controlButton"><img src={next} id="nextButton" onClick={nextSong} /></div>
<div className="controlButton" onClick={shareSong}><img src={share} /></div>
<div className="volumeController">
<div className="controlButton"><img src={unmute} id="muteUnmuteButton" onClick={muteUnmute} /></div>
<input type="range"
value={volume}
onChange={changeVolume}
className="slider"
style={{ width: '125px', position: 'relative', margin: '0 auto', top: '1.4vh', left: '0.5vw', display: 'block' }}
id="volumeRange"
/>
</div>
<div></div>
</div>
</div>
)
}
export default PlayerApi
|
/*
4. Buatlah sebuah program **ArrayUnique** yang menerima 2 parameter berupa array angka. Output adalah program adalah satu array berupa kumpulan angka di array pertama tetapi tidak memiliki duplikasi di di array kedua.
**Sample Test Case**
input: [1, 2, 3, 4] dan [1, 3, 5, 10, 16]
Output: [2, 4]
input: [3, 8] dan [2, 8]
Output: [3]
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
public class ArrayUnique {
public static int[] findUnique(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
List<Integer> list = new ArrayList<>();
// tambahkan semua angka dari nums2 ke dalam set
for (int num : nums2) {
set.add(num);
}
// cek setiap angka pada nums1, jika tidak ada di set, tambahkan ke dalam list
for (int num : nums1) {
if (!set.contains(num)) {
list.add(num);
}
}
// konversi list ke dalam array
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 3, 4};
int[] nums2 = {1, 3, 5, 10, 16};
int[] result = findUnique(nums1, nums2);
System.out.println(Arrays.toString(result)); // output: [2, 4]
nums1 = new int[]{3, 8};
nums2 = new int[]{2, 8};
result = findUnique(nums1, nums2);
System.out.println(Arrays.toString(result)); // output: [3]
}
}
|
#pragma once
#include <raylib.h>
#include <string>
class Button
{
public:
Button(Vector2 renderScale, int x, int y, int width, int height, Texture2D sprite, Texture2D label);
Button(Vector2 renderScale, int x, int y, int width, int height, Texture2D sprite);
~Button();
void UpdateStatus();
void Draw();
bool IsClicked() const;
void SetX(int x) { this->x = x; }
void SetY(int y) { this->y = y; }
void SetRelativeTextX(int relativeTextX) { this->relativeTextX = relativeTextX; }
void SetRelativeTextY(int relativeTextY) { this->relativeTextY = relativeTextY; }
void SetWidth(int width) { this->width = width; }
void SetHeight(int height) { this->height = height; }
void SetText(std::string text) { this->text = text; }
void SetSprite(Texture2D sprite) { this->sprite = sprite; }
void SetLabel(Texture2D label);
std::string GetText() { return text; }
int GetX() { return x; }
int GetY() { return y; }
int GetRelativeTextX() { return relativeTextX; }
int GetRelativeTextY() { return relativeTextY; }
int GetWidth() { return width; }
int GetHeight() { return height; }
bool IsClicked() { return isClicked; }
bool IsHovered() { return isHovered; }
private:
Texture2D sprite;
Texture2D label;
Vector2 renderScale;
bool labelIsSet = false;
bool isClicked = false;
bool isHovered = false;
int x = 0;
int y = 0;
int scaledX;
int scaledY;
int relativeTextX = 0;
int relativeTextY = 0;
int width = 100;
int height = 100;
int scaledWidth;
int scaledHeight;
std::string text;
int fontSize;
Color fontColor;
};
|
# floodmap
This project computes surface water extents from lake shapefile boundary maps. It uses the NRT Global Flood Mapping products produced from the LANCE-MODIS data processing system at NASA Goddard to compute the probability of water in each spatial cell within each shapefile boundary map. It then thresholds this probability to produce water mask files.
## Installation
#### Build Conda Env
If Anaconda is not yet installed in your environment, see: https://www.anaconda.com/products/individual for installation instructions.
```
>> conda create --name floodmap python=3.10 ipython
>> conda activate floodmap; conda install -c conda-forge mamba
(floodmap)>> mamba install -c conda-forge xarray numpy zlib rioxarray shapely pandas bottleneck geopandas utm gdal pyyaml
(floodmap)>> pip install wget
```
#### Install floodmap
```
(floodmap)>> git clone https://github.com/nasa-nccs-cds/floodmap.git
(floodmap)>> cd floodmap
(floodmap)>> python setup.py install
```
#### Download archived data
Download script for archived files for tile h20v09:
```
>> cd {results_dir}/h20v09/allData/61/MCDWD_L3_F2_NRT/Recent
>> scp "adaptlogin.nccs.nasa.gov:/att/nobackup/tpmaxwel/data/MCDWD_NRT/h20v09/allData/61/MCDWD_L3_F2_NRT/Recent/MCDWD_L3_F2_NRT.A*.h20v09.061.tif" .
>> scp "adaptlogin.nccs.nasa.gov:/att/nobackup/dslaybac/MCDWD_NRT/MCDWD_L3_NRT_2021250/MCDWD_L3_NRT.A202124*.h20v09.061.hdf" .
```
#### Configure execution
```
(floodmap)>> cp ./specs/sample-specs.yml ~/specs.yml
(floodmap)>> pico ~/specs.yml
```
#### Run floodmap
```
(floodmap)>> python ./exe/production.py ~/specs.yml
```
#### Visualize the results
```
(floodmap)>> python ./exe/visually_evaluate_workflow.py ~/specs.yml
```
#### Documentation
The floodmap user guide is found at `./docs/floodmap.pdf`
|
/** Reset some basic elements */
body, h1, h2, h3, h4, h5, h6,
p, blockquote, pre, hr,
dl, dd, ol, ul, figure {
margin: 0;
padding: 0;
}
/** Basic styling */
html {
font-size: 140%;
@include media-query($on-palm) {
font-size: 110%;
}
}
body {
font-family: $base-font-family;
font-size: $base-font-size;
font-weight: 300;
color: $text-color;
background-color: $background-color;
}
p {
line-height: $base-line-height;
}
/** Set `margin-bottom` to maintain vertycal rhythm */
h1, h2, h3, h4, h5, h6,
p, blockquote, pre,
ul, ol, dl, figure,
time, %vertical-rhythm {
margin-bottom: $spacing-unit / 2;
}
/** Images */
img {
max-width: 100%;
vertical-align: middle;
margin-top: $spacing-unit / 2;
margin-bottom: $spacing-unit / 2;
}
/** Figures */
figure > img {
display: block;
}
figcaption {
font-size: $small-font-size;
}
/** Lists */
ul, ol {
margin-left: $spacing-unit;
}
li {
> ul,
> ol {
margin-bottom: 0;
}
}
/** Headings */
h1, h2, h3, h4, h5, h6 {
font-weight: 300;
font-family: Raleway, sans-serif;
color: $brand-color;
}
/** Links */
a {
color: $brand-accent-color;
text-decoration: none;
&:visited {
color: darken($brand-accent-color, 10%);
}
&:hover {
color: lighten($brand-accent-color, 10%);
text-decoration: underline;
}
}
/** Times */
time {
font-family: 'Raleway', sans-serif;
font-size: 0.7rem;
color: $grey-color;;
}
/** Blockquotes */
blockquote {
color: $grey-color;
border-left: 4px solid $grey-color-light;
padding-left: $spacing-unit / 2;
font-size: 18px;
letter-spacing: -1px;
font-style: italic;
> :last-child {
margin-bottom: 0;
}
}
/** Code formatting */
pre,
code {
font-size: 15px;
border: 1px solid $grey-color-light;
border-radius: 3px;
background-color: #eef;
font-family: Inconsolata, monospace;
}
code {
padding: 1px 5px;
line-height: $base-line-height / 2;
}
pre {
padding: 8px 12px;
overflow-x: scroll;
> code {
border: 0;
padding-right: 0;
padding-left: 0;
}
}
/** Wrapper */
.wrapper {
max-width: -webkit-calc(800px - (#{$spacing-unit} * 2));
max-width: calc(800px - (#{$spacing-unit} * 2));
margin-right: auto;
margin-left: auto;
padding-right: $spacing-unit;
padding-left: $spacing-unit;
@extend %clearfix;
@include media-query($on-laptop) {
max-width: -webkit-calc(800px - (#{$spacing-unit}));
max-width: calc(800px - (#{$spacing-unit}));
padding-right: $spacing-unit / 2;
padding-left: $spacing-unit / 2;
}
}
/** Clearfix */
%clearfix {
&:after {
content: "";
display: table;
clear: both;
}
}
/** Icons */
.icon {
> svg {
display: inline-block;
width: 16px;
height: 16px;
vertical-align: middle;
path {
fill: $grey-color;
}
}
}
|
/**
* Copyright or © or Copr. IETR/INSA - Rennes (2008 - 2017) :
*
* Antoine Morvan <antoine.morvan@insa-rennes.fr> (2017)
* Clément Guy <clement.guy@insa-rennes.fr> (2014 - 2015)
* Karol Desnos <karol.desnos@insa-rennes.fr> (2014)
* Maxime Pelcat <maxime.pelcat@insa-rennes.fr> (2008 - 2012)
*
* This software is a computer program whose purpose is to help prototyping
* parallel applications using dataflow formalism.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
package org.ietr.preesm.algorithm.exportSdf3Xml;
import java.util.LinkedHashMap;
import java.util.Map;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.ietr.dftools.algorithm.model.sdf.SDFGraph;
import org.ietr.dftools.architecture.slam.Design;
import org.ietr.dftools.workflow.WorkflowException;
import org.ietr.dftools.workflow.elements.Workflow;
import org.ietr.dftools.workflow.implement.AbstractTaskImplementation;
import org.ietr.dftools.workflow.implement.AbstractWorkflowNodeImplementation;
import org.ietr.preesm.core.scenario.PreesmScenario;
import org.ietr.preesm.utils.paths.PathTools;
// TODO: Auto-generated Javadoc
/**
* The Class Sdf3Exporter.
*/
public class Sdf3Exporter extends AbstractTaskImplementation {
/** The Constant PARAM_PATH. */
public static final String PARAM_PATH = "path";
/** The Constant VALUE_PATH_DEFAULT. */
public static final String VALUE_PATH_DEFAULT = "./Code/SDF3/graph.xml";
/*
* (non-Javadoc)
*
* @see org.ietr.dftools.workflow.implement.AbstractTaskImplementation#execute(java.util.Map, java.util.Map, org.eclipse.core.runtime.IProgressMonitor,
* java.lang.String, org.ietr.dftools.workflow.elements.Workflow)
*/
@Override
public Map<String, Object> execute(final Map<String, Object> inputs, final Map<String, String> parameters, final IProgressMonitor monitor,
final String nodeName, final Workflow workflow) throws WorkflowException {
// Retrieve the inputs
final SDFGraph sdf = (SDFGraph) inputs.get(AbstractWorkflowNodeImplementation.KEY_SDF_GRAPH);
final PreesmScenario scenario = (PreesmScenario) inputs.get(AbstractWorkflowNodeImplementation.KEY_SCENARIO);
final Design archi = (Design) inputs.get(AbstractWorkflowNodeImplementation.KEY_ARCHITECTURE);
// Locate the output file
final String sPath = PathTools.getAbsolutePath(parameters.get("path"), workflow.getProjectName());
final IPath path = new Path(sPath);
final SDF3ExporterEngine engine = new SDF3ExporterEngine();
engine.printSDFGraphToSDF3File(sdf, scenario, archi, path);
return new LinkedHashMap<>();
}
/*
* (non-Javadoc)
*
* @see org.ietr.dftools.workflow.implement.AbstractTaskImplementation#getDefaultParameters()
*/
@Override
public Map<String, String> getDefaultParameters() {
final Map<String, String> parameters = new LinkedHashMap<>();
parameters.put(Sdf3Exporter.PARAM_PATH, Sdf3Exporter.VALUE_PATH_DEFAULT);
return parameters;
}
/*
* (non-Javadoc)
*
* @see org.ietr.dftools.workflow.implement.AbstractWorkflowNodeImplementation#monitorMessage()
*/
@Override
public String monitorMessage() {
return "Exporting SDF3 File";
}
}
|
import { Suspense } from "react";
import { Route, Routes, Link } from "react-router-dom";
import { MainPageAsync } from "./pages/MainPage/MainPage.async";
import { AboutPageAsync } from "./pages/AboutPage/AboutPage.async";
import { useTheme } from "./theme/useTheme";
import { classNames } from "./helpers/classNames/classNames";
import "./styles/index.scss";
const App = () => {
const { theme, toggleTheme } = useTheme();
return (
<div className={classNames("app", { hovered: true }, [theme, "ddd"])}>
<button onClick={toggleTheme}>TOGGLE</button>
<Link to="/">Main</Link>
<Link to="/about">About</Link>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/about" element={<AboutPageAsync />} />
<Route path="/" element={<MainPageAsync />} />
</Routes>
</Suspense>
</div>
);
};
export default App;
|
//
// Array+Utils.swift
//
// Created by bujiandi on 14/10/4.
//
extension Int {
public func times(_ function: (Int) -> Void) {
for i in 0 ..< self { function(i) }
}
}
extension Sequence {
/// join in string
@inlinable public func joined(separator:String, includeElement:(Element) throws -> String = { unwrapOptionalToString($0) }) rethrows -> String {
var result:String = ""
for item:Element in self {
if !result.isEmpty { result += separator }
result += try includeElement(item)
}
return result
}
/// change to Set<T>
@inlinable public func setMap<T>(_ transform: (Element) throws -> T) rethrows -> Set<T> where T:Hashable {
var set = Set<T>()
for item:Element in self {
set.insert(try transform(item))
}
return set
}
/// change first Element as U
@inlinable public func firstMap<U>(_ transform: (Element) throws -> U?) rethrows -> U? {
return (try first { try transform($0) != nil }) as? U
}
/// split array by element count
@inlinable public func split(elementCount:Int) throws -> [[Element]] {
if elementCount <= 0 {
throw "elementCount mast bigger than 0" as StringError
}
var result : [[Element]] = []
var list = [Element]()
for item in self {
if list.count == elementCount {
result.append(list)
list.removeAll(keepingCapacity: true)
}
list.append(item)
}
if list.count > 0 { result.append(list) }
return result
}
}
extension RangeReplaceableCollection {
/// ignore nil element append
@inlinable public mutating func appendIgnoreNil(_ element:Element?) {
if let value = element { append(value) }
}
}
extension RangeReplaceableCollection where Element : Hashable {
@inlinable public mutating func remove(element: Element) {
if let i = firstIndex(of: element) {
remove(at: i)
}
}
}
extension Collection {
/// ignore out of range
@inlinable public func element(at index:Index) -> Element? {
if !(startIndex..<endIndex).contains(index) { return nil }
return self[index]
}
}
extension MutableCollection where Index == Int {
/// 数据随机乱序 [已经有了 shuffled()]
// mutating func shuffleInPlace() {
// if count < 2 { return }
//
// for i in 0..<count - 1 {
// let j = Int.random(in: 1..<count)
// guard i != j else { continue }
// swapAt(i, j) // swap(&self[i], &self[j])
// }
// }
}
public func unwrapOptionalToString<T>(_ v:T?) -> String {
var val:String!
guard let value = v else { return "" }
let mirror = Mirror(reflecting: value)
if mirror.displayStyle == .optional {
let children = mirror.children
if children.count == 0 {
val = ""
} else {
val = "\(children[children.startIndex].value)"
}
} else {
val = "\(value)"
}
return val
}
public struct WeakArray<Element> where Element : AnyObject {
private var array:[WeakContainer<Element>] = []
public init() {}
}
extension WeakArray : RangeReplaceableCollection {
public func makeIterator() -> IndexingIterator<[Element]> {
let list = array.compactMap { $0.obj }
return list.makeIterator()
}
/// Creates an array containing the elements of a sequence.
///
/// You can use this initializer to create an array from any other type that
/// conforms to the `Sequence` protocol. For example, you might want to
/// create an array with the integers from 1 through 7. Use this initializer
/// around a range instead of typing all those numbers in an array literal.
///
/// let numbers = Array(1...7)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7]"
///
/// You can also use this initializer to convert a complex sequence or
/// collection type back to an array. For example, the `keys` property of
/// a dictionary isn't an array with its own storage, it's a collection
/// that maps its elements from the dictionary only when they're
/// accessed, saving the time and space needed to allocate an array. If
/// you need to pass those keys to a method that takes an array, however,
/// use this initializer to convert that list from its type of
/// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple
/// `[String]`.
///
/// func cacheImagesWithNames(names: [String]) {
/// // custom image loading and caching
/// }
///
/// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
/// "Gold": 50, "Cerise": 320]
/// let colorNames = Array(namedHues.keys)
/// cacheImagesWithNames(colorNames)
///
/// print(colorNames)
/// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
///
/// - Parameter s: The sequence of elements to turn into an array.
public init<S>(_ s: S) where Element == S.Element, S : Sequence {
}
/// Creates a new array containing the specified number of a single, repeated
/// value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
public init(repeating repeatedValue: Element, count: Int) {
}
/// The number of elements in the array.
public var count: Int { return array.count }
/// The total number of elements that the array can contain without
/// allocating new storage.
///
/// Every array reserves a specific amount of memory to hold its contents.
/// When you add elements to an array and that array begins to exceed its
/// reserved capacity, the array allocates a larger region of memory and
/// copies its elements into the new storage. The new storage is a multiple
/// of the old storage's size. This exponential growth strategy means that
/// appending an element happens in constant time, averaging the performance
/// of many append operations. Append operations that trigger reallocation
/// have a performance cost, but they occur less and less often as the array
/// grows larger.
///
/// The following example creates an array of integers from an array literal,
/// then appends the elements of another collection. Before appending, the
/// array allocates new storage that is large enough store the resulting
/// elements.
///
/// var numbers = [10, 20, 30, 40, 50]
/// // numbers.count == 5
/// // numbers.capacity == 5
///
/// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
/// // numbers.count == 10
/// // numbers.capacity == 12
public var capacity: Int { return array.capacity }
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to an array, use this method
/// to avoid multiple reallocations. This method ensures that the array has
/// unique, mutable, contiguous storage, with space allocated for at least
/// the requested number of elements.
///
/// Calling the `reserveCapacity(_:)` method on an array with bridged storage
/// triggers a copy to contiguous storage even if the existing storage
/// has room to store `minimumCapacity` elements.
///
/// For performance reasons, the size of the newly allocated storage might be
/// greater than the requested capacity. Use the array's `capacity` property
/// to determine the size of the new storage.
///
/// Preserving an Array's Geometric Growth Strategy
///
/// If you implement a custom data structure backed by an array that grows
/// dynamically, naively calling the `reserveCapacity(_:)` method can lead
/// to worse than expected performance. Arrays need to follow a geometric
/// allocation pattern for appending elements to achieve amortized
/// constant-time performance. The `Array` type's `append(_:)` and
/// `append(contentsOf:)` methods take care of this detail for you, but
/// `reserveCapacity(_:)` allocates only as much space as you tell it to
/// (padded to a round value), and no more. This avoids over-allocation, but
/// can result in insertion not having amortized constant-time performance.
///
/// The following code declares `values`, an array of integers, and the
/// `addTenQuadratic()` function, which adds ten more values to the `values`
/// array on each call.
///
/// var values: [Int] = [0, 1, 2, 3]
///
/// // Don't use 'reserveCapacity(_:)' like this
/// func addTenQuadratic() {
/// let newCount = values.count + 10
/// values.reserveCapacity(newCount)
/// for n in values.count..<newCount {
/// values.append(n)
/// }
/// }
///
/// The call to `reserveCapacity(_:)` increases the `values` array's capacity
/// by exactly 10 elements on each pass through `addTenQuadratic()`, which
/// is linear growth. Instead of having constant time when averaged over
/// many calls, the function may decay to performance that is linear in
/// `values.count`. This is almost certainly not what you want.
///
/// In cases like this, the simplest fix is often to simply remove the call
/// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array
/// for you.
///
/// func addTen() {
/// let newCount = values.count + 10
/// for n in values.count..<newCount {
/// values.append(n)
/// }
/// }
///
/// If you need more control over the capacity of your array, implement your
/// own geometric growth strategy, passing the size you compute to
/// `reserveCapacity(_:)`.
///
/// - Parameter minimumCapacity: The requested number of elements to store.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the array.
public mutating func reserveCapacity(_ minimumCapacity: Int) {
array.reserveCapacity(minimumCapacity)
}
/// Adds a new element at the end of the array.
///
/// Use this method to append a single element to the end of a mutable array.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// Because arrays increase their allocated capacity using an exponential
/// strategy, appending a single element to an array is an O(1) operation
/// when averaged over many calls to the `append(_:)` method. When an array
/// has additional capacity and is not sharing its storage with another
/// instance, appending an element is O(1). When an array needs to
/// reallocate storage before appending or its storage is shared with
/// another copy, appending is O(*n*), where *n* is the length of the array.
///
/// - Parameter newElement: The element to append to the array.
///
/// - Complexity: Amortized O(1) over many additions. If the array uses a
/// bridged `NSArray` instance as its storage, the efficiency is
/// unspecified.
public mutating func append(_ newElement: Element) {
array.append(WeakContainer<Element>(newElement))
}
/// Adds the elements of a sequence to the end of the array.
///
/// Use this method to append the elements of a sequence to the end of this
/// array. This example appends the elements of a `Range<Int>` instance
/// to an array of integers.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the array.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting array.
public mutating func append<S>(contentsOf newElements: S) where Element == S.Element, S : Sequence {
array.append(contentsOf: newElements.map { WeakContainer<Element>($0) })
}
/// Inserts a new element at the specified position.
///
/// The new element is inserted before the element currently at the specified
/// index. If you pass the array's `endIndex` property as the `index`
/// parameter, the new element is appended to the array.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// - Parameter newElement: The new element to insert into the array.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index of the array or equal to its `endIndex`
/// property.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
public mutating func insert(_ newElement: Element, at i: Int) {
array.insert(WeakContainer<Element>(newElement), at: i)
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved up to
/// close the gap.
///
/// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"
///
/// - Parameter index: The position of the element to remove. `index` must
/// be a valid index of the array.
/// - Returns: The element at the specified index.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
public mutating func remove(at index: Int) -> Element {
return array.remove(at: index).obj!
}
/// Removes all elements from the array.
///
/// - Parameter keepCapacity: Pass `true` to keep the existing capacity of
/// the array after removing its elements. The default value is
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
array.removeAll(keepingCapacity: keepCapacity)
}
}
extension WeakArray : CustomReflectable {
/// A mirror that reflects the array.
public var customMirror: Mirror { return array.customMirror }
}
extension WeakArray : ExpressibleByArrayLiteral {
/// Creates an array from the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler
/// when you use an array literal. Instead, create a new array by using an
/// array literal as its value. To do this, enclose a comma-separated list of
/// values in square brackets.
///
/// Here, an array of strings is created from an array literal holding
/// only strings.
///
/// let ingredients = ["cocoa beans", "sugar", "cocoa butter", "salt"]
///
/// - Parameter elements: A variadic list of elements of the new array.
public init(arrayLiteral elements: Element...) {
array = elements.map { WeakContainer<Element>($0) }
}
}
extension WeakArray : CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the array and its elements.
public var description: String { return array.description }
/// A textual representation of the array and its elements, suitable for
/// debugging.
public var debugDescription: String { return array.debugDescription }
}
extension WeakArray : RandomAccessCollection, MutableCollection {
/// The index type for arrays, `Int`.
public typealias Index = Int
/// The type that represents the indices that are valid for subscripting an
/// array, in ascending order.
public typealias Indices = CountableRange<Int>
/// The type that allows iteration over an array's elements.
public typealias Iterator = IndexingIterator<[Element]>
/// The position of the first element in a nonempty array.
///
/// For an instance of `Array`, `startIndex` is always zero. If the array
/// is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Int { return array.startIndex }
/// The array's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// When you need a range that includes the last element of an array, use the
/// half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let i = numbers.index(of: 30) {
/// print(numbers[i ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the array is empty, `endIndex` is equal to `startIndex`.
public var endIndex: Int { return array.endIndex }
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index immediately after `i`.
public func index(after i: Int) -> Int {
return array.index(after: i)
}
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
public func formIndex(after i: inout Int) {
return array.formIndex(after: &i)
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index immediately before `i`.
public func index(before i: Int) -> Int {
return array.index(before: i)
}
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
public func formIndex(before i: inout Int) {
return array.formIndex(before: &i)
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - n: The distance to offset `i`.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
public func index(_ i: Int, offsetBy n: Int) -> Int {
return array.index(i, offsetBy: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position. The
/// operation doesn't require going beyond the limiting `numbers.endIndex`
/// value, so it succeeds.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let i = numbers.index(numbers.startIndex,
/// offsetBy: 4,
/// limitedBy: numbers.endIndex) {
/// print(numbers[i])
/// }
/// // Prints "50"
///
/// The next example attempts to retrieve an index ten positions from
/// `numbers.startIndex`, but fails, because that distance is beyond the
/// index passed as `limit`.
///
/// let j = numbers.index(numbers.startIndex,
/// offsetBy: 10,
/// limitedBy: numbers.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - n: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` has no effect if it is less than `i`. Likewise, if `n < 0`,
/// `limit` has no effect if it is greater than `i`.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
public func index(_ i: Int, offsetBy n: Int, limitedBy limit: Int) -> Int? {
return array.index(i, offsetBy: n, limitedBy: limit)
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
public func distance(from start: Int, to end: Int) -> Int {
return array.distance(from: start, to: end)
}
/// Accesses the element at the specified position.
///
/// The following example uses indexed subscripting to update an array's
/// second element. After assigning the new value (`"Butler"`) at a specific
/// position, that value is immediately available at that same position.
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// streets[1] = "Butler"
/// print(streets[1])
/// // Prints "Butler"
///
/// - Parameter index: The position of the element to access. `index` must be
/// greater than or equal to `startIndex` and less than `endIndex`.
///
/// - Complexity: Reading an element from an array is O(1). Writing is O(1)
/// unless the array's storage is shared with another array, in which case
/// writing is O(*n*), where *n* is the length of the array.
/// If the array uses a bridged `NSArray` instance as its storage, the
/// efficiency is unspecified.
public subscript(index: Int) -> Element {
get { return array[index].obj! }
set { array[index].obj = newValue }
}
/// Accesses a contiguous subrange of the array's elements.
///
/// The returned `ArraySlice` instance uses the same indices for the same
/// elements as the original array. In particular, that slice, unlike an
/// array, may have a nonzero `startIndex` and an `endIndex` that is not
/// equal to `count`. Always use the slice's `startIndex` and `endIndex`
/// properties instead of assuming that its indices start or end at a
/// particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let i = streetsSlice.index(of: "Evarts") // 4
/// print(streets[i!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of integers. The bounds of the range must be
/// valid indices of the array.
public subscript(bounds: Range<Int>) -> ArraySlice<Element> {
let list = array.compactMap { $0.obj }
return list[bounds]
}
}
extension WeakArray where Element : Collection {
/// Returns the elements of this collection of collections, concatenated.
///
/// In this example, an array of three ranges is flattened so that the
/// elements of each range can be iterated in turn.
///
/// let ranges = [0..<3, 8..<10, 15..<17]
///
/// // A for-in loop over 'ranges' accesses each range:
/// for range in ranges {
/// print(range)
/// }
/// // Prints "0..<3"
/// // Prints "8..<10"
/// // Prints "15..<17"
///
/// // Use 'joined()' to access each element of each range:
/// for index in ranges.joined() {
/// print(index, terminator: " ")
/// }
/// // Prints: "0 1 2 8 9 15 16"
///
/// - Returns: A flattened view of the elements of this
/// collection of collections.
public func joined() -> FlattenCollection<Array<Element>> {
let list = array.compactMap { $0.obj }
return list.joined()
}
}
extension WeakArray where Element : Sequence {
/// Returns the elements of this sequence of sequences, concatenated.
///
/// In this example, an array of three ranges is flattened so that the
/// elements of each range can be iterated in turn.
///
/// let ranges = [0..<3, 8..<10, 15..<17]
///
/// // A for-in loop over 'ranges' accesses each range:
/// for range in ranges {
/// print(range)
/// }
/// // Prints "0..<3"
/// // Prints "8..<10"
/// // Prints "15..<17"
///
/// // Use 'joined()' to access each element of each range:
/// for index in ranges.joined() {
/// print(index, terminator: " ")
/// }
/// // Prints: "0 1 2 8 9 15 16"
///
/// - Returns: A flattened view of the elements of this
/// sequence of sequences.
public func joined() -> FlattenSequence<Array<Element>> {
let list = array.compactMap { $0.obj }
return list.joined()
}
/// Returns the concatenated elements of this sequence of sequences,
/// inserting the given separator between each element.
///
/// This example shows how an array of `[Int]` instances can be joined, using
/// another `[Int]` instance as the separator:
///
/// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/// let joined = nestedNumbers.joined(separator: [-1, -2])
/// print(Array(joined))
/// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"
///
/// - Parameter separator: A sequence to insert between each of this
/// sequence's elements.
/// - Returns: The joined sequence of elements.
public func joined<Separator>(separator: Separator) -> JoinedSequence<Array<Element>> where Separator : Sequence, Separator.Element == Element.Element {
let list = array.compactMap { $0.obj }
return list.joined(separator: separator)
}
}
extension WeakArray where Element : Equatable {
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the collection are not returned as part
/// of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " "))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
public func split(separator: Element, maxSplits: Int = 0, omittingEmptySubsequences: Bool = false) -> [ArraySlice<Element>] {
let list = array.compactMap { $0.obj }
return list.split(separator: separator, maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences)
}
/// Returns the first index where the specified value appears in the
/// collection.
///
/// After using `index(of:)` to find the position of a particular element in
/// a collection, you can use it to access the element by subscripting. This
/// example shows how you can modify one of the names in an array of
/// students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Maxime"]
/// if let i = students.index(of: "Maxime") {
/// students[i] = "Max"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Max"]"
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The first index where `element` is found. If `element` is not
/// found in the collection, returns `nil`.
public func index(of element: Element) -> Int? {
for (i, container) in array.enumerated() {
if container.obj == element { return i }
}
return nil
}
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are the same as the elements in another sequence.
///
/// This example tests whether one countable range begins with the elements
/// of another countable range.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(b.starts(with: a))
/// // Prints "true"
///
/// Passing a sequence with no elements or an empty collection as
/// `possiblePrefix` always results in `true`.
///
/// print(b.starts(with: []))
/// // Prints "true"
///
/// - Parameter possiblePrefix: A sequence to compare to this sequence.
/// - Returns: `true` if the initial elements of the sequence are the same as
/// the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
public func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix) -> Bool where PossiblePrefix : Sequence, Element == PossiblePrefix.Element {
let list = array.compactMap { $0.obj }
return list.starts(with: possiblePrefix)
}
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain the same elements in the same order.
///
/// At least one of the sequences must be finite.
///
/// This example tests whether one countable range shares the same elements
/// as another countable range and an array.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(a.elementsEqual(b))
/// // Prints "false"
/// print(a.elementsEqual([1, 2, 3]))
/// // Prints "true"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence and `other` contain the same elements
/// in the same order.
public func elementsEqual<OtherSequence>(_ other: OtherSequence) -> Bool where OtherSequence : Sequence, Element == OtherSequence.Element {
let list = array.compactMap { $0.obj }
return list.elementsEqual(other)
}
/// Returns a Boolean value indicating whether the sequence contains the
/// given element.
///
/// This example checks to see whether a favorite actor is in an array
/// storing a movie's cast.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// print(cast.contains("Marlon"))
/// // Prints "true"
/// print(cast.contains("James"))
/// // Prints "false"
///
/// - Parameter element: The element to find in the sequence.
/// - Returns: `true` if the element was found in the sequence; otherwise,
/// `false`.
public func contains(_ element: Element) -> Bool {
let list = array.compactMap { $0.obj }
return list.contains(element)
}
}
extension WeakArray where Element : BidirectionalCollection {
/// Returns the elements of this collection of collections, concatenated.
///
/// In this example, an array of three ranges is flattened so that the
/// elements of each range can be iterated in turn.
///
/// let ranges = [0..<3, 8..<10, 15..<17]
///
/// // A for-in loop over 'ranges' accesses each range:
/// for range in ranges {
/// print(range)
/// }
/// // Prints "0..<3"
/// // Prints "8..<10"
/// // Prints "15..<17"
///
/// // Use 'joined()' to access each element of each range:
/// for index in ranges.joined() {
/// print(index, terminator: " ")
/// }
/// // Prints: "0 1 2 8 9 15 16"
///
/// - Returns: A flattened view of the elements of this
/// collection of collections.
public func joined() -> FlattenCollection<Array<Element>> {
let list = array.compactMap { $0.obj }
return list.joined()
}
}
extension WeakArray where Element : Comparable {
//
// /// Returns the elements of the sequence, sorted.
// ///
// /// You can sort any sequence of elements that conform to the
// /// `Comparable` protocol by calling this method. Elements are sorted in
// /// ascending order.
// ///
// /// The sorting algorithm is not stable. A nonstable sort may change the
// /// relative order of elements that compare equal.
// ///
// /// Here's an example of sorting a list of students' names. Strings in Swift
// /// conform to the `Comparable` protocol, so the names are sorted in
// /// ascending order according to the less-than operator (`<`).
// ///
// /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
// /// let sortedStudents = students.sorted()
// /// print(sortedStudents)
// /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
// ///
// /// To sort the elements of your sequence in descending order, pass the
// /// greater-than operator (`>`) to the `sorted(by:)` method.
// ///
// /// let descendingStudents = students.sorted(by: >)
// /// print(descendingStudents)
// /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
// ///
// /// - Returns: A sorted array of the sequence's elements.
// public func sorted() -> [Element]
//
// /// Returns the elements of the collection, sorted.
// ///
// /// You can sort any collection of elements that conform to the
// /// `Comparable` protocol by calling this method. Elements are sorted in
// /// ascending order.
// ///
// /// The sorting algorithm is not stable. A nonstable sort may change the
// /// relative order of elements that compare equal.
// ///
// /// Here's an example of sorting a list of students' names. Strings in Swift
// /// conform to the `Comparable` protocol, so the names are sorted in
// /// ascending order according to the less-than operator (`<`).
// ///
// /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
// /// let sortedStudents = students.sorted()
// /// print(sortedStudents)
// /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
// ///
// /// To sort the elements of your collection in descending order, pass the
// /// greater-than operator (`>`) to the `sorted(by:)` method.
// ///
// /// let descendingStudents = students.sorted(by: >)
// /// print(descendingStudents)
// /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
// ///
// /// - Returns: A sorted array of the collection's elements.
// public func sorted() -> [Element]
//
// /// Sorts the collection in place.
// ///
// /// You can sort any mutable collection of elements that conform to the
// /// `Comparable` protocol by calling this method. Elements are sorted in
// /// ascending order.
// ///
// /// The sorting algorithm is not stable. A nonstable sort may change the
// /// relative order of elements that compare equal.
// ///
// /// Here's an example of sorting a list of students' names. Strings in Swift
// /// conform to the `Comparable` protocol, so the names are sorted in
// /// ascending order according to the less-than operator (`<`).
// ///
// /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
// /// students.sort()
// /// print(students)
// /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
// ///
// /// To sort the elements of your collection in descending order, pass the
// /// greater-than operator (`>`) to the `sort(by:)` method.
// ///
// /// students.sort(by: >)
// /// print(students)
// /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
// public mutating func sort()
//
// /// Returns the minimum element in the sequence.
// ///
// /// This example finds the smallest value in an array of height measurements.
// ///
// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
// /// let lowestHeight = heights.min()
// /// print(lowestHeight)
// /// // Prints "Optional(58.5)"
// ///
// /// - Returns: The sequence's minimum element. If the sequence has no
// /// elements, returns `nil`.
// @warn_unqualified_access
// public func min() -> Element?
//
// /// Returns the maximum element in the sequence.
// ///
// /// This example finds the largest value in an array of height measurements.
// ///
// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
// /// let greatestHeight = heights.max()
// /// print(greatestHeight)
// /// // Prints "Optional(67.5)"
// ///
// /// - Returns: The sequence's maximum element. If the sequence has no
// /// elements, returns `nil`.
// @warn_unqualified_access
// public func max() -> Element?
//
// /// Returns a Boolean value indicating whether the sequence precedes another
// /// sequence in a lexicographical (dictionary) ordering, using the
// /// less-than operator (`<`) to compare elements.
// ///
// /// This example uses the `lexicographicallyPrecedes` method to test which
// /// array of integers comes first in a lexicographical ordering.
// ///
// /// let a = [1, 2, 2, 2]
// /// let b = [1, 2, 3, 4]
// ///
// /// print(a.lexicographicallyPrecedes(b))
// /// // Prints "true"
// /// print(b.lexicographicallyPrecedes(b))
// /// // Prints "false"
// ///
// /// - Parameter other: A sequence to compare to this sequence.
// /// - Returns: `true` if this sequence precedes `other` in a dictionary
// /// ordering; otherwise, `false`.
// ///
// /// - Note: This method implements the mathematical notion of lexicographical
// /// ordering, which has no connection to Unicode. If you are sorting
// /// strings to present to the end user, use `String` APIs that
// /// perform localized comparison.
// public func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence) -> Bool where OtherSequence : Sequence, Element == OtherSequence.Element {
//
// }
}
extension WeakArray : Equatable where Element : Equatable {
public static func == (lhs: WeakArray<Element>, rhs: WeakArray<Element>) -> Bool {
if lhs.count != rhs.count { return false }
for i in 0..<lhs.count {
if lhs.array[i].obj != rhs.array[i].obj {
return false
}
}
return true
}
}
extension WeakArray : Encodable where Element : Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
let list = array.compactMap { $0.obj }
try container.encode(contentsOf: list)
}
}
extension WeakArray : Decodable where Element : Decodable {
/// Creates a new array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
if let v = try? container.decode(Element.self) {
array.append(WeakContainer<Element>(v))
}
}
}
}
|
'server-only';
import { env } from 'env.mjs';
import { CORS_WHITELIST } from '~/constants/constants';
/**
* Multi purpose CORS lib.
* Note: Based on the `cors` package in npm but using only
* web APIs. Feel free to use it in your own projects.
*/
type StaticOrigin = boolean | string | RegExp | (boolean | string | RegExp)[];
type OriginFn = (
origin: string | undefined,
req: Request,
) => StaticOrigin | Promise<StaticOrigin>;
interface CorsOptions {
origin?: StaticOrigin | OriginFn;
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
credentials?: boolean;
maxAge?: number;
preflightContinue?: boolean;
optionsSuccessStatus?: number;
}
const defaultOptions: CorsOptions = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
};
function isOriginAllowed(origin: string, allowed: StaticOrigin): boolean {
if (Array.isArray(allowed)) {
return allowed.some((o) => isOriginAllowed(origin, o));
}
if (typeof allowed === 'string') {
return origin === allowed;
}
if (allowed instanceof RegExp) {
return allowed.test(origin);
}
return Boolean(allowed);
}
function getOriginHeaders(reqOrigin: string | undefined, origin: StaticOrigin) {
const headers = new Headers();
if (origin === '*') {
// Allow any origin
headers.set('Access-Control-Allow-Origin', '*');
} else if (typeof origin === 'string') {
// Fixed origin
headers.set('Access-Control-Allow-Origin', origin);
headers.append('Vary', 'Origin');
} else {
const allowed = isOriginAllowed(reqOrigin ?? '', origin);
if (allowed && reqOrigin) {
headers.set('Access-Control-Allow-Origin', reqOrigin);
}
headers.append('Vary', 'Origin');
}
return headers;
}
async function originHeadersFromReq(
req: Request,
origin: StaticOrigin | OriginFn,
) {
let reqOrigin: string;
if (req.headers.get('Origin')) {
reqOrigin = req.headers.get('Origin') as unknown as string;
} else if (req.headers.get('X-Forwarded-Host')) {
reqOrigin = `https://${req.headers.get('X-Forwarded-Host')}`;
} else if (req.headers.get('host')) {
reqOrigin = `https://${req.headers.get('host')}`;
} else {
reqOrigin = env.NEXT_PUBLIC_SITE_URL;
}
const value =
typeof origin === 'function' ? await origin(reqOrigin, req) : origin;
if (!value) return;
return getOriginHeaders(reqOrigin, value);
}
function getAllowedHeaders(req: Request, allowed?: string | string[]) {
const headers = new Headers();
if (!allowed) {
const assessControlRequestHeaders = req.headers.get(
'Access-Control-Request-Headers',
) as unknown as string;
// eslint-disable-next-line no-param-reassign
allowed = assessControlRequestHeaders;
headers.append('Vary', 'Access-Control-Request-Headers');
} else if (Array.isArray(allowed)) {
// If the allowed headers is an array, turn it into a string
// eslint-disable-next-line no-param-reassign
allowed = allowed.join(',');
}
if (allowed) {
headers.set('Access-Control-Allow-Headers', allowed);
}
return headers;
}
export const commonOriginFunc = (origin: string | undefined) => {
// nouvelles-*.vercel.app
const corsWhitelist: RegExp[] = CORS_WHITELIST.ORIGIN;
if (env.NODE_ENV === 'development') {
corsWhitelist.push(/^http:\/\/localhost/);
}
if (!origin || corsWhitelist.some((regex) => regex.test(origin))) {
return true;
}
return false;
};
export default async function cors(
req: Request,
res: Response,
options?: CorsOptions,
) {
const opts = { ...defaultOptions, ...options };
const { headers } = res;
const originHeaders = await originHeadersFromReq(req, opts.origin ?? false);
const mergeHeaders = (v: string, k: string) => {
if (k === 'Vary') headers.append(k, v);
else headers.set(k, v);
};
// If there's no origin we won't touch the response
if (!originHeaders) return res;
originHeaders.forEach(mergeHeaders);
if (opts.credentials) {
headers.set('Access-Control-Allow-Credentials', 'true');
}
const exposed = Array.isArray(opts.exposedHeaders)
? opts.exposedHeaders.join(',')
: opts.exposedHeaders;
if (exposed) {
headers.set('Access-Control-Expose-Headers', exposed);
}
// Handle the preflight request
if (req.method === 'OPTIONS') {
if (opts.methods) {
const methods = Array.isArray(opts.methods)
? opts.methods.join(',')
: opts.methods;
headers.set('Access-Control-Allow-Methods', methods);
}
getAllowedHeaders(req, opts.allowedHeaders).forEach(mergeHeaders);
if (typeof opts.maxAge === 'number') {
headers.set('Access-Control-Max-Age', String(opts.maxAge));
}
if (opts.preflightContinue) return res;
headers.set('Content-Length', '0');
return new Response(null, {
status: opts.optionsSuccessStatus,
headers,
});
}
// If we got here, it's a normal request
return res;
}
|
<template>
<nav
:class="expanded ? 'nav-expanded' : ''"
>
<div class="logo">Utility tools</div>
<div class="nav-container">
<router-link to="/" @click="closeExpand">Home</router-link>
<router-link to="/percentage-calculator" @click="closeExpand">Percentage calculator</router-link>
<router-link to="/temperature-converter" @click="closeExpand">Temperature converter</router-link>
<router-link to="/weight-converter" @click="closeExpand">Weight converter</router-link>
<router-link to="/speed-converter" @click="closeExpand">Speed converter</router-link>
<div class="made-with">Slasher © {{ currentYear }}</div>
</div>
<div
class="menu-icon d-inline-flex d-lg-none"
@click="toggleExpand">
<input class="menu-icon__cheeckbox" type="checkbox" />
<div>
<span></span>
<span></span>
</div>
</div>
</nav>
</template>
<script>
export default {
name: 'VueNavigation',
data() {
return {
expanded: false,
currentYear: null,
};
},
mounted() {
this.getCurrentYear();
},
methods: {
toggleExpand() {
this.expanded = this.expanded === false;
this.scrollToTop();
},
closeExpand() {
this.expanded = false;
this.scrollToTop();
},
scrollToTop() {
window.scrollTo(0,0);
},
getCurrentYear() {
return this.currentYear = new Date().getFullYear();
}
},
};
</script>
|
import React from "react";
import { MoonTokenData } from "../Data";
import MoonTokenSmallCard from "../UI/moonTokenSmallCard";
const TokenHeader = () => {
return (
<header>
<div className="bg-[#00008c] h-fit py-8 px-4 lg:px-16 xl:px-32 flex justify-center xl:justify-between flex-col items-center xl:flex-row ">
<div className="flex justify-around flex-col">
<div className="flex items-center justify-center flex-col xl:flex-row my-8 lg:my-0">
<div>
<img src="./moon.png" alt="" />
</div>
<div className="my-6 xl:my-0 md:pl-8 flex flex-col justify-center items-center xl:items-start">
<h3 className="text-3xl font-bold">Moon Token</h3>
<div className="grid grid-cols-3 xl:grid-cols-2 gap-5 pt-4">
<p className="flex items-center pr-4 text-sm text-gray-200">
<img
className="h-4 w-fit pr-2"
src="../etherscan-logo-light-circle.svg"
alt=""
/>{" "}
Etherscans
</p>
<p className="text-sm text-gray-200">
<i className="fa-solid fa-globe h-4 w-fit pr-1 text-[#FFDF0C]"></i>{" "}
Website
</p>
<p className="text-sm text-gray-200">
<i className="fa-solid fa-link pr-1 h-4 w-fit text-[#FFDF0C]"></i>{" "}
Address
</p>
<p className="text-sm text-gray-200">
<i className="fa-brands fa-telegram pr-1 h-4 w-fit text-[#FFDF0C]"></i>{" "}
Telegram
</p>
<p className="flex items-center text-sm text-gray-200">
<i className="bg-[#FFDF0C] py-1 px-[3px] mr-2 flex items-center justify-center text-black text-[8px] rounded-full fa-brands fa-discord"></i>
Discord
</p>
<p className="flex items-center text-sm text-gray-200">
<i className="bg-[#FFDF0C] py-1 px-[4px] mr-1 text-black text-[8px] rounded-full fa-brands fa-twitter"></i>
Twitter
</p>
</div>
</div>
<div className="xl:ml-8 flex flex-row flex-wrap py-10 xl:py-0 justify-center">
{MoonTokenData.map((item) => (
<div className="mx-5 mb-10" key={item.id}>
<MoonTokenSmallCard
name={item.name}
value={item.value}
DateAndAmount={item.DateAndAmount}
DateAndAmountValue={item.DateAndAmountValue}
/>
</div>
))}
</div>
</div>
</div>
<div className="flex items-center justify-center object-contain">
<div className="absolute">
<img className=" h-44 w-fit" src="./rocket.png" alt="" />
</div>
<img
className="h-28 w-fit object-contain relative left-16 top-7 "
src="./rocket.png"
alt=""
/>
</div>
</div>
</header>
);
};
export default TokenHeader;
|
from django.db import models
from ckeditor.fields import RichTextField
from django.db import models
# Create your models here.
class categories(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Blogs(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
content = RichTextField()
date = models.DateField(auto_now_add=True)
image = models.ImageField(upload_to='uploads')
url = models.SlugField(unique=True)
is_published = models.BooleanField(default=True)
category = models.ForeignKey(categories, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.title
class Comment(models.Model):
blog = models.ForeignKey(Blogs, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
message = models.TextField()
is_approved = models.BooleanField(default=False)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.message
|
import 'package:http/http.dart' as http;
import '../models/booking_model.dart';
import '../utils/bookings_converter.dart';
import '../utils/logger.dart';
class BookingsApiHandler {
static final _logger = Logger.debugInstance?.of<BookingsApiLogger>();
static final _url = Uri.http(
'booking-bot.bounceme.net',
// '192.168.68.103:8077',
'api/hotel-listeners',
);
static const _headers = {"Content-Type": "application/json"};
static const _timeLimit = Duration(seconds: 5);
static Future<List<BookingModel>?> fetchBookings() async {
List<BookingModel>? bookings;
String errorMessage = "";
try {
final response =
await http.read(_url, headers: _headers).timeout(_timeLimit);
bookings = BookingsConverter.tryParse(response);
} catch (e) {
errorMessage = e.toString();
} finally {
_logger?.logFetch(bookings: bookings, errorMessage: errorMessage);
}
return bookings;
}
}
|
import { MemoryRouter } from "react-router-dom";
import List from "@material-ui/core/List";
import type { Meta, StoryObj } from "@storybook/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import TaskListItem from "./index";
import { ITaskListItemProps } from "./interface";
const queryClient = new QueryClient();
const meta: Meta<typeof TaskListItem> = {
title: "Components/TaskListItem",
component: TaskListItem,
tags: ["autodocs"],
parameters: {
layout: "fullscreen",
},
argTypes: {
task: {
id: 1,
title: "Sample Task",
description: "This is a sample task description.",
status: "todo",
},
},
decorators: [
(Story) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<List>
<Story />
</List>
</QueryClientProvider>
</MemoryRouter>
),
],
};
export default meta;
const task: ITaskListItemProps["task"] = {
id: 1,
title: "Sample Task",
description: "This is a sample task description.",
status: "todo",
};
type Story = StoryObj<typeof TaskListItem>;
export const TodoTask: Story = {
args: {
task: { ...task, status: "todo" },
},
};
export const DoneTask: Story = {
args: {
task: { ...task, status: "done" },
},
};
|
package org.cardanofoundation.explorer.common.validation.length;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.logging.log4j.util.Strings;
public class LengthValidator implements ConstraintValidator<LengthValid, String> {
private int length;
@Override
public void initialize(LengthValid constraintAnnotation) {
this.length = constraintAnnotation.value();
ConstraintValidator.super.initialize(constraintAnnotation);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (this.length == 0) {
context
.buildConstraintViolationWithTemplate("length value is not configured")
.addConstraintViolation();
return false;
}
if (Strings.isNotBlank(value) && value.length() != this.length) {
context
.buildConstraintViolationWithTemplate(
"The expected length of the hash is " + this.length + " characters")
.addConstraintViolation();
return false;
}
return true;
}
}
|
#ifndef CANVAS_H
#define CANVAS_H
#include <iostream>
class Canvas
{
int width;
int height;
char **matrix;
public:
Canvas(int width, int height) : width(width), height(height) {
matrix = new char* [height];
for (int i = 0;i < height;i++)
matrix[i] = new char[width];
};
void DrawCircle(int x, int y, int ray, char ch);
void FillCircle(int x, int y, int ray, char ch);
void DrawRect(int left, int top, int right, int bottom, char ch);
void FillRect(int left, int top, int right, int bottom, char ch);
void SetPoint(int x, int y, char ch);
void DrawLine(int x1, int y1, int x2, int y2, char ch);
void Print(); // shows what was printed
void Clear(); // clears the canvas
void Deallocate();
};
#endif // !CANVAS_H
|
package com.example.sce.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sce.R;
import com.example.sce.db.course.CourseDao;
import com.example.sce.model.Course;
import com.example.sce.model.Enrollment;
import com.example.sce.model.Purchase;
import com.example.sce.screen.PurchaseDetails;
import java.util.List;
public class PurchaseAdapter extends RecyclerView.Adapter<PurchaseAdapter.PurchaseViewHolder> {
private Context context;
private List<Purchase> purchaseList;
public PurchaseAdapter(Context context, List<Purchase> purchaseList) {
this.context = context;
this.purchaseList = purchaseList;
}
@NonNull
@Override
public PurchaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.enrollment_item_recyler_view, parent, false);
return new PurchaseViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull PurchaseViewHolder holder, int position) {
Purchase purchase = purchaseList.get(position);
holder.textViewPurchasePrice.setText("Purchase Code: " + purchase.getPurchaseCode());
holder.textViewCourseNames.setText(getCoursesNames(purchase));
holder.buttonViewDetails.setOnClickListener(v -> {
Intent intent = new Intent(context, PurchaseDetails.class);
intent.putExtra("purchaseCode", purchase.getPurchaseCode());
context.startActivity(intent);
});
}
private String getCoursesNames(Purchase purchase) {
StringBuilder courseNames = new StringBuilder();
CourseDao courseDao = new CourseDao(context);
for (Enrollment enrollment : purchase.getEnrollments()) {
if (courseNames.length() > 0) {
courseNames.append("\n");
}
try{
Course course = courseDao.getCourse(enrollment.getCourseId());
courseNames.append(course.getCourseName());
}catch (Exception e){
}
}
return courseNames.toString();
}
@Override
public int getItemCount() {
return purchaseList.size();
}
static class PurchaseViewHolder extends RecyclerView.ViewHolder {
TextView textViewPurchasePrice, textViewCourseNames;
Button buttonViewDetails;
public PurchaseViewHolder(@NonNull View itemView) {
super(itemView);
textViewPurchasePrice = itemView.findViewById(R.id.textViewPurchasePrice);
textViewCourseNames = itemView.findViewById(R.id.textViewCourseNames);
buttonViewDetails = itemView.findViewById(R.id.buttonViewDetails);
}
}
}
|
// database.go
package database
import (
"fmt"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// Config contém as configurações do banco de dados
type Config struct {
Host string
Port string
User string
Password string
DBName string
SSLMode string
}
// ComposeDsn cria a string de conexão do banco de dados
func ComposeDsn(config Config) string {
return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
config.Host, config.Port, config.User, config.Password, config.DBName, config.SSLMode)
}
// NewDB cria uma nova instância do Gorm para interagir com o banco de dados
func NewDB(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
// NewTestDB cria uma nova instância do Gorm para o banco de dados de teste
func NewTestDB() (*gorm.DB, error) {
// Configurações específicas para o banco de dados de teste
testConfig := Config{
Host: os.Getenv("DB_HOST"),
Port: os.Getenv("DB_PORT"),
User: os.Getenv("DB_USER"),
Password: os.Getenv("DB_PASSWORD"),
DBName: os.Getenv("DB_NAME") + "_test", // Adiciona um sufixo para o banco de dados de teste, caso queira
SSLMode: os.Getenv("DB_SSL_MODE"),
}
dsn := ComposeDsn(testConfig)
return NewDB(dsn)
}
|
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.BOT.Application.Interfaces.Repositories;
using Telegram.BOT.Application.Interfaces.Services;
using Telegram.BOT.Domain.Enums;
using Telegram.BOT.Application.UseCases.Marc.UpdateMarc.Handlers;
using Telegram.BOT.tests.Builder.Domain.Product;
using Telegram.BOT.Application.UseCases.Marc.UpdateMarc;
using Telegram.BOT.Infrastructure.Service;
using Xunit.Frameworks.Autofac;
using Xunit;
namespace Telegram.BOT.tests.Cases.Application.Marc.UpdateMarc.Handlers
{
[UseAutofacTestFramework]
public class VerifyNameDisponibilityHandlerTest
{
private readonly VerifyNameDisponibilityHandler handler;
private readonly IMarcRepository MarcRepository;
private readonly ICategoryRepository categoryRepository;
private readonly NotificationService notificationService;
public VerifyNameDisponibilityHandlerTest
(VerifyNameDisponibilityHandler handler,
IMarcRepository MarcRepository,
ICategoryRepository categoryRepository,
NotificationService notificationService)
{
this.handler = handler;
this.MarcRepository = MarcRepository;
this.categoryRepository = categoryRepository;
this.notificationService = notificationService;
}
[Fact]
public async Task Should_Execute_Successfully_When_Name_Is_Available()
{
var Marc = MarcBuilder.New().Build();
MarcRepository.Add(Marc);
var request = new UpdateMarcRequest
{
Marc = new BOT.Domain.Products.Marc { Id = Guid.NewGuid(), Name = "New Marc", CategoryId = Guid.NewGuid() }
};
await handler.ProcessRequest(request);
request.Logs.Should().NotBeEmpty();
notificationService.HasNotifications.Should().BeFalse();
}
[Fact]
public async Task Should_Add_Notification_If_Name_Is_Already_Used_By_A_Category()
{
var Marc = MarcBuilder.New().Build();
var category = CategoryBuilder.New().WithName(Marc.Name).Build();
MarcRepository.Add(Marc);
categoryRepository.Add(category);
var request = new UpdateMarcRequest
{
Marc = new BOT.Domain.Products.Marc { Id = Guid.NewGuid(), Name = category.Name , CategoryId = category.Id}
};
await handler.ProcessRequest(request);
notificationService.HasNotifications.Should().BeTrue();
notificationService.Notifications.Should().Contain(notification => notification.Property == "Name Using" );
}
[Fact]
public async Task Should_Add_Notification_If_Name_Is_Already_Used_By_Another_Marc()
{
var Marc = MarcBuilder.New().Build();
var category = CategoryBuilder.New().WithName(Marc.Name).Build();
MarcRepository.Add(Marc);
categoryRepository.Add(category);
var request = new UpdateMarcRequest
{
Marc = new BOT.Domain.Products.Marc { Id = Guid.NewGuid(), Name = Marc.Name, CategoryId = category.Id }
};
await handler.ProcessRequest(request);
notificationService.HasNotifications.Should().BeTrue();
notificationService.Notifications.Should().Contain(notification => notification.Property == "Name Using" );
}
}
}
|
const express = require("express");
const cors = require("cors");
const path = require("path");
class Server {
constructor() {
this.app = express();
this.port = process.env.PORT;
this.paths = {
auth: "/api/auth",
homepage: "/api/homepage",
};
this.middlewares();
this.routes();
}
middlewares() {
this.app.use(cors());
this.app.use(express.json());
this.app.use(
express.static(path.join(__dirname, "../client/build"))
);
}
routes() {
this.app.use(this.paths.auth, require("../routes/auth"));
this.app.use(this.paths.homepage, require("../routes/homepage"));
this.app.get("*", (req, res) => {
res.sendFile(
path.join(__dirname, "../client/build/index.html")
);
});
}
listen() {
this.app.listen(this.port, () => {
console.log("Server running on port: ", this.port);
});
}
}
module.exports = Server;
|
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity({ name: 'groups' })
export class Group {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ type: 'varchar', length: 500 })
description: string;
@Column()
region: string;
@Column()
totalUsers: number;
@Column()
creationDate: Date;
@Column()
isPrivate: boolean;
@Column()
passcode: string;
@Column({ type: 'simple-array' })
tags: string[];
@Column({ type: 'simple-array' })
bannedUsers: number[];
@Column({ type: 'simple-array' })
users: number[];
constructor(name: string);
constructor(
name: string,
description?: string,
totalUsers?: number,
creationDate?: Date,
users?: number[],
bannedUsers?: number[],
isPrivate?: boolean,
tags?: string[],
region?: string,
passcode?: string
);
constructor(
name: string,
description?: string,
totalUsers?: number,
creationDate?: Date,
users?: number[],
bannedUsers?: number[],
isPrivate?: boolean,
tags?: string[],
region?: string,
passcode?: string
) {
this.name = name;
this.description = description || '';
this.totalUsers = totalUsers || 0;
this.creationDate = creationDate || new Date();
this.users = users || [];
this.bannedUsers = bannedUsers || [];
this.isPrivate = isPrivate || false;
this.tags = tags || [];
this.region = region || '';
this.passcode = passcode || '';
}
}
|
package com.sist.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import com.sist.db.ConnectionProvider;
import com.sist.vo.BoardVO;
public class BoardDAO {
int pageSize = 10; // 한 화면에 보여줄 레코드의 수
int totalRecord = 0; // 전체 레코드의 수
public int totalPage = 0; // 전체 페이지의 수
public ArrayList<BoardVO> getMy(String id) {
ArrayList<BoardVO> list = new ArrayList<BoardVO>();
String sql = "select * from board where writer=?";
try {
Connection conn = ConnectionProvider.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
ResultSet res = pstmt.executeQuery();
while (res.next()) {
list.add(new BoardVO(
res.getInt(1),
res.getString(2),
res.getString(3),
res.getString(4),
res.getString(5),
res.getDate(6),
res.getInt(7),
res.getString(8),
res.getString(9),
res.getInt(10),
res.getInt(11),
res.getInt(12)
));
}
ConnectionProvider.close(conn, pstmt, res);
} catch (Exception e) {
System.out.println("내글보기 " + e.getMessage());
}
return list;
}
// 전체 레코드르 수를 반환하는 메소드
public int getTotalRecord(String writer) {
int cnt = 0;
String sql = "select count(*) from board";
if (writer != null) {
sql += " where writer = '"+writer+"'";
}
try {
Connection conn = ConnectionProvider.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
cnt = rs.getInt(1);
}
ConnectionProvider.close(conn, stmt, rs);
} catch (Exception e) {
System.out.println("레코드 수 구하기 " + e.getMessage());
}
return cnt;
}
// 이미 달려있는 답글들의 b_step을 1씩 증가하는 메소드
public int updateStep(int b_ref, int b_step) {
int re = -1;
String sql = "update board set b_step = b_step + 1 "
+ "where b_ref=? and b_step > ?";
try {
Connection conn = ConnectionProvider.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, b_ref);
pstmt.setInt(2, b_step);
re = pstmt.executeUpdate();
ConnectionProvider.close(conn, pstmt);
} catch (Exception e) {
System.out.println("step update 에러 " + e.getMessage());
}
return re;
}
public int delete(BoardVO b) {
int re = -1;
String sql = "delete from board where no=? and pwd=?";
try {
Connection conn = ConnectionProvider.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, b.getNo());
pstmt.setString(2, b.getPwd());
re = pstmt.executeUpdate();
ConnectionProvider.close(conn, pstmt);
} catch (Exception e) {
System.out.println("삭제 : " + e.getMessage());
}
return re;
}
public int update(BoardVO b) {
int re = -1;
String sql =
"update board set title=?,content=?,fname=? where no=? and pwd=?";
try {
Connection conn = ConnectionProvider.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, b.getTitle());
pstmt.setString(2, b.getContent());
pstmt.setString(3, b.getFname());
pstmt.setInt(4, b.getNo());
pstmt.setString(5, b.getPwd());
re = pstmt.executeUpdate();
ConnectionProvider.close(conn, pstmt);
} catch (Exception e) {
System.out.println("수정 : " + e.getMessage());
}
System.out.println(re + "update");
return re;
}
public BoardVO detail(int no) {
BoardVO b = null;
String sql = "select * from board where no=?";
try {
Connection conn = ConnectionProvider.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
ResultSet res = pstmt.executeQuery();
while(res.next()) {
b = new BoardVO(
res.getInt(1),
res.getString(2),
res.getString(3),
res.getString(4),
res.getString(5),
res.getDate(6),
res.getInt(7),
res.getString(8),
res.getString(9),
res.getInt(10),
res.getInt(11),
res.getInt(12)
);
}
ConnectionProvider.close(conn, pstmt, res);
} catch (Exception e) {
System.out.println("detail " + e.getMessage());
}
return b;
}
public int insert(BoardVO b) {
String sql = "insert into board values(?, ?, ?, ?, ?, sysdate, 1, ?, ?, ?, ?, ?)";
int re = -1;
try {
Connection conn = ConnectionProvider.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, b.getNo());
pstmt.setString(2, b.getTitle());
pstmt.setString(3, b.getWriter());
pstmt.setString(4, b.getPwd());
pstmt.setString(5, b.getContent());
pstmt.setString(6, b.getFname());
pstmt.setString(7, b.getIp());
pstmt.setInt(8, b.getB_ref());
pstmt.setInt(9, b.getB_level());
pstmt.setInt(10, b.getB_step());
re = pstmt.executeUpdate();
ConnectionProvider.close(conn, pstmt);
} catch (Exception e) {
System.out.println("추가 " + e.getMessage());
}
return re;
}
public ArrayList<BoardVO> listBoard(int pageNUM, String writer) {
ArrayList<BoardVO> list = new ArrayList<BoardVO>();
totalRecord = getTotalRecord(writer);
totalPage = totalRecord / pageSize +1 ;
int start = (pageNUM - 1) * 10 + 1;
int end = (pageNUM * 10);
String sql = "select * "
+ "from "
+ "(select b.*, rownum rm "
+ "from (select * "
+ "from board";
if (writer != null) {
sql += " where writer = '"+writer+"'";
}
sql += " order by b_ref desc, b_step) b) "
+ "where rm between "+start+" and "+end+"";
try {
ConnectionProvider cp = new ConnectionProvider();
Connection conn = cp.getConnection();
Statement stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
list.add(new BoardVO(
res.getInt(1),
res.getString(2),
res.getString(3),
res.getString(4),
res.getString(5),
res.getDate(6),
res.getInt(7),
res.getString(8),
res.getString(9),
res.getInt(10),
res.getInt(11),
res.getInt(12)
));
}
cp.close(conn, stmt, res);
} catch (Exception e) {
System.out.println("board 목록 에러 : " + e.getMessage());
}
return list;
}
public int getNextNo() {
int no = -1;
String sql = "select nvl(max(no),0) + 1 from board";
try {
Connection conn = ConnectionProvider.getConnection();
Statement stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(sql);
if(res.next()) {
no = res.getInt(1);
}
ConnectionProvider.close(conn, stmt, res);
} catch (Exception e) {
System.out.println("get no : " + e.getMessage());
}
return no;
}
}
|
import React from "react";
import type { Role } from "@/lib/types";
import { StructuredText } from "react-datocms";
import {
renderRule,
isParagraph,
isListItem,
} from "datocms-structured-text-utils";
import { formatDate } from "@/lib/dateFormat";
export function RoleDetails({ startDate, summary, endDate, jobTitle }: Role) {
return (
<>
<h2 className="flex flex-row place-content-between text-lg">
<span className="text-left">
{`${formatDate(startDate)} to ${
endDate ? formatDate(endDate) : "Present"
} `}
</span>
<span className="text-right">{jobTitle}</span>
</h2>
{summary && (
<div className="pb-3">
<StructuredText
data={summary}
customNodeRules={[
renderRule(
isListItem,
({ node, adapter: { renderNode }, children, key }) => {
return renderNode("li", { key, className: "py-1" }, children);
}
),
renderRule(
isParagraph,
({ node, adapter: { renderNode }, children, key }) => {
return renderNode(
"p",
{
key,
className: "text-xs leading-tight font-light ",
},
children
);
}
),
]}
/>
</div>
)}
</>
);
}
|
# DFS 사용
# https://leetcode.com/problems/combination-sum/
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
answer = []
def dfs(current_val, idx, comb_stat):
if current_val < 0: # 0보다 작아지면 조건 만족 x
return
if current_val == 0: # 0으로 떨어지면 조건 만족
answer.append(comb_stat[:]) # 지금까지의 조합 append
for i in range(idx, len(candidates)): # 현재 인덱스 기준으로 모든 경우에 대해 dfs 호출
dfs(current_val - candidates[i], i, comb_stat + [candidates[i]])
dfs(target, 0, [])
return answer
|
<template>
<div class="calendar">
<div class="header">
<button @click="cambiarMes(-1)"><</button>
<h2>{{ nombreMes }} {{ currentYear }}</h2>
<button @click="cambiarMes(1)">></button>
</div>
<div class="days">
<div v-for="(week, index) in weeks" :key="index" class="week">
<div v-for="(day, index) in week" :key="index" class="day" @click="seleccionarFecha(day)">
{{ day }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'DailyCalendar',
data() {
return {
currentMonth: new Date().getMonth(),
currentYear: new Date().getFullYear(),
weeks: []
};
},
mounted() {
this.generarCalendario();
},
methods: {
generarCalendario() {
const firstDayOfMonth = new Date(this.currentYear, this.currentMonth, 1).getDay();
const daysInMonth = new Date(this.currentYear, this.currentMonth + 1, 0).getDate();
let dayCounter = 1;
const calendar = [];
for (let i = 0; i < 6; i++) {
const week = [];
for (let j = 0; j < 7; j++) {
if ((i === 0 && j < firstDayOfMonth) || dayCounter > daysInMonth) {
week.push('');
} else {
week.push(dayCounter);
dayCounter++;
}
}
calendar.push(week);
if (dayCounter > daysInMonth) break;
}
this.weeks = calendar;
},
cambiarMes(step) {
this.currentMonth += step;
if (this.currentMonth < 0) {
this.currentMonth = 11;
this.currentYear--;
} else if (this.currentMonth > 11) {
this.currentMonth = 0;
this.currentYear++;
}
this.generarCalendario();
},
seleccionarFecha(day) {
// Emitir evento para informar al componente padre de la fecha seleccionada
this.$emit('fecha-seleccionada', `${day}/${this.currentMonth + 1}/${this.currentYear}`);
}
},
computed: {
nombreMes() {
const nombresMeses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
return nombresMeses[this.currentMonth];
},
}
};
</script>
<style scoped>
.calendar {
width: auto;
background-color: #f8f8f8;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
.days {
display: grid;
grid-template-columns: repeat(7, 1fr);
border-top: 1px solid #ddd;
}
.week {
display: flex;
}
.day {
flex: 1;
padding: 10px;
text-align: center;
border-right: 1px solid #ddd;
border-bottom: 1px solid #ddd;
cursor: pointer;
}
.day:hover {
background-color: #f0f0f0;
}
.day.empty {
visibility: hidden;
}
</style>
|
import { IsInt, IsNotEmpty, IsNumber, IsString } from 'class-validator';
import { ToppingDto } from './topping.dto';
export class PizzaDto {
@IsInt()
@IsNotEmpty()
id: number;
@IsNotEmpty()
toppings: ToppingDto[];
@IsString()
@IsNotEmpty()
name: string;
@IsNumber()
@IsNotEmpty()
price: number;
@IsString()
@IsNotEmpty()
size: string;
@IsString()
@IsNotEmpty()
img_path: string;
@IsString()
@IsNotEmpty()
description: string;
}
|
<template>
<div class="ag-pop-box-unique" :class="{ agpopBoxHide: !value,isFullscreen:isFullscreen }" ref="box">
<div class="ag-pop-box-unique-head" @mousedown="mousedown">
<span>{{ title }}</span>
<i v-if="fullscreen && !isFullscreen" class="icon-Maximize-1" @click="showFullscreen"></i>
<i v-if="fullscreen && isFullscreen" class="icon-Maximize-3" @click="showFullscreen"></i>
<i class="icon-close" @click="onCancel"></i>
</div>
<div class="ag-pop-box-body">
<div v-if="backgroundImageUrl" class="ag-image" :style="{backgroundImage:'url('+backgroundImageUrl+')',height:imageHeight}"></div>
<slot></slot>
</div>
<div class="ag-pop-box-unique-foot">
<el-button size="mini" v-if="confirm" type="primary" @click="onConfirm">
{{ confirmVal }}
</el-button>
<el-button size="mini" v-if="cancel" @click="onCancel">{{
cancelVal
}}</el-button>
</div>
</div>
</template>
<script>
export default {
name: "AgPopup",
props: {
value: {
type: Boolean,
default: false,
},
confirm: {
type: Boolean,
default: false,
},
cancel: {
type: Boolean,
default: false,
},
title: {
default: null,
},
confirmVal: {
type: String,
default: "是",
},
cancelVal: {
type: String,
default: "否",
},
isDisabled: {
type: Boolean,
default: false,
},
maskHide: {
type: Boolean,
default: true,
},
isMove: {
type: Boolean,
default: true,
},
fullscreen:{
type: Boolean,
default: false,
},
isFullscreen:{
type: Boolean,
default: false,
},
backgroundImageUrl:{
type:String,
default:""
},
imageHeight:{
type:String,
default:"455px"
},
removable:{
type: Boolean,
default: true
}
},
methods: {
showFullscreen(){
this.isFullscreen = !this.isFullscreen
if(!this.isFullscreen){
this.imageHeight ="455px"
}else{
this.imageHeight = document.body.clientHeight+"px"
}
},
maskHandle() {
if (this.maskHide) {
}
},
onConfirm() {
if (!this.isDisabled) {
this.$emit("onConfirm");
}
},
onCancel(e) {
this.$emit("onCancel");
},
mousedown(event) {
if(!this.removable){
return 0;
}
this.selectElement = this.$refs.box;
var dom = this.selectElement;
this.selectElement.style.cursor = "move";
this.isDowm = true;
var distanceX = event.clientX - this.selectElement.offsetLeft;
var distanceY = event.clientY - this.selectElement.offsetTop;
if (this.isMove) {
document.onmousemove = function (ev) {
var oevent = ev || event;
dom.style.left = oevent.clientX - distanceX + "px";
dom.style.top = oevent.clientY - distanceY + "px";
};
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
dom.style.cursor = "default";
};
},
},
};
</script>
<style scoped lang="scss">
.ag-image {
background-size: cover;
background-repeat: no-repeat;
}
.ag-pop-box-unique {
position: fixed;
z-index: 12;
top: 512px;
right: 16px;
border-radius: 10px;
overflow: hidden;
background: rgba(1, 10, 23, 0.8);
min-width: 250px;
}
.agpopBoxHide {
display: none;
}
.ag-pop-box-unique-head {
position: relative;
font-size: 16px;
height: 40px;
vertical-align: middle;
justify-items: center;
line-height: 40px;
font-weight: bold;
background: none;
color: #ffffff;
text-indent: 20px;
border-bottom: 1px solid #919499;
}
.ag-pop-box-unique-head .ag-pop-box-unique-close {
position: absolute;
top: calc(50% - 9px);
right: 20px;
font-size: 15px;
cursor: pointer;
}
.ag-pop-box-unique-foot {
text-align: right;
margin-right: 5px;
}
.ag-pop-box-unique-foot button {
margin: 10px 5px;
}
.ag-pop-box-unique.isFullscreen{
left: 0 !important;
top:0 !important;
width: 100% !important;
height: 100%;
}
.ag-pop-box-unique-head i{
margin-top: 10px;
position: absolute;
height: 16px;
width: 16px;
background-size: 100%;
}
.icon-Maximize-1 {
background: url(../../img/Maximize-1.png) no-repeat;
right: 50px;
}
.icon-Maximize-3 {
background: url(../../img/Maximize-3.png) no-repeat;
right: 50px;
}
.icon-close {
background: url(../../img/close.png) no-repeat;
right: 20px;
}
// /*弹层动画(放大)*/
// .popIn {
// -webkit-animation: popIn .4s;
// animation: popIn .4s;
// -webkit-animation-name: popIn;
// animation-name: popIn;
// }
@-webkit-keyframes popIn {
0% {
-webkit-transform: scale3d(0, 0, 0);
transform: scale3d(0.5, 0.5, 0.5);
opacity: 0;
}
50% {
-webkit-animation-timing-function: cubic-bezier(0.47, 0, 0.745, 0.715);
animation-timing-function: cubic-bezier(0.47, 0, 0.745, 0.715);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
-webkit-animation-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
animation-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
opacity: 1;
}
}
@keyframes popIn {
0% {
-webkit-transform: scale3d(0, 0, 0);
transform: scale3d(0.5, 0.5, 0.5);
opacity: 0;
}
50% {
-webkit-animation-timing-function: cubic-bezier(0.47, 0, 0.745, 0.715);
animation-timing-function: cubic-bezier(0.47, 0, 0.745, 0.715);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
-webkit-animation-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
animation-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
opacity: 1;
}
}
</style>
|
package net.sschwarzbaer.java.tools.rick_and_morty_viewer_backend.ram_api;
public record RAMCharacter(
int id , // id of the character
String name , // name of the character
Status status , // status of the character ('Alive', 'Dead' or 'unknown')
String species , // species of the character
String type , // type or subspecies of the character
Gender gender , // gender of the character ('Female', 'Male', 'Genderless' or 'unknown')
Location origin , // Name and link to the character's origin location
Location location, // Name and link to the character's last known location endpoint
String image , // Link to the character's image. All images are 300x300px and most are medium shots or portraits since they are intended to be used as avatars
String[] episode , // List of episodes in which this character appeared
String url , // Link to the character's own URL endpoint
String created // Time at which the character was created in the database
) {
public enum Status { Alive, Dead, unknown }
public enum Gender { Female, Male, Genderless, unknown }
public record Location(String name, String url) {}
}
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";
import queryString from "querystring";
import { SpotifyAccessClient } from "@/util/SpotifyManager";
type APIError = {
message: string;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<SpotifyAccessClient | string>
) {
const authOptions = {
url: "https://accounts.spotify.com/api/token",
method: "post",
data: queryString.stringify({
grant_type: "client_credentials",
}),
headers: {
Authorization:
"Basic " +
Buffer.from(
process.env.NEXT_PUBLIC_SPOTIFY_CLIENT_ID +
":" +
process.env.SPOTIFY_CLIENT_SECRET
).toString("base64"),
},
json: true,
};
try {
const response = await axios(authOptions);
return res.status(200).json(response.data as SpotifyAccessClient);
} catch (err) {
console.log(err);
return res.status(500).json("An unexpected error occured");
}
}
|
import { useCallback, useState } from 'react';
type UseToggleSelectionResult = [
selectedItems: string[],
toggleSelection: (id: string) => void,
clearSelection: () => void
];
const useToggleSelection = (): UseToggleSelectionResult => {
const [selectedItems, setSelectedItems] = useState<string[]>([]);
const toggleSelection = useCallback((id: string) => {
setSelectedItems((prevSelected) => {
if (prevSelected.includes(id)) {
return prevSelected.filter((itemId) => itemId !== id);
} else {
return [...prevSelected, id];
}
});
}, []);
const clearSelection = () => {
setSelectedItems([]);
};
return [selectedItems, toggleSelection, clearSelection];
};
export default useToggleSelection;
|
import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union
import attr
from dateutil.parser import isoparse
from ..models.invoice_payment_method import InvoicePaymentMethod
from ..models.invoice_status import InvoiceStatus
from ..models.invoice_type import InvoiceType
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.invoice_address import InvoiceAddress
from ..models.invoice_item import InvoiceItem
T = TypeVar("T", bound="Invoice")
@attr.s(auto_attribs=True)
class Invoice:
"""
Attributes:
invoice_id (int): unique id of the invoice in the context of a company
invoice_date (datetime.datetime): invoice date time of the invoice with date-time notation as defined by <a
href="https://tools.ietf.org/html/rfc3339#section-5.6" target="_blank">RFC 3339, section 5.6</a>, for example,
2017-07-21T17:32:28Z
accumulated_price (float): accumulated price of the invoice
currency (str): currency of the invoice formatted as <a href="https://en.wikipedia.org/wiki/ISO_4217"
target="_blank">ISO 4217, alphabetic code</a>
payment_method (InvoicePaymentMethod): payment method used to pay for the invoice
invoice_customer_id (str): id of the customer the invoice belongs to
items (List['InvoiceItem']):
changed_date (Union[Unset, datetime.datetime]): date the invoice entity was changed with date-time notation as
defined by <a href="https://tools.ietf.org/html/rfc3339#section-5.6" target="_blank">RFC 3339, section 5.6</a>,
for example, 2017-07-21T17:32:28Z
customer_email (Union[Unset, str]): email used for sending invoice
payment_method_id (Union[Unset, int]): id of the payment method that is associated with this invoice
purchase_order_indicator (Union[Unset, str]): purchase invoice indicator if provided by the customer
invoice_address (Union[Unset, InvoiceAddress]):
transaction_id (Union[Unset, str]): id of the related transaction if payment was not done via invoice
type (Union[Unset, InvoiceType]): type of the invoice
status (Union[Unset, InvoiceStatus]): payment status of the invoice
payment_changed_to_billing (Union[Unset, bool]): flag indicating if invoice was created because of a failed
payment process
precursor_id (Union[Unset, int]): invoice id which was corrected or canccelled
successor_id (Union[Unset, int]): invoice id of the corrected invoice
invoice_cancellation_id (Union[Unset, int]): invoice id of the cancellation invoice
"""
invoice_id: int
invoice_date: datetime.datetime
accumulated_price: float
currency: str
payment_method: InvoicePaymentMethod
invoice_customer_id: str
items: List["InvoiceItem"]
changed_date: Union[Unset, datetime.datetime] = UNSET
customer_email: Union[Unset, str] = UNSET
payment_method_id: Union[Unset, int] = UNSET
purchase_order_indicator: Union[Unset, str] = UNSET
invoice_address: Union[Unset, "InvoiceAddress"] = UNSET
transaction_id: Union[Unset, str] = UNSET
type: Union[Unset, InvoiceType] = UNSET
status: Union[Unset, InvoiceStatus] = UNSET
payment_changed_to_billing: Union[Unset, bool] = UNSET
precursor_id: Union[Unset, int] = UNSET
successor_id: Union[Unset, int] = UNSET
invoice_cancellation_id: Union[Unset, int] = UNSET
additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)
def to_dict(self) -> Dict[str, Any]:
invoice_id = self.invoice_id
invoice_date = self.invoice_date.isoformat()
accumulated_price = self.accumulated_price
currency = self.currency
payment_method = self.payment_method.value
invoice_customer_id = self.invoice_customer_id
items = []
for items_item_data in self.items:
items_item = items_item_data.to_dict()
items.append(items_item)
changed_date: Union[Unset, str] = UNSET
if not isinstance(self.changed_date, Unset):
changed_date = self.changed_date.isoformat()
customer_email = self.customer_email
payment_method_id = self.payment_method_id
purchase_order_indicator = self.purchase_order_indicator
invoice_address: Union[Unset, Dict[str, Any]] = UNSET
if not isinstance(self.invoice_address, Unset):
invoice_address = self.invoice_address.to_dict()
transaction_id = self.transaction_id
type: Union[Unset, str] = UNSET
if not isinstance(self.type, Unset):
type = self.type.value
status: Union[Unset, str] = UNSET
if not isinstance(self.status, Unset):
status = self.status.value
payment_changed_to_billing = self.payment_changed_to_billing
precursor_id = self.precursor_id
successor_id = self.successor_id
invoice_cancellation_id = self.invoice_cancellation_id
field_dict: Dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
"invoiceId": invoice_id,
"invoiceDate": invoice_date,
"accumulatedPrice": accumulated_price,
"currency": currency,
"paymentMethod": payment_method,
"invoiceCustomerId": invoice_customer_id,
"items": items,
}
)
if changed_date is not UNSET:
field_dict["changedDate"] = changed_date
if customer_email is not UNSET:
field_dict["customerEmail"] = customer_email
if payment_method_id is not UNSET:
field_dict["paymentMethodId"] = payment_method_id
if purchase_order_indicator is not UNSET:
field_dict["purchaseOrderIndicator"] = purchase_order_indicator
if invoice_address is not UNSET:
field_dict["invoiceAddress"] = invoice_address
if transaction_id is not UNSET:
field_dict["transactionId"] = transaction_id
if type is not UNSET:
field_dict["type"] = type
if status is not UNSET:
field_dict["status"] = status
if payment_changed_to_billing is not UNSET:
field_dict["paymentChangedToBilling"] = payment_changed_to_billing
if precursor_id is not UNSET:
field_dict["precursorId"] = precursor_id
if successor_id is not UNSET:
field_dict["successorId"] = successor_id
if invoice_cancellation_id is not UNSET:
field_dict["invoiceCancellationId"] = invoice_cancellation_id
return field_dict
@classmethod
def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
from ..models.invoice_address import InvoiceAddress
from ..models.invoice_item import InvoiceItem
d = src_dict.copy()
invoice_id = d.pop("invoiceId")
invoice_date = isoparse(d.pop("invoiceDate"))
accumulated_price = d.pop("accumulatedPrice")
currency = d.pop("currency")
payment_method = InvoicePaymentMethod(d.pop("paymentMethod"))
invoice_customer_id = d.pop("invoiceCustomerId")
items = []
_items = d.pop("items")
for items_item_data in _items:
items_item = InvoiceItem.from_dict(items_item_data)
items.append(items_item)
_changed_date = d.pop("changedDate", UNSET)
changed_date: Union[Unset, datetime.datetime]
if isinstance(_changed_date, Unset):
changed_date = UNSET
else:
changed_date = isoparse(_changed_date)
customer_email = d.pop("customerEmail", UNSET)
payment_method_id = d.pop("paymentMethodId", UNSET)
purchase_order_indicator = d.pop("purchaseOrderIndicator", UNSET)
_invoice_address = d.pop("invoiceAddress", UNSET)
invoice_address: Union[Unset, InvoiceAddress]
if isinstance(_invoice_address, Unset):
invoice_address = UNSET
else:
invoice_address = InvoiceAddress.from_dict(_invoice_address)
transaction_id = d.pop("transactionId", UNSET)
_type = d.pop("type", UNSET)
type: Union[Unset, InvoiceType]
if isinstance(_type, Unset):
type = UNSET
else:
type = InvoiceType(_type)
_status = d.pop("status", UNSET)
status: Union[Unset, InvoiceStatus]
if isinstance(_status, Unset):
status = UNSET
else:
status = InvoiceStatus(_status)
payment_changed_to_billing = d.pop("paymentChangedToBilling", UNSET)
precursor_id = d.pop("precursorId", UNSET)
successor_id = d.pop("successorId", UNSET)
invoice_cancellation_id = d.pop("invoiceCancellationId", UNSET)
invoice = cls(
invoice_id=invoice_id,
invoice_date=invoice_date,
accumulated_price=accumulated_price,
currency=currency,
payment_method=payment_method,
invoice_customer_id=invoice_customer_id,
items=items,
changed_date=changed_date,
customer_email=customer_email,
payment_method_id=payment_method_id,
purchase_order_indicator=purchase_order_indicator,
invoice_address=invoice_address,
transaction_id=transaction_id,
type=type,
status=status,
payment_changed_to_billing=payment_changed_to_billing,
precursor_id=precursor_id,
successor_id=successor_id,
invoice_cancellation_id=invoice_cancellation_id,
)
invoice.additional_properties = d
return invoice
@property
def additional_keys(self) -> List[str]:
return list(self.additional_properties.keys())
def __getitem__(self, key: str) -> Any:
return self.additional_properties[key]
def __setitem__(self, key: str, value: Any) -> None:
self.additional_properties[key] = value
def __delitem__(self, key: str) -> None:
del self.additional_properties[key]
def __contains__(self, key: str) -> bool:
return key in self.additional_properties
|
// Write a function to find the longest common prefix string amongst an array of strings.
// If there is no common prefix, return an empty string "".
function longestCommonPrefix(strs) {
if (strs.length === 0) {
return "";
}
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
let j = 0;
while (j < prefix.length && j < strs[i].length && prefix[j] === strs[i][j]) {
j++;
}
prefix = prefix.substring(0, j);
if (prefix === "") {
break;
}
}
return prefix;
}
// Example usage:
const example1 = ["flower", "flow", "flight"];
const example2 = ["dog", "racecar", "car"];
console.log(longestCommonPrefix(example1)); // Output: "fl"
console.log(longestCommonPrefix(example2)); // Output: ""
//Time Complexity: O(n * minLen)
//Space Complexity: O(minLen)
|
//
// Model.swift
// YouTubeApi
//
// Created by Лілія on 20.02.2023.
//
import Foundation
protocol ModelDelegate {
func videosFetched(_ videos: [Video])
}
class Model {
var delegate: ModelDelegate?
func getVideos() {
// create url object
let url = URL(string: Constants.apiUrl)
guard url != nil else {return}
// Get a URLSession object
let session = URLSession.shared
//Get a data task from a URLSession object
let dataTask = session.dataTask(with: url!) { (data, response, error ) in
//Check if there were any errors
if error != nil || data == nil {
return
}
do {
// Parsing the data into video objects
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let response = try decoder.decode(Response.self, from: data!)
if response.items != nil{
DispatchQueue.main.async {
// Call the "videosFetched" method of the delegate
self.delegate?.videosFetched(response.items!)
}
}
// dump(response)
}
catch{}
}
// Kick off the task
dataTask.resume()
}
}
|
# ✅ Quiz M4.03
```{admonition} Question
Which of the following estimators can solve linear regression problems?
- a) sklearn.linear_model.LinearRegression
- b) sklearn.linear_model.LogisticRegression
- c) sklearn.linear_model.Ridge
_Select all answers that apply_
```
+++
```{admonition} Question
Regularization allows:
- a) to create a model robust to outliers (samples that differ widely from
other observations)
- b) to reduce overfitting by forcing the weights to stay close to zero
- c) to reduce underfitting by making the problem linearly separable
_Select a single answer_
```
+++
```{admonition} Question
A ridge model is:
- a) the same as linear regression with penalized weights
- b) the same as logistic regression with penalized weights
- c) a linear model
- d) a non linear model
_Select all answers that apply_
```
+++
```{admonition} Question
Assume that a data scientist has prepared a train/test split and plans to use
the test for the final evaluation of a `Ridge` model. The parameter `alpha` of
the `Ridge` model:
- a) is internally tuned when calling `fit` on the train set
- b) should be tuned by running cross-validation on a **train set**
- c) should be tuned by running cross-validation on a **test set**
- d) must be a positive number
_Select all answers that apply_
```
+++
```{admonition} Question
Scaling the data before fitting a model:
- a) is often useful for regularized linear models
- b) is always necessary for regularized linear models
- c) may speed-up fitting
- d) has no impact on the optimal choice of the value of a regularization parameter
_Select all answers that apply_
```
+++
```{admonition} Question
The effect of increasing the regularization strength in a ridge model is to:
- a) shrink all weights towards zero
- b) make all weights equal
- c) set a subset of the weights to exactly zero
- d) constrain all the weights to be positive
_Select all answers that apply_
```
+++
```{admonition} Question
By default, a [`LogisticRegression`](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) in scikit-learn applies:
- a) no penalty
- b) a penalty that shrinks the magnitude of the weights towards zero (also called "l2 penalty")
- c) a penalty that ensures all weights are equal
_Select a single answer_
```
+++
```{admonition} Question
The parameter `C` in a logistic regression is:
- a) similar to the parameter `alpha` in a ridge regressor
- b) similar to `1 / alpha` where `alpha` is the parameter of a ridge regressor
- c) not controlling the regularization
_Select a single answer_
```
+++
```{admonition} Question
In logistic regression, increasing the regularization strength (by
decreasing the value of `C`) makes the model:
- a) more likely to overfit to the training data
- b) more confident: the values returned by `predict_proba` are closer to 0 or 1
- c) less complex, potentially underfitting the training data
_Select a single answer_
```
|
Структура и наполнение таблицы
book_id title author price amount
INT PRIMARY KEY AUTO_INCREMENT VARCHAR(50) VARCHAR(30) DECIMAL(8,2) INT
1 Мастер и Маргарита Булгаков М.А. 670.99 3
2 Белая гвардия Булгаков М.А. 540.50 5
3 Идиот Достоевский Ф.М. 460.00 10
4 Братья Карамазовы Достоевский Ф.М. 799.01 3
5 Игрок Достоевский Ф.М. 480.50 10
6 Стихотворения и поэмы Есенин С.А. 650.00 15
1. Создать таблицу поставка (supply), которая имеет ту же структуру, что и таблиц book.
CREATE TABLE supply (supply_id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(50),author VARCHAR(30), price DECIMAL(8, 2), amount INT)
2. Занесите в таблицу supply четыре записи, чтобы получилась следующая таблица:
supply_id title author price amount
1 Лирика Пастернак Б.Л. 518.99 2
2 Черный человек Есенин С.А. 570.20 6
3 Белая гвардия Булгаков М.А. 540.50 7
4 Идиот Достоевский Ф.М. 360.80 3
INSERT INTO supply (supply_id, title, author, price, amount)
VALUES
(1,'Лирика', 'Пастернак Б.Л.', 518.99, 2),
(2,'Черный человек', 'Есенин С.А.', 570.20, 6),
(3,'Белая гвардия', 'Булгаков М.А.', 540.50, 7),
(4,'Идиот', 'Достоевский Ф.М.', 360.80, 3);
3. Добавить из таблицы supply в таблицу book, все книги, кроме книг, написанных Булгаковым М.А. и Достоевским Ф.М.
INSERT INTO book (title, author, price, amount)
select title, author, price, amount
from supply
where author not in ("Достоевский Ф.М.","Булгаков М.А.");
select * from book;
4. Занести из таблицы supply в таблицу book только те книги, авторов которых нет в book.
insert into book (title, author, price, amount)
select title, author, price, amount
from supply
where author not in (
select author
from book
);
select * from book;
5. Уменьшить на 10% цену тех книг в таблице book, количество которых принадлежит интервалу от 5 до 10, включая границы.
update book
set price = price * 0.9
where amount between 5 and 10;
select * from book;
6. В таблице book необходимо скорректировать значение для покупателя в столбце buy таким образом, чтобы оно не превышало количество экземпляров книг, указанных в столбце amount. А цену тех книг, которые покупатель не заказывал, снизить на 10%.
update book
set buy = if(buy > amount, amount, buy),
price = if( buy = 0, price * 0.9, price);
select * from book;
7. Для тех книг в таблице book , которые есть в таблице supply, не только увеличить их количество в таблице book ( увеличить их количество на значение столбца amountтаблицы supply), но и пересчитать их цену (для каждой книги найти сумму цен из таблиц book и supply и разделить на 2).
update book, supply
set book.amount = supply.amount + book.amount, book.price = (book.price + supply.price)/2
where book.title = supply.title AND book.author = supply.author;
select * from book;
8. Удалить из таблицы supply книги тех авторов, общее количество экземпляров книг которых в таблице book превышает 10.
delete from supply
where author in(
select author from book
group by author
having sum(amount) > 10
);
select * from supply;
9. Создать таблицу заказ (ordering), куда включить авторов и названия тех книг, количество экземпляров которых в таблице book меньше среднего количества экземпляров книг в таблице book. В таблицу включить столбец amount, в котором для всех книг указать одинаковое значение - среднее количество экземпляров книг в таблице book.
create table ordering as
select author, title,
(select round(avg(amount)) from book) as amount
from book
where amount < 7;
select * from ordering;
|
import Product from "../../../domain/product/entity/product";
import ListProductUseCase from "./list.product.usecase";
const product = new Product("123","test",123)
const product2 = new Product("124","test2",124)
const MockRepository = () => {
return {
find: jest.fn(),
findAll: jest.fn().mockReturnValue(Promise.resolve([product,product2])),
create: jest.fn(),
update: jest.fn(),
};
};
describe("Unit Test list product use case", () => {
it("should list a product", async () => {
const productRepository = MockRepository();
const usecase = new ListProductUseCase(productRepository);
const input = {
id: "123",
};
const result = await usecase.execute(input);
expect(result.products.length).toEqual(2);
expect(result.products[0].id).toEqual("123");
expect(result.products[0].name).toEqual("test");
expect(result.products[0].price).toEqual(123);
expect(result.products[1].id).toEqual("124");
expect(result.products[1].name).toEqual("test2");
expect(result.products[1].price).toEqual(124);
});
});
|
# Frontend Mentor - REST Countries API with color theme switcher solution
This is a solution to the [REST Countries API with color theme switcher
challenge on Frontend
Mentor](https://www.frontendmentor.io/challenges/rest-countries-api-with-color-theme-switcher-5cacc469fec04111f7b848ca).
Frontend Mentor challenges help you improve your coding skills by building
realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [My process](#my-process)
- [Built with](#built-with)
- [What I learned](#what-i-learned)
- [Author](#author)
## Overview
### The challenge
Users should be able to:
- See all countries from the API on the homepage
- Search for a country using an `input` field
- Filter countries by region
- Click on a country to see more detailed information on a separate page
- Click through to the border countries on the detail page
- Toggle the color scheme between light and dark mode _(optional)_
### Screenshot

### Links
- Solution URL:
[https://github.com/mamidenn/rest-countries-api-with-color-theme-switcher](https://github.com/mamidenn/rest-countries-api-with-color-theme-switcher)
- Live Site URL:
[https://rest-countries.martin-dennhardt.de/](https://rest-countries.martin-dennhardt.de/)
## My process
### Built with
- Semantic HTML5 markup
- Flexbox
- CSS Grid
- [SvelteKit](https://kit.svelte.dev/) - Frontend framework
- [Tailwind CSS](https://tailwindcss.com/) - CSS framework
### What I learned
I didn't know that Svelte supported Generic Components. I used them to create
the Dropdown Component. It looks like this:
```ts
type T = $$Generic;
export let selected: T | null = null;
export let options: T[] = [];
```
Very handy since you get type-safety when binding the `selected` property.
I also rediscovered the [Description List
(`<dl>`)](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl) element.
I used it to display the country details as they are key-value pairs.
## Author
- Website - [Martin Dennhardt](https://github.com/mamidenn)
- Frontend Mentor - [@mamidenn](https://www.frontendmentor.io/profile/mamidenn)
|
<?php
/*
This is the EveryCook Recipe Database. It is a web application for creating (and storing) machine (and human) readable recipes.
These recipes are linked to foods and suppliers to allow meal planning and shopping list creation. It also guides the user step-by-step through the recipe with the CookAssistant
EveryCook is an open source platform for collecting all data about food and make it available to all kinds of cooking devices.
This program is copyright (C) by EveryCook. Written by Samuel Werder, Matthias Flierl and Alexis Wiasmitinow.
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
See GPLv3.htm in the main folder for details.
*/
/**
* This is the model class for table "cusine_sub_sub_types".
*
* The followings are the available columns in table 'cusine_sub_sub_types':
* @property integer $CSS_ID
* @property integer $CST_ID
* @property double $CSS_GPS_LAT
* @property double $CSS_GPS_LNG
* @property string $CSS_GOOGLE_REGION
* @property string $CSS_IMG_FILENAME
* @property string $CSS_IMG_ETAG
* @property string $CSS_DESC_EN_GB
* @property string $CSS_DESC_DE_CH
* @property integer $CREATED_BY
* @property integer $CREATED_ON
* @property integer $CHANGED_BY
* @property integer $CHANGED_ON
*/
class CusineSubSubTypes extends ActiveRecordEC
{
public $filename;
public $imagechanged;
/**
* Returns the static model of the specified AR class.
* @return CusineSubSubTypes the static model class
*/
public static function model($className=__CLASS__){
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName(){
return 'cusine_sub_sub_types';
}
/**
* @return array validation rules for model attributes.
*/
public function rules(){
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('CST_ID, CSS_DESC_EN_GB, CSS_DESC_DE_CH, CREATED_BY, CREATED_ON, CHANGED_BY, CHANGED_ON', 'required'),
array('CST_ID, CREATED_BY, CREATED_ON, CHANGED_BY, CHANGED_ON', 'numerical', 'integerOnly'=>true),
array('CSS_GPS_LAT, CSS_GPS_LNG', 'numerical'),
array('CSS_GOOGLE_REGION', 'length', 'max'=>50),
array('CSS_IMG_FILENAME', 'length', 'max'=>250),
array('CSS_IMG_ETAG', 'length', 'max'=>40),
array('CSS_DESC_EN_GB, CSS_DESC_DE_CH', 'length', 'max'=>100),
array('CSS_IMG_ETAG', 'required', 'on'=>'withPic'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('CSS_ID, CST_ID, CSS_GPS_LAT, CSS_GPS_LNG, CSS_GOOGLE_REGION, CSS_IMG_FILENAME, CSS_IMG_ETAG, CSS_DESC_EN_GB, CSS_DESC_DE_CH, CREATED_BY, CREATED_ON, CHANGED_BY, CHANGED_ON', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations(){
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels(){
return array(
'CSS_ID' => 'Css',
'CST_ID' => 'Cst',
'CSS_GPS_LAT' => 'Css Gps Lat',
'CSS_GPS_LNG' => 'Css Gps Lng',
'CSS_GOOGLE_REGION' => 'Css Google Region',
'CSS_IMG_FILENAME' => 'Css Img Filename',
'CSS_IMG_ETAG' => 'Css Img Etag',
'CSS_DESC_EN_GB' => 'Css Desc En Gb',
'CSS_DESC_DE_CH' => 'Css Desc De Ch',
'CREATED_BY' => 'Created By',
'CREATED_ON' => 'Created On',
'CHANGED_BY' => 'Changed By',
'CHANGED_ON' => 'Changed On',
);
}
public function getSearchFields(){
return array('CSS_ID', 'CSS_DESC_' . Yii::app()->session['lang']);
}
public function getExportSelectFieldsIgnore(){
return array_merge(parent::getExportSelectFieldsIgnore(), array('CST_ID'));
}
public function getCriteriaString(){
$criteria=new CDbCriteria;
$criteria->compare($this->tableName().'.CSS_ID',$this->CSS_ID);
$criteria->compare($this->tableName().'.CST_ID',$this->CST_ID);
$criteria->compare($this->tableName().'.CSS_GPS_LAT',$this->CSS_GPS_LAT);
$criteria->compare($this->tableName().'.CSS_GPS_LNG',$this->CSS_GPS_LNG);
$criteria->compare($this->tableName().'.CSS_GOOGLE_REGION',$this->CSS_GOOGLE_REGION,true);
$criteria->compare($this->tableName().'.CSS_IMG_FILENAME',$this->CSS_IMG_FILENAME,true);
$criteria->compare($this->tableName().'.CSS_IMG_ETAG',$this->CSS_IMG_ETAG,true);
$criteria->compare($this->tableName().'.CSS_DESC_EN_GB',$this->CSS_DESC_EN_GB,true);
$criteria->compare($this->tableName().'.CSS_DESC_DE_CH',$this->CSS_DESC_DE_CH,true);
$criteria->compare($this->tableName().'.CREATED_BY',$this->CREATED_BY);
$criteria->compare($this->tableName().'.CREATED_ON',$this->CREATED_ON);
$criteria->compare($this->tableName().'.CHANGED_BY',$this->CHANGED_BY);
$criteria->compare($this->tableName().'.CHANGED_ON',$this->CHANGED_ON);
return $criteria;
}
public function getCriteria(){
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('CSS_ID',$this->CSS_ID);
$criteria->compare('CST_ID',$this->CST_ID);
$criteria->compare('CSS_GPS_LAT',$this->CSS_GPS_LAT);
$criteria->compare('CSS_GPS_LNG',$this->CSS_GPS_LNG);
$criteria->compare('CSS_GOOGLE_REGION',$this->CSS_GOOGLE_REGION,true);
$criteria->compare('CSS_IMG_FILENAME',$this->CSS_IMG_FILENAME,true);
$criteria->compare('CSS_IMG_ETAG',$this->CSS_IMG_ETAG,true);
$criteria->compare('CSS_DESC_EN_GB',$this->CSS_DESC_EN_GB,true);
$criteria->compare('CSS_DESC_DE_CH',$this->CSS_DESC_DE_CH,true);
$criteria->compare('CREATED_BY',$this->CREATED_BY);
$criteria->compare('CREATED_ON',$this->CREATED_ON);
$criteria->compare('CHANGED_BY',$this->CHANGED_BY);
$criteria->compare('CHANGED_ON',$this->CHANGED_ON);
//Add with conditions for relations
//$criteria->with = array('???relationName???' => array());
return $criteria;
}
public function getSort(){
$sort = new CSort;
$sort->attributes = array(
/*
'sortId' => array(
'asc' => 'CSS_ID',
'desc' => 'CSS_ID DESC',
),
*/
'*',
);
return $sort;
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search(){
return new CActiveDataProvider($this, array(
'criteria'=>$this->getCriteria(),
'sort'=>$this->getSort(),
));
}
}
|
#pragma once
#include <QtCore/QUrl>
#include <QtCore/QEasingCurve>
#include "types.h"
#include "specialize.h"
/// @class StoryInfo
/// @brief Container class for Story information
///
/// This class is intended as a container for all the information needed
/// for a given Story.
struct StoryInfo
{
QUrl story;
// This value is an internal identify for a Story. It uniquely
// identifies a Story within the system, regardless of any other
// of its settings. The user never sees this value.
QString identity;
// The Story 'angle' is something that will uniquely identify this
// Story for the user. In the case of a local file system entity,
// the full path to that entity will suffice. However, in the case
// of a REST URL, the URL itself may not be unique enough as it will
// simply be the entry point for addition API selectors. So, this
// string value should most uniquely represent that particular story
// type.
QString angle;
// Reporter
QString reporter_beat; // what special genre knowledge do this Reporter possess?
QString reporter_id; // unique identity for thie Reporter
int reporter_parameters_version{0};
QStringList reporter_parameters;// what up-front information does the Reporter need to cover the Story?
// Notifications
uint ttl{5};
// Display
int primary_screen{0};
// Headlines
bool headlines_always_visible{true};
// Size
bool interpret_as_pixels{true};
int headlines_pixel_width{0}, headlines_pixel_height{0};
double headlines_percent_width{0.0}, headlines_percent_height{0.0};
// Visibility
bool limit_content{false};
int limit_content_to{0};
FixedText headlines_fixed_type{FixedText::None};
// Extras
bool include_progress_bar{false};
QString progress_text_re{"\\s(\\d+)%"};
bool progress_on_top{false}; // true = bar on top, false = bar on bottom
// Animation
AnimEntryType entry_type{AnimEntryType::PopCenter};
AnimExitType exit_type{AnimExitType::Pop};
int anim_motion_duration{500};
int fade_target_duration{500};
// Train
// Age Effects
bool train_use_age_effect{false};
AgeEffects train_age_effect{AgeEffects::None};
int train_age_percent{60};
// Dashboard
// Age Effects
bool dashboard_use_age_effect{false};
int dashboard_age_percent{60};
// Group ID
QString dashboard_group_id;
// Chyron settings (reference only; not saved)
int margin{5};
bool dashboard_compact_mode{false};
qreal dashboard_compression{25.0};
// Producer settings (reference only; not saved)
QFont font;
QEasingCurve motion_curve{QEasingCurve::OutCubic};
QEasingCurve fading_curve{QEasingCurve::InCubic};
StoryInfo() {}
StoryInfo(const StoryInfo& source) { *this = source; }
/*!
Retrieves the dimensions of a Headline that will display information
about this particular Story. It uses the 'Size' parameters.
\param w The calculated width value
\param h The calculated height value
*/
void get_dimensions(int& w, int& h)
{
w = 0;
h = 0;
if(interpret_as_pixels)
{
w = headlines_pixel_width;
h = headlines_pixel_height;
}
else
{
auto desktop = QApplication::desktop();
auto r_desktop = desktop->screenGeometry(primary_screen);
w = static_cast<int>((headlines_percent_width / 100.0) * r_desktop.width());
h = static_cast<int>((headlines_percent_height / 100.0) * r_desktop.height());
}
}
};
SPECIALIZE_SHAREDPTR(StoryInfo, StoryInfo) // "StoryInfoPointer"
|
export class MyDate {
constructor(
public year: number = 1993,
private _month: number = 7,
private _day: number = 9,//the underscore is a convention to represent a private value
) {}
//this method is public
public printFormat(): string {
const day = this.addPadding(this._day);
const month = this.addPadding(this._month);
return `${day}/${month}/${this.year}`;
}
//unable to access out site of the class
private addPadding(value: number) {
if(value < 10) {
return `0${value}`;
}
return `${value}`;
}
//this method is also public by default
add(amount: number, type: 'days' | 'months' | 'years') {
//example this is not a good way to add days, months & days
if (type === 'days') {
this._day += amount;
}
if (type === 'months') {
this._month += amount;
}
if (type === 'years') {
this.year += amount;
}
}
get day() {// getters must return a value
// with a method is posible to get access
return this._day;
}
get isLeapYear() {// getters must return a value
if(this.year % 400 === 0) return true;
if(this.year % 100 === 0) return false;
return this.year % 4 === 0;
}
get month() {
return this._month;
}
//setter need a parameter
set month(newValue: number) {//setters are void cannot return a value
if(newValue >=1 && newValue <= 12) {
this._month = newValue;
} else {
throw new Error("That is not a real month");
}
}
}
const myDate = new MyDate(1999, 7, 9);
console.log(myDate.printFormat());// 09/07/1999
myDate.month = 78;
console.log('This wil not be shown in console', myDate.month);
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <frc2/command/CommandBase.h>
#include <frc2/command/CommandHelper.h>
#include <frc2/command/CommandPtr.h>
#include <frc/RobotController.h>
#include <frc/trajectory/Trajectory.h>
#include "subsystems/DriveSubsystem.h"
#include "subsystems/FeederSubsystem.h"
#include "subsystems/Infrastructure.h"
#include "subsystems/ShooterSubsystem.h"
#include <memory>
#include <string_view>
class TimedAutoBase : public frc2::CommandHelper<frc2::CommandBase, TimedAutoBase>
{
protected:
TimedAutoBase(DriveSubsystem *const drive, FeederSubsystem *const feeder, InfrastructureSubsystem *const infrastructure, ShooterSubsystem *const shooter, std::string_view name) noexcept
: m_drive{drive}, m_feeder{feeder}, m_infrastructure{infrastructure}, m_shooter{shooter} { SetName(name); }
public:
virtual ~TimedAutoBase() noexcept = default;
void Initialize() noexcept override;
void Execute() noexcept override;
void End(bool interrupted) noexcept override;
bool IsFinished() noexcept override { return finished_; }
virtual bool Iteration(const uint counter) noexcept { return true; }
protected:
DriveSubsystem *const m_drive;
FeederSubsystem *const m_feeder;
InfrastructureSubsystem *const m_infrastructure;
ShooterSubsystem *const m_shooter;
private:
bool pressure_{false};
bool finished_{false};
uint64_t FPGATime_{0};
uint counter_{0};
};
class OneBallAuto : public TimedAutoBase
{
public:
OneBallAuto(DriveSubsystem *const drive, FeederSubsystem *const feeder, InfrastructureSubsystem *const infrastructure, ShooterSubsystem *const shooter) noexcept
: TimedAutoBase(drive, feeder, infrastructure, shooter, "OneBallAuto") {}
bool Iteration(const uint counter) noexcept override;
static frc2::CommandPtr OneBallAutoCommandFactory(DriveSubsystem *const drive, FeederSubsystem *const feeder, InfrastructureSubsystem *const infrastructure, ShooterSubsystem *const shooter) noexcept
{
return frc2::CommandPtr{std::make_unique<OneBallAuto>(drive, feeder, infrastructure, shooter)};
}
};
class TwoBallAuto : public TimedAutoBase
{
public:
TwoBallAuto(DriveSubsystem *const drive, FeederSubsystem *const feeder, InfrastructureSubsystem *const infrastructure, ShooterSubsystem *const shooter) noexcept
: TimedAutoBase(drive, feeder, infrastructure, shooter, "TwoBallAuto") {}
bool Iteration(const uint counter) noexcept override;
static frc2::CommandPtr TwoBallAutoCommandFactory(DriveSubsystem *const drive, FeederSubsystem *const feeder, InfrastructureSubsystem *const infrastructure, ShooterSubsystem *const shooter) noexcept
{
return frc2::CommandPtr{std::make_unique<TwoBallAuto>(drive, feeder, infrastructure, shooter)};
}
};
namespace TrajectoryAuto
{
frc2::CommandPtr TrajectoryAutoCommandFactory(DriveSubsystem *const drive, std::string_view name, frc::Trajectory &trajectory) noexcept;
};
|
import inspect
import logging
def customLogger(logLevel):
#Gets the name of the class / method from there this method is called
loggerName = inspect.stack()[1][3]
logger = logging.getLogger(loggerName)
# By default, log all messages
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler(filename="{0}.log".format(loggerName), mode='w')
fileHandler.setLevel(logLevel)
formatter = logging.Formatter('%(asctime)s: - %(name)s %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
return logger
|
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { catchError, Observable, of } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class EnrollmentService {
baseUrl = environment.apiBaseUrl;
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
constructor(
private toastr: ToastrService,
private httpClient: HttpClient
) { }
//--- ADD DIVISION OF FEES FUNCTION ---//
addDivOfFees(feesData: any): Observable<any> {
return this.httpClient
.post(`${this.baseUrl}/fees/add`, feesData, this.httpOptions)
.pipe(catchError(this.handleError<any>('Add Division of fees')))
}
//--- GET DIVISION OF FEES ---//
getDivOfFees(studentnumber: any, semester: any, schoolyear: any): Observable<any> {
return this.httpClient
.get(`${this.baseUrl}/fees/${studentnumber}/${semester}/${schoolyear}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Division of Fees')))
}
//--- GET PAID DIVISION OF FEES ---//
getPaidDivOfFees(studentnumber: any, semester: any, schoolyear: any): Observable<any> {
return this.httpClient
.get(`${this.baseUrl}/fees/paid/${studentnumber}/${semester}/${schoolyear}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Paid Fees')))
}
//--- EDIT DIVISION OF FEES ---//
editDivOfFees(
studentnumber: any,
semester: any,
schoolyear: any,
feesData: any
): Observable<any>
{
return this.httpClient
.put(`${this.baseUrl}/fees/edit/${studentnumber}/${semester}/${schoolyear}`, feesData, this.httpOptions)
.pipe(catchError(this.handleError<any>('Edit Division of Fees')))
}
//--- EDIT PAID DIVISION OF FEES ---//
editPaidDivOfFees(
studentnumber: any,
semester: any,
schoolyear: any,
feesData: any
): Observable<any> {
return this.httpClient
.put(`${this.baseUrl}/fees/paid/edit/${studentnumber}/${semester}/${schoolyear}`, feesData, this.httpOptions)
.pipe(catchError(this.handleError<any>('Edit Paid Fees')))
}
//--- ADD STUDENT ENROLLED ---//
addStudEnroll(data: any) {
return this.httpClient
.post(`${this.baseUrl}/student_enroll/add`, data, this.httpOptions)
.pipe(catchError(this.handleError<any>('Add Student Enrolled')))
}
//--- EDIT STUDENT ENROLLED ---//
editStudEnroll(
studentnumber: any,
semester: any,
schoolyear: any,
data: any
): Observable<any> {
return this.httpClient
.put(`${this.baseUrl}/student_enroll/${studentnumber}/${semester}/${schoolyear}`, data, this.httpOptions)
.pipe(catchError(this.handleError<any>('Edit Student Enrolled')))
}
//--- GET STUDENTS ENROLLED ---//
getStudsEnroll(semester: any, schoolyear: any): Observable<any> {
return this.httpClient
.get(`${this.baseUrl}/student_enroll/list/${semester}/${schoolyear}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Students Enrolled')))
}
//--- GET STUDENT ENROLLED ---//
getStudEnroll(
studentNumber: any,
semester: any,
schoolyear: any
): Observable<any> {
return this.httpClient
.get(`${this.baseUrl}/student_enroll/${studentNumber}/${semester}/${schoolyear}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Student Enrolled')))
}
//--- ADD SUBJECT ENROLLED ---//
addSubjEnrolled(data: any): Observable<any> {
return this.httpClient
.post(`${this.baseUrl}/validation/add`, data, this.httpOptions)
.pipe(catchError(this.handleError<any>('Add Subject Enrolled')))
}
//--- GET SUBJECTS ENROLLED ---//
getSubjsEnrolled(studentnumber: any, semester: any, schoolyear: any): Observable<any> {
return this.httpClient
.get(`${this.baseUrl}/validation/get/${studentnumber}/${semester}/${schoolyear}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Subject Enrolled')))
}
//--- DELETE SUBJECT ENROLLED ---//
deleteSubjEnrolled(studentnumber: any, schedcode: any): Observable<any> {
return this.httpClient.delete(`${this.baseUrl}/validation/drop/${studentnumber}/${schedcode}`)
.pipe(catchError(this.handleError<any>('Delete Subject Enrolled')))
}
//--- ADD SUBJECT ---//
addSubject(data: any): Observable<any> {
return this.httpClient.post(`${this.baseUrl}/subject/add`, data, this.httpOptions)
.pipe(catchError(this.handleError<any>('Add Subject')))
}
//--- EDIT SUBJECT ---//
editSubject(subjectcode: any, data: any): Observable<any> {
return this.httpClient.put(`${this.baseUrl}/subject/edit/${subjectcode}`, data, this.httpOptions)
.pipe(catchError(this.handleError<any>('Edit Subject')))
}
//--- GET SUBJECT ---//
getSubject(subjectcode: any) {
return this.httpClient.get(`${this.baseUrl}/subject/get/${subjectcode}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Subject')))
}
//--- GET SUBJECT TITLE ---//
getSubjectTitle(subjectcode: any) {
return this.httpClient.get(`${this.baseUrl}/subject/get/title/${subjectcode}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Subject Title')))
}
getSubjects() {
return this.httpClient.get(`${this.baseUrl}/subject/all`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Subjects')))
}
//--- DELETE SUBJECT ---//
deleteSubject(subjectcode: any) {
return this.httpClient.delete(`${this.baseUrl}/subject/delete/${subjectcode}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Delete Subject')))
}
//--- GET SCHOLARSHIPS ---//
getScholarships(): Observable<any> {
return this.httpClient.get(`${this.baseUrl}/scholarship/list`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Scholarships')))
}
//--- GET SCHOLARSHIP DETAILS ---//
getScholarshipDetails(scholarship: any): Observable<any> {
return this.httpClient.get(`${this.baseUrl}/scholarship/${scholarship}`, this.httpOptions)
.pipe(catchError(this.handleError<any>('Get Scholarship Details')))
}
//--- TRANSACTION FOR STUDENT VALIDATION ---//
addValidateStudent(studentnumber: any, semester: any, schoolyear: any): Observable<any> {
return this.httpClient.post(
`${this.baseUrl}/validate/${studentnumber}/${semester}/${schoolyear}`,
this.httpOptions
).pipe(catchError(this.handleError<any>('Validate Student')))
}
//--- TRANSACTION FOR ADDING SUBJECT ---//
addSubjTransaction(studentnumber: any, semester: any, schoolyear: any, data: any): Observable<any> {
return this.httpClient.post(
`${this.baseUrl}/validate/add/${studentnumber}/${semester}/${schoolyear}`,
data, this.httpOptions
).pipe(catchError(this.handleError<any>('Add Subject')))
}
//--- TRANSACTION FOR DELETING SUBJECT ---//
dropSubjTransaction(studentnumber: any, semester: any, schoolyear: any, data: any): Observable<any> {
return this.httpClient.post(
`${this.baseUrl}/validate/drop/${studentnumber}/${semester}/${schoolyear}`,
data, this.httpOptions
).pipe(catchError(this.handleError<any>('Drop Subject')))
}
//--- GET ALL ASSESSED STUDENTS BY SEEMESTER AND SCHOOLYEAR ---//
getAllAssessed(semester: any, schoolyear: any): Observable<any> {
return this.httpClient.get(
`${this.baseUrl}/assess_list/${semester}/${schoolyear}`, this.httpOptions
).pipe(catchError(this.handleError<any>('Get Assessed Students')))
}
//--- GET ASSESSED STUDENT ---//
getAssessedStudent(studentnumber: any, semester: any, schoolyear: any): Observable<any> {
return this.httpClient.get(
`${this.baseUrl}/assess_list/current/${studentnumber}/${semester}/${schoolyear}`, this.httpOptions
).pipe(catchError(this.handleError<any>('Get Assessed Student')))
}
//--- EDIT SCHOLARSHIP ---//
editScholarship(studentnumber: any, semester: any, schoolyear: any, data: any): Observable<any> {
return this.httpClient.put(
`${this.baseUrl}/assess_list/edit/scholarship/${studentnumber}/${semester}/${schoolyear}`,
data, this.httpOptions
).pipe(catchError(this.handleError<any>('Edit Scholarship')))
}
//--- ERROR HANDLING ---//
private handleError<T>(operation = 'operation', result?: T) {
return (): Observable<T> => {
this.toastr.error(`${operation} failed !`);
return of(result as T);
}
}
}
|
# E-commerce Back End
This application creates an API that accesses a mySQL database using the sequelize ORM in order to execute database operations based on models and relationships.
The API implements CRUD operations for categories, products and tags. This could be the coundation for an API that drives an e-commerce site.
## Description
This is the solution to the UC Berkeley Extensions coding boot camp module 12 challenge.
The challenge itself can be
found [here](https://bootcampspot.instructure.com/courses/3826/assignments/57127?module_item_id=1006828)
and [here](https://git.bootcampcontent.com/University-of-California---Berkeley/UCB-VIRT-FSF-PT-06-2023-U-LOLC/-/tree/main/13-ORM/02-Challenge).
## Table of Contents
- [Video](#video)
- [Installation](#installation)
- [Usage](#usage)
- [License](#license)
- [Contributing](#contributing)
- [Tests](#tests)
- [Questions](#questions)
## Video
You can view the video by clicking on the [link](https://drive.google.com/file/d/1eAEHNpFHcSI8RhG4FqmObQNNp_qSitQD/view?usp=sharing)
## Installation
A current version of node is required to run this application. Make sure you [download](https://nodejs.org/en/download) and install depending on your operating system.
## Usage
Start by cloning the following repo:
```bash
git clone git@github.com:srvidales/shopicity.git
```
CD into the directory:
```bash
cd shopicity
```
Then go ahead and install the dependencies and seed the database:
```bash
npm install
mysql -u root -p -e 'source ./db/schema.sql'
npm run seed
```
And finally run the application:
```bash
npm start
```
## License
[](https://opensource.org/licenses/MIT)
## Contributing
- [Sergio Vidales Perez](mailto://srvidales@gmail.com)
Starter Code:
- [George](mailto://gcyoosf@gmail.com)
- [Xander Rapstine](mailto://xanderrapstine@gmail.com)
- [Xandromus](mailto://xanderrapstine@gmail.com)
- [dependabot-bot](mailto://49699333+dependabot[bot]@users.noreply.github.com)
- [georgeyoo](mailto://<gcyoosf@gmail.com>)
- [rxtATX](mailto://rachel.thiim@gmail.com)
## Tests
Currently, this project does not include any tests.
## Questions
Feel free to reach out with additional questions here: [Contact Me](mailto://srvidales@gmail.com) or here [GitHub](https://github.com/srvidales).
|
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
# Laravel11-Basic-Auth-Api-Starter
Project api using Laravel 11 with sanctum authentication and have role permission.
## Features
- Basic authentication with sanctum
- Role and permission
- Register and login
- Upload profile image
- Simple controller with helper
## Installation
Install my-project with npm
### 1. Clone Project
Find a location on your computer where you want to store the project. A directory made for projects is generally a good choice.
Launch a bash console there and clone the project.
```bash
git clone https://github.com/organization/project.git
```
### 2 CD into project
You will need to be inside the project directory that was just created, so cd into it.
```bash
cd project
```
### 3. Install composer dependencies
Whenever you clone a new Laravel project you must now install all of the project dependencies. This is what actually installs Laravel itself, among other necessary packages to get started.
```bash
composer install
```
### 4. Copy the .env file
.env files are not generally committed to source control for security reasons. But there is a .env.example which is a template of the .env file that the project requires.
So you should make a copy of the .env.example file and name it .env so that you can setup your local deployment configuration in the next few steps.
```bash
cp .env.example .env
```
### 5. Generate an app encryption key
Laravel requires you to have an app encryption key which is generally randomly generated and stored in your .env file. The app will use this encryption key to encode various elements of your application from cookies to password hashes and more.
Laravel’s command line tools thankfully make it easy to generate this. Run this command in the terminal to generate that key.
```bash
php artisan key:generate
```
### 6. Make storage folder can access in public
All project image upload to storage folder
To make these files accessible from the web, you should create a symbolic link from public/storage to storage/app/public. Utilizing this folder convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero down-time deployment systems like Envoyer.
To create the symbolic link, you may use the storage:link Artisan command:
```bash
php artisan storage:link
```
### 7. Running Migrations
To run all of your outstanding migrations, execute the migrate Artisan command:
```bash
php artisan migrate
```
### 8. Running Seeders
You may execute the db:seed Artisan command to seed your database. By default, the db:seed command runs the Database\Seeders\DatabaseSeeder class, which may in turn invoke other seed classes
```bash
php artisan db:seed
```
|
<template>
<div>
<h2 style="text-align: center; font-style: italic;"><i class="fas fa-shopping-cart">Giỏ hàng</i></h2>
<div v-if="cart && cart.items && cart.items.length > 0">
<table>
<thead>
<tr>
<th>Tên sản phẩm</th>
<th>Hình ảnh</th>
<th>Giá</th>
<th>Số lượng</th>
<th>Tổng</th>
<th>Hành động</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in cart.items" :key="index">
<td class="center">{{ item.product.name }}</td>
<td class="center"><img :src="item.product.imgUrl" alt="" style="width: 50px;"></td>
<td class="center">{{ formatCurrency(item.product.discountedPrice || item.product.price ) }}</td>
<td class="center quantity-column">
<div class="quantity-container">
<button @click="decreaseQuantity(item)">
<i class="fas fa-minus"></i>
</button>
<input type="text" :id="'quantity' + item.productId" class="small-input" v-model="item.quantity">
<button @click="increaseQuantity(item)">
<i class="fas fa-plus"></i>
</button>
</div>
</td>
<td class="center">{{ formatCurrency(calculateTotal(item)) }}</td>
<td class="center"><button @click="removeItem(item)">Xóa</button></td>
</tr>
</tbody>
</table>
<!-- Display total sum below the table -->
<div class="total-sum">
<span>Tổng giá:</span>
<span>{{ formatCurrency(calculateTotalSum()) }}</span>
</div>
<button @click="openOrderModal">Đặt hàng ngay</button>
<!-- Order Modal -->
<div v-if="isOrderModalOpen" class="modal">
<div class="modal-content">
<span class="close" @click="closeOrderModal">×</span>
<!-- Order Form -->
<form @submit.prevent="submitOrder" class="modal-form">
<h2 style="text-align: center;">Nhập thông tin khách hàng</h2>
<div class="form-group">
<label for="name">Tên:</label>
<input type="text" id="name" v-model="orderForm.name" required>
</div>
<div class="form-group">
<label for="address">Địa chỉ:</label>
<input type="text" id="address" v-model="orderForm.address" required>
</div>
<div class="form-group">
<label for="phone">Số điện thoại:</label>
<input type="text" id="phone" v-model="orderForm.phone" required>
</div>
<div class="form-group">
<label for="deliveryInstructions">Hướng dẫn giao hàng:</label>
<input id="deliveryInstructions" v-model="orderForm.deliveryInstructions">
</div>
<!-- Chọn phương thức giao hàng -->
<div class="form-group">
<label for="deliveryMethod"><b>Chọn phương thức giao hàng:</b></label>
<select v-model="selectedDeliveryMethod" id="deliveryMethod">
<option v-for="method in deliveryMethods" :key="method.value" :value="method.value">
{{ method.label }}
</option>
</select>
</div>
<!-- Chọn phương thức thanh toán -->
<div class="form-group">
<label for="paymentMethod"><b>Chọn phương thức thanh toán:</b></label>
<select v-model="selectedPaymentMethod" id="paymentMethod">
<option v-for="method in paymentMethods" :key="method.value" :value="method.value">
{{ method.label }}
</option>
</select>
</div>
<!-- Hiển thị tổng tiền trong modal -->
<div class="form-group">
<label><b>Tổng tiền:</b></label>
<span>{{ formatCurrency(totalAmount) }}</span>
</div>
<button type="submit" class="red-button">Đặt hàng</button>
</form>
</div>
</div>
</div>
<div v-else style="text-align: center;" >
<p>Your cart is empty.</p>
</div>
</div>
</template>
<script>
import CartService from "../services/cart.service";
import OrderService from "../services/order.service";
import ProductService from "../services/product.service";
import DiscountService from "../services/discount.service";
import _ from "lodash";
export default {
data() {
return {
cart: { items: [] },
isOrderModalOpen: false,
orderForm: {
name: "",
address: "",
phone: "",
deliveryInstructions: "",
},
// Thêm dữ liệu cho phương thức giao hàng và thanh toán
deliveryMethods: [
{ value: 'Giao hàng tiết kiệm', label: 'Giao hàng tiết kiệm (10,000 VND)' },
{ value: 'Giao hàng nhanh', label: 'Giao hàng nhanh (15,000 VND)' }
],
paymentMethods: [
{ value: 'Khi nhận hàng', label: 'Thanh toán khi nhận hàng' },
{ value: 'VNPay', label: 'VNPay' }
],
selectedDeliveryMethod: 'Giao hàng tiết kiệm',
selectedPaymentMethod: 'Khi nhận hàng',
totalAmount: 0,
orderStatus: "Đã đặt",
};
},
methods: {
async getCart() {
const userId = localStorage.getItem("userId");
this.cart = await CartService.getCart(userId);
// Áp dụng giảm giá cho các sản phẩm trong giỏ hàng
this.applyDiscountsToCartItems();
},
async applyDiscountsToCartItems() {
for (const item of this.cart.items) {
await this.applyDiscountToCartItem(item);
}
},
async applyDiscountToCartItem(cartItem) {
try {
const productDiscount = await DiscountService.getDiscountByCode(cartItem.product.code);
if (productDiscount && productDiscount.discount) {
const discountPercent = productDiscount.discount;
const discountedPrice = cartItem.product.price - (cartItem.product.price * discountPercent / 100);
cartItem.product.discountedPrice = discountedPrice;
console.log("discountedPrice: ",discountedPrice);
}
} catch (error) {
console.error("Error applying discount to cart item:", error);
}
},
calculateTotal(item) {
// Kiểm tra xem sản phẩm có giá đã giảm không
if (item.product.discountedPrice !== undefined && item.product.discountedPrice !== null) {
return item.quantity * item.product.discountedPrice;
} else {
// Nếu không, tính tổng dựa trên giá gốc của sản phẩm
return item.quantity * item.product.price;
}
},
calculateTotalSum() {
if (this.cart && this.cart.items) {
let productsTotal = 0;
// Lặp qua các sản phẩm trong giỏ hàng
this.cart.items.forEach(item => {
// Kiểm tra xem sản phẩm có giá đã giảm không
if (item.product.discountedPrice !== undefined && item.product.discountedPrice !== null) {
// Nếu có giá đã giảm, cộng tổng dựa trên giá đã giảm
productsTotal += item.quantity * item.product.discountedPrice;
} else {
// Nếu không, cộng tổng dựa trên giá gốc của sản phẩm
productsTotal += item.quantity * item.product.price;
}
});
// Tính phí giao hàng
const deliveryCost = this.selectedDeliveryMethod === 'Giao hàng tiết kiệm' ? 10000 : 15000;
// Tính tổng số tiền đặt hàng
this.totalAmount = productsTotal + deliveryCost;
return productsTotal;
} else {
this.totalAmount = 0;
return 0;
}
},
formatCurrency(value) {
return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(value);
},
increaseQuantity(item) {
item.quantity++;
this.updateQuantity(item);
},
decreaseQuantity(item) {
if (item.quantity > 1) {
item.quantity--;
this.updateQuantity(item);
}
},
async updateQuantity(item) {
const userId = localStorage.getItem("userId");
await CartService.updateQuantity(userId, item.productId, item.quantity);
this.getCart();
},
async removeItem(item) {
const userId = localStorage.getItem("userId");
await CartService.removeItem(userId, item.productId);
this.getCart();
},
openOrderModal() {
this.isOrderModalOpen = true;
},
closeOrderModal() {
this.isOrderModalOpen = false;
},
async submitOrder() {
const userId = localStorage.getItem("userId");
// Kiểm tra xem đã chọn phương thức giao hàng và thanh toán chưa
if (!this.selectedDeliveryMethod || !this.selectedPaymentMethod) {
console.error("Vui lòng chọn phương thức giao hàng và thanh toán.");
return;
}
if (!this.orderForm.name || !this.orderForm.address || !this.orderForm.phone) {
console.error("Vui lòng điền đầy đủ thông tin bắt buộc.");
return;
}
if (!this.cart || !this.cart.items) {
console.error("Lỗi khi đặt hàng: Giỏ hàng hoặc sản phẩm trong giỏ hàng không xác định.");
return;
}
try {
const productsTotal = this.calculateTotalSum();
const deliveryCost = this.selectedDeliveryMethod === 'Giao hàng tiết kiệm' ? 10000 : 15000;
const totalAmount = productsTotal + deliveryCost;
const order = await OrderService.createOrder(
userId,
this.cart.items,
this.orderForm.address,
this.orderForm.name,
this.orderForm.phone,
totalAmount,
// this.calculateTotalSum(),
this.orderForm.deliveryInstructions,
this.selectedDeliveryMethod, // Thêm phương thức giao hàng
this.selectedPaymentMethod ,// Thêm phương thức thanh toán
this.orderStatus,
);
// Lấy danh sách sản phẩm trong giỏ hàng
const cartItems = this.cart.items;
// Cập nhật số lượng sản phẩm trong collection "products"
for (const item of cartItems) {
await ProductService.updateCode(item.product.code, { quantity: item.product.quantity - item.quantity });
}
// Xóa giỏ hàng sau khi đặt hàng
await CartService.clearCart(userId);
// Chuyển hướng người dùng đến trang sản phẩm
this.$router.push({ name: 'order' });
} catch (error) {
console.error("Lỗi khi đặt hàng:", error.message);
this.closeOrderModal();
this.getCart();
}
},
},
mounted() {
this.getCart();
},
};
</script>
<style scoped>
/* Your existing styles remain unchanged */
.total-sum {
margin-top: 10px;
text-align: right;
}
.total-sum span {
margin-left: 10px;
font-weight: bold;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 2px solid #0a0a0a;
padding: 10px;
text-align: left;
}
th, td.center {
text-align: center;
}
.th.center {
text-align: center;
}
th {
background-color: yellow;
}
td {
background-color: beige
}
button {
cursor: pointer;
background-color: #4CAF50;
color: white;
padding: 5px 10px;
border: none;
border-radius: 4px;
}
.quantity-container {
display: flex;
align-items: center;
justify-content: center; /* Center the content horizontally */
}
.quantity-container button {
margin: 0 5px;
}
.small-input {
width: 40px; /* Adjust the width as needed */
}
.modal {
display: flex;
align-items: center;
justify-content: center;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 5% auto;
padding: 2px;
border: 1px solid #888;
width: 60%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.modal-form {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
width: 100%;
}
.form-group label {
margin-bottom: 5px;
width: 100%;
}
.form-group input {
padding: 8px;
width: calc(100% - 16px);
}
.red-button {
cursor: pointer;
background-color: #ff0000;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
align-self: flex-start;
margin-top: 10px;
}
/* Thêm style mới cho phương thức thanh toán */
.payment-method {
display: flex;
align-items: left;
}
.payment-method input {
margin-right: 5px; /* Điều chỉnh khoảng cách giữa nút radio và nhãn */
}
</style>
|
import { container } from "tsyringe";
import { UsersRepository } from "../modules/accounts/repositories/implementations/UsersRepository";
import { UsersTokenRepository } from "../modules/accounts/repositories/implementations/UsersTokenRepository";
import { IUsersRepository } from "../modules/accounts/repositories/IUsersRepository";
import { IUsersTokenRepository } from "../modules/accounts/repositories/IUsersTokenRepository";
import { ICarsImagesRepository } from "../modules/cars/repositories/ICarsImagesRepository";
import { ICarsRepository } from "../modules/cars/repositories/ICarsRepository";
import { ICategoriesRepository } from "../modules/cars/repositories/ICategoriesRepository";
import { CarsImagesRepository } from "../modules/cars/repositories/implementations/CarsImagesRepository";
import { CarsRepository } from "../modules/cars/repositories/implementations/CarsRepository";
import { CategoriesRepository } from "../modules/cars/repositories/implementations/CategoriesRepository";
import { SpecificationsRepository } from "../modules/cars/repositories/implementations/SpecificationsRepository";
import { ISpecificationsRepository } from "../modules/cars/repositories/ISpecificationsRepository";
import { RentalsRepository } from "../modules/rentals/repositories/implementations/RentalsRepository";
import { IRentalsRepository } from "../modules/rentals/repositories/IRentalsRepository";
import { IDateProvider } from "./providers/DateProvider/IDateProvider";
import { DayJsDateProvider } from "./providers/DateProvider/implementations/DayjsDateProvider";
import { IMailProvider } from "./providers/MailProvider/IMailProvider";
import { EtherealMailProvider } from "./providers/MailProvider/implementations/EtherealMailProvider";
import { SESMailProvider } from "./providers/MailProvider/implementations/SESMailProvider";
import { LocalStorageProvider } from "./providers/StorageProvider/implementations/LocalStorageProvider";
import { S3StorageProvider } from "./providers/StorageProvider/implementations/S3StorageProvider";
import { IStorageProvider } from "./providers/StorageProvider/IStorageProvider";
container.registerSingleton<ICategoriesRepository>(
"CategoriesRepository",
CategoriesRepository
);
container.registerSingleton<ISpecificationsRepository>(
"SpecificationsRepository",
SpecificationsRepository
);
container.registerSingleton<IUsersRepository>(
"UsersRepository",
UsersRepository
);
container.registerSingleton<ICarsRepository>("CarsRepository", CarsRepository);
container.registerSingleton<ICarsImagesRepository>(
"CarsImagesRepository",
CarsImagesRepository
);
container.registerSingleton<IRentalsRepository>(
"RentalsRepository",
RentalsRepository
);
container.registerSingleton<IUsersTokenRepository>(
"UsersTokenRepository",
UsersTokenRepository
);
container.registerSingleton<IDateProvider>(
"DayJsDateProvider",
DayJsDateProvider
);
const mailProviders = {
ethereal: container.resolve(EtherealMailProvider),
ses: container.resolve(SESMailProvider),
};
container.registerInstance<IMailProvider>(
"MailProvider",
mailProviders[process.env.MAIL_SERVICE]
);
const storageProviders = {
local: container.resolve(LocalStorageProvider),
S3: container.resolve(S3StorageProvider),
};
container.registerInstance<IStorageProvider>(
"StorageProvider",
storageProviders[process.env.disk]
);
|
package workflows
import (
"go.temporal.io/sdk/workflow"
"overdoll/applications/hades/internal/app/workflows/activities"
"time"
)
type CCBillExpirationInput struct {
SubscriptionId string
Timestamp time.Time
}
func CCBillExpiration(ctx workflow.Context, input CCBillExpirationInput) error {
ctx = workflow.WithActivityOptions(ctx, options)
logger := workflow.GetLogger(ctx)
var a *activities.Activities
var subscriptionDetails *activities.GetCCBillSubscriptionDetailsPayload
// get subscription details so we know the club
if err := workflow.ExecuteActivity(ctx, a.GetCCBillSubscriptionDetails, input.SubscriptionId).Get(ctx, &subscriptionDetails); err != nil {
logger.Error("failed to get ccbill subscription details", "Error", err)
return err
}
// ignore duplicate subscription
if subscriptionDetails.Duplicate {
return nil
}
// expire the club supporter subscription
if err := workflow.ExecuteActivity(ctx, a.ExpireAccountClubSupportSubscription,
activities.ExpireAccountClubSupportSubscriptionInput{
AccountClubSupporterSubscriptionId: subscriptionDetails.AccountClubSupporterSubscriptionId,
ExpiredAt: input.Timestamp,
},
).Get(ctx, nil); err != nil {
logger.Error("failed to expire account club supporter subscription", "Error", err)
return err
}
// remove account club support - external
if err := workflow.ExecuteActivity(ctx, a.RemoveClubSupporter,
activities.RemoveClubSupporterInput{
AccountId: subscriptionDetails.AccountId,
ClubId: subscriptionDetails.ClubId,
},
).Get(ctx, nil); err != nil {
logger.Error("failed to remove club supporter", "Error", err)
return err
}
return nil
}
|
use std::str::FromStr;
mod day_1;
mod day_10;
mod day_15;
mod day_16;
mod day_17;
mod day_2;
mod day_4;
mod day_5;
mod day_5_part2;
mod day_6;
mod day_8;
mod day_8_part2;
mod day_9;
mod grid_input;
#[derive(Clone)]
pub enum Part {
One,
Two,
}
impl FromStr for Part {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"1" => Ok(Part::One),
"2" => Ok(Part::Two),
_ => Err("no match"),
}
}
}
pub fn solve(day: u8, part: Part, input: &str) -> u32 {
match (day, part) {
(1, Part::One) => day_1::solve_part1(input),
(2, Part::One) => day_2::solve_part1(input),
(2, Part::Two) => day_2::solve_part2(input),
(5, Part::One) => day_5::solve_part1(input) as u32,
(5, Part::Two) => day_5_part2::solve_part2(input) as u32,
(6, Part::One) => day_6::solve_part1(input) as u32,
(6, Part::Two) => day_6::solve_part2(input) as u32,
(4, Part::One) => day_4::solve_part1(input),
(4, Part::Two) => day_4::solve_part2(input),
(1, Part::Two) => day_1::solve_part2(input),
(8, Part::One) => day_8::solve_part1(input),
(8, Part::Two) => day_8_part2::solve(input) as u32,
(9, Part::One) => day_9::solve_part1(input) as u32,
(9, Part::Two) => day_9::solve_part2(input) as u32,
(10, Part::One) => day_10::solve_part1(input),
(10, Part::Two) => day_10::solve_part2(input),
(15, Part::One) => day_15::solve_part1(input) as u32,
(16, Part::One) => day_16::solve_part1(input) as u32,
(16, Part::Two) => day_16::solve_part2(input) as u32,
(17, Part::One) => day_17::solve_part1(input) as u32,
_ => todo!(),
}
}
|
import {useEffect, useState} from "react";
import {pokemonApi} from "../api/pokemonApi";
import {FullPokemonResponse} from "../interfaces/pokemonInterface";
const usePokemon = (id: string) => {
const [isLoading, setIsLoading] = useState(true);
const [pokemon, setPokemon] = useState<FullPokemonResponse>({} as FullPokemonResponse);
const loadPokemon = async () => {
const resp = await pokemonApi.get<FullPokemonResponse>(
`https://pokeapi.co/api/v2/pokemon/${id}`,
);
setPokemon(resp.data);
setIsLoading(false);
};
useEffect(() => {
loadPokemon();
}, []);
return {
isLoading,
pokemon,
};
};
export default usePokemon;
|
import mongoose from "mongoose";
const { Schema } = mongoose;
const bedroomSchema = new mongoose.Schema(
{
bedType: [{ type: String }],
ensuite: { type: Boolean },
},
{ _id: false }
);
const ListingSchema = new Schema(
{
userId: {
type: String,
},
title: {
type: String,
},
images: [
{
url: String,
filename: String,
file: Object,
progress: Number,
},
],
location: {
address1: { type: String },
city: { type: String },
countryregion: { type: String },
postalcode: { type: String },
stateprovince: { type: String },
unitnumber: { type: String },
lat: { type: Number },
lng: { type: Number },
},
moveInDate: {
type: Date,
},
moveOutDate: {
type: Date,
},
shorterStays: {
type: Boolean,
default: false,
},
availableToView: {
type: Boolean,
default: true,
},
viewingDates: [{ type: String }],
expiryDate: {
type: Date,
},
views: {
type: Number,
default: 0,
},
price: {
type: Number,
default: 0,
},
aboutyourplace: {
propertyType: { type: String },
privacyType: { type: String },
},
basics: {
bedrooms: [bedroomSchema],
bathrooms: { type: Number },
},
amenities: {
inUnitWasherAndDrier: {
type: Boolean,
default: false,
},
airConditioning: {
type: Boolean,
default: false,
},
petsAllowed: {
type: Boolean,
default: false,
},
furnished: {
type: Boolean,
default: false,
},
dishwasher: {
type: Boolean,
default: false,
},
fitnessCenter: {
type: Boolean,
default: false,
},
balcony: {
type: Boolean,
default: false,
},
parking: {
type: Boolean,
default: false,
},
},
utilities: {
hydro: {
type: Boolean,
default: false,
},
electricity: {
type: Boolean,
default: false,
},
water: {
type: Boolean,
default: false,
},
wifi: {
type: Boolean,
default: false,
},
},
description: {
type: String,
},
published: {
type: Boolean,
default: false,
},
transactionInProgress: {
type: Boolean,
default: false,
},
isDeleted: {
type: Boolean,
default: false,
},
bookedDates: [
{
startDate: Date,
endDate: Date,
},
],
isBooked: {
type: Boolean,
default: false,
},
},
{ timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
// // virtual properties
// ListingSchema.virtual("daysLeft").get(function () {
// const now = new Date();
// const diffTime = this.expiryDate.getTime() - now.getTime();
// const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
// return diffDays;
// });
// virtual properties
// (rewriting with extra error handling steps bc some entries in the DB
// don't have .expiryDate anymore and were giving errors)
ListingSchema.virtual("daysLeft").get(function () {
if (this.expiryDate && this.expiryDate instanceof Date) {
const now = new Date();
const diffTime = this.expiryDate.getTime() - now.getTime();
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
} else {
return 0;
}
});
ListingSchema.virtual("numOfBedrooms").get(function () {
return this.basics.bedrooms.length;
});
ListingSchema.set("toObject", { virtuals: true });
ListingSchema.set("toJSON", { virtuals: true });
const ListingModel = mongoose.models.Listing || mongoose.model("Listing", ListingSchema);
export default ListingModel;
|
import { View, Text, ScrollView, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native'
import React from 'react'
import { Link ,useRouter} from 'expo-router'
import { auth } from '../utils/firebaseConfig'
import {signInWithEmailAndPassword} from 'firebase/auth'
import { useAuth } from '../context/authContext'
const Login = () => {
const {setUser,setAuthenticated}=useAuth()
const [email, setEmail] = React.useState('')
const [password, setPassword] = React.useState('')
const [emailError, setEmailError] = React.useState(false)
const [passwordError, setPasswordError] = React.useState(false)
const [error, setError] = React.useState()
const [loading, setLoading] = React.useState(false)
const router=useRouter()
async function login_user() {
setEmailError(false)
setPasswordError(false)
if (email.length < 1) {
setEmailError(true)
return
}
if (password.length < 1) {
setPasswordError(true)
return
}
setLoading(true)
try {
// login(email,password)
const userCred = await signInWithEmailAndPassword(auth, email, password)
const user = userCred.user
setUser(user)
setAuthenticated(true)
setLoading(false)
router.replace('/home')
} catch (e) {
setError(e)
setEmail('')
setPassword('')
setLoading(false)
}
}
return (
<ScrollView contentContainerStyle={{
flex: 1,
width: '100%',
}}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#f0f2f5',marginHorizontal:30, }}>
<View className='text-left w-full'>
<Text className="text-4xl text-black font-bold mb-8 ">Let's Sign you in</Text>
<Text className="text-3xl text-gray-400 font-semibold mb-4 ">Welcome back</Text>
<Text className="text-3xl text-gray-400 font-semibold mb-8 ">You've been missed!</Text>
</View>
<View className='w-full'>
{
error && (
<View className='my-2'>
<Text className='text-red-700 text-center '>{error.message}</Text>
</View>
)
}
<View className='w-full mb-4'>
<Text className="text-lg text-gray-500 font-semibold mb-2">Email</Text>
<TextInput style={{
borderColor:emailError ? 'red' : 'gray'
}} value={email} onChangeText={(e) => {
setEmail(e)
}} inputMode='email' className="w-full p-2 border border-gray-300 rounded-lg" placeholder="Enter your email" />
</View>
<View className='w-full mb-4'>
<Text className="text-lg text-gray-500 font-semibold mb-2">Password</Text>
<TextInput style={{
borderColor:passwordError ? 'red' : 'gray'
}} secureTextEntry value={password} onChangeText={(e) => {
setPassword(e)
}} className="w-full p-2 border border-gray-300 rounded-lg" placeholder="Enter your password" />
</View>
<View className='w-full my-5'>
<TouchableOpacity disabled={loading} onPress={login_user} activeOpacity={0.5} className="p-2 rounded-lg bg-black flex flex-row items-center justify-center gap-x-2" >
{
loading && (
<ActivityIndicator color='white' size='large' />
)
}
<Text className=' text-center font-bold text-lg text-white '>
{
!loading && 'Login'
}
</Text>
</TouchableOpacity>
</View>
<Text className="text-center text-gray-500 mt-4">Don't have an account?
<Link asChild href={'register'}>
<Text className="text-blue-500">Register</Text>
</Link>
</Text>
<Text className="text-center text-gray-500 mt-4">Go to index
<Link asChild href={'/index'}>
<Text className="text-blue-500"> index</Text>
</Link>
</Text>
</View>
</View>
</ScrollView>
)
}
export default Login
|
import React, { Component, Suspense } from 'react';
import { connect } from 'react-redux';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
// import './helpers/Firebase';
import AppLocale from './lang';
import NotificationContainer from './components/common/react-notifications/NotificationContainer';
import { isDemo, radiusType } from './constants/defaultValues';
import { getDirection, getLoggedIn } from './helpers/Utils';
const ViewMain = React.lazy(() => import(/* webpackChunkName: "views" */ './views'));
const ViewApp = React.lazy(() => import(/* webpackChunkName: "views-app" */ './views/app'));
const ViewUser = React.lazy(() => import(/* webpackChunkName: "views-user" */ './views/user'));
const ViewError = React.lazy(() => import(/* webpackChunkName: "views-error" */ './views/error'));
const AuthRoute = ({ component: Component, authUser, ...rest }) => {
return (
<Route
{...rest}
render={(props) =>
// console.log(getLoggedIn())
getLoggedIn() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/user/login',
state: { from: props.location },
}}
/>
)
}
/>
);
};
class App extends Component {
constructor(props) {
super(props);
const direction = getDirection();
if (direction.isRtl) {
document.body.classList.add('rtl');
document.body.classList.remove('ltr');
} else {
document.body.classList.add('ltr');
document.body.classList.remove('rtl');
}
}
componentDidMount() {
if (radiusType === 'flat') {
document.body.classList.remove('rounded');
} else {
document.body.classList.add('rounded');
}
}
render() {
const { locale, loginUser } = this.props;
const currentAppLocale = AppLocale[locale];
return (
<div className="h-100">
<IntlProvider locale={currentAppLocale.locale} messages={currentAppLocale.messages}>
<React.Fragment>
<NotificationContainer />
<Suspense fallback={<div className="loading" />}>
<Router>
<Switch>
<AuthRoute path="/app" authUser={loginUser} component={ViewApp} />
<Route path="/user" render={(props) => <ViewUser {...props} />} />
<AuthRoute path="/error" exact render={(props) => <ViewError {...props} />} />
<AuthRoute path="/" exact render={(props) => <ViewMain {...props} />} />
<Redirect to="/error" />
</Switch>
</Router>
</Suspense>
</React.Fragment>
</IntlProvider>
</div>
);
}
}
const mapStateToProps = ({ authUser, settings }) => {
const { user: loginUser } = authUser;
const { locale } = settings;
return { loginUser, locale };
};
const mapActionsToProps = {};
export default connect(
mapStateToProps,
mapActionsToProps,
)(App);
|
package de.gmuth.ipp.attributes
/**
* Copyright (c) 2020-2023 Gerhard Muth
*/
import de.gmuth.ipp.core.IppAttribute
import de.gmuth.ipp.core.IppAttributeBuilder
import de.gmuth.ipp.core.IppAttributesGroup
import de.gmuth.ipp.core.IppCollection
import de.gmuth.ipp.core.IppTag.BegCollection
import de.gmuth.ipp.core.IppTag.Keyword
// https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobext21-20230210-5100.7.pdf 6.3
class MediaCollection(
val size: MediaSize? = null,
val margin: MediaMargin? = null,
val source: MediaSource? = null,
val type: String? = null
) : IppAttributeBuilder {
override fun buildIppAttribute(printerAttributes: IppAttributesGroup) =
IppAttribute("media-col", BegCollection, IppCollection().apply {
type?.let { addAttribute("media-type", Keyword, it) }
size?.let { add(it.buildIppAttribute(printerAttributes)) }
margin?.let { addAll(it.buildIppAttributes()) }
source?.let { add(it.buildIppAttribute(printerAttributes)) }
})
}
|
import React, {useState} from "react";
import styleCard from "../../Categories/CategoriesCard/cards.module.css";
import img from "../../../assets/img/3.jpg";
import style from "../roductList.module.css";
import {connect} from "react-redux";
import {addToBasket, deleteBasket} from "../../../reduse-store/basket";
const ProductCard = ({ id,image, description, name, price, addToBasket,deleteBasket})=>{
const src = require(`../../../assets/${image}`)
const [isBasket, setBasket ] = useState(false)
const handleAddBasket = ()=>{
if (!isBasket){
setBasket(!isBasket)
const data = {
id,
title: name,
price,
count: 1
}
addToBasket(data)
}
}
const handleDeleteBasket = ()=>{
setBasket(!isBasket)
deleteBasket(id)
}
return(
<div className={styleCard.card}>
<img src={src} alt=""/>
<div className={styleCard.cardText}>
<div className={styleCard.cardHeading}>
<h3>{name}</h3>
</div>
<div className={styleCard.cardInfo}>
<p className={style.ingrediens}>{description}</p>
</div>
<div className={style.cardButtom}>
{!isBasket?
<button className={style.cardBtn} onClick={handleAddBasket}>
<span className={style.btnText}>В корзину</span>
<span className={style.svg}>{price}</span>
</button> :
<button className={style.cardBtn} onClick={handleDeleteBasket}>
<span className={style.btnText}>Добавлено в</span>
<span className={style.svg}>{price}</span>
</button>}
<strong>500$</strong>
</div>
</div>
</div>
)
}
export default connect (null, {addToBasket,deleteBasket})(ProductCard)
|
using MeetMVC.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Owin;
using Microsoft.Owin;
using MeetMVC.Infrastructure;
using MeetMVC.Services;
using MeetMVC.Hubs;
using Microsoft.EntityFrameworkCore.SqlServer;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("ApplicationDbContextConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));;
//builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
// .AddEntityFrameworkStores<ApplicationDbContext>();;
// Add services to the container.
connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlServer(connectionString);
options.UseLazyLoadingProxies();
});
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddRazorPages();
/*builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>().AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddRazorPages();*/
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapHub<ChatHub>("/chatHub");
});
app.Run();
|
<template>
<q-layout view="hHh Lpr lFf">
<q-header elevated>
<q-toolbar>
<q-btn
flat
dense
round
icon="menu"
aria-label="Menu"
@click="toggleLeftDrawer"
/>
<q-toolbar-title>
Financial App
</q-toolbar-title>
<div>v1.0</div>
</q-toolbar>
</q-header>
<q-drawer
v-model="leftDrawerOpen"
show-if-above
bordered
>
<q-list>
<q-item-label
header
>
</q-item-label>
<q-item
v-for="item in menuList"
:key="item.title"
clickable
:to="item.path"
>
<q-item-section
v-if="item.icon"
avatar
>
<q-icon :name="item.icon"/>
</q-item-section>
<q-item-section>
<q-item-label>{{ $t(item.title) }}</q-item-label>
</q-item-section>
</q-item>
<q-item
clickable
@click="logout"
>
<q-item-section avatar>
<q-icon name="logout"/>
</q-item-section>
<q-item-section>
<q-item-label>{{ $t('Logout') }}</q-item-label>
</q-item-section>
</q-item>
</q-list>
</q-drawer>
<q-page-container>
<router-view/>
</q-page-container>
</q-layout>
</template>
<script>
const menuList = [
{
title: 'Entries',
icon: 'sync_alt',
path: 'entries'
},
{
title: 'Accounts',
icon: 'payments',
path: 'accounts'
},
{
title: 'Credit Cards',
icon: 'credit_card',
path: 'credit-cards'
}
]
export default {
name: 'MainLayout',
data () {
return {
leftDrawerOpen: false,
menuList: menuList
}
},
methods: {
toggleLeftDrawer () {
this.leftDrawerOpen = !this.leftDrawerOpen
},
async logout () {
await this.$store.dispatch('user/logout')
this.$router.push(`/login?redirect=${this.$route.fullPath}`)
}
}
}
</script>
|
import React, { useEffect, useState } from 'react'
import { getGifs } from '../helpers/getGifs'
import { GifGridItem } from './GifGridItem'
export const GifGrid = ({category} ) => {
const [images, setImages] = useState([])
useEffect(() => {
getGifs(category)
.then( setImages);
}, [category])
return (
<>
<h3>{category} </h3>
<div className='card-grid'>
{
images.map(img => (
<GifGridItem
key={img.id}
{...img}
/>
))
}
</div>
</>
)
}
|
"""
{} 大括号就是字典的创建符号
<class 'dict'> 字典类型
字典中数据的形式都是键值对的形式 key: value
key: value 键值对之间用英文状态下的冒号隔开
key -->
冒号左边是键
键可以是: 字符串/数值/元组/布尔类型, 列表不行, 因为这个键不能被修改
在一个字典中, 键必须唯一
可以根据键取对应的值 字典名[键]
value -->
冒号右边是键的值, 值可以是任意的Python类型 , 列表, 字典, 元组, 集合 --> 嵌套数据
"""
dict1 = {
'name': '丸子',
15: 20,
('你好',): {
'name': '丸子',
15: 20,
('你好',): {'sex': '女'},
True: [1, 2, 3, 4, 5],
},
True: [1, 2, 3, 4, 5],
# [1,2,3]: '列表'
}
print(dict1)
print(type(dict1))
print(dict1['name'])
print(dict1[15])
print(dict1[('你好',)])
print(dict1[True])
# 空字典的创建
dict2 = {}
dict3 = dict()
|
#frozen_string_literal: true
FactoryBot.define do
factory :shopify_tender_transaction, class: 'ShopifyAPI::TenderTransaction' do
# Basic attributes
id { FFaker::Random.rand(1..1000) }
order_id { FFaker::Random.rand(1..1000) }
amount { FFaker::Random.rand(10.0..1000.0).round(2).to_s }
currency { FFaker::Currency.code }
payment_method { ['credit_card', 'paypal', 'shop_pay', 'apple_pay'].sample }
processed_at { FFaker::Time.date }
remote_reference { FFaker::Lorem.characters(10) }
test { FFaker::Boolean.random }
user_id { FFaker::Random.rand(1..1000) }
# Hash attributes for payment details
payment_details { { credit_card_bin: FFaker::Bank.card_number, avs_result_code: 'Y', cvv_result_code: 'N', credit_card_number: "•••• •••• •••• #{FFaker::Random.rand(1000..9999)}", credit_card_company: 'Visa' } }
# Traits
trait :with_test_mode do
test { true }
end
trait :with_real_mode do
test { false }
end
trait :with_credit_card do
payment_method { 'credit_card' }
payment_details { { credit_card_bin: FFaker::Bank.card_number, avs_result_code: 'Y', cvv_result_code: 'N', credit_card_number: "•••• •••• •••• #{FFaker::Random.rand(1000..9999)}", credit_card_company: 'Visa' } }
end
trait :with_paypal do
payment_method { 'paypal' }
payment_details { { payer_id: FFaker::Internet.user_name, transaction_id: FFaker::Lorem.characters(10), payment_status: 'Completed' } }
end
end
end
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0
maximum-scale=1.0, minimum-scale=1.0">
<title>마우스 이벤트 - 드래그</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #fff700;
border: 5px solid orange;
cursor: pointer;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
// 드래그 대상 요소
const $box = document.querySelector('.box');
// 드래그 시작 시점의 마우스 포인터 위치
const initialMousePos = {x: 0, y: 0};
// 오프셋 : 이동할 거리
const offset = {x: 0, y: 0};
// mousemove 이벤트 핸들러
const move = e => {
console.log("move");
// 오프셋 = 현재 위치 - 시작위치
offset.x = e.clientX - initialMousePos.x;
offset.y = e.clientY - initialMousePos.y;
// translate3d 는 GPU 를 사용하므로 absolute 의 top, left 를 사용하는것보다 빠르다
// top, left 는 레이아웃에 영향을 준다.
$box.style.transform = `translate3d(${offset.x}px, ${offset.y}px, 0)`
};
// mousedown 이벤트가 발생하면 드래그 시작지점에 좌표 저장
// e.clientX / e.clientY -> 뷰포트 상에서 마우스 포인터 좌표 저장
// 한 번 이상 드래그로 이동한 경우 move 핸들러의 translated3d로 이동한 상태이므로
$box.addEventListener('mousedown', e =>{
console.log("mousedown");
initialMousePos.x = e.clientX - offset.x;
initialMousePos.y = e.clientY - offset.y;
// mouse down 이벤트가 발생한 상태에서 mousemove 이벤트가 발생하면 box 이동
document.addEventListener('mousemove', move);
})
// mouseup 이벤트가 발싱하면 mousemove 이벤트를 제거해 이동을 멈춘다.
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', move);
});
</script>
</html>
|
import { Injectable } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router';
import { JhiPaginationUtil, JhiResolvePagingParams } from 'ng-jhipster';
import { UserRouteAccessService } from 'app/core';
import { Observable, of } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { SessionInscriptionMySuffix } from 'app/shared/model/session-inscription-my-suffix.model';
import { SessionInscriptionMySuffixService } from './session-inscription-my-suffix.service';
import { SessionInscriptionMySuffixComponent } from './session-inscription-my-suffix.component';
import { SessionInscriptionMySuffixDetailComponent } from './session-inscription-my-suffix-detail.component';
import { SessionInscriptionMySuffixUpdateComponent } from './session-inscription-my-suffix-update.component';
import { SessionInscriptionMySuffixDeletePopupComponent } from './session-inscription-my-suffix-delete-dialog.component';
import { ISessionInscriptionMySuffix } from 'app/shared/model/session-inscription-my-suffix.model';
@Injectable({ providedIn: 'root' })
export class SessionInscriptionMySuffixResolve implements Resolve<ISessionInscriptionMySuffix> {
constructor(private service: SessionInscriptionMySuffixService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ISessionInscriptionMySuffix> {
const id = route.params['id'] ? route.params['id'] : null;
if (id) {
return this.service.find(id).pipe(
filter((response: HttpResponse<SessionInscriptionMySuffix>) => response.ok),
map((sessionInscription: HttpResponse<SessionInscriptionMySuffix>) => sessionInscription.body)
);
}
return of(new SessionInscriptionMySuffix());
}
}
export const sessionInscriptionRoute: Routes = [
{
path: '',
component: SessionInscriptionMySuffixComponent,
resolve: {
pagingParams: JhiResolvePagingParams
},
data: {
authorities: ['ROLE_USER'],
defaultSort: 'id,asc',
pageTitle: 'jhipsterrtestApp.sessionInscription.home.title'
},
canActivate: [UserRouteAccessService]
},
{
path: ':id/view',
component: SessionInscriptionMySuffixDetailComponent,
resolve: {
sessionInscription: SessionInscriptionMySuffixResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterrtestApp.sessionInscription.home.title'
},
canActivate: [UserRouteAccessService]
},
{
path: 'new',
component: SessionInscriptionMySuffixUpdateComponent,
resolve: {
sessionInscription: SessionInscriptionMySuffixResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterrtestApp.sessionInscription.home.title'
},
canActivate: [UserRouteAccessService]
},
{
path: ':id/edit',
component: SessionInscriptionMySuffixUpdateComponent,
resolve: {
sessionInscription: SessionInscriptionMySuffixResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterrtestApp.sessionInscription.home.title'
},
canActivate: [UserRouteAccessService]
}
];
export const sessionInscriptionPopupRoute: Routes = [
{
path: ':id/delete',
component: SessionInscriptionMySuffixDeletePopupComponent,
resolve: {
sessionInscription: SessionInscriptionMySuffixResolve
},
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterrtestApp.sessionInscription.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
}
];
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2012-2015 Marco Craveiro <marco.craveiro@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#ifndef DOGEN_CODEC_TYPES_ENTITIES_ARTEFACT_HPP
#define DOGEN_CODEC_TYPES_ENTITIES_ARTEFACT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif
#include <string>
#include <algorithm>
#include <boost/filesystem/path.hpp>
namespace dogen::codec::entities {
class artefact final {
public:
artefact() = default;
artefact(const artefact&) = default;
~artefact() = default;
public:
artefact(artefact&& rhs);
public:
artefact(
const boost::filesystem::path& path,
const std::string& codec_name,
const std::string& content);
public:
/**
* @brief Path to the file representing this artefact, if any.
*/
/**@{*/
const boost::filesystem::path& path() const;
boost::filesystem::path& path();
void path(const boost::filesystem::path& v);
void path(const boost::filesystem::path&& v);
/**@}*/
/**
* @brief Name of the codec to process this artefact.
*/
/**@{*/
const std::string& codec_name() const;
std::string& codec_name();
void codec_name(const std::string& v);
void codec_name(const std::string&& v);
/**@}*/
/**
* @brief Contents of the artefact.
*/
/**@{*/
const std::string& content() const;
std::string& content();
void content(const std::string& v);
void content(const std::string&& v);
/**@}*/
public:
bool operator==(const artefact& rhs) const;
bool operator!=(const artefact& rhs) const {
return !this->operator==(rhs);
}
public:
void swap(artefact& other) noexcept;
artefact& operator=(artefact other);
private:
boost::filesystem::path path_;
std::string codec_name_;
std::string content_;
};
}
namespace std {
template<>
inline void swap(
dogen::codec::entities::artefact& lhs,
dogen::codec::entities::artefact& rhs) {
lhs.swap(rhs);
}
}
#endif
|
import { createRouter, createWebHistory } from 'vue-router'
import DiscoverView from '../views/DiscoverView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'discover',
component: DiscoverView
},
{
path: '/history',
name: 'history',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/HistoryView.vue')
},
{
path: '/contact',
name: 'contact',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/TestcontactView.vue')
}
]
})
export default router
|
import type { GetStaticProps, NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import Header from '../components/Header'
import Hero from '../components/Hero'
import About from '../components/About'
import Experiences from '../components/Experiences'
import Skills from '../components/Skills'
import Projects from '../components/Projects'
import Contact from '../components/Contact'
import Link from 'next/link'
import { fetchPageInfo } from '../utils/fetchPageInfo'
import { fetchExperiences } from '../utils/fetchExperiences'
import { fetchProjects } from '../utils/fetchProjects'
import { fetchSkills } from '../utils/fetchSkill'
import { fetchSocials } from '../utils/fetchSocials'
import { Experience, PageInfo, Skill, Project, Social } from '../typing'
type Props = {
pageInfo: PageInfo,
skills: Skill[],
projects: Project[],
experiences: Experience[],
socials: Social[],
}
const Home = ({pageInfo, projects,experiences,socials, skills}:Props) => {
return (
<div className="bg-[rgb(36,36,36)] text-white h-screen snap-y
snap-mandatory overflow-scroll z-0
overflow-y-scroll overflow-x-hidden
scrollbar scrollbar-track-gray-400/20 scrollbar-thumb-[#F7AB0A]
">
<Header socials={socials}></Header>
<section id="hero" className='snap-start'>
<Hero pageInfo={pageInfo}></Hero>
</section>
<section id="about" className='snap-center'>
<About pageInfo={pageInfo}/>
</section>
<section id="experience" className='snap-center'>
<Experiences experiences={experiences} />
</section>
<section id="skills" className='snap-center'>
<Skills skills={skills}/>
</section>
<section id="projects" className='snap-center'>
<Projects projects={projects}/>
</section>
<section id="contact" className='snap-center'>
<Contact />
</section>
<Link href="#hero">
<footer className='sticky bottom-5 w-full cursor-pointer'>
<div className='flex items-center justify-center'>
<img className='h-10 w-10 rounded-full filter grayscale hover:grayscale-0 cursor-pointer' src="https://media-exp1.licdn.com/dms/image/C5103AQFqqz-NQtA5oA/profile-displayphoto-shrink_800_800/0/1585995824841?e=1670457600&v=beta&t=mYhavMFGqu2nJZR5JyeTDgW__xlYhsXEo-GDrWn2bNc"></img>
</div>
</footer>
</Link>
</div>
)
}
export const getStaticProps: GetStaticProps<Props> = async()=>{
const pageInfo: PageInfo = await fetchPageInfo()
const experiences: Experience[] = await fetchExperiences()
const projects: Project[] = await fetchProjects()
const skills: Skill[] = await fetchSkills()
const socials: Social[] = await fetchSocials()
return {
props: {
pageInfo,
experiences,
projects,
skills,
socials,
},
revalidate:10,
}
}
export default Home
|
<script>
export let f7router;
export let f7route;
import { Page, List, Block, ListItem } from 'framework7-svelte';
import CustomNavbar from '../components/CustomNavbar.svelte';
import PiantaItem from './PiantaItem.svelte';
import { onMount } from 'svelte';
import { getCurrentUser, get_current_user_jwt } from '../lib/firebase_auth';
import NotFoundResult from '../components/NotFoundResult.svelte';
let piante = [];
function cache_plants(plants) {
// Cache plants in localStorage, risparmiamo sul costo delle query
sessionStorage.setItem('myplants', JSON.stringify(plants));
}
function get_plants_from_cache() {
const cached_plants = sessionStorage.getItem('myplants');
return cached_plants != null ? JSON.parse(cached_plants) : [];
}
onMount(async () => {
const raw_plants_from_cache = get_plants_from_cache();
if (raw_plants_from_cache.length > 0) {
piante = raw_plants_from_cache;
return; // Stop here, don't do another useless request to AWS
}
const jwt = await get_current_user_jwt();
const user = await getCurrentUser();
fetch(
'https://dlc52l1dnc.execute-api.eu-central-1.amazonaws.com/plant_info_api?sensor_id=NULL',
{
headers: new Headers({
authorization: jwt.token,
'content-type': 'application/x-www-form-urlencoded'
})
}
)
.then((response) => response.json()) // converti a json
.then((json) => {
piante = json;
cache_plants(json);
});
});
let filtered_plants = [];
let empty_filter = false;
function found(e) {
filtered_plants = e.detail.items;
if (filtered_plants == 0) empty_filter = true;
else empty_filter = false;
}
</script>
<Page name="home">
<CustomNavbar
title="Le mie piante"
search_bar={true}
search_bar_placeholder="Cerca una pianta"
search_bar_items={piante}
object_key="plant_name"
on:found={found}
/>
<Block>
{#if empty_filter}
<NotFoundResult></NotFoundResult>
{:else if filtered_plants.length == 0}
{#each piante as pianta}
<div on:click={() => f7router.navigate('/chart/')} on:keydown={() => {}}>
<!-- Cambiare in temperatura dal sensore e aggiungere gli altri parametri -->
<PiantaItem
name={pianta.plant_name}
temp={pianta.default_temperature}
days={pianta.days}
ph={pianta.default_humidity}
/>
</div>
{/each}
{:else}
{#each filtered_plants as pianta}
<div on:click={() => f7router.navigate('/chart/')} on:keydown={() => {}}>
<!-- Cambiare in temperatura dal sensore e aggiungere gli altri parametri -->
<PiantaItem
name={pianta.plant_name}
temp={pianta.default_temperature}
days={pianta.days}
ph={pianta.default_humidity}
/>
</div>
{/each}
{/if}
</Block>
</Page>
|
import React from "react";
import { useState } from "react";
const AddFootItem = (props) => {
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const [path, setPath] = useState("");
const [description, setDescription] = useState("");
const [error, setError] = useState(false);
const handleAddFoodItem = async () => {
if (!name || !price || !path || !description) {
setError(true);
return;
}
else{
setError(false);
}
let resto_id;
const restaurantData = JSON.parse(localStorage.getItem("restaurantUser"));
if(restaurantData){
resto_id = restaurantData._id;
}
let response = await fetch("http://localhost:3000/api/restaurant/foods", {
method: "POST",
body: JSON.stringify({
name,
price,
img_path: path,
description,
resto_id,
}),
});
let data = await response.json();
if (data.success){
alert("food item added");
props.setAddItem(false);
}
else{
alert("failed to add food item");
}
}
return (
<div className="container">
<h1>Add new food item</h1>
<div className="input-wrapper">
<input
type="text"
placeholder="enter food name"
className="input-field"
value={name}
onChange={(e)=>setName(e.target.value)}
/>
{
error && !name && <span className="input-error">Name is required</span>
}
</div>
<div className="input-wrapper">
<input
type="text"
placeholder="enter price"
className="input-field"
value={price}
onChange={(e)=>setPrice(e.target.value)}
/>
{
error && !price && <span className="input-error">Price is required</span>
}
</div>
<div className="input-wrapper">
<input
type="text"
placeholder="enter image path"
className="input-field"
value={path}
onChange={(e)=>setPath(e.target.value)}
/>
{
error && !path && <span className="input-error">Image path is required</span>
}
</div>
<div className="input-wrapper">
<input
type="text"
placeholder="enter food description"
className="input-field"
value={description}
onChange={(e)=>setDescription(e.target.value)}
/>
{
error && !description && <span className="input-error">Description is required</span>
}
</div>
<div className="input-wrapper">
<button className="button"
onClick={handleAddFoodItem}>
Add Food Item
</button>
</div>
</div>
);
};
export default AddFootItem;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Portofolio</title>
<link rel="stylesheet" href="style.css" />
<style>
.disable-pointer-events {
pointer-events: none;
}
.hamburger-icon {
pointer-events: auto;
}
</style>
</head>
<body class="font-body scroll-smooth">
<nav class="hidden lg:block select-none border-b border-white shadow-lg fixed top-0 w-full bg-white z-50">
<div class="flex text-xl justify-around items-center h-[7vh]">
<div class="text-3xl cursor-default"><a href="#top">
My Portofolio
</a></div>
<!-- maybe add active:text-blue-500 somehow -->
<ul>
<li class="list-none inline-block px-5 no-underline transition duration-300 ease-in-out hover:text-blue-500">
<a
href="#about"
>About</a
>
</li>
<li class="list-none inline-block px-5 no-underline transition duration-300 ease-in-out hover:text-blue-500">
<a
href="#experience"
>Experience</a
>
</li>
<li class="list-none inline-block px-5 no-underline transition duration-300 ease-in-out hover:text-blue-500">
<a
href="#projects"
>Projects</a
>
</li>
<li class="list-none inline-block px-5 no-underline transition duration-300 ease-in-out hover:text-blue-500">
<a
href="#contact"
>Contact</a
>
</li>
</ul>
</nav>
<!-- mobile navbar -->
<nav class="lg:hidden select-none border-b border-white shadow-lg fixed top-0 w-full bg-white z-50">
<div class="flex text-xl justify-around items-center h-[8vh]">
<div class="text-2xl cursor-default"><a href="#top">My Portfolio</a></div>
<ion-icon name="menu" class="hamburger-icon absolute right-14 text-4xl cursor-pointer" onclick="toggleMenu(this)"></ion-icon>
<div></div>
<div class="mobile-links bg-white px-[100%] py-[55%] text-xl opacity-0 transition duration-300 ease-in-out absolute top-14 text-center pointer-events-none">
<li class="list-none my-10 no-underline"><a href="#top" class="menu-link cursor-pointer">Profile</a></li>
<li class="list-none my-10 no-underline"><a href="#about" class="menu-link cursor-pointer">About</a></li>
<li class="list-none my-10 no-underline"><a href="#experience" class="menu-link cursor-pointer">Experience</a></li>
<li class="list-none my-10 no-underline"><a href="#projects" class="menu-link cursor-pointer">Projects</a></li>
<li class="list-none my-10 no-underline"><a href="#contact" class="menu-link cursor-pointer">Contact</a></li>
</div>
</div>
</nav>
<section id="profile" class="mt-44">
<div class="flex flex-col lg:flex-row justify-center">
<div class="flex justify-center lg:mr-32 drop-shadow-2xl order-1 lg:order-none">
<img src="assets/profilepic.png" alt="Profile picture of Thodoris Tsironis" class="h-[300px] lg:h-[600px]">
</div>
<div class="mt-5 lg:mt-36 order-2 lg:order-none">
<p class="flex justify-center text-lg sm:text-xl mb-3 sm:mb-5 text-gray-500">
Hello, I'm
</p>
<h1 class="flex justify-center text-3xl sm:text-4xl mb-3 sm:mb-5 font-bold">Thodoris Tsironis</h1>
<p class="flex justify-center text-lg sm:text-xl mb-5 sm:mb-7 text-gray-500">Frontend Developer</p>
<div class="flex justify-center my-2 sm:my-3">
<button aria-label="Download CV" class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-3 sm:px-4 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl" onclick="window.open('assets/ThodorisTsironisCV.pdf')">Download CV</button>
<button aria-label="Contact me" class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-3 sm:px-4 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl" onclick="location.href = '#contact' ">Contact me</button>
</div>
<div class="icons text-2xl sm:text-3xl flex justify-center">
<a href="https://www.linkedin.com/in/thodoris-tsironis-173b1b24a" target="_blank" rel="noopener noreferrer">
<ion-icon class="my-2 mx-1 cursor-pointer hover:opacity-50" name="logo-linkedin"></ion-icon>
</a>
<a href="https://github.com/tsiro66" target="_blank" rel="noopener noreferrer">
<ion-icon class="my-2 mx-1 cursor-pointer hover:opacity-50" name="logo-github"></ion-icon>
</a>
</div>
</div>
</div>
</section>
<section id="about">
<div class="flex flex-col items-center mt-40">
<p class="text-lg sm:text-xl text-gray-500 mt-28 lg:mt-40">Get To Know More</p>
<h1 class="text-4xl lg:text-5xl font-bold">About Me</h1>
</div>
<div class="flex flex-col lg:flex-row mx-4 sm:mx-8 lg:mx-32 justify-center mt-8 lg:mt-16">
<div class="w-full lg:w-5/12 hidden 2xl:flex justify-center items-center">
<img src="assets/aboutme.png" alt="About me" class="mt-12 lg:mt-24 object-contain max-w-xs lg:max-w-2xl">
</div>
<div class="flex flex-wrap justify-center text-center lg:w-1/2">
<div class="lg:flex lg:mt-8">
<article class="border-2 border-gray-400 rounded-3xl mx-2 sm:mx-5 w-60 sm:w-72 py-3 sm:py-5 h-32 sm:h-40 mt-5 flex flex-col items-center">
<ion-icon name="ribbon-outline" class="text-2xl sm:text-3xl text-blue-500"></ion-icon>
<p class="text-lg sm:text-xl font-bold">Work Experience</p>
<p class="text-xs sm:text-sm">Data Engineer</p>
<p class="text-xs sm:text-sm">6 months</p>
</article>
<article class="border-2 border-gray-400 rounded-3xl mx-2 sm:mx-5 w-60 sm:w-72 py-3 sm:py-5 h-32 sm:h-40 mt-5 flex flex-col items-center">
<ion-icon name="school-outline" class="text-2xl sm:text-3xl text-blue-500"></ion-icon>
<p class="text-lg sm:text-xl font-bold">Education</p>
<p class="text-xs sm:text-sm">Bachelor of Computer Engineering</p>
<p class="text-xs sm:text-sm">University of Peloponnese</p>
</article>
</div>
<p class="mt-5 sm:mt-10 mx-2 sm:mx-5 lg:mt-0 lg:mx-0">
Motivated and skilled individual with a strong passion for web development, particularly in the realm of front-end
technologies. Proficient in HTML, CSS, and Tailwind CSS, with a solid understanding of JavaScript, TypeScript, and
SQL. Currently nearing completion of studies, with only the thesis remaining, which entails the development of a website
utilizing Next.js and Tailwind CSS.
</p>
</div>
</div>
</section>
<section id="experience">
<div class="flex flex-col items-center mt-40">
<p class="flex text-xl text-gray-500 mt-20 lg:mt-40">Explore My</p>
<h1 class="flex text-4xl lg:text-5xl font-bold">Experience</h1>
</div>
<div class="flex flex-col lg:flex-row justify-center items-center lg:space-x-10">
<div class=" my-14 lg:my-0 lg:w-1/2">
<div class="flex justify-center">
<div class="flex flex-col lg:flex-row rounded-3xl border-2 border-gray-400 p-2 space-y-10 lg:space-y-0 lg:space-x-10">
<div class="flex lg:flex-col justify-between">
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">HTML</p>
<p class="text-gray-500 text-sm">Experienced</p>
</div>
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">CSS</p>
<p class="text-gray-500 text-sm">Experienced</p>
</div>
</div>
<div class="flex lg:flex-col justify-between">
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">SQL</p>
<p class="text-gray-500 text-sm">Experienced</p>
</div>
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">Java</p>
<p class="text-gray-500 text-sm">Intermediate</p>
</div>
</div>
<div class="flex lg:flex-col justify-between">
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">Tailwind CSS</p>
<p class="text-gray-500 text-sm">Intermediate</p>
</div>
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">Javascript</p>
<p class="text-gray-500 text-sm">Experienced</p>
</div>
</div>
<div class="flex lg:flex-col justify-between">
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">Typescript</p>
<p class="text-gray-500 text-sm">Intermediate</p>
</div>
<div class="p-3 lg:p-5">
<ion-icon name="checkmark-done-circle-outline" class="text-3xl text-blue-500"></ion-icon>
<p class="text-lg font-bold">Python</p>
<p class="text-gray-500 text-sm">Basic</p>
</div>
</div>
</div>
</div>
</div>
<img src="assets/experience.png" alt="Experience" class="hidden xl:block my-14 max-w-xl">
</div>
</section>
<section id="projects">
<div class="py-8 px-4 mx-auto max-w-screen-xl lg:py-16 lg:px-6 mt-20 lg:mt-40">
<div class="mx-auto max-w-screen-md text-center mb-8 lg:mb-12">
<div class="flex flex-col items-center">
<p class="flex text-xl text-gray-500 mt-20">Browse My Recent</p>
<h1 class="flex text-5xl font-bold">Projects</h1>
</div>
</div>
<div class="space-y-8 lg:grid lg:grid-cols-3 sm:gap-6 xl:gap-10 lg:space-y-0 mt-20">
<div class="flex flex-col p-3 mx-auto max-w-sm text-center text-gray-900 bg-white rounded-3xl border border-gray-100 shadow md:max-w-xs xl:p-6">
<img class="rounded-3xl mb-4" src="assets/loading.png">
<p class="mb-2 text-xl font-bold">Incoming...</p>
<div class="py-3">
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-1 px-2 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl"
onclick="">Github</button>
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-1 px-2 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl"
onclick="">Live Demo</button>
</div>
</div>
<div class="flex flex-col p-3 mx-auto max-w-sm text-center text-gray-900 bg-white rounded-3xl border border-gray-100 shadow md:max-w-xs xl:p-6">
<img class="rounded-3xl mb-4" src="assets/loading.png">
<p class="mb-2 text-xl font-bold">Incoming...</p>
<div class="py-3">
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-1 px-2 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl"
onclick="">Github</button>
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-1 px-2 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl"
onclick="">Live Demo</button>
</div>
</div>
<div class="flex flex-col p-3 mx-auto max-w-sm text-center text-gray-900 bg-white rounded-3xl border border-gray-100 shadow md:max-w-xs xl:p-6">
<img class="rounded-3xl mb-4" src="assets/loading.png">
<p class="mb-2 text-xl font-bold">Incoming...</p>
<div class="py-3">
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-1 px-2 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl"
onclick="">Github</button>
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-1 px-2 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl"
onclick="">Live Demo</button>
</div>
</div>
</div>
</div>
</section>
<section id="contact">
<div class="py-8 lg:py-16 px-4 mx-auto max-w-screen-md">
<div class="flex flex-col items-center mb-20">
<p class="flex text-xl text-gray-500 mt-20 lg:mt-32">Get in Touch</p>
<h1 class="flex text-5xl font-bold">Contact Me</h1>
</div>
<form action="https://formsubmit.co/tsiro.thodoris@gmail.com" method="POST" class="space-y-8">
<div>
<label for="email" class="block mb-2 text-sm font-medium text-gray-900">Your email</label>
<input name="email" type="email" id="email" class="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg
focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5" placeholder="name@something.com" required>
</div>
<div>
<label for="subject" class="block mb-2 text-sm font-medium text-gray-900">Subject</label>
<input name="text" type="text" id="subject" class="block p-3 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 shadow-sm
focus:ring-blue-500 focus:border-blue-500" placeholder="Let me know how I can help you" required>
</div>
<div class="sm:col-span-2">
<label for="message" class="block mb-2 text-sm font-medium text-gray-900">Your message</label>
<textarea name="message" id="message" rows="6" class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg shadow-sm border
border-gray-300 focus:ring-blue-500 focus:border-blue-500" placeholder="Leave a comment..."></textarea>
</div>
<div class="flex justify-center">
<button class="mx-1 bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 border-b-4 border-blue-600 hover:border-blue-500 rounded-2xl" onclick="">Send Message</button>
</div>
</form>
</div>
</section>
<footer>
<div class="flex justify-center pb-5 text-gray-500 tracking-wide text-center">
<p class="text-sm sm:text-base md:text-lg lg:text-xl xl:text-xl">Copyright © 2024 Thodoris Tsironis. All Rights Reserved.</p>
</div>
</footer>
<script src="script.js"></script>
<script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>
</body>
</html>
<!-- Problems:
1. Fix Mobile Navbar-->
|
<div *ngIf="order.greeting" class="instructions" [innerHTML]="order.greeting | safeHtml"></div>
<div *ngIf="!order.greeting" class="instructions" [innerHTML]="order.info.greeting | safeHtml"></div>
<ng-template ngFor let-addonItem [ngForOf]="addonItems">
<div class="addon d-flex">
<div class="image-wrapper">
<img src="https://www.just4u.co.il/pictures/{{addonItem.image | encodeSpaces}}">
</div>
<div class="content-wrapper">
<h4 class="color-primary">{{addonItem.name}}<span *ngIf="addonItem.IsGiftCard"> בשווי {{addonItem.LoadSum | number:'2.0-0'}}
ש"ח</span></h4>
<div class="item-desc" [innerHTML]="addonItem.description"></div>
<a class="btn site-link" href="{{addonItem.link}}" target="_blank">לדף המוצר באתר<i class="fa fa-chevron-left"></i></a>
<h4 *ngIf="addonItem.VCVoucherid" style="margin-top: -1.5rem;">הקוד שלך: {{addonItem.VCVoucherid}}</h4>
</div>
</div>
<div class="and-marker"><h3>וגם:</h3></div>
</ng-template>
<ng-template [ngIf]="!order.autoChoose && !inDelivery">
<h4 *ngIf="addonItems.length" class="selectgift-heading">מתנה לבחירתך מתוך המגוון הבא:</h4>
<div class="gifts-grid" [class.ie11]="isIE" #grid>
<div *ngFor="let item of items" class="gift-wrapper" #wrapper>
<ng-template [ngIf]="!wrapper.classList.contains('expanded')" [ngIfElse]="expanded">
<div class="gift-item" (click)="expand($event)"
[style.background-image]="'url(https://www.just4u.co.il/pictures/' + (item.image | encodeSpaces) + ')'">
<div class="item-footer jc-between">
<span>{{item.name}}<span *ngIf="item.IsGiftCard"> בשווי {{item.LoadSum | number:'2.0-0'}}
ש"ח</span></span>
<button class="btn">בחירה<i class="fa fa-chevron-left"></i></button>
</div>
</div>
</ng-template>
<ng-template #expanded>
<div class="item-brief">
<span class="close-btn" (click)="collapse($event)">×</span>
<div class="brief-body" [style.height]="height + 'px'">
<div class="brief-info">
<img src="https://www.just4u.co.il/pictures/{{item.image | encodeSpaces}}">
<h4>{{item.name}}<span *ngIf="item.IsGiftCard"> בשווי {{item.LoadSum | number:'2.0-0'}}
ש"ח</span></h4>
<div class="brief-desc" [innerHTML]="item.description"></div>
</div>
</div>
<div class="brief-footer">
<a class="btn" href="{{item.link}}" target="_blank">מקומות מכבדים<i
class="fa fa-chevron-left"></i></a>
<button class="btn" (click)="doPotentialChoice(item)">
אישור בחירה<i class="fas fa-gift"></i>
</button>
</div>
</div>
</ng-template>
</div>
</div>
</ng-template>
<ng-template [ngIf]="order.autoChoose && !inDelivery">
<div class="addon d-flex auto-choose">
<div class="image-wrapper">
<img src="https://www.just4u.co.il/pictures/{{items[0].image | encodeSpaces}}">
</div>
<div class="content-wrapper">
<h4 class="color-primary">{{items[0].name}}<span *ngIf="items[0].IsGiftCard"> בשווי {{items[0].LoadSum | number:'2.0-0'}}
ש"ח</span></h4>
<div class="item-desc" [innerHTML]="items[0].description"></div>
<a class="btn site-link" href="{{items[0].link}}" target="_blank">לדף המוצר באתר<i class="fa fa-chevron-left"></i></a>
</div>
</div>
<div class="choice-btn"><button class="btn btn-large" (click)="doPotentialChoice(items[0])">אישור בחירה<i class="fas fa-gift"></i></button></div>
</ng-template>
<div *ngIf="inDelivery" class="d-flex delform-wrapper">
<div class="col-3-5"><app-delivery (actionEvent)="deliveryHandler($event)" #delForm></app-delivery></div>
<div class="del-item-brief col-2-5">
<div class="del-brief-body">
<div class="del-brief-info">
<img src="https://www.just4u.co.il/pictures/{{potentialChoice.image | encodeSpaces}}">
<h4>{{potentialChoice.name}}<span *ngIf="potentialChoice.IsGiftCard"> בשווי {{potentialChoice.LoadSum | number:'2.0-0'}}
ש"ח</span></h4>
<div class="del-brief-desc" [innerHTML]="potentialChoice.description"></div>
</div>
</div>
</div>
</div>
<div *ngIf="modalDialog" class="overlay">
<div class="j4u-modal">
בחרתם:<br>
<span *ngFor="let addonItem of addonItems"><strong>{{addonItem.name}}<span *ngIf="addonItem.IsGiftCard"> בשווי
{{addonItem.LoadSum | number:'2.0-0'}} ש"ח</span></strong><br>וגם<br></span>
<strong>{{potentialChoice.name}}<span *ngIf="potentialChoice.IsGiftCard"> בשווי
{{potentialChoice.LoadSum | number:'2.0-0'}} ש"ח</span></strong><br>
<span class="modal-title">בטוחים?</span><br>
לא ניתן יהיה להחליף את הבחירה!
<div class="d-flex jc-between" style="margin-top:1rem;">
<button *ngIf="!isLoading" class="btn" (click)="doChoice(potentialChoice)">כן!</button>
<div *ngIf="isLoading" class="loader">
<div class="lds-ring">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div><button class="btn" (click)="modalDialog = false" [disabled]="isLoading">לא, אני אסתכל עוד קצת</button>
</div>
</div>
</div>
</div>
|
import Router, { useRouter } from "next/router";
import React, { useEffect } from "react";
import data from "../../components/Services/data.json";
import { motion } from "framer-motion";
import Header from "../../components/Header";
import Footer from "../../components/Footer";
import { useMediaQuery } from "@mantine/hooks";
import Head from "next/head";
function id() {
const router = useRouter();
const { id } = router.query;
const obj = data[Number(id)];
const isSmall = useMediaQuery("(max-width: 500px)");
if (obj !== undefined) {
return (
<div className="w-screen bg-white h-screen scrollbar-hide overflow-y-auto overflow-x-hidden">
<Head>
<title>{obj.title}</title>
</Head>
<div className="absolute top-0 z-50 left-0 right-0">
<Header />
</div>
<div className="md:pb-14">
<div className="xl:h-16 md:h-10 h-16"></div>
<div className="md:w-9/12 mx-auto md:rounded-2xl md:mt-20 relative">
<motion.video
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.3, type: "spring", bounce: 0.2 }}
className="w-full md:rounded-2xl mx-auto"
autoPlay
loop
src="/vid.mp4"
></motion.video>
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.3, type: "spring", bounce: 0.2 }}
className="absolute bg-black md:rounded-2xl top-0 left-0 right-0 bottom-0 opacity-40"
></motion.div>
<div className="absolute flex flex-col items-center justify-center top-0 bottom-0 left-0 right-0 text-center">
<motion.h1
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.6, type: "spring", bounce: 0.2 }}
className="text-white xl:text-5xl 2xl:text-6xl md:text-4xl sm:text-2xl text-xl font-inter md:leading-loose w-11/12 my-auto"
>
{obj.title}
</motion.h1>
</div>
</div>
</div>
<div className="flex flex-col bg-white px-10 py-10 space-y-10">
<motion.p
initial={{ opacity: 0 }}
whileInView={{ opacity: 1 }}
viewport={{ once: true }}
transition={{ delay: isSmall ? 1 : 0.3 }}
className="font-inter text-black md:text-lg"
>
FAST O&M's projects range from equipment supply to installation,
including testing and commissioning, our strength lies in our
ability to provide a one-stop solution from the supply of material
to installation and commissioning and any related engineering
services. FAST O&M is continuously adding through its partner's
unique patented technologies in line with company philosophy, some
of the services that FAST O&M currently offers are as given below
</motion.p>
<motion.h1
initial={{ x: 100, opacity: 0 }}
whileInView={{ x: 0, opacity: 1 }}
viewport={{ once: true }}
transition={{ delay: 0.3 }}
className="md:text-4xl xl:text-5xl text-2xl text-black font-inter font-normal"
>
What We Provide
</motion.h1>
<div className="flex flex-col relative space-y-2">
<motion.img
initial={{ scale: 0 }}
whileInView={{ scale: 1 }}
transition={{ delay: 0.2 }}
viewport={{ once: true }}
src={`/services/${id}.png`}
className="md:absolute md:right-0 md:w-3/12 md:h-full h-40 md:object-cover"
alt=""
/>
{obj.provide.map((item, index) => (
<motion.div
initial={{ x: 100, opacity: 0 }}
whileInView={{ x: 0, opacity: 1 }}
viewport={{ once: true }}
transition={{ delay: (index / 2) * 0.1 }}
className="flex space-x-2 items-center"
>
<p className="text-black md:text-lg">{"‣"}</p>
<p className="text-black md:text-lg font-inter">{item}</p>
</motion.div>
))}
</div>
{/* <motion.p
initial={{ opacity: 0 }}
whileInView={{ opacity: 1 }}
viewport={{ once: true }}
transition={{ delay: 0.4 }}
className="font-inter text-center max-w-6xl text-sm md:max-w-4xl mx-auto text-gray-500 font-semibold md:text-lg"
>
To supply clients with services of the highest calibre while
upholding the highest ethical and professional standards possible.
To be the greatest and most reputable industrial service provider
</motion.p> */}
</div>
<Footer />
</div>
);
} else {
return "";
}
}
export default id;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.